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;
   31pub mod items;
   32mod linked_editing_ranges;
   33mod lsp_ext;
   34mod mouse_context_menu;
   35pub mod movement;
   36mod persistence;
   37mod proposed_changes_editor;
   38mod rust_analyzer_ext;
   39pub mod scroll;
   40mod selections_collection;
   41pub mod tasks;
   42
   43#[cfg(test)]
   44mod editor_tests;
   45mod signature_help;
   46#[cfg(any(test, feature = "test-support"))]
   47pub mod test;
   48
   49use ::git::diff::DiffHunkStatus;
   50pub(crate) use actions::*;
   51pub use actions::{OpenExcerpts, OpenExcerptsSplit};
   52use aho_corasick::AhoCorasick;
   53use anyhow::{anyhow, Context as _, Result};
   54use blink_manager::BlinkManager;
   55use client::{Collaborator, ParticipantIndex};
   56use clock::ReplicaId;
   57use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
   58use convert_case::{Case, Casing};
   59use debounced_delay::DebouncedDelay;
   60use display_map::*;
   61pub use display_map::{DisplayPoint, FoldPlaceholder};
   62pub use editor_settings::{
   63    CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
   64};
   65pub use editor_settings_controls::*;
   66use element::LineWithInvisibles;
   67pub use element::{
   68    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   69};
   70use futures::{future, FutureExt};
   71use fuzzy::{StringMatch, StringMatchCandidate};
   72use git::blame::GitBlame;
   73use gpui::{
   74    div, impl_actions, point, prelude::*, px, relative, size, uniform_list, Action, AnyElement,
   75    AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds, ClipboardEntry,
   76    ClipboardItem, Context, DispatchPhase, ElementId, EventEmitter, FocusHandle, FocusOutEvent,
   77    FocusableView, FontId, FontWeight, Global, HighlightStyle, Hsla, InteractiveText, KeyContext,
   78    ListSizingBehavior, Model, ModelContext, MouseButton, PaintQuad, ParentElement, Pixels, Render,
   79    ScrollStrategy, SharedString, Size, StrikethroughStyle, Styled, StyledText, Subscription, Task,
   80    TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle, View,
   81    ViewContext, ViewInputHandler, VisualContext, WeakFocusHandle, WeakView, WindowContext,
   82};
   83use highlight_matching_bracket::refresh_matching_bracket_highlights;
   84use hover_popover::{hide_hover, HoverState};
   85pub(crate) use hunk_diff::HoveredHunk;
   86use hunk_diff::{diff_hunk_to_display, ExpandedHunks};
   87use indent_guides::ActiveIndentGuidesState;
   88use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   89pub use inline_completion::Direction;
   90use inline_completion::{InlayProposal, InlineCompletionProvider, InlineCompletionProviderHandle};
   91pub use items::MAX_TAB_TITLE_LEN;
   92use itertools::Itertools;
   93use language::{
   94    language_settings::{self, all_language_settings, 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    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  103};
  104use similar::{ChangeTag, TextDiff};
  105use std::iter::Peekable;
  106use task::{ResolvedTask, TaskTemplate, TaskVariables};
  107
  108use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  109pub use lsp::CompletionContext;
  110use lsp::{
  111    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  112    LanguageServerId, LanguageServerName,
  113};
  114use mouse_context_menu::MouseContextMenu;
  115use movement::TextLayoutDetails;
  116pub use multi_buffer::{
  117    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
  118    ToPoint,
  119};
  120use multi_buffer::{
  121    ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
  122};
  123use ordered_float::OrderedFloat;
  124use parking_lot::{Mutex, RwLock};
  125use project::{
  126    lsp_store::{FormatTarget, FormatTrigger},
  127    project_settings::{GitGutterSetting, ProjectSettings},
  128    CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
  129    Project, ProjectItem, ProjectTransaction, TaskSourceKind,
  130};
  131use rand::prelude::*;
  132use rpc::{proto::*, ErrorExt};
  133use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  134use selections_collection::{
  135    resolve_selections, MutableSelectionsCollection, SelectionsCollection,
  136};
  137use serde::{Deserialize, Serialize};
  138use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  139use smallvec::SmallVec;
  140use snippet::Snippet;
  141use std::{
  142    any::TypeId,
  143    borrow::Cow,
  144    cell::RefCell,
  145    cmp::{self, Ordering, Reverse},
  146    mem,
  147    num::NonZeroU32,
  148    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  149    path::{Path, PathBuf},
  150    rc::Rc,
  151    sync::Arc,
  152    time::{Duration, Instant},
  153};
  154pub use sum_tree::Bias;
  155use sum_tree::TreeMap;
  156use text::{BufferId, OffsetUtf16, Rope};
  157use theme::{
  158    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  159    ThemeColors, ThemeSettings,
  160};
  161use ui::{
  162    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
  163    ListItem, Popover, PopoverMenuHandle, Tooltip,
  164};
  165use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  166use workspace::item::{ItemHandle, PreviewTabsSettings};
  167use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
  168use workspace::{
  169    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  170};
  171use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  172
  173use crate::hover_links::find_url;
  174use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  175
  176pub const FILE_HEADER_HEIGHT: u32 = 2;
  177pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  178pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  179pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  180const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  181const MAX_LINE_LEN: usize = 1024;
  182const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  183const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  184pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  185#[doc(hidden)]
  186pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  187#[doc(hidden)]
  188pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
  189
  190pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  191pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  192
  193pub fn render_parsed_markdown(
  194    element_id: impl Into<ElementId>,
  195    parsed: &language::ParsedMarkdown,
  196    editor_style: &EditorStyle,
  197    workspace: Option<WeakView<Workspace>>,
  198    cx: &mut WindowContext,
  199) -> InteractiveText {
  200    let code_span_background_color = cx
  201        .theme()
  202        .colors()
  203        .editor_document_highlight_read_background;
  204
  205    let highlights = gpui::combine_highlights(
  206        parsed.highlights.iter().filter_map(|(range, highlight)| {
  207            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  208            Some((range.clone(), highlight))
  209        }),
  210        parsed
  211            .regions
  212            .iter()
  213            .zip(&parsed.region_ranges)
  214            .filter_map(|(region, range)| {
  215                if region.code {
  216                    Some((
  217                        range.clone(),
  218                        HighlightStyle {
  219                            background_color: Some(code_span_background_color),
  220                            ..Default::default()
  221                        },
  222                    ))
  223                } else {
  224                    None
  225                }
  226            }),
  227    );
  228
  229    let mut links = Vec::new();
  230    let mut link_ranges = Vec::new();
  231    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  232        if let Some(link) = region.link.clone() {
  233            links.push(link);
  234            link_ranges.push(range.clone());
  235        }
  236    }
  237
  238    InteractiveText::new(
  239        element_id,
  240        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  241    )
  242    .on_click(link_ranges, move |clicked_range_ix, cx| {
  243        match &links[clicked_range_ix] {
  244            markdown::Link::Web { url } => cx.open_url(url),
  245            markdown::Link::Path { path } => {
  246                if let Some(workspace) = &workspace {
  247                    _ = workspace.update(cx, |workspace, cx| {
  248                        workspace.open_abs_path(path.clone(), false, cx).detach();
  249                    });
  250                }
  251            }
  252        }
  253    })
  254}
  255
  256#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  257pub(crate) enum InlayId {
  258    Suggestion(usize),
  259    Hint(usize),
  260}
  261
  262impl InlayId {
  263    fn id(&self) -> usize {
  264        match self {
  265            Self::Suggestion(id) => *id,
  266            Self::Hint(id) => *id,
  267        }
  268    }
  269}
  270
  271enum DiffRowHighlight {}
  272enum DocumentHighlightRead {}
  273enum DocumentHighlightWrite {}
  274enum InputComposition {}
  275
  276#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  277pub enum Navigated {
  278    Yes,
  279    No,
  280}
  281
  282impl Navigated {
  283    pub fn from_bool(yes: bool) -> Navigated {
  284        if yes {
  285            Navigated::Yes
  286        } else {
  287            Navigated::No
  288        }
  289    }
  290}
  291
  292pub fn init_settings(cx: &mut AppContext) {
  293    EditorSettings::register(cx);
  294}
  295
  296pub fn init(cx: &mut AppContext) {
  297    init_settings(cx);
  298
  299    workspace::register_project_item::<Editor>(cx);
  300    workspace::FollowableViewRegistry::register::<Editor>(cx);
  301    workspace::register_serializable_item::<Editor>(cx);
  302
  303    cx.observe_new_views(
  304        |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
  305            workspace.register_action(Editor::new_file);
  306            workspace.register_action(Editor::new_file_vertical);
  307            workspace.register_action(Editor::new_file_horizontal);
  308        },
  309    )
  310    .detach();
  311
  312    cx.on_action(move |_: &workspace::NewFile, cx| {
  313        let app_state = workspace::AppState::global(cx);
  314        if let Some(app_state) = app_state.upgrade() {
  315            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  316                Editor::new_file(workspace, &Default::default(), cx)
  317            })
  318            .detach();
  319        }
  320    });
  321    cx.on_action(move |_: &workspace::NewWindow, cx| {
  322        let app_state = workspace::AppState::global(cx);
  323        if let Some(app_state) = app_state.upgrade() {
  324            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  325                Editor::new_file(workspace, &Default::default(), cx)
  326            })
  327            .detach();
  328        }
  329    });
  330}
  331
  332pub struct SearchWithinRange;
  333
  334trait InvalidationRegion {
  335    fn ranges(&self) -> &[Range<Anchor>];
  336}
  337
  338#[derive(Clone, Debug, PartialEq)]
  339pub enum SelectPhase {
  340    Begin {
  341        position: DisplayPoint,
  342        add: bool,
  343        click_count: usize,
  344    },
  345    BeginColumnar {
  346        position: DisplayPoint,
  347        reset: bool,
  348        goal_column: u32,
  349    },
  350    Extend {
  351        position: DisplayPoint,
  352        click_count: usize,
  353    },
  354    Update {
  355        position: DisplayPoint,
  356        goal_column: u32,
  357        scroll_delta: gpui::Point<f32>,
  358    },
  359    End,
  360}
  361
  362#[derive(Clone, Debug)]
  363pub enum SelectMode {
  364    Character,
  365    Word(Range<Anchor>),
  366    Line(Range<Anchor>),
  367    All,
  368}
  369
  370#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  371pub enum EditorMode {
  372    SingleLine { auto_width: bool },
  373    AutoHeight { max_lines: usize },
  374    Full,
  375}
  376
  377#[derive(Copy, Clone, Debug)]
  378pub enum SoftWrap {
  379    /// Prefer not to wrap at all.
  380    ///
  381    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  382    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  383    GitDiff,
  384    /// Prefer a single line generally, unless an overly long line is encountered.
  385    None,
  386    /// Soft wrap lines that exceed the editor width.
  387    EditorWidth,
  388    /// Soft wrap lines at the preferred line length.
  389    Column(u32),
  390    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  391    Bounded(u32),
  392}
  393
  394#[derive(Clone)]
  395pub struct EditorStyle {
  396    pub background: Hsla,
  397    pub local_player: PlayerColor,
  398    pub text: TextStyle,
  399    pub scrollbar_width: Pixels,
  400    pub syntax: Arc<SyntaxTheme>,
  401    pub status: StatusColors,
  402    pub inlay_hints_style: HighlightStyle,
  403    pub suggestions_style: HighlightStyle,
  404    pub unnecessary_code_fade: f32,
  405}
  406
  407impl Default for EditorStyle {
  408    fn default() -> Self {
  409        Self {
  410            background: Hsla::default(),
  411            local_player: PlayerColor::default(),
  412            text: TextStyle::default(),
  413            scrollbar_width: Pixels::default(),
  414            syntax: Default::default(),
  415            // HACK: Status colors don't have a real default.
  416            // We should look into removing the status colors from the editor
  417            // style and retrieve them directly from the theme.
  418            status: StatusColors::dark(),
  419            inlay_hints_style: HighlightStyle::default(),
  420            suggestions_style: HighlightStyle::default(),
  421            unnecessary_code_fade: Default::default(),
  422        }
  423    }
  424}
  425
  426pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
  427    let show_background = language_settings::language_settings(None, None, cx)
  428        .inlay_hints
  429        .show_background;
  430
  431    HighlightStyle {
  432        color: Some(cx.theme().status().hint),
  433        background_color: show_background.then(|| cx.theme().status().hint_background),
  434        ..HighlightStyle::default()
  435    }
  436}
  437
  438type CompletionId = usize;
  439
  440#[derive(Clone, Debug)]
  441struct CompletionState {
  442    // render_inlay_ids represents the inlay hints that are inserted
  443    // for rendering the inline completions. They may be discontinuous
  444    // in the event that the completion provider returns some intersection
  445    // with the existing content.
  446    render_inlay_ids: Vec<InlayId>,
  447    // text is the resulting rope that is inserted when the user accepts a completion.
  448    text: Rope,
  449    // position is the position of the cursor when the completion was triggered.
  450    position: multi_buffer::Anchor,
  451    // delete_range is the range of text that this completion state covers.
  452    // if the completion is accepted, this range should be deleted.
  453    delete_range: Option<Range<multi_buffer::Anchor>>,
  454}
  455
  456#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  457struct EditorActionId(usize);
  458
  459impl EditorActionId {
  460    pub fn post_inc(&mut self) -> Self {
  461        let answer = self.0;
  462
  463        *self = Self(answer + 1);
  464
  465        Self(answer)
  466    }
  467}
  468
  469// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  470// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  471
  472type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  473type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
  474
  475#[derive(Default)]
  476struct ScrollbarMarkerState {
  477    scrollbar_size: Size<Pixels>,
  478    dirty: bool,
  479    markers: Arc<[PaintQuad]>,
  480    pending_refresh: Option<Task<Result<()>>>,
  481}
  482
  483impl ScrollbarMarkerState {
  484    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  485        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  486    }
  487}
  488
  489#[derive(Clone, Debug)]
  490struct RunnableTasks {
  491    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  492    offset: MultiBufferOffset,
  493    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  494    column: u32,
  495    // Values of all named captures, including those starting with '_'
  496    extra_variables: HashMap<String, String>,
  497    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  498    context_range: Range<BufferOffset>,
  499}
  500
  501impl RunnableTasks {
  502    fn resolve<'a>(
  503        &'a self,
  504        cx: &'a task::TaskContext,
  505    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  506        self.templates.iter().filter_map(|(kind, template)| {
  507            template
  508                .resolve_task(&kind.to_id_base(), cx)
  509                .map(|task| (kind.clone(), task))
  510        })
  511    }
  512}
  513
  514#[derive(Clone)]
  515struct ResolvedTasks {
  516    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  517    position: Anchor,
  518}
  519#[derive(Copy, Clone, Debug)]
  520struct MultiBufferOffset(usize);
  521#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  522struct BufferOffset(usize);
  523
  524// Addons allow storing per-editor state in other crates (e.g. Vim)
  525pub trait Addon: 'static {
  526    fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
  527
  528    fn to_any(&self) -> &dyn std::any::Any;
  529}
  530
  531#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  532pub enum IsVimMode {
  533    Yes,
  534    No,
  535}
  536
  537/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
  538///
  539/// See the [module level documentation](self) for more information.
  540pub struct Editor {
  541    focus_handle: FocusHandle,
  542    last_focused_descendant: Option<WeakFocusHandle>,
  543    /// The text buffer being edited
  544    buffer: Model<MultiBuffer>,
  545    /// Map of how text in the buffer should be displayed.
  546    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  547    pub display_map: Model<DisplayMap>,
  548    pub selections: SelectionsCollection,
  549    pub scroll_manager: ScrollManager,
  550    /// When inline assist editors are linked, they all render cursors because
  551    /// typing enters text into each of them, even the ones that aren't focused.
  552    pub(crate) show_cursor_when_unfocused: bool,
  553    columnar_selection_tail: Option<Anchor>,
  554    add_selections_state: Option<AddSelectionsState>,
  555    select_next_state: Option<SelectNextState>,
  556    select_prev_state: Option<SelectNextState>,
  557    selection_history: SelectionHistory,
  558    autoclose_regions: Vec<AutocloseRegion>,
  559    snippet_stack: InvalidationStack<SnippetState>,
  560    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  561    ime_transaction: Option<TransactionId>,
  562    active_diagnostics: Option<ActiveDiagnosticGroup>,
  563    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  564
  565    project: Option<Model<Project>>,
  566    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  567    completion_provider: Option<Box<dyn CompletionProvider>>,
  568    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  569    blink_manager: Model<BlinkManager>,
  570    show_cursor_names: bool,
  571    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  572    pub show_local_selections: bool,
  573    mode: EditorMode,
  574    show_breadcrumbs: bool,
  575    show_gutter: bool,
  576    show_line_numbers: Option<bool>,
  577    use_relative_line_numbers: Option<bool>,
  578    show_git_diff_gutter: Option<bool>,
  579    show_code_actions: Option<bool>,
  580    show_runnables: Option<bool>,
  581    show_wrap_guides: Option<bool>,
  582    show_indent_guides: Option<bool>,
  583    placeholder_text: Option<Arc<str>>,
  584    highlight_order: usize,
  585    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  586    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  587    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  588    scrollbar_marker_state: ScrollbarMarkerState,
  589    active_indent_guides_state: ActiveIndentGuidesState,
  590    nav_history: Option<ItemNavHistory>,
  591    context_menu: RwLock<Option<ContextMenu>>,
  592    mouse_context_menu: Option<MouseContextMenu>,
  593    hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
  594    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  595    signature_help_state: SignatureHelpState,
  596    auto_signature_help: Option<bool>,
  597    find_all_references_task_sources: Vec<Anchor>,
  598    next_completion_id: CompletionId,
  599    available_code_actions: Option<(Location, Arc<[AvailableCodeAction]>)>,
  600    code_actions_task: Option<Task<Result<()>>>,
  601    document_highlights_task: Option<Task<()>>,
  602    linked_editing_range_task: Option<Task<Option<()>>>,
  603    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  604    pending_rename: Option<RenameState>,
  605    searchable: bool,
  606    cursor_shape: CursorShape,
  607    current_line_highlight: Option<CurrentLineHighlight>,
  608    collapse_matches: bool,
  609    autoindent_mode: Option<AutoindentMode>,
  610    workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
  611    input_enabled: bool,
  612    use_modal_editing: bool,
  613    read_only: bool,
  614    leader_peer_id: Option<PeerId>,
  615    remote_id: Option<ViewId>,
  616    hover_state: HoverState,
  617    gutter_hovered: bool,
  618    hovered_link_state: Option<HoveredLinkState>,
  619    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  620    code_action_providers: Vec<Arc<dyn CodeActionProvider>>,
  621    active_inline_completion: Option<CompletionState>,
  622    // enable_inline_completions is a switch that Vim can use to disable
  623    // inline completions based on its mode.
  624    enable_inline_completions: bool,
  625    show_inline_completions_override: Option<bool>,
  626    inlay_hint_cache: InlayHintCache,
  627    expanded_hunks: ExpandedHunks,
  628    next_inlay_id: usize,
  629    _subscriptions: Vec<Subscription>,
  630    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  631    gutter_dimensions: GutterDimensions,
  632    style: Option<EditorStyle>,
  633    text_style_refinement: Option<TextStyleRefinement>,
  634    next_editor_action_id: EditorActionId,
  635    editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
  636    use_autoclose: bool,
  637    use_auto_surround: bool,
  638    auto_replace_emoji_shortcode: bool,
  639    show_git_blame_gutter: bool,
  640    show_git_blame_inline: bool,
  641    show_git_blame_inline_delay_task: Option<Task<()>>,
  642    git_blame_inline_enabled: bool,
  643    serialize_dirty_buffers: bool,
  644    show_selection_menu: Option<bool>,
  645    blame: Option<Model<GitBlame>>,
  646    blame_subscription: Option<Subscription>,
  647    custom_context_menu: Option<
  648        Box<
  649            dyn 'static
  650                + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
  651        >,
  652    >,
  653    last_bounds: Option<Bounds<Pixels>>,
  654    expect_bounds_change: Option<Bounds<Pixels>>,
  655    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  656    tasks_update_task: Option<Task<()>>,
  657    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  658    breadcrumb_header: Option<String>,
  659    focused_block: Option<FocusedBlock>,
  660    next_scroll_position: NextScrollCursorCenterTopBottom,
  661    addons: HashMap<TypeId, Box<dyn Addon>>,
  662    _scroll_cursor_center_top_bottom_task: Task<()>,
  663}
  664
  665#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  666enum NextScrollCursorCenterTopBottom {
  667    #[default]
  668    Center,
  669    Top,
  670    Bottom,
  671}
  672
  673impl NextScrollCursorCenterTopBottom {
  674    fn next(&self) -> Self {
  675        match self {
  676            Self::Center => Self::Top,
  677            Self::Top => Self::Bottom,
  678            Self::Bottom => Self::Center,
  679        }
  680    }
  681}
  682
  683#[derive(Clone)]
  684pub struct EditorSnapshot {
  685    pub mode: EditorMode,
  686    show_gutter: bool,
  687    show_line_numbers: Option<bool>,
  688    show_git_diff_gutter: Option<bool>,
  689    show_code_actions: Option<bool>,
  690    show_runnables: Option<bool>,
  691    git_blame_gutter_max_author_length: Option<usize>,
  692    pub display_snapshot: DisplaySnapshot,
  693    pub placeholder_text: Option<Arc<str>>,
  694    is_focused: bool,
  695    scroll_anchor: ScrollAnchor,
  696    ongoing_scroll: OngoingScroll,
  697    current_line_highlight: CurrentLineHighlight,
  698    gutter_hovered: bool,
  699}
  700
  701const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  702
  703#[derive(Default, Debug, Clone, Copy)]
  704pub struct GutterDimensions {
  705    pub left_padding: Pixels,
  706    pub right_padding: Pixels,
  707    pub width: Pixels,
  708    pub margin: Pixels,
  709    pub git_blame_entries_width: Option<Pixels>,
  710}
  711
  712impl GutterDimensions {
  713    /// The full width of the space taken up by the gutter.
  714    pub fn full_width(&self) -> Pixels {
  715        self.margin + self.width
  716    }
  717
  718    /// The width of the space reserved for the fold indicators,
  719    /// use alongside 'justify_end' and `gutter_width` to
  720    /// right align content with the line numbers
  721    pub fn fold_area_width(&self) -> Pixels {
  722        self.margin + self.right_padding
  723    }
  724}
  725
  726#[derive(Debug)]
  727pub struct RemoteSelection {
  728    pub replica_id: ReplicaId,
  729    pub selection: Selection<Anchor>,
  730    pub cursor_shape: CursorShape,
  731    pub peer_id: PeerId,
  732    pub line_mode: bool,
  733    pub participant_index: Option<ParticipantIndex>,
  734    pub user_name: Option<SharedString>,
  735}
  736
  737#[derive(Clone, Debug)]
  738struct SelectionHistoryEntry {
  739    selections: Arc<[Selection<Anchor>]>,
  740    select_next_state: Option<SelectNextState>,
  741    select_prev_state: Option<SelectNextState>,
  742    add_selections_state: Option<AddSelectionsState>,
  743}
  744
  745enum SelectionHistoryMode {
  746    Normal,
  747    Undoing,
  748    Redoing,
  749}
  750
  751#[derive(Clone, PartialEq, Eq, Hash)]
  752struct HoveredCursor {
  753    replica_id: u16,
  754    selection_id: usize,
  755}
  756
  757impl Default for SelectionHistoryMode {
  758    fn default() -> Self {
  759        Self::Normal
  760    }
  761}
  762
  763#[derive(Default)]
  764struct SelectionHistory {
  765    #[allow(clippy::type_complexity)]
  766    selections_by_transaction:
  767        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  768    mode: SelectionHistoryMode,
  769    undo_stack: VecDeque<SelectionHistoryEntry>,
  770    redo_stack: VecDeque<SelectionHistoryEntry>,
  771}
  772
  773impl SelectionHistory {
  774    fn insert_transaction(
  775        &mut self,
  776        transaction_id: TransactionId,
  777        selections: Arc<[Selection<Anchor>]>,
  778    ) {
  779        self.selections_by_transaction
  780            .insert(transaction_id, (selections, None));
  781    }
  782
  783    #[allow(clippy::type_complexity)]
  784    fn transaction(
  785        &self,
  786        transaction_id: TransactionId,
  787    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  788        self.selections_by_transaction.get(&transaction_id)
  789    }
  790
  791    #[allow(clippy::type_complexity)]
  792    fn transaction_mut(
  793        &mut self,
  794        transaction_id: TransactionId,
  795    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  796        self.selections_by_transaction.get_mut(&transaction_id)
  797    }
  798
  799    fn push(&mut self, entry: SelectionHistoryEntry) {
  800        if !entry.selections.is_empty() {
  801            match self.mode {
  802                SelectionHistoryMode::Normal => {
  803                    self.push_undo(entry);
  804                    self.redo_stack.clear();
  805                }
  806                SelectionHistoryMode::Undoing => self.push_redo(entry),
  807                SelectionHistoryMode::Redoing => self.push_undo(entry),
  808            }
  809        }
  810    }
  811
  812    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  813        if self
  814            .undo_stack
  815            .back()
  816            .map_or(true, |e| e.selections != entry.selections)
  817        {
  818            self.undo_stack.push_back(entry);
  819            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  820                self.undo_stack.pop_front();
  821            }
  822        }
  823    }
  824
  825    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  826        if self
  827            .redo_stack
  828            .back()
  829            .map_or(true, |e| e.selections != entry.selections)
  830        {
  831            self.redo_stack.push_back(entry);
  832            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  833                self.redo_stack.pop_front();
  834            }
  835        }
  836    }
  837}
  838
  839struct RowHighlight {
  840    index: usize,
  841    range: Range<Anchor>,
  842    color: Hsla,
  843    should_autoscroll: bool,
  844}
  845
  846#[derive(Clone, Debug)]
  847struct AddSelectionsState {
  848    above: bool,
  849    stack: Vec<usize>,
  850}
  851
  852#[derive(Clone)]
  853struct SelectNextState {
  854    query: AhoCorasick,
  855    wordwise: bool,
  856    done: bool,
  857}
  858
  859impl std::fmt::Debug for SelectNextState {
  860    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  861        f.debug_struct(std::any::type_name::<Self>())
  862            .field("wordwise", &self.wordwise)
  863            .field("done", &self.done)
  864            .finish()
  865    }
  866}
  867
  868#[derive(Debug)]
  869struct AutocloseRegion {
  870    selection_id: usize,
  871    range: Range<Anchor>,
  872    pair: BracketPair,
  873}
  874
  875#[derive(Debug)]
  876struct SnippetState {
  877    ranges: Vec<Vec<Range<Anchor>>>,
  878    active_index: usize,
  879    choices: Vec<Option<Vec<String>>>,
  880}
  881
  882#[doc(hidden)]
  883pub struct RenameState {
  884    pub range: Range<Anchor>,
  885    pub old_name: Arc<str>,
  886    pub editor: View<Editor>,
  887    block_id: CustomBlockId,
  888}
  889
  890struct InvalidationStack<T>(Vec<T>);
  891
  892struct RegisteredInlineCompletionProvider {
  893    provider: Arc<dyn InlineCompletionProviderHandle>,
  894    _subscription: Subscription,
  895}
  896
  897enum ContextMenu {
  898    Completions(CompletionsMenu),
  899    CodeActions(CodeActionsMenu),
  900}
  901
  902impl ContextMenu {
  903    fn select_first(
  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_first(provider, cx),
  911                ContextMenu::CodeActions(menu) => menu.select_first(cx),
  912            }
  913            true
  914        } else {
  915            false
  916        }
  917    }
  918
  919    fn select_prev(
  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_prev(provider, cx),
  927                ContextMenu::CodeActions(menu) => menu.select_prev(cx),
  928            }
  929            true
  930        } else {
  931            false
  932        }
  933    }
  934
  935    fn select_next(
  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_next(provider, cx),
  943                ContextMenu::CodeActions(menu) => menu.select_next(cx),
  944            }
  945            true
  946        } else {
  947            false
  948        }
  949    }
  950
  951    fn select_last(
  952        &mut self,
  953        provider: Option<&dyn CompletionProvider>,
  954        cx: &mut ViewContext<Editor>,
  955    ) -> bool {
  956        if self.visible() {
  957            match self {
  958                ContextMenu::Completions(menu) => menu.select_last(provider, cx),
  959                ContextMenu::CodeActions(menu) => menu.select_last(cx),
  960            }
  961            true
  962        } else {
  963            false
  964        }
  965    }
  966
  967    fn visible(&self) -> bool {
  968        match self {
  969            ContextMenu::Completions(menu) => menu.visible(),
  970            ContextMenu::CodeActions(menu) => menu.visible(),
  971        }
  972    }
  973
  974    fn render(
  975        &self,
  976        cursor_position: DisplayPoint,
  977        style: &EditorStyle,
  978        max_height: Pixels,
  979        workspace: Option<WeakView<Workspace>>,
  980        cx: &mut ViewContext<Editor>,
  981    ) -> (ContextMenuOrigin, AnyElement) {
  982        match self {
  983            ContextMenu::Completions(menu) => (
  984                ContextMenuOrigin::EditorPoint(cursor_position),
  985                menu.render(style, max_height, workspace, cx),
  986            ),
  987            ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
  988        }
  989    }
  990}
  991
  992enum ContextMenuOrigin {
  993    EditorPoint(DisplayPoint),
  994    GutterIndicator(DisplayRow),
  995}
  996
  997#[derive(Clone, Debug)]
  998struct CompletionsMenu {
  999    id: CompletionId,
 1000    sort_completions: bool,
 1001    initial_position: Anchor,
 1002    buffer: Model<Buffer>,
 1003    completions: Arc<RwLock<Box<[Completion]>>>,
 1004    match_candidates: Arc<[StringMatchCandidate]>,
 1005    matches: Arc<[StringMatch]>,
 1006    selected_item: usize,
 1007    scroll_handle: UniformListScrollHandle,
 1008    selected_completion_resolve_debounce: Option<Arc<Mutex<DebouncedDelay>>>,
 1009}
 1010
 1011impl CompletionsMenu {
 1012    fn new(
 1013        id: CompletionId,
 1014        sort_completions: bool,
 1015        initial_position: Anchor,
 1016        buffer: Model<Buffer>,
 1017        completions: Box<[Completion]>,
 1018    ) -> Self {
 1019        let match_candidates = completions
 1020            .iter()
 1021            .enumerate()
 1022            .map(|(id, completion)| {
 1023                StringMatchCandidate::new(
 1024                    id,
 1025                    completion.label.text[completion.label.filter_range.clone()].into(),
 1026                )
 1027            })
 1028            .collect();
 1029
 1030        Self {
 1031            id,
 1032            sort_completions,
 1033            initial_position,
 1034            buffer,
 1035            completions: Arc::new(RwLock::new(completions)),
 1036            match_candidates,
 1037            matches: Vec::new().into(),
 1038            selected_item: 0,
 1039            scroll_handle: UniformListScrollHandle::new(),
 1040            selected_completion_resolve_debounce: Some(Arc::new(Mutex::new(DebouncedDelay::new()))),
 1041        }
 1042    }
 1043
 1044    fn new_snippet_choices(
 1045        id: CompletionId,
 1046        sort_completions: bool,
 1047        choices: &Vec<String>,
 1048        selection: Range<Anchor>,
 1049        buffer: Model<Buffer>,
 1050    ) -> Self {
 1051        let completions = choices
 1052            .iter()
 1053            .map(|choice| Completion {
 1054                old_range: selection.start.text_anchor..selection.end.text_anchor,
 1055                new_text: choice.to_string(),
 1056                label: CodeLabel {
 1057                    text: choice.to_string(),
 1058                    runs: Default::default(),
 1059                    filter_range: Default::default(),
 1060                },
 1061                server_id: LanguageServerId(usize::MAX),
 1062                documentation: None,
 1063                lsp_completion: Default::default(),
 1064                confirm: None,
 1065            })
 1066            .collect();
 1067
 1068        let match_candidates = choices
 1069            .iter()
 1070            .enumerate()
 1071            .map(|(id, completion)| StringMatchCandidate::new(id, completion.to_string()))
 1072            .collect();
 1073        let matches = choices
 1074            .iter()
 1075            .enumerate()
 1076            .map(|(id, completion)| StringMatch {
 1077                candidate_id: id,
 1078                score: 1.,
 1079                positions: vec![],
 1080                string: completion.clone(),
 1081            })
 1082            .collect();
 1083        Self {
 1084            id,
 1085            sort_completions,
 1086            initial_position: selection.start,
 1087            buffer,
 1088            completions: Arc::new(RwLock::new(completions)),
 1089            match_candidates,
 1090            matches,
 1091            selected_item: 0,
 1092            scroll_handle: UniformListScrollHandle::new(),
 1093            selected_completion_resolve_debounce: Some(Arc::new(Mutex::new(DebouncedDelay::new()))),
 1094        }
 1095    }
 1096
 1097    fn suppress_documentation_resolution(mut self) -> Self {
 1098        self.selected_completion_resolve_debounce.take();
 1099        self
 1100    }
 1101
 1102    fn select_first(
 1103        &mut self,
 1104        provider: Option<&dyn CompletionProvider>,
 1105        cx: &mut ViewContext<Editor>,
 1106    ) {
 1107        self.selected_item = 0;
 1108        self.scroll_handle
 1109            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1110        self.resolve_selected_completion(provider, cx);
 1111        cx.notify();
 1112    }
 1113
 1114    fn select_prev(
 1115        &mut self,
 1116        provider: Option<&dyn CompletionProvider>,
 1117        cx: &mut ViewContext<Editor>,
 1118    ) {
 1119        if self.selected_item > 0 {
 1120            self.selected_item -= 1;
 1121        } else {
 1122            self.selected_item = self.matches.len() - 1;
 1123        }
 1124        self.scroll_handle
 1125            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1126        self.resolve_selected_completion(provider, cx);
 1127        cx.notify();
 1128    }
 1129
 1130    fn select_next(
 1131        &mut self,
 1132        provider: Option<&dyn CompletionProvider>,
 1133        cx: &mut ViewContext<Editor>,
 1134    ) {
 1135        if self.selected_item + 1 < self.matches.len() {
 1136            self.selected_item += 1;
 1137        } else {
 1138            self.selected_item = 0;
 1139        }
 1140        self.scroll_handle
 1141            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1142        self.resolve_selected_completion(provider, cx);
 1143        cx.notify();
 1144    }
 1145
 1146    fn select_last(
 1147        &mut self,
 1148        provider: Option<&dyn CompletionProvider>,
 1149        cx: &mut ViewContext<Editor>,
 1150    ) {
 1151        self.selected_item = self.matches.len() - 1;
 1152        self.scroll_handle
 1153            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1154        self.resolve_selected_completion(provider, cx);
 1155        cx.notify();
 1156    }
 1157
 1158    fn resolve_selected_completion(
 1159        &mut self,
 1160        provider: Option<&dyn CompletionProvider>,
 1161        cx: &mut ViewContext<Editor>,
 1162    ) {
 1163        let completion_index = self.matches[self.selected_item].candidate_id;
 1164        let Some(provider) = provider else {
 1165            return;
 1166        };
 1167        let Some(completion_resolve) = self.selected_completion_resolve_debounce.as_ref() else {
 1168            return;
 1169        };
 1170
 1171        let resolve_task = provider.resolve_completions(
 1172            self.buffer.clone(),
 1173            vec![completion_index],
 1174            self.completions.clone(),
 1175            cx,
 1176        );
 1177
 1178        let delay_ms =
 1179            EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
 1180        let delay = Duration::from_millis(delay_ms);
 1181
 1182        completion_resolve.lock().fire_new(delay, cx, |_, cx| {
 1183            cx.spawn(move |this, mut cx| async move {
 1184                if let Some(true) = resolve_task.await.log_err() {
 1185                    this.update(&mut cx, |_, cx| cx.notify()).ok();
 1186                }
 1187            })
 1188        });
 1189    }
 1190
 1191    fn visible(&self) -> bool {
 1192        !self.matches.is_empty()
 1193    }
 1194
 1195    fn render(
 1196        &self,
 1197        style: &EditorStyle,
 1198        max_height: Pixels,
 1199        workspace: Option<WeakView<Workspace>>,
 1200        cx: &mut ViewContext<Editor>,
 1201    ) -> AnyElement {
 1202        let settings = EditorSettings::get_global(cx);
 1203        let show_completion_documentation = settings.show_completion_documentation;
 1204
 1205        let widest_completion_ix = self
 1206            .matches
 1207            .iter()
 1208            .enumerate()
 1209            .max_by_key(|(_, mat)| {
 1210                let completions = self.completions.read();
 1211                let completion = &completions[mat.candidate_id];
 1212                let documentation = &completion.documentation;
 1213
 1214                let mut len = completion.label.text.chars().count();
 1215                if let Some(Documentation::SingleLine(text)) = documentation {
 1216                    if show_completion_documentation {
 1217                        len += text.chars().count();
 1218                    }
 1219                }
 1220
 1221                len
 1222            })
 1223            .map(|(ix, _)| ix);
 1224
 1225        let completions = self.completions.clone();
 1226        let matches = self.matches.clone();
 1227        let selected_item = self.selected_item;
 1228        let style = style.clone();
 1229
 1230        let multiline_docs = if show_completion_documentation {
 1231            let mat = &self.matches[selected_item];
 1232            let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
 1233                Some(Documentation::MultiLinePlainText(text)) => {
 1234                    Some(div().child(SharedString::from(text.clone())))
 1235                }
 1236                Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
 1237                    Some(div().child(render_parsed_markdown(
 1238                        "completions_markdown",
 1239                        parsed,
 1240                        &style,
 1241                        workspace,
 1242                        cx,
 1243                    )))
 1244                }
 1245                _ => None,
 1246            };
 1247            multiline_docs.map(|div| {
 1248                div.id("multiline_docs")
 1249                    .max_h(max_height)
 1250                    .flex_1()
 1251                    .px_1p5()
 1252                    .py_1()
 1253                    .min_w(px(260.))
 1254                    .max_w(px(640.))
 1255                    .w(px(500.))
 1256                    .overflow_y_scroll()
 1257                    .occlude()
 1258            })
 1259        } else {
 1260            None
 1261        };
 1262
 1263        let list = uniform_list(
 1264            cx.view().clone(),
 1265            "completions",
 1266            matches.len(),
 1267            move |_editor, range, cx| {
 1268                let start_ix = range.start;
 1269                let completions_guard = completions.read();
 1270
 1271                matches[range]
 1272                    .iter()
 1273                    .enumerate()
 1274                    .map(|(ix, mat)| {
 1275                        let item_ix = start_ix + ix;
 1276                        let candidate_id = mat.candidate_id;
 1277                        let completion = &completions_guard[candidate_id];
 1278
 1279                        let documentation = if show_completion_documentation {
 1280                            &completion.documentation
 1281                        } else {
 1282                            &None
 1283                        };
 1284
 1285                        let highlights = gpui::combine_highlights(
 1286                            mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
 1287                            styled_runs_for_code_label(&completion.label, &style.syntax).map(
 1288                                |(range, mut highlight)| {
 1289                                    // Ignore font weight for syntax highlighting, as we'll use it
 1290                                    // for fuzzy matches.
 1291                                    highlight.font_weight = None;
 1292
 1293                                    if completion.lsp_completion.deprecated.unwrap_or(false) {
 1294                                        highlight.strikethrough = Some(StrikethroughStyle {
 1295                                            thickness: 1.0.into(),
 1296                                            ..Default::default()
 1297                                        });
 1298                                        highlight.color = Some(cx.theme().colors().text_muted);
 1299                                    }
 1300
 1301                                    (range, highlight)
 1302                                },
 1303                            ),
 1304                        );
 1305                        let completion_label = StyledText::new(completion.label.text.clone())
 1306                            .with_highlights(&style.text, highlights);
 1307                        let documentation_label =
 1308                            if let Some(Documentation::SingleLine(text)) = documentation {
 1309                                if text.trim().is_empty() {
 1310                                    None
 1311                                } else {
 1312                                    Some(
 1313                                        Label::new(text.clone())
 1314                                            .ml_4()
 1315                                            .size(LabelSize::Small)
 1316                                            .color(Color::Muted),
 1317                                    )
 1318                                }
 1319                            } else {
 1320                                None
 1321                            };
 1322
 1323                        let color_swatch = completion
 1324                            .color()
 1325                            .map(|color| div().size_4().bg(color).rounded_sm());
 1326
 1327                        div().min_w(px(220.)).max_w(px(540.)).child(
 1328                            ListItem::new(mat.candidate_id)
 1329                                .inset(true)
 1330                                .selected(item_ix == selected_item)
 1331                                .on_click(cx.listener(move |editor, _event, cx| {
 1332                                    cx.stop_propagation();
 1333                                    if let Some(task) = editor.confirm_completion(
 1334                                        &ConfirmCompletion {
 1335                                            item_ix: Some(item_ix),
 1336                                        },
 1337                                        cx,
 1338                                    ) {
 1339                                        task.detach_and_log_err(cx)
 1340                                    }
 1341                                }))
 1342                                .start_slot::<Div>(color_swatch)
 1343                                .child(h_flex().overflow_hidden().child(completion_label))
 1344                                .end_slot::<Label>(documentation_label),
 1345                        )
 1346                    })
 1347                    .collect()
 1348            },
 1349        )
 1350        .occlude()
 1351        .max_h(max_height)
 1352        .track_scroll(self.scroll_handle.clone())
 1353        .with_width_from_item(widest_completion_ix)
 1354        .with_sizing_behavior(ListSizingBehavior::Infer);
 1355
 1356        Popover::new()
 1357            .child(list)
 1358            .when_some(multiline_docs, |popover, multiline_docs| {
 1359                popover.aside(multiline_docs)
 1360            })
 1361            .into_any_element()
 1362    }
 1363
 1364    pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
 1365        let mut matches = if let Some(query) = query {
 1366            fuzzy::match_strings(
 1367                &self.match_candidates,
 1368                query,
 1369                query.chars().any(|c| c.is_uppercase()),
 1370                100,
 1371                &Default::default(),
 1372                executor,
 1373            )
 1374            .await
 1375        } else {
 1376            self.match_candidates
 1377                .iter()
 1378                .enumerate()
 1379                .map(|(candidate_id, candidate)| StringMatch {
 1380                    candidate_id,
 1381                    score: Default::default(),
 1382                    positions: Default::default(),
 1383                    string: candidate.string.clone(),
 1384                })
 1385                .collect()
 1386        };
 1387
 1388        // Remove all candidates where the query's start does not match the start of any word in the candidate
 1389        if let Some(query) = query {
 1390            if let Some(query_start) = query.chars().next() {
 1391                matches.retain(|string_match| {
 1392                    split_words(&string_match.string).any(|word| {
 1393                        // Check that the first codepoint of the word as lowercase matches the first
 1394                        // codepoint of the query as lowercase
 1395                        word.chars()
 1396                            .flat_map(|codepoint| codepoint.to_lowercase())
 1397                            .zip(query_start.to_lowercase())
 1398                            .all(|(word_cp, query_cp)| word_cp == query_cp)
 1399                    })
 1400                });
 1401            }
 1402        }
 1403
 1404        let completions = self.completions.read();
 1405        if self.sort_completions {
 1406            matches.sort_unstable_by_key(|mat| {
 1407                // We do want to strike a balance here between what the language server tells us
 1408                // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
 1409                // `Creat` and there is a local variable called `CreateComponent`).
 1410                // So what we do is: we bucket all matches into two buckets
 1411                // - Strong matches
 1412                // - Weak matches
 1413                // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
 1414                // and the Weak matches are the rest.
 1415                //
 1416                // For the strong matches, we sort by our fuzzy-finder score first and for the weak
 1417                // matches, we prefer language-server sort_text first.
 1418                //
 1419                // The thinking behind that: we want to show strong matches first in order of relevance(fuzzy score).
 1420                // Rest of the matches(weak) can be sorted as language-server expects.
 1421
 1422                #[derive(PartialEq, Eq, PartialOrd, Ord)]
 1423                enum MatchScore<'a> {
 1424                    Strong {
 1425                        score: Reverse<OrderedFloat<f64>>,
 1426                        sort_text: Option<&'a str>,
 1427                        sort_key: (usize, &'a str),
 1428                    },
 1429                    Weak {
 1430                        sort_text: Option<&'a str>,
 1431                        score: Reverse<OrderedFloat<f64>>,
 1432                        sort_key: (usize, &'a str),
 1433                    },
 1434                }
 1435
 1436                let completion = &completions[mat.candidate_id];
 1437                let sort_key = completion.sort_key();
 1438                let sort_text = completion.lsp_completion.sort_text.as_deref();
 1439                let score = Reverse(OrderedFloat(mat.score));
 1440
 1441                if mat.score >= 0.2 {
 1442                    MatchScore::Strong {
 1443                        score,
 1444                        sort_text,
 1445                        sort_key,
 1446                    }
 1447                } else {
 1448                    MatchScore::Weak {
 1449                        sort_text,
 1450                        score,
 1451                        sort_key,
 1452                    }
 1453                }
 1454            });
 1455        }
 1456
 1457        for mat in &mut matches {
 1458            let completion = &completions[mat.candidate_id];
 1459            mat.string.clone_from(&completion.label.text);
 1460            for position in &mut mat.positions {
 1461                *position += completion.label.filter_range.start;
 1462            }
 1463        }
 1464        drop(completions);
 1465
 1466        self.matches = matches.into();
 1467        self.selected_item = 0;
 1468    }
 1469}
 1470
 1471#[derive(Clone)]
 1472struct AvailableCodeAction {
 1473    excerpt_id: ExcerptId,
 1474    action: CodeAction,
 1475    provider: Arc<dyn CodeActionProvider>,
 1476}
 1477
 1478#[derive(Clone)]
 1479struct CodeActionContents {
 1480    tasks: Option<Arc<ResolvedTasks>>,
 1481    actions: Option<Arc<[AvailableCodeAction]>>,
 1482}
 1483
 1484impl CodeActionContents {
 1485    fn len(&self) -> usize {
 1486        match (&self.tasks, &self.actions) {
 1487            (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
 1488            (Some(tasks), None) => tasks.templates.len(),
 1489            (None, Some(actions)) => actions.len(),
 1490            (None, None) => 0,
 1491        }
 1492    }
 1493
 1494    fn is_empty(&self) -> bool {
 1495        match (&self.tasks, &self.actions) {
 1496            (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
 1497            (Some(tasks), None) => tasks.templates.is_empty(),
 1498            (None, Some(actions)) => actions.is_empty(),
 1499            (None, None) => true,
 1500        }
 1501    }
 1502
 1503    fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
 1504        self.tasks
 1505            .iter()
 1506            .flat_map(|tasks| {
 1507                tasks
 1508                    .templates
 1509                    .iter()
 1510                    .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
 1511            })
 1512            .chain(self.actions.iter().flat_map(|actions| {
 1513                actions.iter().map(|available| CodeActionsItem::CodeAction {
 1514                    excerpt_id: available.excerpt_id,
 1515                    action: available.action.clone(),
 1516                    provider: available.provider.clone(),
 1517                })
 1518            }))
 1519    }
 1520    fn get(&self, index: usize) -> Option<CodeActionsItem> {
 1521        match (&self.tasks, &self.actions) {
 1522            (Some(tasks), Some(actions)) => {
 1523                if index < tasks.templates.len() {
 1524                    tasks
 1525                        .templates
 1526                        .get(index)
 1527                        .cloned()
 1528                        .map(|(kind, task)| CodeActionsItem::Task(kind, task))
 1529                } else {
 1530                    actions.get(index - tasks.templates.len()).map(|available| {
 1531                        CodeActionsItem::CodeAction {
 1532                            excerpt_id: available.excerpt_id,
 1533                            action: available.action.clone(),
 1534                            provider: available.provider.clone(),
 1535                        }
 1536                    })
 1537                }
 1538            }
 1539            (Some(tasks), None) => tasks
 1540                .templates
 1541                .get(index)
 1542                .cloned()
 1543                .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
 1544            (None, Some(actions)) => {
 1545                actions
 1546                    .get(index)
 1547                    .map(|available| CodeActionsItem::CodeAction {
 1548                        excerpt_id: available.excerpt_id,
 1549                        action: available.action.clone(),
 1550                        provider: available.provider.clone(),
 1551                    })
 1552            }
 1553            (None, None) => None,
 1554        }
 1555    }
 1556}
 1557
 1558#[allow(clippy::large_enum_variant)]
 1559#[derive(Clone)]
 1560enum CodeActionsItem {
 1561    Task(TaskSourceKind, ResolvedTask),
 1562    CodeAction {
 1563        excerpt_id: ExcerptId,
 1564        action: CodeAction,
 1565        provider: Arc<dyn CodeActionProvider>,
 1566    },
 1567}
 1568
 1569impl CodeActionsItem {
 1570    fn as_task(&self) -> Option<&ResolvedTask> {
 1571        let Self::Task(_, task) = self else {
 1572            return None;
 1573        };
 1574        Some(task)
 1575    }
 1576    fn as_code_action(&self) -> Option<&CodeAction> {
 1577        let Self::CodeAction { action, .. } = self else {
 1578            return None;
 1579        };
 1580        Some(action)
 1581    }
 1582    fn label(&self) -> String {
 1583        match self {
 1584            Self::CodeAction { action, .. } => action.lsp_action.title.clone(),
 1585            Self::Task(_, task) => task.resolved_label.clone(),
 1586        }
 1587    }
 1588}
 1589
 1590struct CodeActionsMenu {
 1591    actions: CodeActionContents,
 1592    buffer: Model<Buffer>,
 1593    selected_item: usize,
 1594    scroll_handle: UniformListScrollHandle,
 1595    deployed_from_indicator: Option<DisplayRow>,
 1596}
 1597
 1598impl CodeActionsMenu {
 1599    fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
 1600        self.selected_item = 0;
 1601        self.scroll_handle
 1602            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1603        cx.notify()
 1604    }
 1605
 1606    fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
 1607        if self.selected_item > 0 {
 1608            self.selected_item -= 1;
 1609        } else {
 1610            self.selected_item = self.actions.len() - 1;
 1611        }
 1612        self.scroll_handle
 1613            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1614        cx.notify();
 1615    }
 1616
 1617    fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
 1618        if self.selected_item + 1 < self.actions.len() {
 1619            self.selected_item += 1;
 1620        } else {
 1621            self.selected_item = 0;
 1622        }
 1623        self.scroll_handle
 1624            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1625        cx.notify();
 1626    }
 1627
 1628    fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
 1629        self.selected_item = self.actions.len() - 1;
 1630        self.scroll_handle
 1631            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1632        cx.notify()
 1633    }
 1634
 1635    fn visible(&self) -> bool {
 1636        !self.actions.is_empty()
 1637    }
 1638
 1639    fn render(
 1640        &self,
 1641        cursor_position: DisplayPoint,
 1642        _style: &EditorStyle,
 1643        max_height: Pixels,
 1644        cx: &mut ViewContext<Editor>,
 1645    ) -> (ContextMenuOrigin, AnyElement) {
 1646        let actions = self.actions.clone();
 1647        let selected_item = self.selected_item;
 1648        let element = uniform_list(
 1649            cx.view().clone(),
 1650            "code_actions_menu",
 1651            self.actions.len(),
 1652            move |_this, range, cx| {
 1653                actions
 1654                    .iter()
 1655                    .skip(range.start)
 1656                    .take(range.end - range.start)
 1657                    .enumerate()
 1658                    .map(|(ix, action)| {
 1659                        let item_ix = range.start + ix;
 1660                        let selected = selected_item == item_ix;
 1661                        let colors = cx.theme().colors();
 1662                        div()
 1663                            .px_1()
 1664                            .rounded_md()
 1665                            .text_color(colors.text)
 1666                            .when(selected, |style| {
 1667                                style
 1668                                    .bg(colors.element_active)
 1669                                    .text_color(colors.text_accent)
 1670                            })
 1671                            .hover(|style| {
 1672                                style
 1673                                    .bg(colors.element_hover)
 1674                                    .text_color(colors.text_accent)
 1675                            })
 1676                            .whitespace_nowrap()
 1677                            .when_some(action.as_code_action(), |this, action| {
 1678                                this.on_mouse_down(
 1679                                    MouseButton::Left,
 1680                                    cx.listener(move |editor, _, cx| {
 1681                                        cx.stop_propagation();
 1682                                        if let Some(task) = editor.confirm_code_action(
 1683                                            &ConfirmCodeAction {
 1684                                                item_ix: Some(item_ix),
 1685                                            },
 1686                                            cx,
 1687                                        ) {
 1688                                            task.detach_and_log_err(cx)
 1689                                        }
 1690                                    }),
 1691                                )
 1692                                // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
 1693                                .child(SharedString::from(action.lsp_action.title.clone()))
 1694                            })
 1695                            .when_some(action.as_task(), |this, task| {
 1696                                this.on_mouse_down(
 1697                                    MouseButton::Left,
 1698                                    cx.listener(move |editor, _, cx| {
 1699                                        cx.stop_propagation();
 1700                                        if let Some(task) = editor.confirm_code_action(
 1701                                            &ConfirmCodeAction {
 1702                                                item_ix: Some(item_ix),
 1703                                            },
 1704                                            cx,
 1705                                        ) {
 1706                                            task.detach_and_log_err(cx)
 1707                                        }
 1708                                    }),
 1709                                )
 1710                                .child(SharedString::from(task.resolved_label.clone()))
 1711                            })
 1712                    })
 1713                    .collect()
 1714            },
 1715        )
 1716        .elevation_1(cx)
 1717        .p_1()
 1718        .max_h(max_height)
 1719        .occlude()
 1720        .track_scroll(self.scroll_handle.clone())
 1721        .with_width_from_item(
 1722            self.actions
 1723                .iter()
 1724                .enumerate()
 1725                .max_by_key(|(_, action)| match action {
 1726                    CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
 1727                    CodeActionsItem::CodeAction { action, .. } => {
 1728                        action.lsp_action.title.chars().count()
 1729                    }
 1730                })
 1731                .map(|(ix, _)| ix),
 1732        )
 1733        .with_sizing_behavior(ListSizingBehavior::Infer)
 1734        .into_any_element();
 1735
 1736        let cursor_position = if let Some(row) = self.deployed_from_indicator {
 1737            ContextMenuOrigin::GutterIndicator(row)
 1738        } else {
 1739            ContextMenuOrigin::EditorPoint(cursor_position)
 1740        };
 1741
 1742        (cursor_position, element)
 1743    }
 1744}
 1745
 1746#[derive(Debug)]
 1747struct ActiveDiagnosticGroup {
 1748    primary_range: Range<Anchor>,
 1749    primary_message: String,
 1750    group_id: usize,
 1751    blocks: HashMap<CustomBlockId, Diagnostic>,
 1752    is_valid: bool,
 1753}
 1754
 1755#[derive(Serialize, Deserialize, Clone, Debug)]
 1756pub struct ClipboardSelection {
 1757    pub len: usize,
 1758    pub is_entire_line: bool,
 1759    pub first_line_indent: u32,
 1760}
 1761
 1762#[derive(Debug)]
 1763pub(crate) struct NavigationData {
 1764    cursor_anchor: Anchor,
 1765    cursor_position: Point,
 1766    scroll_anchor: ScrollAnchor,
 1767    scroll_top_row: u32,
 1768}
 1769
 1770#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1771pub enum GotoDefinitionKind {
 1772    Symbol,
 1773    Declaration,
 1774    Type,
 1775    Implementation,
 1776}
 1777
 1778#[derive(Debug, Clone)]
 1779enum InlayHintRefreshReason {
 1780    Toggle(bool),
 1781    SettingsChange(InlayHintSettings),
 1782    NewLinesShown,
 1783    BufferEdited(HashSet<Arc<Language>>),
 1784    RefreshRequested,
 1785    ExcerptsRemoved(Vec<ExcerptId>),
 1786}
 1787
 1788impl InlayHintRefreshReason {
 1789    fn description(&self) -> &'static str {
 1790        match self {
 1791            Self::Toggle(_) => "toggle",
 1792            Self::SettingsChange(_) => "settings change",
 1793            Self::NewLinesShown => "new lines shown",
 1794            Self::BufferEdited(_) => "buffer edited",
 1795            Self::RefreshRequested => "refresh requested",
 1796            Self::ExcerptsRemoved(_) => "excerpts removed",
 1797        }
 1798    }
 1799}
 1800
 1801pub(crate) struct FocusedBlock {
 1802    id: BlockId,
 1803    focus_handle: WeakFocusHandle,
 1804}
 1805
 1806#[derive(Clone)]
 1807struct JumpData {
 1808    excerpt_id: ExcerptId,
 1809    position: Point,
 1810    anchor: text::Anchor,
 1811    path: Option<project::ProjectPath>,
 1812    line_offset_from_top: u32,
 1813}
 1814
 1815impl Editor {
 1816    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
 1817        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1818        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1819        Self::new(
 1820            EditorMode::SingleLine { auto_width: false },
 1821            buffer,
 1822            None,
 1823            false,
 1824            cx,
 1825        )
 1826    }
 1827
 1828    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
 1829        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1830        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1831        Self::new(EditorMode::Full, buffer, None, false, cx)
 1832    }
 1833
 1834    pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
 1835        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1836        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1837        Self::new(
 1838            EditorMode::SingleLine { auto_width: true },
 1839            buffer,
 1840            None,
 1841            false,
 1842            cx,
 1843        )
 1844    }
 1845
 1846    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
 1847        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1848        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1849        Self::new(
 1850            EditorMode::AutoHeight { max_lines },
 1851            buffer,
 1852            None,
 1853            false,
 1854            cx,
 1855        )
 1856    }
 1857
 1858    pub fn for_buffer(
 1859        buffer: Model<Buffer>,
 1860        project: Option<Model<Project>>,
 1861        cx: &mut ViewContext<Self>,
 1862    ) -> Self {
 1863        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1864        Self::new(EditorMode::Full, buffer, project, false, cx)
 1865    }
 1866
 1867    pub fn for_multibuffer(
 1868        buffer: Model<MultiBuffer>,
 1869        project: Option<Model<Project>>,
 1870        show_excerpt_controls: bool,
 1871        cx: &mut ViewContext<Self>,
 1872    ) -> Self {
 1873        Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
 1874    }
 1875
 1876    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 1877        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1878        let mut clone = Self::new(
 1879            self.mode,
 1880            self.buffer.clone(),
 1881            self.project.clone(),
 1882            show_excerpt_controls,
 1883            cx,
 1884        );
 1885        self.display_map.update(cx, |display_map, cx| {
 1886            let snapshot = display_map.snapshot(cx);
 1887            clone.display_map.update(cx, |display_map, cx| {
 1888                display_map.set_state(&snapshot, cx);
 1889            });
 1890        });
 1891        clone.selections.clone_state(&self.selections);
 1892        clone.scroll_manager.clone_state(&self.scroll_manager);
 1893        clone.searchable = self.searchable;
 1894        clone
 1895    }
 1896
 1897    pub fn new(
 1898        mode: EditorMode,
 1899        buffer: Model<MultiBuffer>,
 1900        project: Option<Model<Project>>,
 1901        show_excerpt_controls: bool,
 1902        cx: &mut ViewContext<Self>,
 1903    ) -> Self {
 1904        let style = cx.text_style();
 1905        let font_size = style.font_size.to_pixels(cx.rem_size());
 1906        let editor = cx.view().downgrade();
 1907        let fold_placeholder = FoldPlaceholder {
 1908            constrain_width: true,
 1909            render: Arc::new(move |fold_id, fold_range, cx| {
 1910                let editor = editor.clone();
 1911                div()
 1912                    .id(fold_id)
 1913                    .bg(cx.theme().colors().ghost_element_background)
 1914                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1915                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1916                    .rounded_sm()
 1917                    .size_full()
 1918                    .cursor_pointer()
 1919                    .child("")
 1920                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 1921                    .on_click(move |_, cx| {
 1922                        editor
 1923                            .update(cx, |editor, cx| {
 1924                                editor.unfold_ranges(
 1925                                    &[fold_range.start..fold_range.end],
 1926                                    true,
 1927                                    false,
 1928                                    cx,
 1929                                );
 1930                                cx.stop_propagation();
 1931                            })
 1932                            .ok();
 1933                    })
 1934                    .into_any()
 1935            }),
 1936            merge_adjacent: true,
 1937            ..Default::default()
 1938        };
 1939        let display_map = cx.new_model(|cx| {
 1940            DisplayMap::new(
 1941                buffer.clone(),
 1942                style.font(),
 1943                font_size,
 1944                None,
 1945                show_excerpt_controls,
 1946                FILE_HEADER_HEIGHT,
 1947                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1948                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1949                fold_placeholder,
 1950                cx,
 1951            )
 1952        });
 1953
 1954        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1955
 1956        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1957
 1958        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1959            .then(|| language_settings::SoftWrap::None);
 1960
 1961        let mut project_subscriptions = Vec::new();
 1962        if mode == EditorMode::Full {
 1963            if let Some(project) = project.as_ref() {
 1964                if buffer.read(cx).is_singleton() {
 1965                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
 1966                        cx.emit(EditorEvent::TitleChanged);
 1967                    }));
 1968                }
 1969                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
 1970                    if let project::Event::RefreshInlayHints = event {
 1971                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1972                    } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1973                        if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1974                            let focus_handle = editor.focus_handle(cx);
 1975                            if focus_handle.is_focused(cx) {
 1976                                let snapshot = buffer.read(cx).snapshot();
 1977                                for (range, snippet) in snippet_edits {
 1978                                    let editor_range =
 1979                                        language::range_from_lsp(*range).to_offset(&snapshot);
 1980                                    editor
 1981                                        .insert_snippet(&[editor_range], snippet.clone(), cx)
 1982                                        .ok();
 1983                                }
 1984                            }
 1985                        }
 1986                    }
 1987                }));
 1988                if let Some(task_inventory) = project
 1989                    .read(cx)
 1990                    .task_store()
 1991                    .read(cx)
 1992                    .task_inventory()
 1993                    .cloned()
 1994                {
 1995                    project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
 1996                        editor.tasks_update_task = Some(editor.refresh_runnables(cx));
 1997                    }));
 1998                }
 1999            }
 2000        }
 2001
 2002        let inlay_hint_settings = inlay_hint_settings(
 2003            selections.newest_anchor().head(),
 2004            &buffer.read(cx).snapshot(cx),
 2005            cx,
 2006        );
 2007        let focus_handle = cx.focus_handle();
 2008        cx.on_focus(&focus_handle, Self::handle_focus).detach();
 2009        cx.on_focus_in(&focus_handle, Self::handle_focus_in)
 2010            .detach();
 2011        cx.on_focus_out(&focus_handle, Self::handle_focus_out)
 2012            .detach();
 2013        cx.on_blur(&focus_handle, Self::handle_blur).detach();
 2014
 2015        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 2016            Some(false)
 2017        } else {
 2018            None
 2019        };
 2020
 2021        let mut code_action_providers = Vec::new();
 2022        if let Some(project) = project.clone() {
 2023            code_action_providers.push(Arc::new(project) as Arc<_>);
 2024        }
 2025
 2026        let mut this = Self {
 2027            focus_handle,
 2028            show_cursor_when_unfocused: false,
 2029            last_focused_descendant: None,
 2030            buffer: buffer.clone(),
 2031            display_map: display_map.clone(),
 2032            selections,
 2033            scroll_manager: ScrollManager::new(cx),
 2034            columnar_selection_tail: None,
 2035            add_selections_state: None,
 2036            select_next_state: None,
 2037            select_prev_state: None,
 2038            selection_history: Default::default(),
 2039            autoclose_regions: Default::default(),
 2040            snippet_stack: Default::default(),
 2041            select_larger_syntax_node_stack: Vec::new(),
 2042            ime_transaction: Default::default(),
 2043            active_diagnostics: None,
 2044            soft_wrap_mode_override,
 2045            completion_provider: project.clone().map(|project| Box::new(project) as _),
 2046            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 2047            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 2048            project,
 2049            blink_manager: blink_manager.clone(),
 2050            show_local_selections: true,
 2051            mode,
 2052            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 2053            show_gutter: mode == EditorMode::Full,
 2054            show_line_numbers: None,
 2055            use_relative_line_numbers: None,
 2056            show_git_diff_gutter: None,
 2057            show_code_actions: None,
 2058            show_runnables: None,
 2059            show_wrap_guides: None,
 2060            show_indent_guides,
 2061            placeholder_text: None,
 2062            highlight_order: 0,
 2063            highlighted_rows: HashMap::default(),
 2064            background_highlights: Default::default(),
 2065            gutter_highlights: TreeMap::default(),
 2066            scrollbar_marker_state: ScrollbarMarkerState::default(),
 2067            active_indent_guides_state: ActiveIndentGuidesState::default(),
 2068            nav_history: None,
 2069            context_menu: RwLock::new(None),
 2070            mouse_context_menu: None,
 2071            hunk_controls_menu_handle: PopoverMenuHandle::default(),
 2072            completion_tasks: Default::default(),
 2073            signature_help_state: SignatureHelpState::default(),
 2074            auto_signature_help: None,
 2075            find_all_references_task_sources: Vec::new(),
 2076            next_completion_id: 0,
 2077            next_inlay_id: 0,
 2078            code_action_providers,
 2079            available_code_actions: Default::default(),
 2080            code_actions_task: Default::default(),
 2081            document_highlights_task: Default::default(),
 2082            linked_editing_range_task: Default::default(),
 2083            pending_rename: Default::default(),
 2084            searchable: true,
 2085            cursor_shape: EditorSettings::get_global(cx)
 2086                .cursor_shape
 2087                .unwrap_or_default(),
 2088            current_line_highlight: None,
 2089            autoindent_mode: Some(AutoindentMode::EachLine),
 2090            collapse_matches: false,
 2091            workspace: None,
 2092            input_enabled: true,
 2093            use_modal_editing: mode == EditorMode::Full,
 2094            read_only: false,
 2095            use_autoclose: true,
 2096            use_auto_surround: true,
 2097            auto_replace_emoji_shortcode: false,
 2098            leader_peer_id: None,
 2099            remote_id: None,
 2100            hover_state: Default::default(),
 2101            hovered_link_state: Default::default(),
 2102            inline_completion_provider: None,
 2103            active_inline_completion: None,
 2104            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 2105            expanded_hunks: ExpandedHunks::default(),
 2106            gutter_hovered: false,
 2107            pixel_position_of_newest_cursor: None,
 2108            last_bounds: None,
 2109            expect_bounds_change: None,
 2110            gutter_dimensions: GutterDimensions::default(),
 2111            style: None,
 2112            show_cursor_names: false,
 2113            hovered_cursors: Default::default(),
 2114            next_editor_action_id: EditorActionId::default(),
 2115            editor_actions: Rc::default(),
 2116            show_inline_completions_override: None,
 2117            enable_inline_completions: true,
 2118            custom_context_menu: None,
 2119            show_git_blame_gutter: false,
 2120            show_git_blame_inline: false,
 2121            show_selection_menu: None,
 2122            show_git_blame_inline_delay_task: None,
 2123            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 2124            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 2125                .session
 2126                .restore_unsaved_buffers,
 2127            blame: None,
 2128            blame_subscription: None,
 2129            tasks: Default::default(),
 2130            _subscriptions: vec![
 2131                cx.observe(&buffer, Self::on_buffer_changed),
 2132                cx.subscribe(&buffer, Self::on_buffer_event),
 2133                cx.observe(&display_map, Self::on_display_map_changed),
 2134                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 2135                cx.observe_global::<SettingsStore>(Self::settings_changed),
 2136                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 2137                cx.observe_window_activation(|editor, cx| {
 2138                    let active = cx.is_window_active();
 2139                    editor.blink_manager.update(cx, |blink_manager, cx| {
 2140                        if active {
 2141                            blink_manager.enable(cx);
 2142                        } else {
 2143                            blink_manager.disable(cx);
 2144                        }
 2145                    });
 2146                }),
 2147            ],
 2148            tasks_update_task: None,
 2149            linked_edit_ranges: Default::default(),
 2150            previous_search_ranges: None,
 2151            breadcrumb_header: None,
 2152            focused_block: None,
 2153            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 2154            addons: HashMap::default(),
 2155            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 2156            text_style_refinement: None,
 2157        };
 2158        this.tasks_update_task = Some(this.refresh_runnables(cx));
 2159        this._subscriptions.extend(project_subscriptions);
 2160
 2161        this.end_selection(cx);
 2162        this.scroll_manager.show_scrollbar(cx);
 2163
 2164        if mode == EditorMode::Full {
 2165            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 2166            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 2167
 2168            if this.git_blame_inline_enabled {
 2169                this.git_blame_inline_enabled = true;
 2170                this.start_git_blame_inline(false, cx);
 2171            }
 2172        }
 2173
 2174        this.report_editor_event("open", None, cx);
 2175        this
 2176    }
 2177
 2178    pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
 2179        self.mouse_context_menu
 2180            .as_ref()
 2181            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
 2182    }
 2183
 2184    fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
 2185        let mut key_context = KeyContext::new_with_defaults();
 2186        key_context.add("Editor");
 2187        let mode = match self.mode {
 2188            EditorMode::SingleLine { .. } => "single_line",
 2189            EditorMode::AutoHeight { .. } => "auto_height",
 2190            EditorMode::Full => "full",
 2191        };
 2192
 2193        if EditorSettings::jupyter_enabled(cx) {
 2194            key_context.add("jupyter");
 2195        }
 2196
 2197        key_context.set("mode", mode);
 2198        if self.pending_rename.is_some() {
 2199            key_context.add("renaming");
 2200        }
 2201        if self.context_menu_visible() {
 2202            match self.context_menu.read().as_ref() {
 2203                Some(ContextMenu::Completions(_)) => {
 2204                    key_context.add("menu");
 2205                    key_context.add("showing_completions")
 2206                }
 2207                Some(ContextMenu::CodeActions(_)) => {
 2208                    key_context.add("menu");
 2209                    key_context.add("showing_code_actions")
 2210                }
 2211                None => {}
 2212            }
 2213        }
 2214
 2215        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 2216        if !self.focus_handle(cx).contains_focused(cx)
 2217            || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
 2218        {
 2219            for addon in self.addons.values() {
 2220                addon.extend_key_context(&mut key_context, cx)
 2221            }
 2222        }
 2223
 2224        if let Some(extension) = self
 2225            .buffer
 2226            .read(cx)
 2227            .as_singleton()
 2228            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 2229        {
 2230            key_context.set("extension", extension.to_string());
 2231        }
 2232
 2233        if self.has_active_inline_completion(cx) {
 2234            key_context.add("copilot_suggestion");
 2235            key_context.add("inline_completion");
 2236        }
 2237
 2238        key_context
 2239    }
 2240
 2241    pub fn new_file(
 2242        workspace: &mut Workspace,
 2243        _: &workspace::NewFile,
 2244        cx: &mut ViewContext<Workspace>,
 2245    ) {
 2246        Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
 2247            "Failed to create buffer",
 2248            cx,
 2249            |e, _| match e.error_code() {
 2250                ErrorCode::RemoteUpgradeRequired => Some(format!(
 2251                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2252                e.error_tag("required").unwrap_or("the latest version")
 2253            )),
 2254                _ => None,
 2255            },
 2256        );
 2257    }
 2258
 2259    pub fn new_in_workspace(
 2260        workspace: &mut Workspace,
 2261        cx: &mut ViewContext<Workspace>,
 2262    ) -> Task<Result<View<Editor>>> {
 2263        let project = workspace.project().clone();
 2264        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2265
 2266        cx.spawn(|workspace, mut cx| async move {
 2267            let buffer = create.await?;
 2268            workspace.update(&mut cx, |workspace, cx| {
 2269                let editor =
 2270                    cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
 2271                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 2272                editor
 2273            })
 2274        })
 2275    }
 2276
 2277    fn new_file_vertical(
 2278        workspace: &mut Workspace,
 2279        _: &workspace::NewFileSplitVertical,
 2280        cx: &mut ViewContext<Workspace>,
 2281    ) {
 2282        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
 2283    }
 2284
 2285    fn new_file_horizontal(
 2286        workspace: &mut Workspace,
 2287        _: &workspace::NewFileSplitHorizontal,
 2288        cx: &mut ViewContext<Workspace>,
 2289    ) {
 2290        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
 2291    }
 2292
 2293    fn new_file_in_direction(
 2294        workspace: &mut Workspace,
 2295        direction: SplitDirection,
 2296        cx: &mut ViewContext<Workspace>,
 2297    ) {
 2298        let project = workspace.project().clone();
 2299        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2300
 2301        cx.spawn(|workspace, mut cx| async move {
 2302            let buffer = create.await?;
 2303            workspace.update(&mut cx, move |workspace, cx| {
 2304                workspace.split_item(
 2305                    direction,
 2306                    Box::new(
 2307                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 2308                    ),
 2309                    cx,
 2310                )
 2311            })?;
 2312            anyhow::Ok(())
 2313        })
 2314        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 2315            ErrorCode::RemoteUpgradeRequired => Some(format!(
 2316                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2317                e.error_tag("required").unwrap_or("the latest version")
 2318            )),
 2319            _ => None,
 2320        });
 2321    }
 2322
 2323    pub fn leader_peer_id(&self) -> Option<PeerId> {
 2324        self.leader_peer_id
 2325    }
 2326
 2327    pub fn buffer(&self) -> &Model<MultiBuffer> {
 2328        &self.buffer
 2329    }
 2330
 2331    pub fn workspace(&self) -> Option<View<Workspace>> {
 2332        self.workspace.as_ref()?.0.upgrade()
 2333    }
 2334
 2335    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
 2336        self.buffer().read(cx).title(cx)
 2337    }
 2338
 2339    pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
 2340        let git_blame_gutter_max_author_length = self
 2341            .render_git_blame_gutter(cx)
 2342            .then(|| {
 2343                if let Some(blame) = self.blame.as_ref() {
 2344                    let max_author_length =
 2345                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 2346                    Some(max_author_length)
 2347                } else {
 2348                    None
 2349                }
 2350            })
 2351            .flatten();
 2352
 2353        EditorSnapshot {
 2354            mode: self.mode,
 2355            show_gutter: self.show_gutter,
 2356            show_line_numbers: self.show_line_numbers,
 2357            show_git_diff_gutter: self.show_git_diff_gutter,
 2358            show_code_actions: self.show_code_actions,
 2359            show_runnables: self.show_runnables,
 2360            git_blame_gutter_max_author_length,
 2361            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 2362            scroll_anchor: self.scroll_manager.anchor(),
 2363            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 2364            placeholder_text: self.placeholder_text.clone(),
 2365            is_focused: self.focus_handle.is_focused(cx),
 2366            current_line_highlight: self
 2367                .current_line_highlight
 2368                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 2369            gutter_hovered: self.gutter_hovered,
 2370        }
 2371    }
 2372
 2373    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
 2374        self.buffer.read(cx).language_at(point, cx)
 2375    }
 2376
 2377    pub fn file_at<T: ToOffset>(
 2378        &self,
 2379        point: T,
 2380        cx: &AppContext,
 2381    ) -> Option<Arc<dyn language::File>> {
 2382        self.buffer.read(cx).read(cx).file_at(point).cloned()
 2383    }
 2384
 2385    pub fn active_excerpt(
 2386        &self,
 2387        cx: &AppContext,
 2388    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
 2389        self.buffer
 2390            .read(cx)
 2391            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 2392    }
 2393
 2394    pub fn mode(&self) -> EditorMode {
 2395        self.mode
 2396    }
 2397
 2398    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 2399        self.collaboration_hub.as_deref()
 2400    }
 2401
 2402    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 2403        self.collaboration_hub = Some(hub);
 2404    }
 2405
 2406    pub fn set_custom_context_menu(
 2407        &mut self,
 2408        f: impl 'static
 2409            + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
 2410    ) {
 2411        self.custom_context_menu = Some(Box::new(f))
 2412    }
 2413
 2414    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 2415        self.completion_provider = provider;
 2416    }
 2417
 2418    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 2419        self.semantics_provider.clone()
 2420    }
 2421
 2422    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 2423        self.semantics_provider = provider;
 2424    }
 2425
 2426    pub fn set_inline_completion_provider<T>(
 2427        &mut self,
 2428        provider: Option<Model<T>>,
 2429        cx: &mut ViewContext<Self>,
 2430    ) where
 2431        T: InlineCompletionProvider,
 2432    {
 2433        self.inline_completion_provider =
 2434            provider.map(|provider| RegisteredInlineCompletionProvider {
 2435                _subscription: cx.observe(&provider, |this, _, cx| {
 2436                    if this.focus_handle.is_focused(cx) {
 2437                        this.update_visible_inline_completion(cx);
 2438                    }
 2439                }),
 2440                provider: Arc::new(provider),
 2441            });
 2442        self.refresh_inline_completion(false, false, cx);
 2443    }
 2444
 2445    pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
 2446        self.placeholder_text.as_deref()
 2447    }
 2448
 2449    pub fn set_placeholder_text(
 2450        &mut self,
 2451        placeholder_text: impl Into<Arc<str>>,
 2452        cx: &mut ViewContext<Self>,
 2453    ) {
 2454        let placeholder_text = Some(placeholder_text.into());
 2455        if self.placeholder_text != placeholder_text {
 2456            self.placeholder_text = placeholder_text;
 2457            cx.notify();
 2458        }
 2459    }
 2460
 2461    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
 2462        self.cursor_shape = cursor_shape;
 2463
 2464        // Disrupt blink for immediate user feedback that the cursor shape has changed
 2465        self.blink_manager.update(cx, BlinkManager::show_cursor);
 2466
 2467        cx.notify();
 2468    }
 2469
 2470    pub fn set_current_line_highlight(
 2471        &mut self,
 2472        current_line_highlight: Option<CurrentLineHighlight>,
 2473    ) {
 2474        self.current_line_highlight = current_line_highlight;
 2475    }
 2476
 2477    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 2478        self.collapse_matches = collapse_matches;
 2479    }
 2480
 2481    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 2482        if self.collapse_matches {
 2483            return range.start..range.start;
 2484        }
 2485        range.clone()
 2486    }
 2487
 2488    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
 2489        if self.display_map.read(cx).clip_at_line_ends != clip {
 2490            self.display_map
 2491                .update(cx, |map, _| map.clip_at_line_ends = clip);
 2492        }
 2493    }
 2494
 2495    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 2496        self.input_enabled = input_enabled;
 2497    }
 2498
 2499    pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
 2500        self.enable_inline_completions = enabled;
 2501    }
 2502
 2503    pub fn set_autoindent(&mut self, autoindent: bool) {
 2504        if autoindent {
 2505            self.autoindent_mode = Some(AutoindentMode::EachLine);
 2506        } else {
 2507            self.autoindent_mode = None;
 2508        }
 2509    }
 2510
 2511    pub fn read_only(&self, cx: &AppContext) -> bool {
 2512        self.read_only || self.buffer.read(cx).read_only()
 2513    }
 2514
 2515    pub fn set_read_only(&mut self, read_only: bool) {
 2516        self.read_only = read_only;
 2517    }
 2518
 2519    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 2520        self.use_autoclose = autoclose;
 2521    }
 2522
 2523    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 2524        self.use_auto_surround = auto_surround;
 2525    }
 2526
 2527    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 2528        self.auto_replace_emoji_shortcode = auto_replace;
 2529    }
 2530
 2531    pub fn toggle_inline_completions(
 2532        &mut self,
 2533        _: &ToggleInlineCompletions,
 2534        cx: &mut ViewContext<Self>,
 2535    ) {
 2536        if self.show_inline_completions_override.is_some() {
 2537            self.set_show_inline_completions(None, cx);
 2538        } else {
 2539            let cursor = self.selections.newest_anchor().head();
 2540            if let Some((buffer, cursor_buffer_position)) =
 2541                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 2542            {
 2543                let show_inline_completions =
 2544                    !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
 2545                self.set_show_inline_completions(Some(show_inline_completions), cx);
 2546            }
 2547        }
 2548    }
 2549
 2550    pub fn set_show_inline_completions(
 2551        &mut self,
 2552        show_inline_completions: Option<bool>,
 2553        cx: &mut ViewContext<Self>,
 2554    ) {
 2555        self.show_inline_completions_override = show_inline_completions;
 2556        self.refresh_inline_completion(false, true, cx);
 2557    }
 2558
 2559    fn should_show_inline_completions(
 2560        &self,
 2561        buffer: &Model<Buffer>,
 2562        buffer_position: language::Anchor,
 2563        cx: &AppContext,
 2564    ) -> bool {
 2565        if !self.snippet_stack.is_empty() {
 2566            return false;
 2567        }
 2568
 2569        if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
 2570            return false;
 2571        }
 2572
 2573        if let Some(provider) = self.inline_completion_provider() {
 2574            if let Some(show_inline_completions) = self.show_inline_completions_override {
 2575                show_inline_completions
 2576            } else {
 2577                self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
 2578            }
 2579        } else {
 2580            false
 2581        }
 2582    }
 2583
 2584    fn inline_completions_disabled_in_scope(
 2585        &self,
 2586        buffer: &Model<Buffer>,
 2587        buffer_position: language::Anchor,
 2588        cx: &AppContext,
 2589    ) -> bool {
 2590        let snapshot = buffer.read(cx).snapshot();
 2591        let settings = snapshot.settings_at(buffer_position, cx);
 2592
 2593        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 2594            return false;
 2595        };
 2596
 2597        scope.override_name().map_or(false, |scope_name| {
 2598            settings
 2599                .inline_completions_disabled_in
 2600                .iter()
 2601                .any(|s| s == scope_name)
 2602        })
 2603    }
 2604
 2605    pub fn set_use_modal_editing(&mut self, to: bool) {
 2606        self.use_modal_editing = to;
 2607    }
 2608
 2609    pub fn use_modal_editing(&self) -> bool {
 2610        self.use_modal_editing
 2611    }
 2612
 2613    fn selections_did_change(
 2614        &mut self,
 2615        local: bool,
 2616        old_cursor_position: &Anchor,
 2617        show_completions: bool,
 2618        cx: &mut ViewContext<Self>,
 2619    ) {
 2620        cx.invalidate_character_coordinates();
 2621
 2622        // Copy selections to primary selection buffer
 2623        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 2624        if local {
 2625            let selections = self.selections.all::<usize>(cx);
 2626            let buffer_handle = self.buffer.read(cx).read(cx);
 2627
 2628            let mut text = String::new();
 2629            for (index, selection) in selections.iter().enumerate() {
 2630                let text_for_selection = buffer_handle
 2631                    .text_for_range(selection.start..selection.end)
 2632                    .collect::<String>();
 2633
 2634                text.push_str(&text_for_selection);
 2635                if index != selections.len() - 1 {
 2636                    text.push('\n');
 2637                }
 2638            }
 2639
 2640            if !text.is_empty() {
 2641                cx.write_to_primary(ClipboardItem::new_string(text));
 2642            }
 2643        }
 2644
 2645        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
 2646            self.buffer.update(cx, |buffer, cx| {
 2647                buffer.set_active_selections(
 2648                    &self.selections.disjoint_anchors(),
 2649                    self.selections.line_mode,
 2650                    self.cursor_shape,
 2651                    cx,
 2652                )
 2653            });
 2654        }
 2655        let display_map = self
 2656            .display_map
 2657            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2658        let buffer = &display_map.buffer_snapshot;
 2659        self.add_selections_state = None;
 2660        self.select_next_state = None;
 2661        self.select_prev_state = None;
 2662        self.select_larger_syntax_node_stack.clear();
 2663        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2664        self.snippet_stack
 2665            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2666        self.take_rename(false, cx);
 2667
 2668        let new_cursor_position = self.selections.newest_anchor().head();
 2669
 2670        self.push_to_nav_history(
 2671            *old_cursor_position,
 2672            Some(new_cursor_position.to_point(buffer)),
 2673            cx,
 2674        );
 2675
 2676        if local {
 2677            let new_cursor_position = self.selections.newest_anchor().head();
 2678            let mut context_menu = self.context_menu.write();
 2679            let completion_menu = match context_menu.as_ref() {
 2680                Some(ContextMenu::Completions(menu)) => Some(menu),
 2681
 2682                _ => {
 2683                    *context_menu = None;
 2684                    None
 2685                }
 2686            };
 2687
 2688            if let Some(completion_menu) = completion_menu {
 2689                let cursor_position = new_cursor_position.to_offset(buffer);
 2690                let (word_range, kind) =
 2691                    buffer.surrounding_word(completion_menu.initial_position, true);
 2692                if kind == Some(CharKind::Word)
 2693                    && word_range.to_inclusive().contains(&cursor_position)
 2694                {
 2695                    let mut completion_menu = completion_menu.clone();
 2696                    drop(context_menu);
 2697
 2698                    let query = Self::completion_query(buffer, cursor_position);
 2699                    cx.spawn(move |this, mut cx| async move {
 2700                        completion_menu
 2701                            .filter(query.as_deref(), cx.background_executor().clone())
 2702                            .await;
 2703
 2704                        this.update(&mut cx, |this, cx| {
 2705                            let mut context_menu = this.context_menu.write();
 2706                            let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
 2707                                return;
 2708                            };
 2709
 2710                            if menu.id > completion_menu.id {
 2711                                return;
 2712                            }
 2713
 2714                            *context_menu = Some(ContextMenu::Completions(completion_menu));
 2715                            drop(context_menu);
 2716                            cx.notify();
 2717                        })
 2718                    })
 2719                    .detach();
 2720
 2721                    if show_completions {
 2722                        self.show_completions(&ShowCompletions { trigger: None }, cx);
 2723                    }
 2724                } else {
 2725                    drop(context_menu);
 2726                    self.hide_context_menu(cx);
 2727                }
 2728            } else {
 2729                drop(context_menu);
 2730            }
 2731
 2732            hide_hover(self, cx);
 2733
 2734            if old_cursor_position.to_display_point(&display_map).row()
 2735                != new_cursor_position.to_display_point(&display_map).row()
 2736            {
 2737                self.available_code_actions.take();
 2738            }
 2739            self.refresh_code_actions(cx);
 2740            self.refresh_document_highlights(cx);
 2741            refresh_matching_bracket_highlights(self, cx);
 2742            self.discard_inline_completion(false, cx);
 2743            linked_editing_ranges::refresh_linked_ranges(self, cx);
 2744            if self.git_blame_inline_enabled {
 2745                self.start_inline_blame_timer(cx);
 2746            }
 2747        }
 2748
 2749        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2750        cx.emit(EditorEvent::SelectionsChanged { local });
 2751
 2752        if self.selections.disjoint_anchors().len() == 1 {
 2753            cx.emit(SearchEvent::ActiveMatchChanged)
 2754        }
 2755        cx.notify();
 2756    }
 2757
 2758    pub fn change_selections<R>(
 2759        &mut self,
 2760        autoscroll: Option<Autoscroll>,
 2761        cx: &mut ViewContext<Self>,
 2762        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2763    ) -> R {
 2764        self.change_selections_inner(autoscroll, true, cx, change)
 2765    }
 2766
 2767    pub fn change_selections_inner<R>(
 2768        &mut self,
 2769        autoscroll: Option<Autoscroll>,
 2770        request_completions: bool,
 2771        cx: &mut ViewContext<Self>,
 2772        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2773    ) -> R {
 2774        let old_cursor_position = self.selections.newest_anchor().head();
 2775        self.push_to_selection_history();
 2776
 2777        let (changed, result) = self.selections.change_with(cx, change);
 2778
 2779        if changed {
 2780            if let Some(autoscroll) = autoscroll {
 2781                self.request_autoscroll(autoscroll, cx);
 2782            }
 2783            self.selections_did_change(true, &old_cursor_position, request_completions, cx);
 2784
 2785            if self.should_open_signature_help_automatically(
 2786                &old_cursor_position,
 2787                self.signature_help_state.backspace_pressed(),
 2788                cx,
 2789            ) {
 2790                self.show_signature_help(&ShowSignatureHelp, cx);
 2791            }
 2792            self.signature_help_state.set_backspace_pressed(false);
 2793        }
 2794
 2795        result
 2796    }
 2797
 2798    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2799    where
 2800        I: IntoIterator<Item = (Range<S>, T)>,
 2801        S: ToOffset,
 2802        T: Into<Arc<str>>,
 2803    {
 2804        if self.read_only(cx) {
 2805            return;
 2806        }
 2807
 2808        self.buffer
 2809            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2810    }
 2811
 2812    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2813    where
 2814        I: IntoIterator<Item = (Range<S>, T)>,
 2815        S: ToOffset,
 2816        T: Into<Arc<str>>,
 2817    {
 2818        if self.read_only(cx) {
 2819            return;
 2820        }
 2821
 2822        self.buffer.update(cx, |buffer, cx| {
 2823            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2824        });
 2825    }
 2826
 2827    pub fn edit_with_block_indent<I, S, T>(
 2828        &mut self,
 2829        edits: I,
 2830        original_indent_columns: Vec<u32>,
 2831        cx: &mut ViewContext<Self>,
 2832    ) where
 2833        I: IntoIterator<Item = (Range<S>, T)>,
 2834        S: ToOffset,
 2835        T: Into<Arc<str>>,
 2836    {
 2837        if self.read_only(cx) {
 2838            return;
 2839        }
 2840
 2841        self.buffer.update(cx, |buffer, cx| {
 2842            buffer.edit(
 2843                edits,
 2844                Some(AutoindentMode::Block {
 2845                    original_indent_columns,
 2846                }),
 2847                cx,
 2848            )
 2849        });
 2850    }
 2851
 2852    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
 2853        self.hide_context_menu(cx);
 2854
 2855        match phase {
 2856            SelectPhase::Begin {
 2857                position,
 2858                add,
 2859                click_count,
 2860            } => self.begin_selection(position, add, click_count, cx),
 2861            SelectPhase::BeginColumnar {
 2862                position,
 2863                goal_column,
 2864                reset,
 2865            } => self.begin_columnar_selection(position, goal_column, reset, cx),
 2866            SelectPhase::Extend {
 2867                position,
 2868                click_count,
 2869            } => self.extend_selection(position, click_count, cx),
 2870            SelectPhase::Update {
 2871                position,
 2872                goal_column,
 2873                scroll_delta,
 2874            } => self.update_selection(position, goal_column, scroll_delta, cx),
 2875            SelectPhase::End => self.end_selection(cx),
 2876        }
 2877    }
 2878
 2879    fn extend_selection(
 2880        &mut self,
 2881        position: DisplayPoint,
 2882        click_count: usize,
 2883        cx: &mut ViewContext<Self>,
 2884    ) {
 2885        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2886        let tail = self.selections.newest::<usize>(cx).tail();
 2887        self.begin_selection(position, false, click_count, cx);
 2888
 2889        let position = position.to_offset(&display_map, Bias::Left);
 2890        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2891
 2892        let mut pending_selection = self
 2893            .selections
 2894            .pending_anchor()
 2895            .expect("extend_selection not called with pending selection");
 2896        if position >= tail {
 2897            pending_selection.start = tail_anchor;
 2898        } else {
 2899            pending_selection.end = tail_anchor;
 2900            pending_selection.reversed = true;
 2901        }
 2902
 2903        let mut pending_mode = self.selections.pending_mode().unwrap();
 2904        match &mut pending_mode {
 2905            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2906            _ => {}
 2907        }
 2908
 2909        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 2910            s.set_pending(pending_selection, pending_mode)
 2911        });
 2912    }
 2913
 2914    fn begin_selection(
 2915        &mut self,
 2916        position: DisplayPoint,
 2917        add: bool,
 2918        click_count: usize,
 2919        cx: &mut ViewContext<Self>,
 2920    ) {
 2921        if !self.focus_handle.is_focused(cx) {
 2922            self.last_focused_descendant = None;
 2923            cx.focus(&self.focus_handle);
 2924        }
 2925
 2926        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2927        let buffer = &display_map.buffer_snapshot;
 2928        let newest_selection = self.selections.newest_anchor().clone();
 2929        let position = display_map.clip_point(position, Bias::Left);
 2930
 2931        let start;
 2932        let end;
 2933        let mode;
 2934        let mut auto_scroll;
 2935        match click_count {
 2936            1 => {
 2937                start = buffer.anchor_before(position.to_point(&display_map));
 2938                end = start;
 2939                mode = SelectMode::Character;
 2940                auto_scroll = true;
 2941            }
 2942            2 => {
 2943                let range = movement::surrounding_word(&display_map, position);
 2944                start = buffer.anchor_before(range.start.to_point(&display_map));
 2945                end = buffer.anchor_before(range.end.to_point(&display_map));
 2946                mode = SelectMode::Word(start..end);
 2947                auto_scroll = true;
 2948            }
 2949            3 => {
 2950                let position = display_map
 2951                    .clip_point(position, Bias::Left)
 2952                    .to_point(&display_map);
 2953                let line_start = display_map.prev_line_boundary(position).0;
 2954                let next_line_start = buffer.clip_point(
 2955                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2956                    Bias::Left,
 2957                );
 2958                start = buffer.anchor_before(line_start);
 2959                end = buffer.anchor_before(next_line_start);
 2960                mode = SelectMode::Line(start..end);
 2961                auto_scroll = true;
 2962            }
 2963            _ => {
 2964                start = buffer.anchor_before(0);
 2965                end = buffer.anchor_before(buffer.len());
 2966                mode = SelectMode::All;
 2967                auto_scroll = false;
 2968            }
 2969        }
 2970        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2971
 2972        let point_to_delete: Option<usize> = {
 2973            let selected_points: Vec<Selection<Point>> =
 2974                self.selections.disjoint_in_range(start..end, cx);
 2975
 2976            if !add || click_count > 1 {
 2977                None
 2978            } else if !selected_points.is_empty() {
 2979                Some(selected_points[0].id)
 2980            } else {
 2981                let clicked_point_already_selected =
 2982                    self.selections.disjoint.iter().find(|selection| {
 2983                        selection.start.to_point(buffer) == start.to_point(buffer)
 2984                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2985                    });
 2986
 2987                clicked_point_already_selected.map(|selection| selection.id)
 2988            }
 2989        };
 2990
 2991        let selections_count = self.selections.count();
 2992
 2993        self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
 2994            if let Some(point_to_delete) = point_to_delete {
 2995                s.delete(point_to_delete);
 2996
 2997                if selections_count == 1 {
 2998                    s.set_pending_anchor_range(start..end, mode);
 2999                }
 3000            } else {
 3001                if !add {
 3002                    s.clear_disjoint();
 3003                } else if click_count > 1 {
 3004                    s.delete(newest_selection.id)
 3005                }
 3006
 3007                s.set_pending_anchor_range(start..end, mode);
 3008            }
 3009        });
 3010    }
 3011
 3012    fn begin_columnar_selection(
 3013        &mut self,
 3014        position: DisplayPoint,
 3015        goal_column: u32,
 3016        reset: bool,
 3017        cx: &mut ViewContext<Self>,
 3018    ) {
 3019        if !self.focus_handle.is_focused(cx) {
 3020            self.last_focused_descendant = None;
 3021            cx.focus(&self.focus_handle);
 3022        }
 3023
 3024        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 3025
 3026        if reset {
 3027            let pointer_position = display_map
 3028                .buffer_snapshot
 3029                .anchor_before(position.to_point(&display_map));
 3030
 3031            self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 3032                s.clear_disjoint();
 3033                s.set_pending_anchor_range(
 3034                    pointer_position..pointer_position,
 3035                    SelectMode::Character,
 3036                );
 3037            });
 3038        }
 3039
 3040        let tail = self.selections.newest::<Point>(cx).tail();
 3041        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 3042
 3043        if !reset {
 3044            self.select_columns(
 3045                tail.to_display_point(&display_map),
 3046                position,
 3047                goal_column,
 3048                &display_map,
 3049                cx,
 3050            );
 3051        }
 3052    }
 3053
 3054    fn update_selection(
 3055        &mut self,
 3056        position: DisplayPoint,
 3057        goal_column: u32,
 3058        scroll_delta: gpui::Point<f32>,
 3059        cx: &mut ViewContext<Self>,
 3060    ) {
 3061        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 3062
 3063        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 3064            let tail = tail.to_display_point(&display_map);
 3065            self.select_columns(tail, position, goal_column, &display_map, cx);
 3066        } else if let Some(mut pending) = self.selections.pending_anchor() {
 3067            let buffer = self.buffer.read(cx).snapshot(cx);
 3068            let head;
 3069            let tail;
 3070            let mode = self.selections.pending_mode().unwrap();
 3071            match &mode {
 3072                SelectMode::Character => {
 3073                    head = position.to_point(&display_map);
 3074                    tail = pending.tail().to_point(&buffer);
 3075                }
 3076                SelectMode::Word(original_range) => {
 3077                    let original_display_range = original_range.start.to_display_point(&display_map)
 3078                        ..original_range.end.to_display_point(&display_map);
 3079                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 3080                        ..original_display_range.end.to_point(&display_map);
 3081                    if movement::is_inside_word(&display_map, position)
 3082                        || original_display_range.contains(&position)
 3083                    {
 3084                        let word_range = movement::surrounding_word(&display_map, position);
 3085                        if word_range.start < original_display_range.start {
 3086                            head = word_range.start.to_point(&display_map);
 3087                        } else {
 3088                            head = word_range.end.to_point(&display_map);
 3089                        }
 3090                    } else {
 3091                        head = position.to_point(&display_map);
 3092                    }
 3093
 3094                    if head <= original_buffer_range.start {
 3095                        tail = original_buffer_range.end;
 3096                    } else {
 3097                        tail = original_buffer_range.start;
 3098                    }
 3099                }
 3100                SelectMode::Line(original_range) => {
 3101                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 3102
 3103                    let position = display_map
 3104                        .clip_point(position, Bias::Left)
 3105                        .to_point(&display_map);
 3106                    let line_start = display_map.prev_line_boundary(position).0;
 3107                    let next_line_start = buffer.clip_point(
 3108                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 3109                        Bias::Left,
 3110                    );
 3111
 3112                    if line_start < original_range.start {
 3113                        head = line_start
 3114                    } else {
 3115                        head = next_line_start
 3116                    }
 3117
 3118                    if head <= original_range.start {
 3119                        tail = original_range.end;
 3120                    } else {
 3121                        tail = original_range.start;
 3122                    }
 3123                }
 3124                SelectMode::All => {
 3125                    return;
 3126                }
 3127            };
 3128
 3129            if head < tail {
 3130                pending.start = buffer.anchor_before(head);
 3131                pending.end = buffer.anchor_before(tail);
 3132                pending.reversed = true;
 3133            } else {
 3134                pending.start = buffer.anchor_before(tail);
 3135                pending.end = buffer.anchor_before(head);
 3136                pending.reversed = false;
 3137            }
 3138
 3139            self.change_selections(None, cx, |s| {
 3140                s.set_pending(pending, mode);
 3141            });
 3142        } else {
 3143            log::error!("update_selection dispatched with no pending selection");
 3144            return;
 3145        }
 3146
 3147        self.apply_scroll_delta(scroll_delta, cx);
 3148        cx.notify();
 3149    }
 3150
 3151    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 3152        self.columnar_selection_tail.take();
 3153        if self.selections.pending_anchor().is_some() {
 3154            let selections = self.selections.all::<usize>(cx);
 3155            self.change_selections(None, cx, |s| {
 3156                s.select(selections);
 3157                s.clear_pending();
 3158            });
 3159        }
 3160    }
 3161
 3162    fn select_columns(
 3163        &mut self,
 3164        tail: DisplayPoint,
 3165        head: DisplayPoint,
 3166        goal_column: u32,
 3167        display_map: &DisplaySnapshot,
 3168        cx: &mut ViewContext<Self>,
 3169    ) {
 3170        let start_row = cmp::min(tail.row(), head.row());
 3171        let end_row = cmp::max(tail.row(), head.row());
 3172        let start_column = cmp::min(tail.column(), goal_column);
 3173        let end_column = cmp::max(tail.column(), goal_column);
 3174        let reversed = start_column < tail.column();
 3175
 3176        let selection_ranges = (start_row.0..=end_row.0)
 3177            .map(DisplayRow)
 3178            .filter_map(|row| {
 3179                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 3180                    let start = display_map
 3181                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 3182                        .to_point(display_map);
 3183                    let end = display_map
 3184                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 3185                        .to_point(display_map);
 3186                    if reversed {
 3187                        Some(end..start)
 3188                    } else {
 3189                        Some(start..end)
 3190                    }
 3191                } else {
 3192                    None
 3193                }
 3194            })
 3195            .collect::<Vec<_>>();
 3196
 3197        self.change_selections(None, cx, |s| {
 3198            s.select_ranges(selection_ranges);
 3199        });
 3200        cx.notify();
 3201    }
 3202
 3203    pub fn has_pending_nonempty_selection(&self) -> bool {
 3204        let pending_nonempty_selection = match self.selections.pending_anchor() {
 3205            Some(Selection { start, end, .. }) => start != end,
 3206            None => false,
 3207        };
 3208
 3209        pending_nonempty_selection
 3210            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 3211    }
 3212
 3213    pub fn has_pending_selection(&self) -> bool {
 3214        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 3215    }
 3216
 3217    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 3218        if self.clear_expanded_diff_hunks(cx) {
 3219            cx.notify();
 3220            return;
 3221        }
 3222        if self.dismiss_menus_and_popups(true, cx) {
 3223            return;
 3224        }
 3225
 3226        if self.mode == EditorMode::Full
 3227            && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
 3228        {
 3229            return;
 3230        }
 3231
 3232        cx.propagate();
 3233    }
 3234
 3235    pub fn dismiss_menus_and_popups(
 3236        &mut self,
 3237        should_report_inline_completion_event: bool,
 3238        cx: &mut ViewContext<Self>,
 3239    ) -> bool {
 3240        if self.take_rename(false, cx).is_some() {
 3241            return true;
 3242        }
 3243
 3244        if hide_hover(self, cx) {
 3245            return true;
 3246        }
 3247
 3248        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 3249            return true;
 3250        }
 3251
 3252        if self.hide_context_menu(cx).is_some() {
 3253            return true;
 3254        }
 3255
 3256        if self.mouse_context_menu.take().is_some() {
 3257            return true;
 3258        }
 3259
 3260        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 3261            return true;
 3262        }
 3263
 3264        if self.snippet_stack.pop().is_some() {
 3265            return true;
 3266        }
 3267
 3268        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 3269            self.dismiss_diagnostics(cx);
 3270            return true;
 3271        }
 3272
 3273        false
 3274    }
 3275
 3276    fn linked_editing_ranges_for(
 3277        &self,
 3278        selection: Range<text::Anchor>,
 3279        cx: &AppContext,
 3280    ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
 3281        if self.linked_edit_ranges.is_empty() {
 3282            return None;
 3283        }
 3284        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 3285            selection.end.buffer_id.and_then(|end_buffer_id| {
 3286                if selection.start.buffer_id != Some(end_buffer_id) {
 3287                    return None;
 3288                }
 3289                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 3290                let snapshot = buffer.read(cx).snapshot();
 3291                self.linked_edit_ranges
 3292                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 3293                    .map(|ranges| (ranges, snapshot, buffer))
 3294            })?;
 3295        use text::ToOffset as TO;
 3296        // find offset from the start of current range to current cursor position
 3297        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 3298
 3299        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 3300        let start_difference = start_offset - start_byte_offset;
 3301        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 3302        let end_difference = end_offset - start_byte_offset;
 3303        // Current range has associated linked ranges.
 3304        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3305        for range in linked_ranges.iter() {
 3306            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 3307            let end_offset = start_offset + end_difference;
 3308            let start_offset = start_offset + start_difference;
 3309            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 3310                continue;
 3311            }
 3312            if self.selections.disjoint_anchor_ranges().iter().any(|s| {
 3313                if s.start.buffer_id != selection.start.buffer_id
 3314                    || s.end.buffer_id != selection.end.buffer_id
 3315                {
 3316                    return false;
 3317                }
 3318                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 3319                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 3320            }) {
 3321                continue;
 3322            }
 3323            let start = buffer_snapshot.anchor_after(start_offset);
 3324            let end = buffer_snapshot.anchor_after(end_offset);
 3325            linked_edits
 3326                .entry(buffer.clone())
 3327                .or_default()
 3328                .push(start..end);
 3329        }
 3330        Some(linked_edits)
 3331    }
 3332
 3333    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3334        let text: Arc<str> = text.into();
 3335
 3336        if self.read_only(cx) {
 3337            return;
 3338        }
 3339
 3340        let selections = self.selections.all_adjusted(cx);
 3341        let mut bracket_inserted = false;
 3342        let mut edits = Vec::new();
 3343        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3344        let mut new_selections = Vec::with_capacity(selections.len());
 3345        let mut new_autoclose_regions = Vec::new();
 3346        let snapshot = self.buffer.read(cx).read(cx);
 3347
 3348        for (selection, autoclose_region) in
 3349            self.selections_with_autoclose_regions(selections, &snapshot)
 3350        {
 3351            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 3352                // Determine if the inserted text matches the opening or closing
 3353                // bracket of any of this language's bracket pairs.
 3354                let mut bracket_pair = None;
 3355                let mut is_bracket_pair_start = false;
 3356                let mut is_bracket_pair_end = false;
 3357                if !text.is_empty() {
 3358                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 3359                    //  and they are removing the character that triggered IME popup.
 3360                    for (pair, enabled) in scope.brackets() {
 3361                        if !pair.close && !pair.surround {
 3362                            continue;
 3363                        }
 3364
 3365                        if enabled && pair.start.ends_with(text.as_ref()) {
 3366                            let prefix_len = pair.start.len() - text.len();
 3367                            let preceding_text_matches_prefix = prefix_len == 0
 3368                                || (selection.start.column >= (prefix_len as u32)
 3369                                    && snapshot.contains_str_at(
 3370                                        Point::new(
 3371                                            selection.start.row,
 3372                                            selection.start.column - (prefix_len as u32),
 3373                                        ),
 3374                                        &pair.start[..prefix_len],
 3375                                    ));
 3376                            if preceding_text_matches_prefix {
 3377                                bracket_pair = Some(pair.clone());
 3378                                is_bracket_pair_start = true;
 3379                                break;
 3380                            }
 3381                        }
 3382                        if pair.end.as_str() == text.as_ref() {
 3383                            bracket_pair = Some(pair.clone());
 3384                            is_bracket_pair_end = true;
 3385                            break;
 3386                        }
 3387                    }
 3388                }
 3389
 3390                if let Some(bracket_pair) = bracket_pair {
 3391                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 3392                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 3393                    let auto_surround =
 3394                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 3395                    if selection.is_empty() {
 3396                        if is_bracket_pair_start {
 3397                            // If the inserted text is a suffix of an opening bracket and the
 3398                            // selection is preceded by the rest of the opening bracket, then
 3399                            // insert the closing bracket.
 3400                            let following_text_allows_autoclose = snapshot
 3401                                .chars_at(selection.start)
 3402                                .next()
 3403                                .map_or(true, |c| scope.should_autoclose_before(c));
 3404
 3405                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 3406                                && bracket_pair.start.len() == 1
 3407                            {
 3408                                let target = bracket_pair.start.chars().next().unwrap();
 3409                                let current_line_count = snapshot
 3410                                    .reversed_chars_at(selection.start)
 3411                                    .take_while(|&c| c != '\n')
 3412                                    .filter(|&c| c == target)
 3413                                    .count();
 3414                                current_line_count % 2 == 1
 3415                            } else {
 3416                                false
 3417                            };
 3418
 3419                            if autoclose
 3420                                && bracket_pair.close
 3421                                && following_text_allows_autoclose
 3422                                && !is_closing_quote
 3423                            {
 3424                                let anchor = snapshot.anchor_before(selection.end);
 3425                                new_selections.push((selection.map(|_| anchor), text.len()));
 3426                                new_autoclose_regions.push((
 3427                                    anchor,
 3428                                    text.len(),
 3429                                    selection.id,
 3430                                    bracket_pair.clone(),
 3431                                ));
 3432                                edits.push((
 3433                                    selection.range(),
 3434                                    format!("{}{}", text, bracket_pair.end).into(),
 3435                                ));
 3436                                bracket_inserted = true;
 3437                                continue;
 3438                            }
 3439                        }
 3440
 3441                        if let Some(region) = autoclose_region {
 3442                            // If the selection is followed by an auto-inserted closing bracket,
 3443                            // then don't insert that closing bracket again; just move the selection
 3444                            // past the closing bracket.
 3445                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3446                                && text.as_ref() == region.pair.end.as_str();
 3447                            if should_skip {
 3448                                let anchor = snapshot.anchor_after(selection.end);
 3449                                new_selections
 3450                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3451                                continue;
 3452                            }
 3453                        }
 3454
 3455                        let always_treat_brackets_as_autoclosed = snapshot
 3456                            .settings_at(selection.start, cx)
 3457                            .always_treat_brackets_as_autoclosed;
 3458                        if always_treat_brackets_as_autoclosed
 3459                            && is_bracket_pair_end
 3460                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3461                        {
 3462                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3463                            // and the inserted text is a closing bracket and the selection is followed
 3464                            // by the closing bracket then move the selection past the closing bracket.
 3465                            let anchor = snapshot.anchor_after(selection.end);
 3466                            new_selections.push((selection.map(|_| anchor), text.len()));
 3467                            continue;
 3468                        }
 3469                    }
 3470                    // If an opening bracket is 1 character long and is typed while
 3471                    // text is selected, then surround that text with the bracket pair.
 3472                    else if auto_surround
 3473                        && bracket_pair.surround
 3474                        && is_bracket_pair_start
 3475                        && bracket_pair.start.chars().count() == 1
 3476                    {
 3477                        edits.push((selection.start..selection.start, text.clone()));
 3478                        edits.push((
 3479                            selection.end..selection.end,
 3480                            bracket_pair.end.as_str().into(),
 3481                        ));
 3482                        bracket_inserted = true;
 3483                        new_selections.push((
 3484                            Selection {
 3485                                id: selection.id,
 3486                                start: snapshot.anchor_after(selection.start),
 3487                                end: snapshot.anchor_before(selection.end),
 3488                                reversed: selection.reversed,
 3489                                goal: selection.goal,
 3490                            },
 3491                            0,
 3492                        ));
 3493                        continue;
 3494                    }
 3495                }
 3496            }
 3497
 3498            if self.auto_replace_emoji_shortcode
 3499                && selection.is_empty()
 3500                && text.as_ref().ends_with(':')
 3501            {
 3502                if let Some(possible_emoji_short_code) =
 3503                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3504                {
 3505                    if !possible_emoji_short_code.is_empty() {
 3506                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3507                            let emoji_shortcode_start = Point::new(
 3508                                selection.start.row,
 3509                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3510                            );
 3511
 3512                            // Remove shortcode from buffer
 3513                            edits.push((
 3514                                emoji_shortcode_start..selection.start,
 3515                                "".to_string().into(),
 3516                            ));
 3517                            new_selections.push((
 3518                                Selection {
 3519                                    id: selection.id,
 3520                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3521                                    end: snapshot.anchor_before(selection.start),
 3522                                    reversed: selection.reversed,
 3523                                    goal: selection.goal,
 3524                                },
 3525                                0,
 3526                            ));
 3527
 3528                            // Insert emoji
 3529                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3530                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3531                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3532
 3533                            continue;
 3534                        }
 3535                    }
 3536                }
 3537            }
 3538
 3539            // If not handling any auto-close operation, then just replace the selected
 3540            // text with the given input and move the selection to the end of the
 3541            // newly inserted text.
 3542            let anchor = snapshot.anchor_after(selection.end);
 3543            if !self.linked_edit_ranges.is_empty() {
 3544                let start_anchor = snapshot.anchor_before(selection.start);
 3545
 3546                let is_word_char = text.chars().next().map_or(true, |char| {
 3547                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3548                    classifier.is_word(char)
 3549                });
 3550
 3551                if is_word_char {
 3552                    if let Some(ranges) = self
 3553                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3554                    {
 3555                        for (buffer, edits) in ranges {
 3556                            linked_edits
 3557                                .entry(buffer.clone())
 3558                                .or_default()
 3559                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3560                        }
 3561                    }
 3562                }
 3563            }
 3564
 3565            new_selections.push((selection.map(|_| anchor), 0));
 3566            edits.push((selection.start..selection.end, text.clone()));
 3567        }
 3568
 3569        drop(snapshot);
 3570
 3571        self.transact(cx, |this, cx| {
 3572            this.buffer.update(cx, |buffer, cx| {
 3573                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3574            });
 3575            for (buffer, edits) in linked_edits {
 3576                buffer.update(cx, |buffer, cx| {
 3577                    let snapshot = buffer.snapshot();
 3578                    let edits = edits
 3579                        .into_iter()
 3580                        .map(|(range, text)| {
 3581                            use text::ToPoint as TP;
 3582                            let end_point = TP::to_point(&range.end, &snapshot);
 3583                            let start_point = TP::to_point(&range.start, &snapshot);
 3584                            (start_point..end_point, text)
 3585                        })
 3586                        .sorted_by_key(|(range, _)| range.start)
 3587                        .collect::<Vec<_>>();
 3588                    buffer.edit(edits, None, cx);
 3589                })
 3590            }
 3591            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3592            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3593            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3594            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3595                .zip(new_selection_deltas)
 3596                .map(|(selection, delta)| Selection {
 3597                    id: selection.id,
 3598                    start: selection.start + delta,
 3599                    end: selection.end + delta,
 3600                    reversed: selection.reversed,
 3601                    goal: SelectionGoal::None,
 3602                })
 3603                .collect::<Vec<_>>();
 3604
 3605            let mut i = 0;
 3606            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3607                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3608                let start = map.buffer_snapshot.anchor_before(position);
 3609                let end = map.buffer_snapshot.anchor_after(position);
 3610                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3611                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3612                        Ordering::Less => i += 1,
 3613                        Ordering::Greater => break,
 3614                        Ordering::Equal => {
 3615                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3616                                Ordering::Less => i += 1,
 3617                                Ordering::Equal => break,
 3618                                Ordering::Greater => break,
 3619                            }
 3620                        }
 3621                    }
 3622                }
 3623                this.autoclose_regions.insert(
 3624                    i,
 3625                    AutocloseRegion {
 3626                        selection_id,
 3627                        range: start..end,
 3628                        pair,
 3629                    },
 3630                );
 3631            }
 3632
 3633            let had_active_inline_completion = this.has_active_inline_completion(cx);
 3634            this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
 3635                s.select(new_selections)
 3636            });
 3637
 3638            if !bracket_inserted {
 3639                if let Some(on_type_format_task) =
 3640                    this.trigger_on_type_formatting(text.to_string(), cx)
 3641                {
 3642                    on_type_format_task.detach_and_log_err(cx);
 3643                }
 3644            }
 3645
 3646            let editor_settings = EditorSettings::get_global(cx);
 3647            if bracket_inserted
 3648                && (editor_settings.auto_signature_help
 3649                    || editor_settings.show_signature_help_after_edits)
 3650            {
 3651                this.show_signature_help(&ShowSignatureHelp, cx);
 3652            }
 3653
 3654            let trigger_in_words = !had_active_inline_completion;
 3655            this.trigger_completion_on_input(&text, trigger_in_words, cx);
 3656            linked_editing_ranges::refresh_linked_ranges(this, cx);
 3657            this.refresh_inline_completion(true, false, cx);
 3658        });
 3659    }
 3660
 3661    fn find_possible_emoji_shortcode_at_position(
 3662        snapshot: &MultiBufferSnapshot,
 3663        position: Point,
 3664    ) -> Option<String> {
 3665        let mut chars = Vec::new();
 3666        let mut found_colon = false;
 3667        for char in snapshot.reversed_chars_at(position).take(100) {
 3668            // Found a possible emoji shortcode in the middle of the buffer
 3669            if found_colon {
 3670                if char.is_whitespace() {
 3671                    chars.reverse();
 3672                    return Some(chars.iter().collect());
 3673                }
 3674                // If the previous character is not a whitespace, we are in the middle of a word
 3675                // and we only want to complete the shortcode if the word is made up of other emojis
 3676                let mut containing_word = String::new();
 3677                for ch in snapshot
 3678                    .reversed_chars_at(position)
 3679                    .skip(chars.len() + 1)
 3680                    .take(100)
 3681                {
 3682                    if ch.is_whitespace() {
 3683                        break;
 3684                    }
 3685                    containing_word.push(ch);
 3686                }
 3687                let containing_word = containing_word.chars().rev().collect::<String>();
 3688                if util::word_consists_of_emojis(containing_word.as_str()) {
 3689                    chars.reverse();
 3690                    return Some(chars.iter().collect());
 3691                }
 3692            }
 3693
 3694            if char.is_whitespace() || !char.is_ascii() {
 3695                return None;
 3696            }
 3697            if char == ':' {
 3698                found_colon = true;
 3699            } else {
 3700                chars.push(char);
 3701            }
 3702        }
 3703        // Found a possible emoji shortcode at the beginning of the buffer
 3704        chars.reverse();
 3705        Some(chars.iter().collect())
 3706    }
 3707
 3708    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 3709        self.transact(cx, |this, cx| {
 3710            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3711                let selections = this.selections.all::<usize>(cx);
 3712                let multi_buffer = this.buffer.read(cx);
 3713                let buffer = multi_buffer.snapshot(cx);
 3714                selections
 3715                    .iter()
 3716                    .map(|selection| {
 3717                        let start_point = selection.start.to_point(&buffer);
 3718                        let mut indent =
 3719                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3720                        indent.len = cmp::min(indent.len, start_point.column);
 3721                        let start = selection.start;
 3722                        let end = selection.end;
 3723                        let selection_is_empty = start == end;
 3724                        let language_scope = buffer.language_scope_at(start);
 3725                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3726                            &language_scope
 3727                        {
 3728                            let leading_whitespace_len = buffer
 3729                                .reversed_chars_at(start)
 3730                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3731                                .map(|c| c.len_utf8())
 3732                                .sum::<usize>();
 3733
 3734                            let trailing_whitespace_len = buffer
 3735                                .chars_at(end)
 3736                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3737                                .map(|c| c.len_utf8())
 3738                                .sum::<usize>();
 3739
 3740                            let insert_extra_newline =
 3741                                language.brackets().any(|(pair, enabled)| {
 3742                                    let pair_start = pair.start.trim_end();
 3743                                    let pair_end = pair.end.trim_start();
 3744
 3745                                    enabled
 3746                                        && pair.newline
 3747                                        && buffer.contains_str_at(
 3748                                            end + trailing_whitespace_len,
 3749                                            pair_end,
 3750                                        )
 3751                                        && buffer.contains_str_at(
 3752                                            (start - leading_whitespace_len)
 3753                                                .saturating_sub(pair_start.len()),
 3754                                            pair_start,
 3755                                        )
 3756                                });
 3757
 3758                            // Comment extension on newline is allowed only for cursor selections
 3759                            let comment_delimiter = maybe!({
 3760                                if !selection_is_empty {
 3761                                    return None;
 3762                                }
 3763
 3764                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3765                                    return None;
 3766                                }
 3767
 3768                                let delimiters = language.line_comment_prefixes();
 3769                                let max_len_of_delimiter =
 3770                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3771                                let (snapshot, range) =
 3772                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3773
 3774                                let mut index_of_first_non_whitespace = 0;
 3775                                let comment_candidate = snapshot
 3776                                    .chars_for_range(range)
 3777                                    .skip_while(|c| {
 3778                                        let should_skip = c.is_whitespace();
 3779                                        if should_skip {
 3780                                            index_of_first_non_whitespace += 1;
 3781                                        }
 3782                                        should_skip
 3783                                    })
 3784                                    .take(max_len_of_delimiter)
 3785                                    .collect::<String>();
 3786                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3787                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3788                                })?;
 3789                                let cursor_is_placed_after_comment_marker =
 3790                                    index_of_first_non_whitespace + comment_prefix.len()
 3791                                        <= start_point.column as usize;
 3792                                if cursor_is_placed_after_comment_marker {
 3793                                    Some(comment_prefix.clone())
 3794                                } else {
 3795                                    None
 3796                                }
 3797                            });
 3798                            (comment_delimiter, insert_extra_newline)
 3799                        } else {
 3800                            (None, false)
 3801                        };
 3802
 3803                        let capacity_for_delimiter = comment_delimiter
 3804                            .as_deref()
 3805                            .map(str::len)
 3806                            .unwrap_or_default();
 3807                        let mut new_text =
 3808                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3809                        new_text.push('\n');
 3810                        new_text.extend(indent.chars());
 3811                        if let Some(delimiter) = &comment_delimiter {
 3812                            new_text.push_str(delimiter);
 3813                        }
 3814                        if insert_extra_newline {
 3815                            new_text = new_text.repeat(2);
 3816                        }
 3817
 3818                        let anchor = buffer.anchor_after(end);
 3819                        let new_selection = selection.map(|_| anchor);
 3820                        (
 3821                            (start..end, new_text),
 3822                            (insert_extra_newline, new_selection),
 3823                        )
 3824                    })
 3825                    .unzip()
 3826            };
 3827
 3828            this.edit_with_autoindent(edits, cx);
 3829            let buffer = this.buffer.read(cx).snapshot(cx);
 3830            let new_selections = selection_fixup_info
 3831                .into_iter()
 3832                .map(|(extra_newline_inserted, new_selection)| {
 3833                    let mut cursor = new_selection.end.to_point(&buffer);
 3834                    if extra_newline_inserted {
 3835                        cursor.row -= 1;
 3836                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3837                    }
 3838                    new_selection.map(|_| cursor)
 3839                })
 3840                .collect();
 3841
 3842            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3843            this.refresh_inline_completion(true, false, cx);
 3844        });
 3845    }
 3846
 3847    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3848        let buffer = self.buffer.read(cx);
 3849        let snapshot = buffer.snapshot(cx);
 3850
 3851        let mut edits = Vec::new();
 3852        let mut rows = Vec::new();
 3853
 3854        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3855            let cursor = selection.head();
 3856            let row = cursor.row;
 3857
 3858            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3859
 3860            let newline = "\n".to_string();
 3861            edits.push((start_of_line..start_of_line, newline));
 3862
 3863            rows.push(row + rows_inserted as u32);
 3864        }
 3865
 3866        self.transact(cx, |editor, cx| {
 3867            editor.edit(edits, cx);
 3868
 3869            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3870                let mut index = 0;
 3871                s.move_cursors_with(|map, _, _| {
 3872                    let row = rows[index];
 3873                    index += 1;
 3874
 3875                    let point = Point::new(row, 0);
 3876                    let boundary = map.next_line_boundary(point).1;
 3877                    let clipped = map.clip_point(boundary, Bias::Left);
 3878
 3879                    (clipped, SelectionGoal::None)
 3880                });
 3881            });
 3882
 3883            let mut indent_edits = Vec::new();
 3884            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3885            for row in rows {
 3886                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3887                for (row, indent) in indents {
 3888                    if indent.len == 0 {
 3889                        continue;
 3890                    }
 3891
 3892                    let text = match indent.kind {
 3893                        IndentKind::Space => " ".repeat(indent.len as usize),
 3894                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3895                    };
 3896                    let point = Point::new(row.0, 0);
 3897                    indent_edits.push((point..point, text));
 3898                }
 3899            }
 3900            editor.edit(indent_edits, cx);
 3901        });
 3902    }
 3903
 3904    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3905        let buffer = self.buffer.read(cx);
 3906        let snapshot = buffer.snapshot(cx);
 3907
 3908        let mut edits = Vec::new();
 3909        let mut rows = Vec::new();
 3910        let mut rows_inserted = 0;
 3911
 3912        for selection in self.selections.all_adjusted(cx) {
 3913            let cursor = selection.head();
 3914            let row = cursor.row;
 3915
 3916            let point = Point::new(row + 1, 0);
 3917            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3918
 3919            let newline = "\n".to_string();
 3920            edits.push((start_of_line..start_of_line, newline));
 3921
 3922            rows_inserted += 1;
 3923            rows.push(row + rows_inserted);
 3924        }
 3925
 3926        self.transact(cx, |editor, cx| {
 3927            editor.edit(edits, cx);
 3928
 3929            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3930                let mut index = 0;
 3931                s.move_cursors_with(|map, _, _| {
 3932                    let row = rows[index];
 3933                    index += 1;
 3934
 3935                    let point = Point::new(row, 0);
 3936                    let boundary = map.next_line_boundary(point).1;
 3937                    let clipped = map.clip_point(boundary, Bias::Left);
 3938
 3939                    (clipped, SelectionGoal::None)
 3940                });
 3941            });
 3942
 3943            let mut indent_edits = Vec::new();
 3944            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3945            for row in rows {
 3946                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3947                for (row, indent) in indents {
 3948                    if indent.len == 0 {
 3949                        continue;
 3950                    }
 3951
 3952                    let text = match indent.kind {
 3953                        IndentKind::Space => " ".repeat(indent.len as usize),
 3954                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3955                    };
 3956                    let point = Point::new(row.0, 0);
 3957                    indent_edits.push((point..point, text));
 3958                }
 3959            }
 3960            editor.edit(indent_edits, cx);
 3961        });
 3962    }
 3963
 3964    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3965        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3966            original_indent_columns: Vec::new(),
 3967        });
 3968        self.insert_with_autoindent_mode(text, autoindent, cx);
 3969    }
 3970
 3971    fn insert_with_autoindent_mode(
 3972        &mut self,
 3973        text: &str,
 3974        autoindent_mode: Option<AutoindentMode>,
 3975        cx: &mut ViewContext<Self>,
 3976    ) {
 3977        if self.read_only(cx) {
 3978            return;
 3979        }
 3980
 3981        let text: Arc<str> = text.into();
 3982        self.transact(cx, |this, cx| {
 3983            let old_selections = this.selections.all_adjusted(cx);
 3984            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3985                let anchors = {
 3986                    let snapshot = buffer.read(cx);
 3987                    old_selections
 3988                        .iter()
 3989                        .map(|s| {
 3990                            let anchor = snapshot.anchor_after(s.head());
 3991                            s.map(|_| anchor)
 3992                        })
 3993                        .collect::<Vec<_>>()
 3994                };
 3995                buffer.edit(
 3996                    old_selections
 3997                        .iter()
 3998                        .map(|s| (s.start..s.end, text.clone())),
 3999                    autoindent_mode,
 4000                    cx,
 4001                );
 4002                anchors
 4003            });
 4004
 4005            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 4006                s.select_anchors(selection_anchors);
 4007            })
 4008        });
 4009    }
 4010
 4011    fn trigger_completion_on_input(
 4012        &mut self,
 4013        text: &str,
 4014        trigger_in_words: bool,
 4015        cx: &mut ViewContext<Self>,
 4016    ) {
 4017        if self.is_completion_trigger(text, trigger_in_words, cx) {
 4018            self.show_completions(
 4019                &ShowCompletions {
 4020                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 4021                },
 4022                cx,
 4023            );
 4024        } else {
 4025            self.hide_context_menu(cx);
 4026        }
 4027    }
 4028
 4029    fn is_completion_trigger(
 4030        &self,
 4031        text: &str,
 4032        trigger_in_words: bool,
 4033        cx: &mut ViewContext<Self>,
 4034    ) -> bool {
 4035        let position = self.selections.newest_anchor().head();
 4036        let multibuffer = self.buffer.read(cx);
 4037        let Some(buffer) = position
 4038            .buffer_id
 4039            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 4040        else {
 4041            return false;
 4042        };
 4043
 4044        if let Some(completion_provider) = &self.completion_provider {
 4045            completion_provider.is_completion_trigger(
 4046                &buffer,
 4047                position.text_anchor,
 4048                text,
 4049                trigger_in_words,
 4050                cx,
 4051            )
 4052        } else {
 4053            false
 4054        }
 4055    }
 4056
 4057    /// If any empty selections is touching the start of its innermost containing autoclose
 4058    /// region, expand it to select the brackets.
 4059    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 4060        let selections = self.selections.all::<usize>(cx);
 4061        let buffer = self.buffer.read(cx).read(cx);
 4062        let new_selections = self
 4063            .selections_with_autoclose_regions(selections, &buffer)
 4064            .map(|(mut selection, region)| {
 4065                if !selection.is_empty() {
 4066                    return selection;
 4067                }
 4068
 4069                if let Some(region) = region {
 4070                    let mut range = region.range.to_offset(&buffer);
 4071                    if selection.start == range.start && range.start >= region.pair.start.len() {
 4072                        range.start -= region.pair.start.len();
 4073                        if buffer.contains_str_at(range.start, &region.pair.start)
 4074                            && buffer.contains_str_at(range.end, &region.pair.end)
 4075                        {
 4076                            range.end += region.pair.end.len();
 4077                            selection.start = range.start;
 4078                            selection.end = range.end;
 4079
 4080                            return selection;
 4081                        }
 4082                    }
 4083                }
 4084
 4085                let always_treat_brackets_as_autoclosed = buffer
 4086                    .settings_at(selection.start, cx)
 4087                    .always_treat_brackets_as_autoclosed;
 4088
 4089                if !always_treat_brackets_as_autoclosed {
 4090                    return selection;
 4091                }
 4092
 4093                if let Some(scope) = buffer.language_scope_at(selection.start) {
 4094                    for (pair, enabled) in scope.brackets() {
 4095                        if !enabled || !pair.close {
 4096                            continue;
 4097                        }
 4098
 4099                        if buffer.contains_str_at(selection.start, &pair.end) {
 4100                            let pair_start_len = pair.start.len();
 4101                            if buffer.contains_str_at(
 4102                                selection.start.saturating_sub(pair_start_len),
 4103                                &pair.start,
 4104                            ) {
 4105                                selection.start -= pair_start_len;
 4106                                selection.end += pair.end.len();
 4107
 4108                                return selection;
 4109                            }
 4110                        }
 4111                    }
 4112                }
 4113
 4114                selection
 4115            })
 4116            .collect();
 4117
 4118        drop(buffer);
 4119        self.change_selections(None, cx, |selections| selections.select(new_selections));
 4120    }
 4121
 4122    /// Iterate the given selections, and for each one, find the smallest surrounding
 4123    /// autoclose region. This uses the ordering of the selections and the autoclose
 4124    /// regions to avoid repeated comparisons.
 4125    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 4126        &'a self,
 4127        selections: impl IntoIterator<Item = Selection<D>>,
 4128        buffer: &'a MultiBufferSnapshot,
 4129    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 4130        let mut i = 0;
 4131        let mut regions = self.autoclose_regions.as_slice();
 4132        selections.into_iter().map(move |selection| {
 4133            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 4134
 4135            let mut enclosing = None;
 4136            while let Some(pair_state) = regions.get(i) {
 4137                if pair_state.range.end.to_offset(buffer) < range.start {
 4138                    regions = &regions[i + 1..];
 4139                    i = 0;
 4140                } else if pair_state.range.start.to_offset(buffer) > range.end {
 4141                    break;
 4142                } else {
 4143                    if pair_state.selection_id == selection.id {
 4144                        enclosing = Some(pair_state);
 4145                    }
 4146                    i += 1;
 4147                }
 4148            }
 4149
 4150            (selection, enclosing)
 4151        })
 4152    }
 4153
 4154    /// Remove any autoclose regions that no longer contain their selection.
 4155    fn invalidate_autoclose_regions(
 4156        &mut self,
 4157        mut selections: &[Selection<Anchor>],
 4158        buffer: &MultiBufferSnapshot,
 4159    ) {
 4160        self.autoclose_regions.retain(|state| {
 4161            let mut i = 0;
 4162            while let Some(selection) = selections.get(i) {
 4163                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 4164                    selections = &selections[1..];
 4165                    continue;
 4166                }
 4167                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 4168                    break;
 4169                }
 4170                if selection.id == state.selection_id {
 4171                    return true;
 4172                } else {
 4173                    i += 1;
 4174                }
 4175            }
 4176            false
 4177        });
 4178    }
 4179
 4180    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 4181        let offset = position.to_offset(buffer);
 4182        let (word_range, kind) = buffer.surrounding_word(offset, true);
 4183        if offset > word_range.start && kind == Some(CharKind::Word) {
 4184            Some(
 4185                buffer
 4186                    .text_for_range(word_range.start..offset)
 4187                    .collect::<String>(),
 4188            )
 4189        } else {
 4190            None
 4191        }
 4192    }
 4193
 4194    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 4195        self.refresh_inlay_hints(
 4196            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 4197            cx,
 4198        );
 4199    }
 4200
 4201    pub fn inlay_hints_enabled(&self) -> bool {
 4202        self.inlay_hint_cache.enabled
 4203    }
 4204
 4205    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 4206        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 4207            return;
 4208        }
 4209
 4210        let reason_description = reason.description();
 4211        let ignore_debounce = matches!(
 4212            reason,
 4213            InlayHintRefreshReason::SettingsChange(_)
 4214                | InlayHintRefreshReason::Toggle(_)
 4215                | InlayHintRefreshReason::ExcerptsRemoved(_)
 4216        );
 4217        let (invalidate_cache, required_languages) = match reason {
 4218            InlayHintRefreshReason::Toggle(enabled) => {
 4219                self.inlay_hint_cache.enabled = enabled;
 4220                if enabled {
 4221                    (InvalidationStrategy::RefreshRequested, None)
 4222                } else {
 4223                    self.inlay_hint_cache.clear();
 4224                    self.splice_inlays(
 4225                        self.visible_inlay_hints(cx)
 4226                            .iter()
 4227                            .map(|inlay| inlay.id)
 4228                            .collect(),
 4229                        Vec::new(),
 4230                        cx,
 4231                    );
 4232                    return;
 4233                }
 4234            }
 4235            InlayHintRefreshReason::SettingsChange(new_settings) => {
 4236                match self.inlay_hint_cache.update_settings(
 4237                    &self.buffer,
 4238                    new_settings,
 4239                    self.visible_inlay_hints(cx),
 4240                    cx,
 4241                ) {
 4242                    ControlFlow::Break(Some(InlaySplice {
 4243                        to_remove,
 4244                        to_insert,
 4245                    })) => {
 4246                        self.splice_inlays(to_remove, to_insert, cx);
 4247                        return;
 4248                    }
 4249                    ControlFlow::Break(None) => return,
 4250                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 4251                }
 4252            }
 4253            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 4254                if let Some(InlaySplice {
 4255                    to_remove,
 4256                    to_insert,
 4257                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 4258                {
 4259                    self.splice_inlays(to_remove, to_insert, cx);
 4260                }
 4261                return;
 4262            }
 4263            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 4264            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 4265                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 4266            }
 4267            InlayHintRefreshReason::RefreshRequested => {
 4268                (InvalidationStrategy::RefreshRequested, None)
 4269            }
 4270        };
 4271
 4272        if let Some(InlaySplice {
 4273            to_remove,
 4274            to_insert,
 4275        }) = self.inlay_hint_cache.spawn_hint_refresh(
 4276            reason_description,
 4277            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 4278            invalidate_cache,
 4279            ignore_debounce,
 4280            cx,
 4281        ) {
 4282            self.splice_inlays(to_remove, to_insert, cx);
 4283        }
 4284    }
 4285
 4286    fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
 4287        self.display_map
 4288            .read(cx)
 4289            .current_inlays()
 4290            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 4291            .cloned()
 4292            .collect()
 4293    }
 4294
 4295    pub fn excerpts_for_inlay_hints_query(
 4296        &self,
 4297        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 4298        cx: &mut ViewContext<Editor>,
 4299    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 4300        let Some(project) = self.project.as_ref() else {
 4301            return HashMap::default();
 4302        };
 4303        let project = project.read(cx);
 4304        let multi_buffer = self.buffer().read(cx);
 4305        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 4306        let multi_buffer_visible_start = self
 4307            .scroll_manager
 4308            .anchor()
 4309            .anchor
 4310            .to_point(&multi_buffer_snapshot);
 4311        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 4312            multi_buffer_visible_start
 4313                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 4314            Bias::Left,
 4315        );
 4316        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 4317        multi_buffer
 4318            .range_to_buffer_ranges(multi_buffer_visible_range, cx)
 4319            .into_iter()
 4320            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 4321            .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
 4322                let buffer = buffer_handle.read(cx);
 4323                let buffer_file = project::File::from_dyn(buffer.file())?;
 4324                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 4325                let worktree_entry = buffer_worktree
 4326                    .read(cx)
 4327                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 4328                if worktree_entry.is_ignored {
 4329                    return None;
 4330                }
 4331
 4332                let language = buffer.language()?;
 4333                if let Some(restrict_to_languages) = restrict_to_languages {
 4334                    if !restrict_to_languages.contains(language) {
 4335                        return None;
 4336                    }
 4337                }
 4338                Some((
 4339                    excerpt_id,
 4340                    (
 4341                        buffer_handle,
 4342                        buffer.version().clone(),
 4343                        excerpt_visible_range,
 4344                    ),
 4345                ))
 4346            })
 4347            .collect()
 4348    }
 4349
 4350    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 4351        TextLayoutDetails {
 4352            text_system: cx.text_system().clone(),
 4353            editor_style: self.style.clone().unwrap(),
 4354            rem_size: cx.rem_size(),
 4355            scroll_anchor: self.scroll_manager.anchor(),
 4356            visible_rows: self.visible_line_count(),
 4357            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 4358        }
 4359    }
 4360
 4361    fn splice_inlays(
 4362        &self,
 4363        to_remove: Vec<InlayId>,
 4364        to_insert: Vec<Inlay>,
 4365        cx: &mut ViewContext<Self>,
 4366    ) {
 4367        self.display_map.update(cx, |display_map, cx| {
 4368            display_map.splice_inlays(to_remove, to_insert, cx);
 4369        });
 4370        cx.notify();
 4371    }
 4372
 4373    fn trigger_on_type_formatting(
 4374        &self,
 4375        input: String,
 4376        cx: &mut ViewContext<Self>,
 4377    ) -> Option<Task<Result<()>>> {
 4378        if input.len() != 1 {
 4379            return None;
 4380        }
 4381
 4382        let project = self.project.as_ref()?;
 4383        let position = self.selections.newest_anchor().head();
 4384        let (buffer, buffer_position) = self
 4385            .buffer
 4386            .read(cx)
 4387            .text_anchor_for_position(position, cx)?;
 4388
 4389        let settings = language_settings::language_settings(
 4390            buffer
 4391                .read(cx)
 4392                .language_at(buffer_position)
 4393                .map(|l| l.name()),
 4394            buffer.read(cx).file(),
 4395            cx,
 4396        );
 4397        if !settings.use_on_type_format {
 4398            return None;
 4399        }
 4400
 4401        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 4402        // hence we do LSP request & edit on host side only — add formats to host's history.
 4403        let push_to_lsp_host_history = true;
 4404        // If this is not the host, append its history with new edits.
 4405        let push_to_client_history = project.read(cx).is_via_collab();
 4406
 4407        let on_type_formatting = project.update(cx, |project, cx| {
 4408            project.on_type_format(
 4409                buffer.clone(),
 4410                buffer_position,
 4411                input,
 4412                push_to_lsp_host_history,
 4413                cx,
 4414            )
 4415        });
 4416        Some(cx.spawn(|editor, mut cx| async move {
 4417            if let Some(transaction) = on_type_formatting.await? {
 4418                if push_to_client_history {
 4419                    buffer
 4420                        .update(&mut cx, |buffer, _| {
 4421                            buffer.push_transaction(transaction, Instant::now());
 4422                        })
 4423                        .ok();
 4424                }
 4425                editor.update(&mut cx, |editor, cx| {
 4426                    editor.refresh_document_highlights(cx);
 4427                })?;
 4428            }
 4429            Ok(())
 4430        }))
 4431    }
 4432
 4433    pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
 4434        if self.pending_rename.is_some() {
 4435            return;
 4436        }
 4437
 4438        let Some(provider) = self.completion_provider.as_ref() else {
 4439            return;
 4440        };
 4441
 4442        if !self.snippet_stack.is_empty() && self.context_menu.read().as_ref().is_some() {
 4443            return;
 4444        }
 4445
 4446        let position = self.selections.newest_anchor().head();
 4447        let (buffer, buffer_position) =
 4448            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4449                output
 4450            } else {
 4451                return;
 4452            };
 4453
 4454        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4455        let trigger_kind = match &options.trigger {
 4456            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4457                CompletionTriggerKind::TRIGGER_CHARACTER
 4458            }
 4459            _ => CompletionTriggerKind::INVOKED,
 4460        };
 4461        let completion_context = CompletionContext {
 4462            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 4463                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4464                    Some(String::from(trigger))
 4465                } else {
 4466                    None
 4467                }
 4468            }),
 4469            trigger_kind,
 4470        };
 4471        let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
 4472        let sort_completions = provider.sort_completions();
 4473
 4474        let id = post_inc(&mut self.next_completion_id);
 4475        let task = cx.spawn(|editor, mut cx| {
 4476            async move {
 4477                editor.update(&mut cx, |this, _| {
 4478                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4479                })?;
 4480                let completions = completions.await.log_err();
 4481                let menu = if let Some(completions) = completions {
 4482                    let mut menu = CompletionsMenu::new(
 4483                        id,
 4484                        sort_completions,
 4485                        position,
 4486                        buffer.clone(),
 4487                        completions.into(),
 4488                    );
 4489                    menu.filter(query.as_deref(), cx.background_executor().clone())
 4490                        .await;
 4491
 4492                    if menu.matches.is_empty() {
 4493                        None
 4494                    } else {
 4495                        Some(menu)
 4496                    }
 4497                } else {
 4498                    None
 4499                };
 4500
 4501                editor.update(&mut cx, |editor, cx| {
 4502                    let mut context_menu = editor.context_menu.write();
 4503                    match context_menu.as_ref() {
 4504                        None => {}
 4505
 4506                        Some(ContextMenu::Completions(prev_menu)) => {
 4507                            if prev_menu.id > id {
 4508                                return;
 4509                            }
 4510                        }
 4511
 4512                        _ => return,
 4513                    }
 4514
 4515                    if editor.focus_handle.is_focused(cx) && menu.is_some() {
 4516                        let mut menu = menu.unwrap();
 4517                        menu.resolve_selected_completion(editor.completion_provider.as_deref(), cx);
 4518                        *context_menu = Some(ContextMenu::Completions(menu));
 4519                        drop(context_menu);
 4520                        editor.discard_inline_completion(false, cx);
 4521                        cx.notify();
 4522                    } else if editor.completion_tasks.len() <= 1 {
 4523                        // If there are no more completion tasks and the last menu was
 4524                        // empty, we should hide it. If it was already hidden, we should
 4525                        // also show the copilot completion when available.
 4526                        drop(context_menu);
 4527                        if editor.hide_context_menu(cx).is_none() {
 4528                            editor.update_visible_inline_completion(cx);
 4529                        }
 4530                    }
 4531                })?;
 4532
 4533                Ok::<_, anyhow::Error>(())
 4534            }
 4535            .log_err()
 4536        });
 4537
 4538        self.completion_tasks.push((id, task));
 4539    }
 4540
 4541    pub fn confirm_completion(
 4542        &mut self,
 4543        action: &ConfirmCompletion,
 4544        cx: &mut ViewContext<Self>,
 4545    ) -> Option<Task<Result<()>>> {
 4546        self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
 4547    }
 4548
 4549    pub fn compose_completion(
 4550        &mut self,
 4551        action: &ComposeCompletion,
 4552        cx: &mut ViewContext<Self>,
 4553    ) -> Option<Task<Result<()>>> {
 4554        self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
 4555    }
 4556
 4557    fn do_completion(
 4558        &mut self,
 4559        item_ix: Option<usize>,
 4560        intent: CompletionIntent,
 4561        cx: &mut ViewContext<Editor>,
 4562    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 4563        use language::ToOffset as _;
 4564
 4565        let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 4566            menu
 4567        } else {
 4568            return None;
 4569        };
 4570
 4571        let mat = completions_menu
 4572            .matches
 4573            .get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4574        let buffer_handle = completions_menu.buffer;
 4575        let completions = completions_menu.completions.read();
 4576        let completion = completions.get(mat.candidate_id)?;
 4577        cx.stop_propagation();
 4578
 4579        let snippet;
 4580        let text;
 4581
 4582        if completion.is_snippet() {
 4583            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4584            text = snippet.as_ref().unwrap().text.clone();
 4585        } else {
 4586            snippet = None;
 4587            text = completion.new_text.clone();
 4588        };
 4589        let selections = self.selections.all::<usize>(cx);
 4590        let buffer = buffer_handle.read(cx);
 4591        let old_range = completion.old_range.to_offset(buffer);
 4592        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4593
 4594        let newest_selection = self.selections.newest_anchor();
 4595        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4596            return None;
 4597        }
 4598
 4599        let lookbehind = newest_selection
 4600            .start
 4601            .text_anchor
 4602            .to_offset(buffer)
 4603            .saturating_sub(old_range.start);
 4604        let lookahead = old_range
 4605            .end
 4606            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4607        let mut common_prefix_len = old_text
 4608            .bytes()
 4609            .zip(text.bytes())
 4610            .take_while(|(a, b)| a == b)
 4611            .count();
 4612
 4613        let snapshot = self.buffer.read(cx).snapshot(cx);
 4614        let mut range_to_replace: Option<Range<isize>> = None;
 4615        let mut ranges = Vec::new();
 4616        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4617        for selection in &selections {
 4618            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4619                let start = selection.start.saturating_sub(lookbehind);
 4620                let end = selection.end + lookahead;
 4621                if selection.id == newest_selection.id {
 4622                    range_to_replace = Some(
 4623                        ((start + common_prefix_len) as isize - selection.start as isize)
 4624                            ..(end as isize - selection.start as isize),
 4625                    );
 4626                }
 4627                ranges.push(start + common_prefix_len..end);
 4628            } else {
 4629                common_prefix_len = 0;
 4630                ranges.clear();
 4631                ranges.extend(selections.iter().map(|s| {
 4632                    if s.id == newest_selection.id {
 4633                        range_to_replace = Some(
 4634                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4635                                - selection.start as isize
 4636                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4637                                    - selection.start as isize,
 4638                        );
 4639                        old_range.clone()
 4640                    } else {
 4641                        s.start..s.end
 4642                    }
 4643                }));
 4644                break;
 4645            }
 4646            if !self.linked_edit_ranges.is_empty() {
 4647                let start_anchor = snapshot.anchor_before(selection.head());
 4648                let end_anchor = snapshot.anchor_after(selection.tail());
 4649                if let Some(ranges) = self
 4650                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4651                {
 4652                    for (buffer, edits) in ranges {
 4653                        linked_edits.entry(buffer.clone()).or_default().extend(
 4654                            edits
 4655                                .into_iter()
 4656                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4657                        );
 4658                    }
 4659                }
 4660            }
 4661        }
 4662        let text = &text[common_prefix_len..];
 4663
 4664        cx.emit(EditorEvent::InputHandled {
 4665            utf16_range_to_replace: range_to_replace,
 4666            text: text.into(),
 4667        });
 4668
 4669        self.transact(cx, |this, cx| {
 4670            if let Some(mut snippet) = snippet {
 4671                snippet.text = text.to_string();
 4672                for tabstop in snippet
 4673                    .tabstops
 4674                    .iter_mut()
 4675                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4676                {
 4677                    tabstop.start -= common_prefix_len as isize;
 4678                    tabstop.end -= common_prefix_len as isize;
 4679                }
 4680
 4681                this.insert_snippet(&ranges, snippet, cx).log_err();
 4682            } else {
 4683                this.buffer.update(cx, |buffer, cx| {
 4684                    buffer.edit(
 4685                        ranges.iter().map(|range| (range.clone(), text)),
 4686                        this.autoindent_mode.clone(),
 4687                        cx,
 4688                    );
 4689                });
 4690            }
 4691            for (buffer, edits) in linked_edits {
 4692                buffer.update(cx, |buffer, cx| {
 4693                    let snapshot = buffer.snapshot();
 4694                    let edits = edits
 4695                        .into_iter()
 4696                        .map(|(range, text)| {
 4697                            use text::ToPoint as TP;
 4698                            let end_point = TP::to_point(&range.end, &snapshot);
 4699                            let start_point = TP::to_point(&range.start, &snapshot);
 4700                            (start_point..end_point, text)
 4701                        })
 4702                        .sorted_by_key(|(range, _)| range.start)
 4703                        .collect::<Vec<_>>();
 4704                    buffer.edit(edits, None, cx);
 4705                })
 4706            }
 4707
 4708            this.refresh_inline_completion(true, false, cx);
 4709        });
 4710
 4711        let show_new_completions_on_confirm = completion
 4712            .confirm
 4713            .as_ref()
 4714            .map_or(false, |confirm| confirm(intent, cx));
 4715        if show_new_completions_on_confirm {
 4716            self.show_completions(&ShowCompletions { trigger: None }, cx);
 4717        }
 4718
 4719        let provider = self.completion_provider.as_ref()?;
 4720        let apply_edits = provider.apply_additional_edits_for_completion(
 4721            buffer_handle,
 4722            completion.clone(),
 4723            true,
 4724            cx,
 4725        );
 4726
 4727        let editor_settings = EditorSettings::get_global(cx);
 4728        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4729            // After the code completion is finished, users often want to know what signatures are needed.
 4730            // so we should automatically call signature_help
 4731            self.show_signature_help(&ShowSignatureHelp, cx);
 4732        }
 4733
 4734        Some(cx.foreground_executor().spawn(async move {
 4735            apply_edits.await?;
 4736            Ok(())
 4737        }))
 4738    }
 4739
 4740    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 4741        let mut context_menu = self.context_menu.write();
 4742        if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4743            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4744                // Toggle if we're selecting the same one
 4745                *context_menu = None;
 4746                cx.notify();
 4747                return;
 4748            } else {
 4749                // Otherwise, clear it and start a new one
 4750                *context_menu = None;
 4751                cx.notify();
 4752            }
 4753        }
 4754        drop(context_menu);
 4755        let snapshot = self.snapshot(cx);
 4756        let deployed_from_indicator = action.deployed_from_indicator;
 4757        let mut task = self.code_actions_task.take();
 4758        let action = action.clone();
 4759        cx.spawn(|editor, mut cx| async move {
 4760            while let Some(prev_task) = task {
 4761                prev_task.await.log_err();
 4762                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4763            }
 4764
 4765            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 4766                if editor.focus_handle.is_focused(cx) {
 4767                    let multibuffer_point = action
 4768                        .deployed_from_indicator
 4769                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4770                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4771                    let (buffer, buffer_row) = snapshot
 4772                        .buffer_snapshot
 4773                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4774                        .and_then(|(buffer_snapshot, range)| {
 4775                            editor
 4776                                .buffer
 4777                                .read(cx)
 4778                                .buffer(buffer_snapshot.remote_id())
 4779                                .map(|buffer| (buffer, range.start.row))
 4780                        })?;
 4781                    let (_, code_actions) = editor
 4782                        .available_code_actions
 4783                        .clone()
 4784                        .and_then(|(location, code_actions)| {
 4785                            let snapshot = location.buffer.read(cx).snapshot();
 4786                            let point_range = location.range.to_point(&snapshot);
 4787                            let point_range = point_range.start.row..=point_range.end.row;
 4788                            if point_range.contains(&buffer_row) {
 4789                                Some((location, code_actions))
 4790                            } else {
 4791                                None
 4792                            }
 4793                        })
 4794                        .unzip();
 4795                    let buffer_id = buffer.read(cx).remote_id();
 4796                    let tasks = editor
 4797                        .tasks
 4798                        .get(&(buffer_id, buffer_row))
 4799                        .map(|t| Arc::new(t.to_owned()));
 4800                    if tasks.is_none() && code_actions.is_none() {
 4801                        return None;
 4802                    }
 4803
 4804                    editor.completion_tasks.clear();
 4805                    editor.discard_inline_completion(false, cx);
 4806                    let task_context =
 4807                        tasks
 4808                            .as_ref()
 4809                            .zip(editor.project.clone())
 4810                            .map(|(tasks, project)| {
 4811                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4812                            });
 4813
 4814                    Some(cx.spawn(|editor, mut cx| async move {
 4815                        let task_context = match task_context {
 4816                            Some(task_context) => task_context.await,
 4817                            None => None,
 4818                        };
 4819                        let resolved_tasks =
 4820                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4821                                Arc::new(ResolvedTasks {
 4822                                    templates: tasks.resolve(&task_context).collect(),
 4823                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4824                                        multibuffer_point.row,
 4825                                        tasks.column,
 4826                                    )),
 4827                                })
 4828                            });
 4829                        let spawn_straight_away = resolved_tasks
 4830                            .as_ref()
 4831                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4832                            && code_actions
 4833                                .as_ref()
 4834                                .map_or(true, |actions| actions.is_empty());
 4835                        if let Ok(task) = editor.update(&mut cx, |editor, cx| {
 4836                            *editor.context_menu.write() =
 4837                                Some(ContextMenu::CodeActions(CodeActionsMenu {
 4838                                    buffer,
 4839                                    actions: CodeActionContents {
 4840                                        tasks: resolved_tasks,
 4841                                        actions: code_actions,
 4842                                    },
 4843                                    selected_item: Default::default(),
 4844                                    scroll_handle: UniformListScrollHandle::default(),
 4845                                    deployed_from_indicator,
 4846                                }));
 4847                            if spawn_straight_away {
 4848                                if let Some(task) = editor.confirm_code_action(
 4849                                    &ConfirmCodeAction { item_ix: Some(0) },
 4850                                    cx,
 4851                                ) {
 4852                                    cx.notify();
 4853                                    return task;
 4854                                }
 4855                            }
 4856                            cx.notify();
 4857                            Task::ready(Ok(()))
 4858                        }) {
 4859                            task.await
 4860                        } else {
 4861                            Ok(())
 4862                        }
 4863                    }))
 4864                } else {
 4865                    Some(Task::ready(Ok(())))
 4866                }
 4867            })?;
 4868            if let Some(task) = spawned_test_task {
 4869                task.await?;
 4870            }
 4871
 4872            Ok::<_, anyhow::Error>(())
 4873        })
 4874        .detach_and_log_err(cx);
 4875    }
 4876
 4877    pub fn confirm_code_action(
 4878        &mut self,
 4879        action: &ConfirmCodeAction,
 4880        cx: &mut ViewContext<Self>,
 4881    ) -> Option<Task<Result<()>>> {
 4882        let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4883            menu
 4884        } else {
 4885            return None;
 4886        };
 4887        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4888        let action = actions_menu.actions.get(action_ix)?;
 4889        let title = action.label();
 4890        let buffer = actions_menu.buffer;
 4891        let workspace = self.workspace()?;
 4892
 4893        match action {
 4894            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4895                workspace.update(cx, |workspace, cx| {
 4896                    workspace::tasks::schedule_resolved_task(
 4897                        workspace,
 4898                        task_source_kind,
 4899                        resolved_task,
 4900                        false,
 4901                        cx,
 4902                    );
 4903
 4904                    Some(Task::ready(Ok(())))
 4905                })
 4906            }
 4907            CodeActionsItem::CodeAction {
 4908                excerpt_id,
 4909                action,
 4910                provider,
 4911            } => {
 4912                let apply_code_action =
 4913                    provider.apply_code_action(buffer, action, excerpt_id, true, cx);
 4914                let workspace = workspace.downgrade();
 4915                Some(cx.spawn(|editor, cx| async move {
 4916                    let project_transaction = apply_code_action.await?;
 4917                    Self::open_project_transaction(
 4918                        &editor,
 4919                        workspace,
 4920                        project_transaction,
 4921                        title,
 4922                        cx,
 4923                    )
 4924                    .await
 4925                }))
 4926            }
 4927        }
 4928    }
 4929
 4930    pub async fn open_project_transaction(
 4931        this: &WeakView<Editor>,
 4932        workspace: WeakView<Workspace>,
 4933        transaction: ProjectTransaction,
 4934        title: String,
 4935        mut cx: AsyncWindowContext,
 4936    ) -> Result<()> {
 4937        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4938        cx.update(|cx| {
 4939            entries.sort_unstable_by_key(|(buffer, _)| {
 4940                buffer.read(cx).file().map(|f| f.path().clone())
 4941            });
 4942        })?;
 4943
 4944        // If the project transaction's edits are all contained within this editor, then
 4945        // avoid opening a new editor to display them.
 4946
 4947        if let Some((buffer, transaction)) = entries.first() {
 4948            if entries.len() == 1 {
 4949                let excerpt = this.update(&mut cx, |editor, cx| {
 4950                    editor
 4951                        .buffer()
 4952                        .read(cx)
 4953                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4954                })?;
 4955                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4956                    if excerpted_buffer == *buffer {
 4957                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4958                            let excerpt_range = excerpt_range.to_offset(buffer);
 4959                            buffer
 4960                                .edited_ranges_for_transaction::<usize>(transaction)
 4961                                .all(|range| {
 4962                                    excerpt_range.start <= range.start
 4963                                        && excerpt_range.end >= range.end
 4964                                })
 4965                        })?;
 4966
 4967                        if all_edits_within_excerpt {
 4968                            return Ok(());
 4969                        }
 4970                    }
 4971                }
 4972            }
 4973        } else {
 4974            return Ok(());
 4975        }
 4976
 4977        let mut ranges_to_highlight = Vec::new();
 4978        let excerpt_buffer = cx.new_model(|cx| {
 4979            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4980            for (buffer_handle, transaction) in &entries {
 4981                let buffer = buffer_handle.read(cx);
 4982                ranges_to_highlight.extend(
 4983                    multibuffer.push_excerpts_with_context_lines(
 4984                        buffer_handle.clone(),
 4985                        buffer
 4986                            .edited_ranges_for_transaction::<usize>(transaction)
 4987                            .collect(),
 4988                        DEFAULT_MULTIBUFFER_CONTEXT,
 4989                        cx,
 4990                    ),
 4991                );
 4992            }
 4993            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4994            multibuffer
 4995        })?;
 4996
 4997        workspace.update(&mut cx, |workspace, cx| {
 4998            let project = workspace.project().clone();
 4999            let editor =
 5000                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 5001            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 5002            editor.update(cx, |editor, cx| {
 5003                editor.highlight_background::<Self>(
 5004                    &ranges_to_highlight,
 5005                    |theme| theme.editor_highlighted_line_background,
 5006                    cx,
 5007                );
 5008            });
 5009        })?;
 5010
 5011        Ok(())
 5012    }
 5013
 5014    pub fn clear_code_action_providers(&mut self) {
 5015        self.code_action_providers.clear();
 5016        self.available_code_actions.take();
 5017    }
 5018
 5019    pub fn push_code_action_provider(
 5020        &mut self,
 5021        provider: Arc<dyn CodeActionProvider>,
 5022        cx: &mut ViewContext<Self>,
 5023    ) {
 5024        self.code_action_providers.push(provider);
 5025        self.refresh_code_actions(cx);
 5026    }
 5027
 5028    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 5029        let buffer = self.buffer.read(cx);
 5030        let newest_selection = self.selections.newest_anchor().clone();
 5031        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 5032        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 5033        if start_buffer != end_buffer {
 5034            return None;
 5035        }
 5036
 5037        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 5038            cx.background_executor()
 5039                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 5040                .await;
 5041
 5042            let (providers, tasks) = this.update(&mut cx, |this, cx| {
 5043                let providers = this.code_action_providers.clone();
 5044                let tasks = this
 5045                    .code_action_providers
 5046                    .iter()
 5047                    .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
 5048                    .collect::<Vec<_>>();
 5049                (providers, tasks)
 5050            })?;
 5051
 5052            let mut actions = Vec::new();
 5053            for (provider, provider_actions) in
 5054                providers.into_iter().zip(future::join_all(tasks).await)
 5055            {
 5056                if let Some(provider_actions) = provider_actions.log_err() {
 5057                    actions.extend(provider_actions.into_iter().map(|action| {
 5058                        AvailableCodeAction {
 5059                            excerpt_id: newest_selection.start.excerpt_id,
 5060                            action,
 5061                            provider: provider.clone(),
 5062                        }
 5063                    }));
 5064                }
 5065            }
 5066
 5067            this.update(&mut cx, |this, cx| {
 5068                this.available_code_actions = if actions.is_empty() {
 5069                    None
 5070                } else {
 5071                    Some((
 5072                        Location {
 5073                            buffer: start_buffer,
 5074                            range: start..end,
 5075                        },
 5076                        actions.into(),
 5077                    ))
 5078                };
 5079                cx.notify();
 5080            })
 5081        }));
 5082        None
 5083    }
 5084
 5085    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 5086        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 5087            self.show_git_blame_inline = false;
 5088
 5089            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 5090                cx.background_executor().timer(delay).await;
 5091
 5092                this.update(&mut cx, |this, cx| {
 5093                    this.show_git_blame_inline = true;
 5094                    cx.notify();
 5095                })
 5096                .log_err();
 5097            }));
 5098        }
 5099    }
 5100
 5101    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 5102        if self.pending_rename.is_some() {
 5103            return None;
 5104        }
 5105
 5106        let provider = self.semantics_provider.clone()?;
 5107        let buffer = self.buffer.read(cx);
 5108        let newest_selection = self.selections.newest_anchor().clone();
 5109        let cursor_position = newest_selection.head();
 5110        let (cursor_buffer, cursor_buffer_position) =
 5111            buffer.text_anchor_for_position(cursor_position, cx)?;
 5112        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 5113        if cursor_buffer != tail_buffer {
 5114            return None;
 5115        }
 5116
 5117        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 5118            cx.background_executor()
 5119                .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
 5120                .await;
 5121
 5122            let highlights = if let Some(highlights) = cx
 5123                .update(|cx| {
 5124                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 5125                })
 5126                .ok()
 5127                .flatten()
 5128            {
 5129                highlights.await.log_err()
 5130            } else {
 5131                None
 5132            };
 5133
 5134            if let Some(highlights) = highlights {
 5135                this.update(&mut cx, |this, cx| {
 5136                    if this.pending_rename.is_some() {
 5137                        return;
 5138                    }
 5139
 5140                    let buffer_id = cursor_position.buffer_id;
 5141                    let buffer = this.buffer.read(cx);
 5142                    if !buffer
 5143                        .text_anchor_for_position(cursor_position, cx)
 5144                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 5145                    {
 5146                        return;
 5147                    }
 5148
 5149                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 5150                    let mut write_ranges = Vec::new();
 5151                    let mut read_ranges = Vec::new();
 5152                    for highlight in highlights {
 5153                        for (excerpt_id, excerpt_range) in
 5154                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 5155                        {
 5156                            let start = highlight
 5157                                .range
 5158                                .start
 5159                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 5160                            let end = highlight
 5161                                .range
 5162                                .end
 5163                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 5164                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 5165                                continue;
 5166                            }
 5167
 5168                            let range = Anchor {
 5169                                buffer_id,
 5170                                excerpt_id,
 5171                                text_anchor: start,
 5172                            }..Anchor {
 5173                                buffer_id,
 5174                                excerpt_id,
 5175                                text_anchor: end,
 5176                            };
 5177                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 5178                                write_ranges.push(range);
 5179                            } else {
 5180                                read_ranges.push(range);
 5181                            }
 5182                        }
 5183                    }
 5184
 5185                    this.highlight_background::<DocumentHighlightRead>(
 5186                        &read_ranges,
 5187                        |theme| theme.editor_document_highlight_read_background,
 5188                        cx,
 5189                    );
 5190                    this.highlight_background::<DocumentHighlightWrite>(
 5191                        &write_ranges,
 5192                        |theme| theme.editor_document_highlight_write_background,
 5193                        cx,
 5194                    );
 5195                    cx.notify();
 5196                })
 5197                .log_err();
 5198            }
 5199        }));
 5200        None
 5201    }
 5202
 5203    pub fn refresh_inline_completion(
 5204        &mut self,
 5205        debounce: bool,
 5206        user_requested: bool,
 5207        cx: &mut ViewContext<Self>,
 5208    ) -> Option<()> {
 5209        let provider = self.inline_completion_provider()?;
 5210        let cursor = self.selections.newest_anchor().head();
 5211        let (buffer, cursor_buffer_position) =
 5212            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5213
 5214        if !user_requested
 5215            && (!self.enable_inline_completions
 5216                || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx))
 5217        {
 5218            self.discard_inline_completion(false, cx);
 5219            return None;
 5220        }
 5221
 5222        self.update_visible_inline_completion(cx);
 5223        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 5224        Some(())
 5225    }
 5226
 5227    fn cycle_inline_completion(
 5228        &mut self,
 5229        direction: Direction,
 5230        cx: &mut ViewContext<Self>,
 5231    ) -> Option<()> {
 5232        let provider = self.inline_completion_provider()?;
 5233        let cursor = self.selections.newest_anchor().head();
 5234        let (buffer, cursor_buffer_position) =
 5235            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5236        if !self.enable_inline_completions
 5237            || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 5238        {
 5239            return None;
 5240        }
 5241
 5242        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5243        self.update_visible_inline_completion(cx);
 5244
 5245        Some(())
 5246    }
 5247
 5248    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 5249        if !self.has_active_inline_completion(cx) {
 5250            self.refresh_inline_completion(false, true, cx);
 5251            return;
 5252        }
 5253
 5254        self.update_visible_inline_completion(cx);
 5255    }
 5256
 5257    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 5258        self.show_cursor_names(cx);
 5259    }
 5260
 5261    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 5262        self.show_cursor_names = true;
 5263        cx.notify();
 5264        cx.spawn(|this, mut cx| async move {
 5265            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5266            this.update(&mut cx, |this, cx| {
 5267                this.show_cursor_names = false;
 5268                cx.notify()
 5269            })
 5270            .ok()
 5271        })
 5272        .detach();
 5273    }
 5274
 5275    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 5276        if self.has_active_inline_completion(cx) {
 5277            self.cycle_inline_completion(Direction::Next, cx);
 5278        } else {
 5279            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5280            if is_copilot_disabled {
 5281                cx.propagate();
 5282            }
 5283        }
 5284    }
 5285
 5286    pub fn previous_inline_completion(
 5287        &mut self,
 5288        _: &PreviousInlineCompletion,
 5289        cx: &mut ViewContext<Self>,
 5290    ) {
 5291        if self.has_active_inline_completion(cx) {
 5292            self.cycle_inline_completion(Direction::Prev, cx);
 5293        } else {
 5294            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5295            if is_copilot_disabled {
 5296                cx.propagate();
 5297            }
 5298        }
 5299    }
 5300
 5301    pub fn accept_inline_completion(
 5302        &mut self,
 5303        _: &AcceptInlineCompletion,
 5304        cx: &mut ViewContext<Self>,
 5305    ) {
 5306        let Some(completion) = self.take_active_inline_completion(cx) else {
 5307            return;
 5308        };
 5309        if let Some(provider) = self.inline_completion_provider() {
 5310            provider.accept(cx);
 5311        }
 5312
 5313        cx.emit(EditorEvent::InputHandled {
 5314            utf16_range_to_replace: None,
 5315            text: completion.text.to_string().into(),
 5316        });
 5317
 5318        if let Some(range) = completion.delete_range {
 5319            self.change_selections(None, cx, |s| s.select_ranges([range]))
 5320        }
 5321        self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
 5322        self.refresh_inline_completion(true, true, cx);
 5323        cx.notify();
 5324    }
 5325
 5326    pub fn accept_partial_inline_completion(
 5327        &mut self,
 5328        _: &AcceptPartialInlineCompletion,
 5329        cx: &mut ViewContext<Self>,
 5330    ) {
 5331        if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
 5332            if let Some(completion) = self.take_active_inline_completion(cx) {
 5333                let mut partial_completion = completion
 5334                    .text
 5335                    .chars()
 5336                    .by_ref()
 5337                    .take_while(|c| c.is_alphabetic())
 5338                    .collect::<String>();
 5339                if partial_completion.is_empty() {
 5340                    partial_completion = completion
 5341                        .text
 5342                        .chars()
 5343                        .by_ref()
 5344                        .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5345                        .collect::<String>();
 5346                }
 5347
 5348                cx.emit(EditorEvent::InputHandled {
 5349                    utf16_range_to_replace: None,
 5350                    text: partial_completion.clone().into(),
 5351                });
 5352
 5353                if let Some(range) = completion.delete_range {
 5354                    self.change_selections(None, cx, |s| s.select_ranges([range]))
 5355                }
 5356                self.insert_with_autoindent_mode(&partial_completion, None, cx);
 5357
 5358                self.refresh_inline_completion(true, true, cx);
 5359                cx.notify();
 5360            }
 5361        }
 5362    }
 5363
 5364    fn discard_inline_completion(
 5365        &mut self,
 5366        should_report_inline_completion_event: bool,
 5367        cx: &mut ViewContext<Self>,
 5368    ) -> bool {
 5369        if let Some(provider) = self.inline_completion_provider() {
 5370            provider.discard(should_report_inline_completion_event, cx);
 5371        }
 5372
 5373        self.take_active_inline_completion(cx).is_some()
 5374    }
 5375
 5376    pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
 5377        if let Some(completion) = self.active_inline_completion.as_ref() {
 5378            let buffer = self.buffer.read(cx).read(cx);
 5379            completion.position.is_valid(&buffer)
 5380        } else {
 5381            false
 5382        }
 5383    }
 5384
 5385    fn take_active_inline_completion(
 5386        &mut self,
 5387        cx: &mut ViewContext<Self>,
 5388    ) -> Option<CompletionState> {
 5389        let completion = self.active_inline_completion.take()?;
 5390        let render_inlay_ids = completion.render_inlay_ids.clone();
 5391        self.display_map.update(cx, |map, cx| {
 5392            map.splice_inlays(render_inlay_ids, Default::default(), cx);
 5393        });
 5394        let buffer = self.buffer.read(cx).read(cx);
 5395
 5396        if completion.position.is_valid(&buffer) {
 5397            Some(completion)
 5398        } else {
 5399            None
 5400        }
 5401    }
 5402
 5403    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
 5404        let selection = self.selections.newest_anchor();
 5405        let cursor = selection.head();
 5406
 5407        let excerpt_id = cursor.excerpt_id;
 5408
 5409        if self.context_menu.read().is_none()
 5410            && self.completion_tasks.is_empty()
 5411            && selection.start == selection.end
 5412        {
 5413            if let Some(provider) = self.inline_completion_provider() {
 5414                if let Some((buffer, cursor_buffer_position)) =
 5415                    self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5416                {
 5417                    if let Some(proposal) =
 5418                        provider.active_completion_text(&buffer, cursor_buffer_position, cx)
 5419                    {
 5420                        let mut to_remove = Vec::new();
 5421                        if let Some(completion) = self.active_inline_completion.take() {
 5422                            to_remove.extend(completion.render_inlay_ids.iter());
 5423                        }
 5424
 5425                        let to_add = proposal
 5426                            .inlays
 5427                            .iter()
 5428                            .filter_map(|inlay| {
 5429                                let snapshot = self.buffer.read(cx).snapshot(cx);
 5430                                let id = post_inc(&mut self.next_inlay_id);
 5431                                match inlay {
 5432                                    InlayProposal::Hint(position, hint) => {
 5433                                        let position =
 5434                                            snapshot.anchor_in_excerpt(excerpt_id, *position)?;
 5435                                        Some(Inlay::hint(id, position, hint))
 5436                                    }
 5437                                    InlayProposal::Suggestion(position, text) => {
 5438                                        let position =
 5439                                            snapshot.anchor_in_excerpt(excerpt_id, *position)?;
 5440                                        Some(Inlay::suggestion(id, position, text.clone()))
 5441                                    }
 5442                                }
 5443                            })
 5444                            .collect_vec();
 5445
 5446                        self.active_inline_completion = Some(CompletionState {
 5447                            position: cursor,
 5448                            text: proposal.text,
 5449                            delete_range: proposal.delete_range.and_then(|range| {
 5450                                let snapshot = self.buffer.read(cx).snapshot(cx);
 5451                                let start = snapshot.anchor_in_excerpt(excerpt_id, range.start);
 5452                                let end = snapshot.anchor_in_excerpt(excerpt_id, range.end);
 5453                                Some(start?..end?)
 5454                            }),
 5455                            render_inlay_ids: to_add.iter().map(|i| i.id).collect(),
 5456                        });
 5457
 5458                        self.display_map
 5459                            .update(cx, move |map, cx| map.splice_inlays(to_remove, to_add, cx));
 5460
 5461                        cx.notify();
 5462                        return;
 5463                    }
 5464                }
 5465            }
 5466        }
 5467
 5468        self.discard_inline_completion(false, cx);
 5469    }
 5470
 5471    fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5472        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 5473    }
 5474
 5475    fn render_code_actions_indicator(
 5476        &self,
 5477        _style: &EditorStyle,
 5478        row: DisplayRow,
 5479        is_active: bool,
 5480        cx: &mut ViewContext<Self>,
 5481    ) -> Option<IconButton> {
 5482        if self.available_code_actions.is_some() {
 5483            Some(
 5484                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5485                    .shape(ui::IconButtonShape::Square)
 5486                    .icon_size(IconSize::XSmall)
 5487                    .icon_color(Color::Muted)
 5488                    .selected(is_active)
 5489                    .tooltip({
 5490                        let focus_handle = self.focus_handle.clone();
 5491                        move |cx| {
 5492                            Tooltip::for_action_in(
 5493                                "Toggle Code Actions",
 5494                                &ToggleCodeActions {
 5495                                    deployed_from_indicator: None,
 5496                                },
 5497                                &focus_handle,
 5498                                cx,
 5499                            )
 5500                        }
 5501                    })
 5502                    .on_click(cx.listener(move |editor, _e, cx| {
 5503                        editor.focus(cx);
 5504                        editor.toggle_code_actions(
 5505                            &ToggleCodeActions {
 5506                                deployed_from_indicator: Some(row),
 5507                            },
 5508                            cx,
 5509                        );
 5510                    })),
 5511            )
 5512        } else {
 5513            None
 5514        }
 5515    }
 5516
 5517    fn clear_tasks(&mut self) {
 5518        self.tasks.clear()
 5519    }
 5520
 5521    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5522        if self.tasks.insert(key, value).is_some() {
 5523            // This case should hopefully be rare, but just in case...
 5524            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5525        }
 5526    }
 5527
 5528    fn build_tasks_context(
 5529        project: &Model<Project>,
 5530        buffer: &Model<Buffer>,
 5531        buffer_row: u32,
 5532        tasks: &Arc<RunnableTasks>,
 5533        cx: &mut ViewContext<Self>,
 5534    ) -> Task<Option<task::TaskContext>> {
 5535        let position = Point::new(buffer_row, tasks.column);
 5536        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5537        let location = Location {
 5538            buffer: buffer.clone(),
 5539            range: range_start..range_start,
 5540        };
 5541        // Fill in the environmental variables from the tree-sitter captures
 5542        let mut captured_task_variables = TaskVariables::default();
 5543        for (capture_name, value) in tasks.extra_variables.clone() {
 5544            captured_task_variables.insert(
 5545                task::VariableName::Custom(capture_name.into()),
 5546                value.clone(),
 5547            );
 5548        }
 5549        project.update(cx, |project, cx| {
 5550            project.task_store().update(cx, |task_store, cx| {
 5551                task_store.task_context_for_location(captured_task_variables, location, cx)
 5552            })
 5553        })
 5554    }
 5555
 5556    pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
 5557        let Some((workspace, _)) = self.workspace.clone() else {
 5558            return;
 5559        };
 5560        let Some(project) = self.project.clone() else {
 5561            return;
 5562        };
 5563
 5564        // Try to find a closest, enclosing node using tree-sitter that has a
 5565        // task
 5566        let Some((buffer, buffer_row, tasks)) = self
 5567            .find_enclosing_node_task(cx)
 5568            // Or find the task that's closest in row-distance.
 5569            .or_else(|| self.find_closest_task(cx))
 5570        else {
 5571            return;
 5572        };
 5573
 5574        let reveal_strategy = action.reveal;
 5575        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5576        cx.spawn(|_, mut cx| async move {
 5577            let context = task_context.await?;
 5578            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5579
 5580            let resolved = resolved_task.resolved.as_mut()?;
 5581            resolved.reveal = reveal_strategy;
 5582
 5583            workspace
 5584                .update(&mut cx, |workspace, cx| {
 5585                    workspace::tasks::schedule_resolved_task(
 5586                        workspace,
 5587                        task_source_kind,
 5588                        resolved_task,
 5589                        false,
 5590                        cx,
 5591                    );
 5592                })
 5593                .ok()
 5594        })
 5595        .detach();
 5596    }
 5597
 5598    fn find_closest_task(
 5599        &mut self,
 5600        cx: &mut ViewContext<Self>,
 5601    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5602        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5603
 5604        let ((buffer_id, row), tasks) = self
 5605            .tasks
 5606            .iter()
 5607            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5608
 5609        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5610        let tasks = Arc::new(tasks.to_owned());
 5611        Some((buffer, *row, tasks))
 5612    }
 5613
 5614    fn find_enclosing_node_task(
 5615        &mut self,
 5616        cx: &mut ViewContext<Self>,
 5617    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5618        let snapshot = self.buffer.read(cx).snapshot(cx);
 5619        let offset = self.selections.newest::<usize>(cx).head();
 5620        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5621        let buffer_id = excerpt.buffer().remote_id();
 5622
 5623        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5624        let mut cursor = layer.node().walk();
 5625
 5626        while cursor.goto_first_child_for_byte(offset).is_some() {
 5627            if cursor.node().end_byte() == offset {
 5628                cursor.goto_next_sibling();
 5629            }
 5630        }
 5631
 5632        // Ascend to the smallest ancestor that contains the range and has a task.
 5633        loop {
 5634            let node = cursor.node();
 5635            let node_range = node.byte_range();
 5636            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5637
 5638            // Check if this node contains our offset
 5639            if node_range.start <= offset && node_range.end >= offset {
 5640                // If it contains offset, check for task
 5641                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5642                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5643                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5644                }
 5645            }
 5646
 5647            if !cursor.goto_parent() {
 5648                break;
 5649            }
 5650        }
 5651        None
 5652    }
 5653
 5654    fn render_run_indicator(
 5655        &self,
 5656        _style: &EditorStyle,
 5657        is_active: bool,
 5658        row: DisplayRow,
 5659        cx: &mut ViewContext<Self>,
 5660    ) -> IconButton {
 5661        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5662            .shape(ui::IconButtonShape::Square)
 5663            .icon_size(IconSize::XSmall)
 5664            .icon_color(Color::Muted)
 5665            .selected(is_active)
 5666            .on_click(cx.listener(move |editor, _e, cx| {
 5667                editor.focus(cx);
 5668                editor.toggle_code_actions(
 5669                    &ToggleCodeActions {
 5670                        deployed_from_indicator: Some(row),
 5671                    },
 5672                    cx,
 5673                );
 5674            }))
 5675    }
 5676
 5677    pub fn context_menu_visible(&self) -> bool {
 5678        self.context_menu
 5679            .read()
 5680            .as_ref()
 5681            .map_or(false, |menu| menu.visible())
 5682    }
 5683
 5684    fn render_context_menu(
 5685        &self,
 5686        cursor_position: DisplayPoint,
 5687        style: &EditorStyle,
 5688        max_height: Pixels,
 5689        cx: &mut ViewContext<Editor>,
 5690    ) -> Option<(ContextMenuOrigin, AnyElement)> {
 5691        self.context_menu.read().as_ref().map(|menu| {
 5692            menu.render(
 5693                cursor_position,
 5694                style,
 5695                max_height,
 5696                self.workspace.as_ref().map(|(w, _)| w.clone()),
 5697                cx,
 5698            )
 5699        })
 5700    }
 5701
 5702    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
 5703        cx.notify();
 5704        self.completion_tasks.clear();
 5705        let context_menu = self.context_menu.write().take();
 5706        if context_menu.is_some() {
 5707            self.update_visible_inline_completion(cx);
 5708        }
 5709        context_menu
 5710    }
 5711
 5712    fn show_snippet_choices(
 5713        &mut self,
 5714        choices: &Vec<String>,
 5715        selection: Range<Anchor>,
 5716        cx: &mut ViewContext<Self>,
 5717    ) {
 5718        if selection.start.buffer_id.is_none() {
 5719            return;
 5720        }
 5721        let buffer_id = selection.start.buffer_id.unwrap();
 5722        let buffer = self.buffer().read(cx).buffer(buffer_id);
 5723        let id = post_inc(&mut self.next_completion_id);
 5724
 5725        if let Some(buffer) = buffer {
 5726            *self.context_menu.write() = Some(ContextMenu::Completions(
 5727                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer)
 5728                    .suppress_documentation_resolution(),
 5729            ));
 5730        }
 5731    }
 5732
 5733    pub fn insert_snippet(
 5734        &mut self,
 5735        insertion_ranges: &[Range<usize>],
 5736        snippet: Snippet,
 5737        cx: &mut ViewContext<Self>,
 5738    ) -> Result<()> {
 5739        struct Tabstop<T> {
 5740            is_end_tabstop: bool,
 5741            ranges: Vec<Range<T>>,
 5742            choices: Option<Vec<String>>,
 5743        }
 5744
 5745        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5746            let snippet_text: Arc<str> = snippet.text.clone().into();
 5747            buffer.edit(
 5748                insertion_ranges
 5749                    .iter()
 5750                    .cloned()
 5751                    .map(|range| (range, snippet_text.clone())),
 5752                Some(AutoindentMode::EachLine),
 5753                cx,
 5754            );
 5755
 5756            let snapshot = &*buffer.read(cx);
 5757            let snippet = &snippet;
 5758            snippet
 5759                .tabstops
 5760                .iter()
 5761                .map(|tabstop| {
 5762                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 5763                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5764                    });
 5765                    let mut tabstop_ranges = tabstop
 5766                        .ranges
 5767                        .iter()
 5768                        .flat_map(|tabstop_range| {
 5769                            let mut delta = 0_isize;
 5770                            insertion_ranges.iter().map(move |insertion_range| {
 5771                                let insertion_start = insertion_range.start as isize + delta;
 5772                                delta +=
 5773                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5774
 5775                                let start = ((insertion_start + tabstop_range.start) as usize)
 5776                                    .min(snapshot.len());
 5777                                let end = ((insertion_start + tabstop_range.end) as usize)
 5778                                    .min(snapshot.len());
 5779                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5780                            })
 5781                        })
 5782                        .collect::<Vec<_>>();
 5783                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5784
 5785                    Tabstop {
 5786                        is_end_tabstop,
 5787                        ranges: tabstop_ranges,
 5788                        choices: tabstop.choices.clone(),
 5789                    }
 5790                })
 5791                .collect::<Vec<_>>()
 5792        });
 5793        if let Some(tabstop) = tabstops.first() {
 5794            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5795                s.select_ranges(tabstop.ranges.iter().cloned());
 5796            });
 5797
 5798            if let Some(choices) = &tabstop.choices {
 5799                if let Some(selection) = tabstop.ranges.first() {
 5800                    self.show_snippet_choices(choices, selection.clone(), cx)
 5801                }
 5802            }
 5803
 5804            // If we're already at the last tabstop and it's at the end of the snippet,
 5805            // we're done, we don't need to keep the state around.
 5806            if !tabstop.is_end_tabstop {
 5807                let choices = tabstops
 5808                    .iter()
 5809                    .map(|tabstop| tabstop.choices.clone())
 5810                    .collect();
 5811
 5812                let ranges = tabstops
 5813                    .into_iter()
 5814                    .map(|tabstop| tabstop.ranges)
 5815                    .collect::<Vec<_>>();
 5816
 5817                self.snippet_stack.push(SnippetState {
 5818                    active_index: 0,
 5819                    ranges,
 5820                    choices,
 5821                });
 5822            }
 5823
 5824            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5825            if self.autoclose_regions.is_empty() {
 5826                let snapshot = self.buffer.read(cx).snapshot(cx);
 5827                for selection in &mut self.selections.all::<Point>(cx) {
 5828                    let selection_head = selection.head();
 5829                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5830                        continue;
 5831                    };
 5832
 5833                    let mut bracket_pair = None;
 5834                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5835                    let prev_chars = snapshot
 5836                        .reversed_chars_at(selection_head)
 5837                        .collect::<String>();
 5838                    for (pair, enabled) in scope.brackets() {
 5839                        if enabled
 5840                            && pair.close
 5841                            && prev_chars.starts_with(pair.start.as_str())
 5842                            && next_chars.starts_with(pair.end.as_str())
 5843                        {
 5844                            bracket_pair = Some(pair.clone());
 5845                            break;
 5846                        }
 5847                    }
 5848                    if let Some(pair) = bracket_pair {
 5849                        let start = snapshot.anchor_after(selection_head);
 5850                        let end = snapshot.anchor_after(selection_head);
 5851                        self.autoclose_regions.push(AutocloseRegion {
 5852                            selection_id: selection.id,
 5853                            range: start..end,
 5854                            pair,
 5855                        });
 5856                    }
 5857                }
 5858            }
 5859        }
 5860        Ok(())
 5861    }
 5862
 5863    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5864        self.move_to_snippet_tabstop(Bias::Right, cx)
 5865    }
 5866
 5867    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5868        self.move_to_snippet_tabstop(Bias::Left, cx)
 5869    }
 5870
 5871    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5872        if let Some(mut snippet) = self.snippet_stack.pop() {
 5873            match bias {
 5874                Bias::Left => {
 5875                    if snippet.active_index > 0 {
 5876                        snippet.active_index -= 1;
 5877                    } else {
 5878                        self.snippet_stack.push(snippet);
 5879                        return false;
 5880                    }
 5881                }
 5882                Bias::Right => {
 5883                    if snippet.active_index + 1 < snippet.ranges.len() {
 5884                        snippet.active_index += 1;
 5885                    } else {
 5886                        self.snippet_stack.push(snippet);
 5887                        return false;
 5888                    }
 5889                }
 5890            }
 5891            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5892                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5893                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5894                });
 5895
 5896                if let Some(choices) = &snippet.choices[snippet.active_index] {
 5897                    if let Some(selection) = current_ranges.first() {
 5898                        self.show_snippet_choices(&choices, selection.clone(), cx);
 5899                    }
 5900                }
 5901
 5902                // If snippet state is not at the last tabstop, push it back on the stack
 5903                if snippet.active_index + 1 < snippet.ranges.len() {
 5904                    self.snippet_stack.push(snippet);
 5905                }
 5906                return true;
 5907            }
 5908        }
 5909
 5910        false
 5911    }
 5912
 5913    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 5914        self.transact(cx, |this, cx| {
 5915            this.select_all(&SelectAll, cx);
 5916            this.insert("", cx);
 5917        });
 5918    }
 5919
 5920    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 5921        self.transact(cx, |this, cx| {
 5922            this.select_autoclose_pair(cx);
 5923            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5924            if !this.linked_edit_ranges.is_empty() {
 5925                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5926                let snapshot = this.buffer.read(cx).snapshot(cx);
 5927
 5928                for selection in selections.iter() {
 5929                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5930                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 5931                    if selection_start.buffer_id != selection_end.buffer_id {
 5932                        continue;
 5933                    }
 5934                    if let Some(ranges) =
 5935                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 5936                    {
 5937                        for (buffer, entries) in ranges {
 5938                            linked_ranges.entry(buffer).or_default().extend(entries);
 5939                        }
 5940                    }
 5941                }
 5942            }
 5943
 5944            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 5945            if !this.selections.line_mode {
 5946                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 5947                for selection in &mut selections {
 5948                    if selection.is_empty() {
 5949                        let old_head = selection.head();
 5950                        let mut new_head =
 5951                            movement::left(&display_map, old_head.to_display_point(&display_map))
 5952                                .to_point(&display_map);
 5953                        if let Some((buffer, line_buffer_range)) = display_map
 5954                            .buffer_snapshot
 5955                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 5956                        {
 5957                            let indent_size =
 5958                                buffer.indent_size_for_line(line_buffer_range.start.row);
 5959                            let indent_len = match indent_size.kind {
 5960                                IndentKind::Space => {
 5961                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 5962                                }
 5963                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 5964                            };
 5965                            if old_head.column <= indent_size.len && old_head.column > 0 {
 5966                                let indent_len = indent_len.get();
 5967                                new_head = cmp::min(
 5968                                    new_head,
 5969                                    MultiBufferPoint::new(
 5970                                        old_head.row,
 5971                                        ((old_head.column - 1) / indent_len) * indent_len,
 5972                                    ),
 5973                                );
 5974                            }
 5975                        }
 5976
 5977                        selection.set_head(new_head, SelectionGoal::None);
 5978                    }
 5979                }
 5980            }
 5981
 5982            this.signature_help_state.set_backspace_pressed(true);
 5983            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5984            this.insert("", cx);
 5985            let empty_str: Arc<str> = Arc::from("");
 5986            for (buffer, edits) in linked_ranges {
 5987                let snapshot = buffer.read(cx).snapshot();
 5988                use text::ToPoint as TP;
 5989
 5990                let edits = edits
 5991                    .into_iter()
 5992                    .map(|range| {
 5993                        let end_point = TP::to_point(&range.end, &snapshot);
 5994                        let mut start_point = TP::to_point(&range.start, &snapshot);
 5995
 5996                        if end_point == start_point {
 5997                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 5998                                .saturating_sub(1);
 5999                            start_point = TP::to_point(&offset, &snapshot);
 6000                        };
 6001
 6002                        (start_point..end_point, empty_str.clone())
 6003                    })
 6004                    .sorted_by_key(|(range, _)| range.start)
 6005                    .collect::<Vec<_>>();
 6006                buffer.update(cx, |this, cx| {
 6007                    this.edit(edits, None, cx);
 6008                })
 6009            }
 6010            this.refresh_inline_completion(true, false, cx);
 6011            linked_editing_ranges::refresh_linked_ranges(this, cx);
 6012        });
 6013    }
 6014
 6015    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 6016        self.transact(cx, |this, cx| {
 6017            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6018                let line_mode = s.line_mode;
 6019                s.move_with(|map, selection| {
 6020                    if selection.is_empty() && !line_mode {
 6021                        let cursor = movement::right(map, selection.head());
 6022                        selection.end = cursor;
 6023                        selection.reversed = true;
 6024                        selection.goal = SelectionGoal::None;
 6025                    }
 6026                })
 6027            });
 6028            this.insert("", cx);
 6029            this.refresh_inline_completion(true, false, cx);
 6030        });
 6031    }
 6032
 6033    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 6034        if self.move_to_prev_snippet_tabstop(cx) {
 6035            return;
 6036        }
 6037
 6038        self.outdent(&Outdent, cx);
 6039    }
 6040
 6041    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 6042        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 6043            return;
 6044        }
 6045
 6046        let mut selections = self.selections.all_adjusted(cx);
 6047        let buffer = self.buffer.read(cx);
 6048        let snapshot = buffer.snapshot(cx);
 6049        let rows_iter = selections.iter().map(|s| s.head().row);
 6050        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 6051
 6052        let mut edits = Vec::new();
 6053        let mut prev_edited_row = 0;
 6054        let mut row_delta = 0;
 6055        for selection in &mut selections {
 6056            if selection.start.row != prev_edited_row {
 6057                row_delta = 0;
 6058            }
 6059            prev_edited_row = selection.end.row;
 6060
 6061            // If the selection is non-empty, then increase the indentation of the selected lines.
 6062            if !selection.is_empty() {
 6063                row_delta =
 6064                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6065                continue;
 6066            }
 6067
 6068            // If the selection is empty and the cursor is in the leading whitespace before the
 6069            // suggested indentation, then auto-indent the line.
 6070            let cursor = selection.head();
 6071            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 6072            if let Some(suggested_indent) =
 6073                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 6074            {
 6075                if cursor.column < suggested_indent.len
 6076                    && cursor.column <= current_indent.len
 6077                    && current_indent.len <= suggested_indent.len
 6078                {
 6079                    selection.start = Point::new(cursor.row, suggested_indent.len);
 6080                    selection.end = selection.start;
 6081                    if row_delta == 0 {
 6082                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 6083                            cursor.row,
 6084                            current_indent,
 6085                            suggested_indent,
 6086                        ));
 6087                        row_delta = suggested_indent.len - current_indent.len;
 6088                    }
 6089                    continue;
 6090                }
 6091            }
 6092
 6093            // Otherwise, insert a hard or soft tab.
 6094            let settings = buffer.settings_at(cursor, cx);
 6095            let tab_size = if settings.hard_tabs {
 6096                IndentSize::tab()
 6097            } else {
 6098                let tab_size = settings.tab_size.get();
 6099                let char_column = snapshot
 6100                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 6101                    .flat_map(str::chars)
 6102                    .count()
 6103                    + row_delta as usize;
 6104                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 6105                IndentSize::spaces(chars_to_next_tab_stop)
 6106            };
 6107            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 6108            selection.end = selection.start;
 6109            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 6110            row_delta += tab_size.len;
 6111        }
 6112
 6113        self.transact(cx, |this, cx| {
 6114            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6115            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6116            this.refresh_inline_completion(true, false, cx);
 6117        });
 6118    }
 6119
 6120    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 6121        if self.read_only(cx) {
 6122            return;
 6123        }
 6124        let mut selections = self.selections.all::<Point>(cx);
 6125        let mut prev_edited_row = 0;
 6126        let mut row_delta = 0;
 6127        let mut edits = Vec::new();
 6128        let buffer = self.buffer.read(cx);
 6129        let snapshot = buffer.snapshot(cx);
 6130        for selection in &mut selections {
 6131            if selection.start.row != prev_edited_row {
 6132                row_delta = 0;
 6133            }
 6134            prev_edited_row = selection.end.row;
 6135
 6136            row_delta =
 6137                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6138        }
 6139
 6140        self.transact(cx, |this, cx| {
 6141            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6142            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6143        });
 6144    }
 6145
 6146    fn indent_selection(
 6147        buffer: &MultiBuffer,
 6148        snapshot: &MultiBufferSnapshot,
 6149        selection: &mut Selection<Point>,
 6150        edits: &mut Vec<(Range<Point>, String)>,
 6151        delta_for_start_row: u32,
 6152        cx: &AppContext,
 6153    ) -> u32 {
 6154        let settings = buffer.settings_at(selection.start, cx);
 6155        let tab_size = settings.tab_size.get();
 6156        let indent_kind = if settings.hard_tabs {
 6157            IndentKind::Tab
 6158        } else {
 6159            IndentKind::Space
 6160        };
 6161        let mut start_row = selection.start.row;
 6162        let mut end_row = selection.end.row + 1;
 6163
 6164        // If a selection ends at the beginning of a line, don't indent
 6165        // that last line.
 6166        if selection.end.column == 0 && selection.end.row > selection.start.row {
 6167            end_row -= 1;
 6168        }
 6169
 6170        // Avoid re-indenting a row that has already been indented by a
 6171        // previous selection, but still update this selection's column
 6172        // to reflect that indentation.
 6173        if delta_for_start_row > 0 {
 6174            start_row += 1;
 6175            selection.start.column += delta_for_start_row;
 6176            if selection.end.row == selection.start.row {
 6177                selection.end.column += delta_for_start_row;
 6178            }
 6179        }
 6180
 6181        let mut delta_for_end_row = 0;
 6182        let has_multiple_rows = start_row + 1 != end_row;
 6183        for row in start_row..end_row {
 6184            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 6185            let indent_delta = match (current_indent.kind, indent_kind) {
 6186                (IndentKind::Space, IndentKind::Space) => {
 6187                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 6188                    IndentSize::spaces(columns_to_next_tab_stop)
 6189                }
 6190                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 6191                (_, IndentKind::Tab) => IndentSize::tab(),
 6192            };
 6193
 6194            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 6195                0
 6196            } else {
 6197                selection.start.column
 6198            };
 6199            let row_start = Point::new(row, start);
 6200            edits.push((
 6201                row_start..row_start,
 6202                indent_delta.chars().collect::<String>(),
 6203            ));
 6204
 6205            // Update this selection's endpoints to reflect the indentation.
 6206            if row == selection.start.row {
 6207                selection.start.column += indent_delta.len;
 6208            }
 6209            if row == selection.end.row {
 6210                selection.end.column += indent_delta.len;
 6211                delta_for_end_row = indent_delta.len;
 6212            }
 6213        }
 6214
 6215        if selection.start.row == selection.end.row {
 6216            delta_for_start_row + delta_for_end_row
 6217        } else {
 6218            delta_for_end_row
 6219        }
 6220    }
 6221
 6222    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 6223        if self.read_only(cx) {
 6224            return;
 6225        }
 6226        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6227        let selections = self.selections.all::<Point>(cx);
 6228        let mut deletion_ranges = Vec::new();
 6229        let mut last_outdent = None;
 6230        {
 6231            let buffer = self.buffer.read(cx);
 6232            let snapshot = buffer.snapshot(cx);
 6233            for selection in &selections {
 6234                let settings = buffer.settings_at(selection.start, cx);
 6235                let tab_size = settings.tab_size.get();
 6236                let mut rows = selection.spanned_rows(false, &display_map);
 6237
 6238                // Avoid re-outdenting a row that has already been outdented by a
 6239                // previous selection.
 6240                if let Some(last_row) = last_outdent {
 6241                    if last_row == rows.start {
 6242                        rows.start = rows.start.next_row();
 6243                    }
 6244                }
 6245                let has_multiple_rows = rows.len() > 1;
 6246                for row in rows.iter_rows() {
 6247                    let indent_size = snapshot.indent_size_for_line(row);
 6248                    if indent_size.len > 0 {
 6249                        let deletion_len = match indent_size.kind {
 6250                            IndentKind::Space => {
 6251                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 6252                                if columns_to_prev_tab_stop == 0 {
 6253                                    tab_size
 6254                                } else {
 6255                                    columns_to_prev_tab_stop
 6256                                }
 6257                            }
 6258                            IndentKind::Tab => 1,
 6259                        };
 6260                        let start = if has_multiple_rows
 6261                            || deletion_len > selection.start.column
 6262                            || indent_size.len < selection.start.column
 6263                        {
 6264                            0
 6265                        } else {
 6266                            selection.start.column - deletion_len
 6267                        };
 6268                        deletion_ranges.push(
 6269                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 6270                        );
 6271                        last_outdent = Some(row);
 6272                    }
 6273                }
 6274            }
 6275        }
 6276
 6277        self.transact(cx, |this, cx| {
 6278            this.buffer.update(cx, |buffer, cx| {
 6279                let empty_str: Arc<str> = Arc::default();
 6280                buffer.edit(
 6281                    deletion_ranges
 6282                        .into_iter()
 6283                        .map(|range| (range, empty_str.clone())),
 6284                    None,
 6285                    cx,
 6286                );
 6287            });
 6288            let selections = this.selections.all::<usize>(cx);
 6289            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6290        });
 6291    }
 6292
 6293    pub fn autoindent(&mut self, _: &AutoIndent, cx: &mut ViewContext<Self>) {
 6294        if self.read_only(cx) {
 6295            return;
 6296        }
 6297        let selections = self
 6298            .selections
 6299            .all::<usize>(cx)
 6300            .into_iter()
 6301            .map(|s| s.range());
 6302
 6303        self.transact(cx, |this, cx| {
 6304            this.buffer.update(cx, |buffer, cx| {
 6305                buffer.autoindent_ranges(selections, cx);
 6306            });
 6307            let selections = this.selections.all::<usize>(cx);
 6308            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6309        });
 6310    }
 6311
 6312    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 6313        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6314        let selections = self.selections.all::<Point>(cx);
 6315
 6316        let mut new_cursors = Vec::new();
 6317        let mut edit_ranges = Vec::new();
 6318        let mut selections = selections.iter().peekable();
 6319        while let Some(selection) = selections.next() {
 6320            let mut rows = selection.spanned_rows(false, &display_map);
 6321            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6322
 6323            // Accumulate contiguous regions of rows that we want to delete.
 6324            while let Some(next_selection) = selections.peek() {
 6325                let next_rows = next_selection.spanned_rows(false, &display_map);
 6326                if next_rows.start <= rows.end {
 6327                    rows.end = next_rows.end;
 6328                    selections.next().unwrap();
 6329                } else {
 6330                    break;
 6331                }
 6332            }
 6333
 6334            let buffer = &display_map.buffer_snapshot;
 6335            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6336            let edit_end;
 6337            let cursor_buffer_row;
 6338            if buffer.max_point().row >= rows.end.0 {
 6339                // If there's a line after the range, delete the \n from the end of the row range
 6340                // and position the cursor on the next line.
 6341                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6342                cursor_buffer_row = rows.end;
 6343            } else {
 6344                // If there isn't a line after the range, delete the \n from the line before the
 6345                // start of the row range and position the cursor there.
 6346                edit_start = edit_start.saturating_sub(1);
 6347                edit_end = buffer.len();
 6348                cursor_buffer_row = rows.start.previous_row();
 6349            }
 6350
 6351            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6352            *cursor.column_mut() =
 6353                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6354
 6355            new_cursors.push((
 6356                selection.id,
 6357                buffer.anchor_after(cursor.to_point(&display_map)),
 6358            ));
 6359            edit_ranges.push(edit_start..edit_end);
 6360        }
 6361
 6362        self.transact(cx, |this, cx| {
 6363            let buffer = this.buffer.update(cx, |buffer, cx| {
 6364                let empty_str: Arc<str> = Arc::default();
 6365                buffer.edit(
 6366                    edit_ranges
 6367                        .into_iter()
 6368                        .map(|range| (range, empty_str.clone())),
 6369                    None,
 6370                    cx,
 6371                );
 6372                buffer.snapshot(cx)
 6373            });
 6374            let new_selections = new_cursors
 6375                .into_iter()
 6376                .map(|(id, cursor)| {
 6377                    let cursor = cursor.to_point(&buffer);
 6378                    Selection {
 6379                        id,
 6380                        start: cursor,
 6381                        end: cursor,
 6382                        reversed: false,
 6383                        goal: SelectionGoal::None,
 6384                    }
 6385                })
 6386                .collect();
 6387
 6388            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6389                s.select(new_selections);
 6390            });
 6391        });
 6392    }
 6393
 6394    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 6395        if self.read_only(cx) {
 6396            return;
 6397        }
 6398        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6399        for selection in self.selections.all::<Point>(cx) {
 6400            let start = MultiBufferRow(selection.start.row);
 6401            // Treat single line selections as if they include the next line. Otherwise this action
 6402            // would do nothing for single line selections individual cursors.
 6403            let end = if selection.start.row == selection.end.row {
 6404                MultiBufferRow(selection.start.row + 1)
 6405            } else {
 6406                MultiBufferRow(selection.end.row)
 6407            };
 6408
 6409            if let Some(last_row_range) = row_ranges.last_mut() {
 6410                if start <= last_row_range.end {
 6411                    last_row_range.end = end;
 6412                    continue;
 6413                }
 6414            }
 6415            row_ranges.push(start..end);
 6416        }
 6417
 6418        let snapshot = self.buffer.read(cx).snapshot(cx);
 6419        let mut cursor_positions = Vec::new();
 6420        for row_range in &row_ranges {
 6421            let anchor = snapshot.anchor_before(Point::new(
 6422                row_range.end.previous_row().0,
 6423                snapshot.line_len(row_range.end.previous_row()),
 6424            ));
 6425            cursor_positions.push(anchor..anchor);
 6426        }
 6427
 6428        self.transact(cx, |this, cx| {
 6429            for row_range in row_ranges.into_iter().rev() {
 6430                for row in row_range.iter_rows().rev() {
 6431                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6432                    let next_line_row = row.next_row();
 6433                    let indent = snapshot.indent_size_for_line(next_line_row);
 6434                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 6435
 6436                    let replace = if snapshot.line_len(next_line_row) > indent.len {
 6437                        " "
 6438                    } else {
 6439                        ""
 6440                    };
 6441
 6442                    this.buffer.update(cx, |buffer, cx| {
 6443                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6444                    });
 6445                }
 6446            }
 6447
 6448            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6449                s.select_anchor_ranges(cursor_positions)
 6450            });
 6451        });
 6452    }
 6453
 6454    pub fn sort_lines_case_sensitive(
 6455        &mut self,
 6456        _: &SortLinesCaseSensitive,
 6457        cx: &mut ViewContext<Self>,
 6458    ) {
 6459        self.manipulate_lines(cx, |lines| lines.sort())
 6460    }
 6461
 6462    pub fn sort_lines_case_insensitive(
 6463        &mut self,
 6464        _: &SortLinesCaseInsensitive,
 6465        cx: &mut ViewContext<Self>,
 6466    ) {
 6467        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 6468    }
 6469
 6470    pub fn unique_lines_case_insensitive(
 6471        &mut self,
 6472        _: &UniqueLinesCaseInsensitive,
 6473        cx: &mut ViewContext<Self>,
 6474    ) {
 6475        self.manipulate_lines(cx, |lines| {
 6476            let mut seen = HashSet::default();
 6477            lines.retain(|line| seen.insert(line.to_lowercase()));
 6478        })
 6479    }
 6480
 6481    pub fn unique_lines_case_sensitive(
 6482        &mut self,
 6483        _: &UniqueLinesCaseSensitive,
 6484        cx: &mut ViewContext<Self>,
 6485    ) {
 6486        self.manipulate_lines(cx, |lines| {
 6487            let mut seen = HashSet::default();
 6488            lines.retain(|line| seen.insert(*line));
 6489        })
 6490    }
 6491
 6492    pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
 6493        let mut revert_changes = HashMap::default();
 6494        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 6495        for hunk in hunks_for_rows(
 6496            Some(MultiBufferRow(0)..multi_buffer_snapshot.max_row()).into_iter(),
 6497            &multi_buffer_snapshot,
 6498        ) {
 6499            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 6500        }
 6501        if !revert_changes.is_empty() {
 6502            self.transact(cx, |editor, cx| {
 6503                editor.revert(revert_changes, cx);
 6504            });
 6505        }
 6506    }
 6507
 6508    pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
 6509        let Some(project) = self.project.clone() else {
 6510            return;
 6511        };
 6512        self.reload(project, cx).detach_and_notify_err(cx);
 6513    }
 6514
 6515    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 6516        let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
 6517        if !revert_changes.is_empty() {
 6518            self.transact(cx, |editor, cx| {
 6519                editor.revert(revert_changes, cx);
 6520            });
 6521        }
 6522    }
 6523
 6524    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 6525        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6526            let project_path = buffer.read(cx).project_path(cx)?;
 6527            let project = self.project.as_ref()?.read(cx);
 6528            let entry = project.entry_for_path(&project_path, cx)?;
 6529            let parent = match &entry.canonical_path {
 6530                Some(canonical_path) => canonical_path.to_path_buf(),
 6531                None => project.absolute_path(&project_path, cx)?,
 6532            }
 6533            .parent()?
 6534            .to_path_buf();
 6535            Some(parent)
 6536        }) {
 6537            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 6538        }
 6539    }
 6540
 6541    fn gather_revert_changes(
 6542        &mut self,
 6543        selections: &[Selection<Anchor>],
 6544        cx: &mut ViewContext<'_, Editor>,
 6545    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 6546        let mut revert_changes = HashMap::default();
 6547        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 6548        for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
 6549            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 6550        }
 6551        revert_changes
 6552    }
 6553
 6554    pub fn prepare_revert_change(
 6555        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6556        multi_buffer: &Model<MultiBuffer>,
 6557        hunk: &MultiBufferDiffHunk,
 6558        cx: &AppContext,
 6559    ) -> Option<()> {
 6560        let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
 6561        let buffer = buffer.read(cx);
 6562        let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
 6563        let buffer_snapshot = buffer.snapshot();
 6564        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6565        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6566            probe
 6567                .0
 6568                .start
 6569                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6570                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6571        }) {
 6572            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6573            Some(())
 6574        } else {
 6575            None
 6576        }
 6577    }
 6578
 6579    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 6580        self.manipulate_lines(cx, |lines| lines.reverse())
 6581    }
 6582
 6583    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 6584        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 6585    }
 6586
 6587    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6588    where
 6589        Fn: FnMut(&mut Vec<&str>),
 6590    {
 6591        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6592        let buffer = self.buffer.read(cx).snapshot(cx);
 6593
 6594        let mut edits = Vec::new();
 6595
 6596        let selections = self.selections.all::<Point>(cx);
 6597        let mut selections = selections.iter().peekable();
 6598        let mut contiguous_row_selections = Vec::new();
 6599        let mut new_selections = Vec::new();
 6600        let mut added_lines = 0;
 6601        let mut removed_lines = 0;
 6602
 6603        while let Some(selection) = selections.next() {
 6604            let (start_row, end_row) = consume_contiguous_rows(
 6605                &mut contiguous_row_selections,
 6606                selection,
 6607                &display_map,
 6608                &mut selections,
 6609            );
 6610
 6611            let start_point = Point::new(start_row.0, 0);
 6612            let end_point = Point::new(
 6613                end_row.previous_row().0,
 6614                buffer.line_len(end_row.previous_row()),
 6615            );
 6616            let text = buffer
 6617                .text_for_range(start_point..end_point)
 6618                .collect::<String>();
 6619
 6620            let mut lines = text.split('\n').collect_vec();
 6621
 6622            let lines_before = lines.len();
 6623            callback(&mut lines);
 6624            let lines_after = lines.len();
 6625
 6626            edits.push((start_point..end_point, lines.join("\n")));
 6627
 6628            // Selections must change based on added and removed line count
 6629            let start_row =
 6630                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6631            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6632            new_selections.push(Selection {
 6633                id: selection.id,
 6634                start: start_row,
 6635                end: end_row,
 6636                goal: SelectionGoal::None,
 6637                reversed: selection.reversed,
 6638            });
 6639
 6640            if lines_after > lines_before {
 6641                added_lines += lines_after - lines_before;
 6642            } else if lines_before > lines_after {
 6643                removed_lines += lines_before - lines_after;
 6644            }
 6645        }
 6646
 6647        self.transact(cx, |this, cx| {
 6648            let buffer = this.buffer.update(cx, |buffer, cx| {
 6649                buffer.edit(edits, None, cx);
 6650                buffer.snapshot(cx)
 6651            });
 6652
 6653            // Recalculate offsets on newly edited buffer
 6654            let new_selections = new_selections
 6655                .iter()
 6656                .map(|s| {
 6657                    let start_point = Point::new(s.start.0, 0);
 6658                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6659                    Selection {
 6660                        id: s.id,
 6661                        start: buffer.point_to_offset(start_point),
 6662                        end: buffer.point_to_offset(end_point),
 6663                        goal: s.goal,
 6664                        reversed: s.reversed,
 6665                    }
 6666                })
 6667                .collect();
 6668
 6669            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6670                s.select(new_selections);
 6671            });
 6672
 6673            this.request_autoscroll(Autoscroll::fit(), cx);
 6674        });
 6675    }
 6676
 6677    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 6678        self.manipulate_text(cx, |text| text.to_uppercase())
 6679    }
 6680
 6681    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 6682        self.manipulate_text(cx, |text| text.to_lowercase())
 6683    }
 6684
 6685    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 6686        self.manipulate_text(cx, |text| {
 6687            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6688            // https://github.com/rutrum/convert-case/issues/16
 6689            text.split('\n')
 6690                .map(|line| line.to_case(Case::Title))
 6691                .join("\n")
 6692        })
 6693    }
 6694
 6695    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6696        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6697    }
 6698
 6699    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6700        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6701    }
 6702
 6703    pub fn convert_to_upper_camel_case(
 6704        &mut self,
 6705        _: &ConvertToUpperCamelCase,
 6706        cx: &mut ViewContext<Self>,
 6707    ) {
 6708        self.manipulate_text(cx, |text| {
 6709            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6710            // https://github.com/rutrum/convert-case/issues/16
 6711            text.split('\n')
 6712                .map(|line| line.to_case(Case::UpperCamel))
 6713                .join("\n")
 6714        })
 6715    }
 6716
 6717    pub fn convert_to_lower_camel_case(
 6718        &mut self,
 6719        _: &ConvertToLowerCamelCase,
 6720        cx: &mut ViewContext<Self>,
 6721    ) {
 6722        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6723    }
 6724
 6725    pub fn convert_to_opposite_case(
 6726        &mut self,
 6727        _: &ConvertToOppositeCase,
 6728        cx: &mut ViewContext<Self>,
 6729    ) {
 6730        self.manipulate_text(cx, |text| {
 6731            text.chars()
 6732                .fold(String::with_capacity(text.len()), |mut t, c| {
 6733                    if c.is_uppercase() {
 6734                        t.extend(c.to_lowercase());
 6735                    } else {
 6736                        t.extend(c.to_uppercase());
 6737                    }
 6738                    t
 6739                })
 6740        })
 6741    }
 6742
 6743    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6744    where
 6745        Fn: FnMut(&str) -> String,
 6746    {
 6747        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6748        let buffer = self.buffer.read(cx).snapshot(cx);
 6749
 6750        let mut new_selections = Vec::new();
 6751        let mut edits = Vec::new();
 6752        let mut selection_adjustment = 0i32;
 6753
 6754        for selection in self.selections.all::<usize>(cx) {
 6755            let selection_is_empty = selection.is_empty();
 6756
 6757            let (start, end) = if selection_is_empty {
 6758                let word_range = movement::surrounding_word(
 6759                    &display_map,
 6760                    selection.start.to_display_point(&display_map),
 6761                );
 6762                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6763                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6764                (start, end)
 6765            } else {
 6766                (selection.start, selection.end)
 6767            };
 6768
 6769            let text = buffer.text_for_range(start..end).collect::<String>();
 6770            let old_length = text.len() as i32;
 6771            let text = callback(&text);
 6772
 6773            new_selections.push(Selection {
 6774                start: (start as i32 - selection_adjustment) as usize,
 6775                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6776                goal: SelectionGoal::None,
 6777                ..selection
 6778            });
 6779
 6780            selection_adjustment += old_length - text.len() as i32;
 6781
 6782            edits.push((start..end, text));
 6783        }
 6784
 6785        self.transact(cx, |this, cx| {
 6786            this.buffer.update(cx, |buffer, cx| {
 6787                buffer.edit(edits, None, cx);
 6788            });
 6789
 6790            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6791                s.select(new_selections);
 6792            });
 6793
 6794            this.request_autoscroll(Autoscroll::fit(), cx);
 6795        });
 6796    }
 6797
 6798    pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
 6799        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6800        let buffer = &display_map.buffer_snapshot;
 6801        let selections = self.selections.all::<Point>(cx);
 6802
 6803        let mut edits = Vec::new();
 6804        let mut selections_iter = selections.iter().peekable();
 6805        while let Some(selection) = selections_iter.next() {
 6806            // Avoid duplicating the same lines twice.
 6807            let mut rows = selection.spanned_rows(false, &display_map);
 6808
 6809            while let Some(next_selection) = selections_iter.peek() {
 6810                let next_rows = next_selection.spanned_rows(false, &display_map);
 6811                if next_rows.start < rows.end {
 6812                    rows.end = next_rows.end;
 6813                    selections_iter.next().unwrap();
 6814                } else {
 6815                    break;
 6816                }
 6817            }
 6818
 6819            // Copy the text from the selected row region and splice it either at the start
 6820            // or end of the region.
 6821            let start = Point::new(rows.start.0, 0);
 6822            let end = Point::new(
 6823                rows.end.previous_row().0,
 6824                buffer.line_len(rows.end.previous_row()),
 6825            );
 6826            let text = buffer
 6827                .text_for_range(start..end)
 6828                .chain(Some("\n"))
 6829                .collect::<String>();
 6830            let insert_location = if upwards {
 6831                Point::new(rows.end.0, 0)
 6832            } else {
 6833                start
 6834            };
 6835            edits.push((insert_location..insert_location, text));
 6836        }
 6837
 6838        self.transact(cx, |this, cx| {
 6839            this.buffer.update(cx, |buffer, cx| {
 6840                buffer.edit(edits, None, cx);
 6841            });
 6842
 6843            this.request_autoscroll(Autoscroll::fit(), cx);
 6844        });
 6845    }
 6846
 6847    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6848        self.duplicate_line(true, cx);
 6849    }
 6850
 6851    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6852        self.duplicate_line(false, cx);
 6853    }
 6854
 6855    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6856        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6857        let buffer = self.buffer.read(cx).snapshot(cx);
 6858
 6859        let mut edits = Vec::new();
 6860        let mut unfold_ranges = Vec::new();
 6861        let mut refold_creases = Vec::new();
 6862
 6863        let selections = self.selections.all::<Point>(cx);
 6864        let mut selections = selections.iter().peekable();
 6865        let mut contiguous_row_selections = Vec::new();
 6866        let mut new_selections = Vec::new();
 6867
 6868        while let Some(selection) = selections.next() {
 6869            // Find all the selections that span a contiguous row range
 6870            let (start_row, end_row) = consume_contiguous_rows(
 6871                &mut contiguous_row_selections,
 6872                selection,
 6873                &display_map,
 6874                &mut selections,
 6875            );
 6876
 6877            // Move the text spanned by the row range to be before the line preceding the row range
 6878            if start_row.0 > 0 {
 6879                let range_to_move = Point::new(
 6880                    start_row.previous_row().0,
 6881                    buffer.line_len(start_row.previous_row()),
 6882                )
 6883                    ..Point::new(
 6884                        end_row.previous_row().0,
 6885                        buffer.line_len(end_row.previous_row()),
 6886                    );
 6887                let insertion_point = display_map
 6888                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6889                    .0;
 6890
 6891                // Don't move lines across excerpts
 6892                if buffer
 6893                    .excerpt_boundaries_in_range((
 6894                        Bound::Excluded(insertion_point),
 6895                        Bound::Included(range_to_move.end),
 6896                    ))
 6897                    .next()
 6898                    .is_none()
 6899                {
 6900                    let text = buffer
 6901                        .text_for_range(range_to_move.clone())
 6902                        .flat_map(|s| s.chars())
 6903                        .skip(1)
 6904                        .chain(['\n'])
 6905                        .collect::<String>();
 6906
 6907                    edits.push((
 6908                        buffer.anchor_after(range_to_move.start)
 6909                            ..buffer.anchor_before(range_to_move.end),
 6910                        String::new(),
 6911                    ));
 6912                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6913                    edits.push((insertion_anchor..insertion_anchor, text));
 6914
 6915                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6916
 6917                    // Move selections up
 6918                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6919                        |mut selection| {
 6920                            selection.start.row -= row_delta;
 6921                            selection.end.row -= row_delta;
 6922                            selection
 6923                        },
 6924                    ));
 6925
 6926                    // Move folds up
 6927                    unfold_ranges.push(range_to_move.clone());
 6928                    for fold in display_map.folds_in_range(
 6929                        buffer.anchor_before(range_to_move.start)
 6930                            ..buffer.anchor_after(range_to_move.end),
 6931                    ) {
 6932                        let mut start = fold.range.start.to_point(&buffer);
 6933                        let mut end = fold.range.end.to_point(&buffer);
 6934                        start.row -= row_delta;
 6935                        end.row -= row_delta;
 6936                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6937                    }
 6938                }
 6939            }
 6940
 6941            // If we didn't move line(s), preserve the existing selections
 6942            new_selections.append(&mut contiguous_row_selections);
 6943        }
 6944
 6945        self.transact(cx, |this, cx| {
 6946            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6947            this.buffer.update(cx, |buffer, cx| {
 6948                for (range, text) in edits {
 6949                    buffer.edit([(range, text)], None, cx);
 6950                }
 6951            });
 6952            this.fold_creases(refold_creases, true, cx);
 6953            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6954                s.select(new_selections);
 6955            })
 6956        });
 6957    }
 6958
 6959    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 6960        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6961        let buffer = self.buffer.read(cx).snapshot(cx);
 6962
 6963        let mut edits = Vec::new();
 6964        let mut unfold_ranges = Vec::new();
 6965        let mut refold_creases = Vec::new();
 6966
 6967        let selections = self.selections.all::<Point>(cx);
 6968        let mut selections = selections.iter().peekable();
 6969        let mut contiguous_row_selections = Vec::new();
 6970        let mut new_selections = Vec::new();
 6971
 6972        while let Some(selection) = selections.next() {
 6973            // Find all the selections that span a contiguous row range
 6974            let (start_row, end_row) = consume_contiguous_rows(
 6975                &mut contiguous_row_selections,
 6976                selection,
 6977                &display_map,
 6978                &mut selections,
 6979            );
 6980
 6981            // Move the text spanned by the row range to be after the last line of the row range
 6982            if end_row.0 <= buffer.max_point().row {
 6983                let range_to_move =
 6984                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 6985                let insertion_point = display_map
 6986                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 6987                    .0;
 6988
 6989                // Don't move lines across excerpt boundaries
 6990                if buffer
 6991                    .excerpt_boundaries_in_range((
 6992                        Bound::Excluded(range_to_move.start),
 6993                        Bound::Included(insertion_point),
 6994                    ))
 6995                    .next()
 6996                    .is_none()
 6997                {
 6998                    let mut text = String::from("\n");
 6999                    text.extend(buffer.text_for_range(range_to_move.clone()));
 7000                    text.pop(); // Drop trailing newline
 7001                    edits.push((
 7002                        buffer.anchor_after(range_to_move.start)
 7003                            ..buffer.anchor_before(range_to_move.end),
 7004                        String::new(),
 7005                    ));
 7006                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7007                    edits.push((insertion_anchor..insertion_anchor, text));
 7008
 7009                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 7010
 7011                    // Move selections down
 7012                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7013                        |mut selection| {
 7014                            selection.start.row += row_delta;
 7015                            selection.end.row += row_delta;
 7016                            selection
 7017                        },
 7018                    ));
 7019
 7020                    // Move folds down
 7021                    unfold_ranges.push(range_to_move.clone());
 7022                    for fold in display_map.folds_in_range(
 7023                        buffer.anchor_before(range_to_move.start)
 7024                            ..buffer.anchor_after(range_to_move.end),
 7025                    ) {
 7026                        let mut start = fold.range.start.to_point(&buffer);
 7027                        let mut end = fold.range.end.to_point(&buffer);
 7028                        start.row += row_delta;
 7029                        end.row += row_delta;
 7030                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7031                    }
 7032                }
 7033            }
 7034
 7035            // If we didn't move line(s), preserve the existing selections
 7036            new_selections.append(&mut contiguous_row_selections);
 7037        }
 7038
 7039        self.transact(cx, |this, cx| {
 7040            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7041            this.buffer.update(cx, |buffer, cx| {
 7042                for (range, text) in edits {
 7043                    buffer.edit([(range, text)], None, cx);
 7044                }
 7045            });
 7046            this.fold_creases(refold_creases, true, cx);
 7047            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 7048        });
 7049    }
 7050
 7051    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 7052        let text_layout_details = &self.text_layout_details(cx);
 7053        self.transact(cx, |this, cx| {
 7054            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7055                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 7056                let line_mode = s.line_mode;
 7057                s.move_with(|display_map, selection| {
 7058                    if !selection.is_empty() || line_mode {
 7059                        return;
 7060                    }
 7061
 7062                    let mut head = selection.head();
 7063                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 7064                    if head.column() == display_map.line_len(head.row()) {
 7065                        transpose_offset = display_map
 7066                            .buffer_snapshot
 7067                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7068                    }
 7069
 7070                    if transpose_offset == 0 {
 7071                        return;
 7072                    }
 7073
 7074                    *head.column_mut() += 1;
 7075                    head = display_map.clip_point(head, Bias::Right);
 7076                    let goal = SelectionGoal::HorizontalPosition(
 7077                        display_map
 7078                            .x_for_display_point(head, text_layout_details)
 7079                            .into(),
 7080                    );
 7081                    selection.collapse_to(head, goal);
 7082
 7083                    let transpose_start = display_map
 7084                        .buffer_snapshot
 7085                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7086                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 7087                        let transpose_end = display_map
 7088                            .buffer_snapshot
 7089                            .clip_offset(transpose_offset + 1, Bias::Right);
 7090                        if let Some(ch) =
 7091                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 7092                        {
 7093                            edits.push((transpose_start..transpose_offset, String::new()));
 7094                            edits.push((transpose_end..transpose_end, ch.to_string()));
 7095                        }
 7096                    }
 7097                });
 7098                edits
 7099            });
 7100            this.buffer
 7101                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7102            let selections = this.selections.all::<usize>(cx);
 7103            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7104                s.select(selections);
 7105            });
 7106        });
 7107    }
 7108
 7109    pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
 7110        self.rewrap_impl(IsVimMode::No, cx)
 7111    }
 7112
 7113    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
 7114        let buffer = self.buffer.read(cx).snapshot(cx);
 7115        let selections = self.selections.all::<Point>(cx);
 7116        let mut selections = selections.iter().peekable();
 7117
 7118        let mut edits = Vec::new();
 7119        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 7120
 7121        while let Some(selection) = selections.next() {
 7122            let mut start_row = selection.start.row;
 7123            let mut end_row = selection.end.row;
 7124
 7125            // Skip selections that overlap with a range that has already been rewrapped.
 7126            let selection_range = start_row..end_row;
 7127            if rewrapped_row_ranges
 7128                .iter()
 7129                .any(|range| range.overlaps(&selection_range))
 7130            {
 7131                continue;
 7132            }
 7133
 7134            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 7135
 7136            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 7137                match language_scope.language_name().0.as_ref() {
 7138                    "Markdown" | "Plain Text" => {
 7139                        should_rewrap = true;
 7140                    }
 7141                    _ => {}
 7142                }
 7143            }
 7144
 7145            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 7146
 7147            // Since not all lines in the selection may be at the same indent
 7148            // level, choose the indent size that is the most common between all
 7149            // of the lines.
 7150            //
 7151            // If there is a tie, we use the deepest indent.
 7152            let (indent_size, indent_end) = {
 7153                let mut indent_size_occurrences = HashMap::default();
 7154                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 7155
 7156                for row in start_row..=end_row {
 7157                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 7158                    rows_by_indent_size.entry(indent).or_default().push(row);
 7159                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 7160                }
 7161
 7162                let indent_size = indent_size_occurrences
 7163                    .into_iter()
 7164                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 7165                    .map(|(indent, _)| indent)
 7166                    .unwrap_or_default();
 7167                let row = rows_by_indent_size[&indent_size][0];
 7168                let indent_end = Point::new(row, indent_size.len);
 7169
 7170                (indent_size, indent_end)
 7171            };
 7172
 7173            let mut line_prefix = indent_size.chars().collect::<String>();
 7174
 7175            if let Some(comment_prefix) =
 7176                buffer
 7177                    .language_scope_at(selection.head())
 7178                    .and_then(|language| {
 7179                        language
 7180                            .line_comment_prefixes()
 7181                            .iter()
 7182                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 7183                            .cloned()
 7184                    })
 7185            {
 7186                line_prefix.push_str(&comment_prefix);
 7187                should_rewrap = true;
 7188            }
 7189
 7190            if !should_rewrap {
 7191                continue;
 7192            }
 7193
 7194            if selection.is_empty() {
 7195                'expand_upwards: while start_row > 0 {
 7196                    let prev_row = start_row - 1;
 7197                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 7198                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 7199                    {
 7200                        start_row = prev_row;
 7201                    } else {
 7202                        break 'expand_upwards;
 7203                    }
 7204                }
 7205
 7206                'expand_downwards: while end_row < buffer.max_point().row {
 7207                    let next_row = end_row + 1;
 7208                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 7209                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 7210                    {
 7211                        end_row = next_row;
 7212                    } else {
 7213                        break 'expand_downwards;
 7214                    }
 7215                }
 7216            }
 7217
 7218            let start = Point::new(start_row, 0);
 7219            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 7220            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 7221            let Some(lines_without_prefixes) = selection_text
 7222                .lines()
 7223                .map(|line| {
 7224                    line.strip_prefix(&line_prefix)
 7225                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 7226                        .ok_or_else(|| {
 7227                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 7228                        })
 7229                })
 7230                .collect::<Result<Vec<_>, _>>()
 7231                .log_err()
 7232            else {
 7233                continue;
 7234            };
 7235
 7236            let wrap_column = buffer
 7237                .settings_at(Point::new(start_row, 0), cx)
 7238                .preferred_line_length as usize;
 7239            let wrapped_text = wrap_with_prefix(
 7240                line_prefix,
 7241                lines_without_prefixes.join(" "),
 7242                wrap_column,
 7243                tab_size,
 7244            );
 7245
 7246            // TODO: should always use char-based diff while still supporting cursor behavior that
 7247            // matches vim.
 7248            let diff = match is_vim_mode {
 7249                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 7250                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 7251            };
 7252            let mut offset = start.to_offset(&buffer);
 7253            let mut moved_since_edit = true;
 7254
 7255            for change in diff.iter_all_changes() {
 7256                let value = change.value();
 7257                match change.tag() {
 7258                    ChangeTag::Equal => {
 7259                        offset += value.len();
 7260                        moved_since_edit = true;
 7261                    }
 7262                    ChangeTag::Delete => {
 7263                        let start = buffer.anchor_after(offset);
 7264                        let end = buffer.anchor_before(offset + value.len());
 7265
 7266                        if moved_since_edit {
 7267                            edits.push((start..end, String::new()));
 7268                        } else {
 7269                            edits.last_mut().unwrap().0.end = end;
 7270                        }
 7271
 7272                        offset += value.len();
 7273                        moved_since_edit = false;
 7274                    }
 7275                    ChangeTag::Insert => {
 7276                        if moved_since_edit {
 7277                            let anchor = buffer.anchor_after(offset);
 7278                            edits.push((anchor..anchor, value.to_string()));
 7279                        } else {
 7280                            edits.last_mut().unwrap().1.push_str(value);
 7281                        }
 7282
 7283                        moved_since_edit = false;
 7284                    }
 7285                }
 7286            }
 7287
 7288            rewrapped_row_ranges.push(start_row..=end_row);
 7289        }
 7290
 7291        self.buffer
 7292            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7293    }
 7294
 7295    pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
 7296        let mut text = String::new();
 7297        let buffer = self.buffer.read(cx).snapshot(cx);
 7298        let mut selections = self.selections.all::<Point>(cx);
 7299        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7300        {
 7301            let max_point = buffer.max_point();
 7302            let mut is_first = true;
 7303            for selection in &mut selections {
 7304                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7305                if is_entire_line {
 7306                    selection.start = Point::new(selection.start.row, 0);
 7307                    if !selection.is_empty() && selection.end.column == 0 {
 7308                        selection.end = cmp::min(max_point, selection.end);
 7309                    } else {
 7310                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7311                    }
 7312                    selection.goal = SelectionGoal::None;
 7313                }
 7314                if is_first {
 7315                    is_first = false;
 7316                } else {
 7317                    text += "\n";
 7318                }
 7319                let mut len = 0;
 7320                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7321                    text.push_str(chunk);
 7322                    len += chunk.len();
 7323                }
 7324                clipboard_selections.push(ClipboardSelection {
 7325                    len,
 7326                    is_entire_line,
 7327                    first_line_indent: buffer
 7328                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7329                        .len,
 7330                });
 7331            }
 7332        }
 7333
 7334        self.transact(cx, |this, cx| {
 7335            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7336                s.select(selections);
 7337            });
 7338            this.insert("", cx);
 7339        });
 7340        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 7341    }
 7342
 7343    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 7344        let item = self.cut_common(cx);
 7345        cx.write_to_clipboard(item);
 7346    }
 7347
 7348    pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
 7349        self.change_selections(None, cx, |s| {
 7350            s.move_with(|snapshot, sel| {
 7351                if sel.is_empty() {
 7352                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 7353                }
 7354            });
 7355        });
 7356        let item = self.cut_common(cx);
 7357        cx.set_global(KillRing(item))
 7358    }
 7359
 7360    pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
 7361        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 7362            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 7363                (kill_ring.text().to_string(), kill_ring.metadata_json())
 7364            } else {
 7365                return;
 7366            }
 7367        } else {
 7368            return;
 7369        };
 7370        self.do_paste(&text, metadata, false, cx);
 7371    }
 7372
 7373    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 7374        let selections = self.selections.all::<Point>(cx);
 7375        let buffer = self.buffer.read(cx).read(cx);
 7376        let mut text = String::new();
 7377
 7378        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7379        {
 7380            let max_point = buffer.max_point();
 7381            let mut is_first = true;
 7382            for selection in selections.iter() {
 7383                let mut start = selection.start;
 7384                let mut end = selection.end;
 7385                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7386                if is_entire_line {
 7387                    start = Point::new(start.row, 0);
 7388                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 7389                }
 7390                if is_first {
 7391                    is_first = false;
 7392                } else {
 7393                    text += "\n";
 7394                }
 7395                let mut len = 0;
 7396                for chunk in buffer.text_for_range(start..end) {
 7397                    text.push_str(chunk);
 7398                    len += chunk.len();
 7399                }
 7400                clipboard_selections.push(ClipboardSelection {
 7401                    len,
 7402                    is_entire_line,
 7403                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 7404                });
 7405            }
 7406        }
 7407
 7408        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7409            text,
 7410            clipboard_selections,
 7411        ));
 7412    }
 7413
 7414    pub fn do_paste(
 7415        &mut self,
 7416        text: &String,
 7417        clipboard_selections: Option<Vec<ClipboardSelection>>,
 7418        handle_entire_lines: bool,
 7419        cx: &mut ViewContext<Self>,
 7420    ) {
 7421        if self.read_only(cx) {
 7422            return;
 7423        }
 7424
 7425        let clipboard_text = Cow::Borrowed(text);
 7426
 7427        self.transact(cx, |this, cx| {
 7428            if let Some(mut clipboard_selections) = clipboard_selections {
 7429                let old_selections = this.selections.all::<usize>(cx);
 7430                let all_selections_were_entire_line =
 7431                    clipboard_selections.iter().all(|s| s.is_entire_line);
 7432                let first_selection_indent_column =
 7433                    clipboard_selections.first().map(|s| s.first_line_indent);
 7434                if clipboard_selections.len() != old_selections.len() {
 7435                    clipboard_selections.drain(..);
 7436                }
 7437                let cursor_offset = this.selections.last::<usize>(cx).head();
 7438                let mut auto_indent_on_paste = true;
 7439
 7440                this.buffer.update(cx, |buffer, cx| {
 7441                    let snapshot = buffer.read(cx);
 7442                    auto_indent_on_paste =
 7443                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 7444
 7445                    let mut start_offset = 0;
 7446                    let mut edits = Vec::new();
 7447                    let mut original_indent_columns = Vec::new();
 7448                    for (ix, selection) in old_selections.iter().enumerate() {
 7449                        let to_insert;
 7450                        let entire_line;
 7451                        let original_indent_column;
 7452                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 7453                            let end_offset = start_offset + clipboard_selection.len;
 7454                            to_insert = &clipboard_text[start_offset..end_offset];
 7455                            entire_line = clipboard_selection.is_entire_line;
 7456                            start_offset = end_offset + 1;
 7457                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7458                        } else {
 7459                            to_insert = clipboard_text.as_str();
 7460                            entire_line = all_selections_were_entire_line;
 7461                            original_indent_column = first_selection_indent_column
 7462                        }
 7463
 7464                        // If the corresponding selection was empty when this slice of the
 7465                        // clipboard text was written, then the entire line containing the
 7466                        // selection was copied. If this selection is also currently empty,
 7467                        // then paste the line before the current line of the buffer.
 7468                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7469                            let column = selection.start.to_point(&snapshot).column as usize;
 7470                            let line_start = selection.start - column;
 7471                            line_start..line_start
 7472                        } else {
 7473                            selection.range()
 7474                        };
 7475
 7476                        edits.push((range, to_insert));
 7477                        original_indent_columns.extend(original_indent_column);
 7478                    }
 7479                    drop(snapshot);
 7480
 7481                    buffer.edit(
 7482                        edits,
 7483                        if auto_indent_on_paste {
 7484                            Some(AutoindentMode::Block {
 7485                                original_indent_columns,
 7486                            })
 7487                        } else {
 7488                            None
 7489                        },
 7490                        cx,
 7491                    );
 7492                });
 7493
 7494                let selections = this.selections.all::<usize>(cx);
 7495                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 7496            } else {
 7497                this.insert(&clipboard_text, cx);
 7498            }
 7499        });
 7500    }
 7501
 7502    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 7503        if let Some(item) = cx.read_from_clipboard() {
 7504            let entries = item.entries();
 7505
 7506            match entries.first() {
 7507                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7508                // of all the pasted entries.
 7509                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7510                    .do_paste(
 7511                        clipboard_string.text(),
 7512                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7513                        true,
 7514                        cx,
 7515                    ),
 7516                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
 7517            }
 7518        }
 7519    }
 7520
 7521    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 7522        if self.read_only(cx) {
 7523            return;
 7524        }
 7525
 7526        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7527            if let Some((selections, _)) =
 7528                self.selection_history.transaction(transaction_id).cloned()
 7529            {
 7530                self.change_selections(None, cx, |s| {
 7531                    s.select_anchors(selections.to_vec());
 7532                });
 7533            }
 7534            self.request_autoscroll(Autoscroll::fit(), cx);
 7535            self.unmark_text(cx);
 7536            self.refresh_inline_completion(true, false, cx);
 7537            cx.emit(EditorEvent::Edited { transaction_id });
 7538            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7539        }
 7540    }
 7541
 7542    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 7543        if self.read_only(cx) {
 7544            return;
 7545        }
 7546
 7547        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7548            if let Some((_, Some(selections))) =
 7549                self.selection_history.transaction(transaction_id).cloned()
 7550            {
 7551                self.change_selections(None, cx, |s| {
 7552                    s.select_anchors(selections.to_vec());
 7553                });
 7554            }
 7555            self.request_autoscroll(Autoscroll::fit(), cx);
 7556            self.unmark_text(cx);
 7557            self.refresh_inline_completion(true, false, cx);
 7558            cx.emit(EditorEvent::Edited { transaction_id });
 7559        }
 7560    }
 7561
 7562    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 7563        self.buffer
 7564            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7565    }
 7566
 7567    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 7568        self.buffer
 7569            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7570    }
 7571
 7572    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 7573        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7574            let line_mode = s.line_mode;
 7575            s.move_with(|map, selection| {
 7576                let cursor = if selection.is_empty() && !line_mode {
 7577                    movement::left(map, selection.start)
 7578                } else {
 7579                    selection.start
 7580                };
 7581                selection.collapse_to(cursor, SelectionGoal::None);
 7582            });
 7583        })
 7584    }
 7585
 7586    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 7587        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7588            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7589        })
 7590    }
 7591
 7592    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 7593        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7594            let line_mode = s.line_mode;
 7595            s.move_with(|map, selection| {
 7596                let cursor = if selection.is_empty() && !line_mode {
 7597                    movement::right(map, selection.end)
 7598                } else {
 7599                    selection.end
 7600                };
 7601                selection.collapse_to(cursor, SelectionGoal::None)
 7602            });
 7603        })
 7604    }
 7605
 7606    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 7607        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7608            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7609        })
 7610    }
 7611
 7612    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 7613        if self.take_rename(true, cx).is_some() {
 7614            return;
 7615        }
 7616
 7617        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7618            cx.propagate();
 7619            return;
 7620        }
 7621
 7622        let text_layout_details = &self.text_layout_details(cx);
 7623        let selection_count = self.selections.count();
 7624        let first_selection = self.selections.first_anchor();
 7625
 7626        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7627            let line_mode = s.line_mode;
 7628            s.move_with(|map, selection| {
 7629                if !selection.is_empty() && !line_mode {
 7630                    selection.goal = SelectionGoal::None;
 7631                }
 7632                let (cursor, goal) = movement::up(
 7633                    map,
 7634                    selection.start,
 7635                    selection.goal,
 7636                    false,
 7637                    text_layout_details,
 7638                );
 7639                selection.collapse_to(cursor, goal);
 7640            });
 7641        });
 7642
 7643        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7644        {
 7645            cx.propagate();
 7646        }
 7647    }
 7648
 7649    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 7650        if self.take_rename(true, cx).is_some() {
 7651            return;
 7652        }
 7653
 7654        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7655            cx.propagate();
 7656            return;
 7657        }
 7658
 7659        let text_layout_details = &self.text_layout_details(cx);
 7660
 7661        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7662            let line_mode = s.line_mode;
 7663            s.move_with(|map, selection| {
 7664                if !selection.is_empty() && !line_mode {
 7665                    selection.goal = SelectionGoal::None;
 7666                }
 7667                let (cursor, goal) = movement::up_by_rows(
 7668                    map,
 7669                    selection.start,
 7670                    action.lines,
 7671                    selection.goal,
 7672                    false,
 7673                    text_layout_details,
 7674                );
 7675                selection.collapse_to(cursor, goal);
 7676            });
 7677        })
 7678    }
 7679
 7680    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 7681        if self.take_rename(true, cx).is_some() {
 7682            return;
 7683        }
 7684
 7685        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7686            cx.propagate();
 7687            return;
 7688        }
 7689
 7690        let text_layout_details = &self.text_layout_details(cx);
 7691
 7692        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7693            let line_mode = s.line_mode;
 7694            s.move_with(|map, selection| {
 7695                if !selection.is_empty() && !line_mode {
 7696                    selection.goal = SelectionGoal::None;
 7697                }
 7698                let (cursor, goal) = movement::down_by_rows(
 7699                    map,
 7700                    selection.start,
 7701                    action.lines,
 7702                    selection.goal,
 7703                    false,
 7704                    text_layout_details,
 7705                );
 7706                selection.collapse_to(cursor, goal);
 7707            });
 7708        })
 7709    }
 7710
 7711    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 7712        let text_layout_details = &self.text_layout_details(cx);
 7713        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7714            s.move_heads_with(|map, head, goal| {
 7715                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7716            })
 7717        })
 7718    }
 7719
 7720    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 7721        let text_layout_details = &self.text_layout_details(cx);
 7722        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7723            s.move_heads_with(|map, head, goal| {
 7724                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7725            })
 7726        })
 7727    }
 7728
 7729    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 7730        let Some(row_count) = self.visible_row_count() else {
 7731            return;
 7732        };
 7733
 7734        let text_layout_details = &self.text_layout_details(cx);
 7735
 7736        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7737            s.move_heads_with(|map, head, goal| {
 7738                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7739            })
 7740        })
 7741    }
 7742
 7743    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 7744        if self.take_rename(true, cx).is_some() {
 7745            return;
 7746        }
 7747
 7748        if self
 7749            .context_menu
 7750            .write()
 7751            .as_mut()
 7752            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 7753            .unwrap_or(false)
 7754        {
 7755            return;
 7756        }
 7757
 7758        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7759            cx.propagate();
 7760            return;
 7761        }
 7762
 7763        let Some(row_count) = self.visible_row_count() else {
 7764            return;
 7765        };
 7766
 7767        let autoscroll = if action.center_cursor {
 7768            Autoscroll::center()
 7769        } else {
 7770            Autoscroll::fit()
 7771        };
 7772
 7773        let text_layout_details = &self.text_layout_details(cx);
 7774
 7775        self.change_selections(Some(autoscroll), cx, |s| {
 7776            let line_mode = s.line_mode;
 7777            s.move_with(|map, selection| {
 7778                if !selection.is_empty() && !line_mode {
 7779                    selection.goal = SelectionGoal::None;
 7780                }
 7781                let (cursor, goal) = movement::up_by_rows(
 7782                    map,
 7783                    selection.end,
 7784                    row_count,
 7785                    selection.goal,
 7786                    false,
 7787                    text_layout_details,
 7788                );
 7789                selection.collapse_to(cursor, goal);
 7790            });
 7791        });
 7792    }
 7793
 7794    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 7795        let text_layout_details = &self.text_layout_details(cx);
 7796        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7797            s.move_heads_with(|map, head, goal| {
 7798                movement::up(map, head, goal, false, text_layout_details)
 7799            })
 7800        })
 7801    }
 7802
 7803    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 7804        self.take_rename(true, cx);
 7805
 7806        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7807            cx.propagate();
 7808            return;
 7809        }
 7810
 7811        let text_layout_details = &self.text_layout_details(cx);
 7812        let selection_count = self.selections.count();
 7813        let first_selection = self.selections.first_anchor();
 7814
 7815        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7816            let line_mode = s.line_mode;
 7817            s.move_with(|map, selection| {
 7818                if !selection.is_empty() && !line_mode {
 7819                    selection.goal = SelectionGoal::None;
 7820                }
 7821                let (cursor, goal) = movement::down(
 7822                    map,
 7823                    selection.end,
 7824                    selection.goal,
 7825                    false,
 7826                    text_layout_details,
 7827                );
 7828                selection.collapse_to(cursor, goal);
 7829            });
 7830        });
 7831
 7832        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7833        {
 7834            cx.propagate();
 7835        }
 7836    }
 7837
 7838    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 7839        let Some(row_count) = self.visible_row_count() else {
 7840            return;
 7841        };
 7842
 7843        let text_layout_details = &self.text_layout_details(cx);
 7844
 7845        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7846            s.move_heads_with(|map, head, goal| {
 7847                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 7848            })
 7849        })
 7850    }
 7851
 7852    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 7853        if self.take_rename(true, cx).is_some() {
 7854            return;
 7855        }
 7856
 7857        if self
 7858            .context_menu
 7859            .write()
 7860            .as_mut()
 7861            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 7862            .unwrap_or(false)
 7863        {
 7864            return;
 7865        }
 7866
 7867        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7868            cx.propagate();
 7869            return;
 7870        }
 7871
 7872        let Some(row_count) = self.visible_row_count() else {
 7873            return;
 7874        };
 7875
 7876        let autoscroll = if action.center_cursor {
 7877            Autoscroll::center()
 7878        } else {
 7879            Autoscroll::fit()
 7880        };
 7881
 7882        let text_layout_details = &self.text_layout_details(cx);
 7883        self.change_selections(Some(autoscroll), cx, |s| {
 7884            let line_mode = s.line_mode;
 7885            s.move_with(|map, selection| {
 7886                if !selection.is_empty() && !line_mode {
 7887                    selection.goal = SelectionGoal::None;
 7888                }
 7889                let (cursor, goal) = movement::down_by_rows(
 7890                    map,
 7891                    selection.end,
 7892                    row_count,
 7893                    selection.goal,
 7894                    false,
 7895                    text_layout_details,
 7896                );
 7897                selection.collapse_to(cursor, goal);
 7898            });
 7899        });
 7900    }
 7901
 7902    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 7903        let text_layout_details = &self.text_layout_details(cx);
 7904        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7905            s.move_heads_with(|map, head, goal| {
 7906                movement::down(map, head, goal, false, text_layout_details)
 7907            })
 7908        });
 7909    }
 7910
 7911    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 7912        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7913            context_menu.select_first(self.completion_provider.as_deref(), cx);
 7914        }
 7915    }
 7916
 7917    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 7918        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7919            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 7920        }
 7921    }
 7922
 7923    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7924        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7925            context_menu.select_next(self.completion_provider.as_deref(), cx);
 7926        }
 7927    }
 7928
 7929    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 7930        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7931            context_menu.select_last(self.completion_provider.as_deref(), cx);
 7932        }
 7933    }
 7934
 7935    pub fn move_to_previous_word_start(
 7936        &mut self,
 7937        _: &MoveToPreviousWordStart,
 7938        cx: &mut ViewContext<Self>,
 7939    ) {
 7940        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7941            s.move_cursors_with(|map, head, _| {
 7942                (
 7943                    movement::previous_word_start(map, head),
 7944                    SelectionGoal::None,
 7945                )
 7946            });
 7947        })
 7948    }
 7949
 7950    pub fn move_to_previous_subword_start(
 7951        &mut self,
 7952        _: &MoveToPreviousSubwordStart,
 7953        cx: &mut ViewContext<Self>,
 7954    ) {
 7955        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7956            s.move_cursors_with(|map, head, _| {
 7957                (
 7958                    movement::previous_subword_start(map, head),
 7959                    SelectionGoal::None,
 7960                )
 7961            });
 7962        })
 7963    }
 7964
 7965    pub fn select_to_previous_word_start(
 7966        &mut self,
 7967        _: &SelectToPreviousWordStart,
 7968        cx: &mut ViewContext<Self>,
 7969    ) {
 7970        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7971            s.move_heads_with(|map, head, _| {
 7972                (
 7973                    movement::previous_word_start(map, head),
 7974                    SelectionGoal::None,
 7975                )
 7976            });
 7977        })
 7978    }
 7979
 7980    pub fn select_to_previous_subword_start(
 7981        &mut self,
 7982        _: &SelectToPreviousSubwordStart,
 7983        cx: &mut ViewContext<Self>,
 7984    ) {
 7985        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7986            s.move_heads_with(|map, head, _| {
 7987                (
 7988                    movement::previous_subword_start(map, head),
 7989                    SelectionGoal::None,
 7990                )
 7991            });
 7992        })
 7993    }
 7994
 7995    pub fn delete_to_previous_word_start(
 7996        &mut self,
 7997        action: &DeleteToPreviousWordStart,
 7998        cx: &mut ViewContext<Self>,
 7999    ) {
 8000        self.transact(cx, |this, cx| {
 8001            this.select_autoclose_pair(cx);
 8002            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8003                let line_mode = s.line_mode;
 8004                s.move_with(|map, selection| {
 8005                    if selection.is_empty() && !line_mode {
 8006                        let cursor = if action.ignore_newlines {
 8007                            movement::previous_word_start(map, selection.head())
 8008                        } else {
 8009                            movement::previous_word_start_or_newline(map, selection.head())
 8010                        };
 8011                        selection.set_head(cursor, SelectionGoal::None);
 8012                    }
 8013                });
 8014            });
 8015            this.insert("", cx);
 8016        });
 8017    }
 8018
 8019    pub fn delete_to_previous_subword_start(
 8020        &mut self,
 8021        _: &DeleteToPreviousSubwordStart,
 8022        cx: &mut ViewContext<Self>,
 8023    ) {
 8024        self.transact(cx, |this, cx| {
 8025            this.select_autoclose_pair(cx);
 8026            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8027                let line_mode = s.line_mode;
 8028                s.move_with(|map, selection| {
 8029                    if selection.is_empty() && !line_mode {
 8030                        let cursor = movement::previous_subword_start(map, selection.head());
 8031                        selection.set_head(cursor, SelectionGoal::None);
 8032                    }
 8033                });
 8034            });
 8035            this.insert("", cx);
 8036        });
 8037    }
 8038
 8039    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 8040        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8041            s.move_cursors_with(|map, head, _| {
 8042                (movement::next_word_end(map, head), SelectionGoal::None)
 8043            });
 8044        })
 8045    }
 8046
 8047    pub fn move_to_next_subword_end(
 8048        &mut self,
 8049        _: &MoveToNextSubwordEnd,
 8050        cx: &mut ViewContext<Self>,
 8051    ) {
 8052        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8053            s.move_cursors_with(|map, head, _| {
 8054                (movement::next_subword_end(map, head), SelectionGoal::None)
 8055            });
 8056        })
 8057    }
 8058
 8059    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 8060        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8061            s.move_heads_with(|map, head, _| {
 8062                (movement::next_word_end(map, head), SelectionGoal::None)
 8063            });
 8064        })
 8065    }
 8066
 8067    pub fn select_to_next_subword_end(
 8068        &mut self,
 8069        _: &SelectToNextSubwordEnd,
 8070        cx: &mut ViewContext<Self>,
 8071    ) {
 8072        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8073            s.move_heads_with(|map, head, _| {
 8074                (movement::next_subword_end(map, head), SelectionGoal::None)
 8075            });
 8076        })
 8077    }
 8078
 8079    pub fn delete_to_next_word_end(
 8080        &mut self,
 8081        action: &DeleteToNextWordEnd,
 8082        cx: &mut ViewContext<Self>,
 8083    ) {
 8084        self.transact(cx, |this, cx| {
 8085            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8086                let line_mode = s.line_mode;
 8087                s.move_with(|map, selection| {
 8088                    if selection.is_empty() && !line_mode {
 8089                        let cursor = if action.ignore_newlines {
 8090                            movement::next_word_end(map, selection.head())
 8091                        } else {
 8092                            movement::next_word_end_or_newline(map, selection.head())
 8093                        };
 8094                        selection.set_head(cursor, SelectionGoal::None);
 8095                    }
 8096                });
 8097            });
 8098            this.insert("", cx);
 8099        });
 8100    }
 8101
 8102    pub fn delete_to_next_subword_end(
 8103        &mut self,
 8104        _: &DeleteToNextSubwordEnd,
 8105        cx: &mut ViewContext<Self>,
 8106    ) {
 8107        self.transact(cx, |this, cx| {
 8108            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8109                s.move_with(|map, selection| {
 8110                    if selection.is_empty() {
 8111                        let cursor = movement::next_subword_end(map, selection.head());
 8112                        selection.set_head(cursor, SelectionGoal::None);
 8113                    }
 8114                });
 8115            });
 8116            this.insert("", cx);
 8117        });
 8118    }
 8119
 8120    pub fn move_to_beginning_of_line(
 8121        &mut self,
 8122        action: &MoveToBeginningOfLine,
 8123        cx: &mut ViewContext<Self>,
 8124    ) {
 8125        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8126            s.move_cursors_with(|map, head, _| {
 8127                (
 8128                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8129                    SelectionGoal::None,
 8130                )
 8131            });
 8132        })
 8133    }
 8134
 8135    pub fn select_to_beginning_of_line(
 8136        &mut self,
 8137        action: &SelectToBeginningOfLine,
 8138        cx: &mut ViewContext<Self>,
 8139    ) {
 8140        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8141            s.move_heads_with(|map, head, _| {
 8142                (
 8143                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8144                    SelectionGoal::None,
 8145                )
 8146            });
 8147        });
 8148    }
 8149
 8150    pub fn delete_to_beginning_of_line(
 8151        &mut self,
 8152        _: &DeleteToBeginningOfLine,
 8153        cx: &mut ViewContext<Self>,
 8154    ) {
 8155        self.transact(cx, |this, cx| {
 8156            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8157                s.move_with(|_, selection| {
 8158                    selection.reversed = true;
 8159                });
 8160            });
 8161
 8162            this.select_to_beginning_of_line(
 8163                &SelectToBeginningOfLine {
 8164                    stop_at_soft_wraps: false,
 8165                },
 8166                cx,
 8167            );
 8168            this.backspace(&Backspace, cx);
 8169        });
 8170    }
 8171
 8172    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 8173        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8174            s.move_cursors_with(|map, head, _| {
 8175                (
 8176                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8177                    SelectionGoal::None,
 8178                )
 8179            });
 8180        })
 8181    }
 8182
 8183    pub fn select_to_end_of_line(
 8184        &mut self,
 8185        action: &SelectToEndOfLine,
 8186        cx: &mut ViewContext<Self>,
 8187    ) {
 8188        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8189            s.move_heads_with(|map, head, _| {
 8190                (
 8191                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8192                    SelectionGoal::None,
 8193                )
 8194            });
 8195        })
 8196    }
 8197
 8198    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 8199        self.transact(cx, |this, cx| {
 8200            this.select_to_end_of_line(
 8201                &SelectToEndOfLine {
 8202                    stop_at_soft_wraps: false,
 8203                },
 8204                cx,
 8205            );
 8206            this.delete(&Delete, cx);
 8207        });
 8208    }
 8209
 8210    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 8211        self.transact(cx, |this, cx| {
 8212            this.select_to_end_of_line(
 8213                &SelectToEndOfLine {
 8214                    stop_at_soft_wraps: false,
 8215                },
 8216                cx,
 8217            );
 8218            this.cut(&Cut, cx);
 8219        });
 8220    }
 8221
 8222    pub fn move_to_start_of_paragraph(
 8223        &mut self,
 8224        _: &MoveToStartOfParagraph,
 8225        cx: &mut ViewContext<Self>,
 8226    ) {
 8227        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8228            cx.propagate();
 8229            return;
 8230        }
 8231
 8232        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8233            s.move_with(|map, selection| {
 8234                selection.collapse_to(
 8235                    movement::start_of_paragraph(map, selection.head(), 1),
 8236                    SelectionGoal::None,
 8237                )
 8238            });
 8239        })
 8240    }
 8241
 8242    pub fn move_to_end_of_paragraph(
 8243        &mut self,
 8244        _: &MoveToEndOfParagraph,
 8245        cx: &mut ViewContext<Self>,
 8246    ) {
 8247        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8248            cx.propagate();
 8249            return;
 8250        }
 8251
 8252        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8253            s.move_with(|map, selection| {
 8254                selection.collapse_to(
 8255                    movement::end_of_paragraph(map, selection.head(), 1),
 8256                    SelectionGoal::None,
 8257                )
 8258            });
 8259        })
 8260    }
 8261
 8262    pub fn select_to_start_of_paragraph(
 8263        &mut self,
 8264        _: &SelectToStartOfParagraph,
 8265        cx: &mut ViewContext<Self>,
 8266    ) {
 8267        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8268            cx.propagate();
 8269            return;
 8270        }
 8271
 8272        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8273            s.move_heads_with(|map, head, _| {
 8274                (
 8275                    movement::start_of_paragraph(map, head, 1),
 8276                    SelectionGoal::None,
 8277                )
 8278            });
 8279        })
 8280    }
 8281
 8282    pub fn select_to_end_of_paragraph(
 8283        &mut self,
 8284        _: &SelectToEndOfParagraph,
 8285        cx: &mut ViewContext<Self>,
 8286    ) {
 8287        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8288            cx.propagate();
 8289            return;
 8290        }
 8291
 8292        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8293            s.move_heads_with(|map, head, _| {
 8294                (
 8295                    movement::end_of_paragraph(map, head, 1),
 8296                    SelectionGoal::None,
 8297                )
 8298            });
 8299        })
 8300    }
 8301
 8302    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 8303        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8304            cx.propagate();
 8305            return;
 8306        }
 8307
 8308        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8309            s.select_ranges(vec![0..0]);
 8310        });
 8311    }
 8312
 8313    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 8314        let mut selection = self.selections.last::<Point>(cx);
 8315        selection.set_head(Point::zero(), SelectionGoal::None);
 8316
 8317        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8318            s.select(vec![selection]);
 8319        });
 8320    }
 8321
 8322    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 8323        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8324            cx.propagate();
 8325            return;
 8326        }
 8327
 8328        let cursor = self.buffer.read(cx).read(cx).len();
 8329        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8330            s.select_ranges(vec![cursor..cursor])
 8331        });
 8332    }
 8333
 8334    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 8335        self.nav_history = nav_history;
 8336    }
 8337
 8338    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 8339        self.nav_history.as_ref()
 8340    }
 8341
 8342    fn push_to_nav_history(
 8343        &mut self,
 8344        cursor_anchor: Anchor,
 8345        new_position: Option<Point>,
 8346        cx: &mut ViewContext<Self>,
 8347    ) {
 8348        if let Some(nav_history) = self.nav_history.as_mut() {
 8349            let buffer = self.buffer.read(cx).read(cx);
 8350            let cursor_position = cursor_anchor.to_point(&buffer);
 8351            let scroll_state = self.scroll_manager.anchor();
 8352            let scroll_top_row = scroll_state.top_row(&buffer);
 8353            drop(buffer);
 8354
 8355            if let Some(new_position) = new_position {
 8356                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 8357                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 8358                    return;
 8359                }
 8360            }
 8361
 8362            nav_history.push(
 8363                Some(NavigationData {
 8364                    cursor_anchor,
 8365                    cursor_position,
 8366                    scroll_anchor: scroll_state,
 8367                    scroll_top_row,
 8368                }),
 8369                cx,
 8370            );
 8371        }
 8372    }
 8373
 8374    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 8375        let buffer = self.buffer.read(cx).snapshot(cx);
 8376        let mut selection = self.selections.first::<usize>(cx);
 8377        selection.set_head(buffer.len(), SelectionGoal::None);
 8378        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8379            s.select(vec![selection]);
 8380        });
 8381    }
 8382
 8383    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 8384        let end = self.buffer.read(cx).read(cx).len();
 8385        self.change_selections(None, cx, |s| {
 8386            s.select_ranges(vec![0..end]);
 8387        });
 8388    }
 8389
 8390    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 8391        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8392        let mut selections = self.selections.all::<Point>(cx);
 8393        let max_point = display_map.buffer_snapshot.max_point();
 8394        for selection in &mut selections {
 8395            let rows = selection.spanned_rows(true, &display_map);
 8396            selection.start = Point::new(rows.start.0, 0);
 8397            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 8398            selection.reversed = false;
 8399        }
 8400        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8401            s.select(selections);
 8402        });
 8403    }
 8404
 8405    pub fn split_selection_into_lines(
 8406        &mut self,
 8407        _: &SplitSelectionIntoLines,
 8408        cx: &mut ViewContext<Self>,
 8409    ) {
 8410        let mut to_unfold = Vec::new();
 8411        let mut new_selection_ranges = Vec::new();
 8412        {
 8413            let selections = self.selections.all::<Point>(cx);
 8414            let buffer = self.buffer.read(cx).read(cx);
 8415            for selection in selections {
 8416                for row in selection.start.row..selection.end.row {
 8417                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 8418                    new_selection_ranges.push(cursor..cursor);
 8419                }
 8420                new_selection_ranges.push(selection.end..selection.end);
 8421                to_unfold.push(selection.start..selection.end);
 8422            }
 8423        }
 8424        self.unfold_ranges(&to_unfold, true, true, cx);
 8425        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8426            s.select_ranges(new_selection_ranges);
 8427        });
 8428    }
 8429
 8430    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 8431        self.add_selection(true, cx);
 8432    }
 8433
 8434    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 8435        self.add_selection(false, cx);
 8436    }
 8437
 8438    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 8439        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8440        let mut selections = self.selections.all::<Point>(cx);
 8441        let text_layout_details = self.text_layout_details(cx);
 8442        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 8443            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 8444            let range = oldest_selection.display_range(&display_map).sorted();
 8445
 8446            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 8447            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 8448            let positions = start_x.min(end_x)..start_x.max(end_x);
 8449
 8450            selections.clear();
 8451            let mut stack = Vec::new();
 8452            for row in range.start.row().0..=range.end.row().0 {
 8453                if let Some(selection) = self.selections.build_columnar_selection(
 8454                    &display_map,
 8455                    DisplayRow(row),
 8456                    &positions,
 8457                    oldest_selection.reversed,
 8458                    &text_layout_details,
 8459                ) {
 8460                    stack.push(selection.id);
 8461                    selections.push(selection);
 8462                }
 8463            }
 8464
 8465            if above {
 8466                stack.reverse();
 8467            }
 8468
 8469            AddSelectionsState { above, stack }
 8470        });
 8471
 8472        let last_added_selection = *state.stack.last().unwrap();
 8473        let mut new_selections = Vec::new();
 8474        if above == state.above {
 8475            let end_row = if above {
 8476                DisplayRow(0)
 8477            } else {
 8478                display_map.max_point().row()
 8479            };
 8480
 8481            'outer: for selection in selections {
 8482                if selection.id == last_added_selection {
 8483                    let range = selection.display_range(&display_map).sorted();
 8484                    debug_assert_eq!(range.start.row(), range.end.row());
 8485                    let mut row = range.start.row();
 8486                    let positions =
 8487                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 8488                            px(start)..px(end)
 8489                        } else {
 8490                            let start_x =
 8491                                display_map.x_for_display_point(range.start, &text_layout_details);
 8492                            let end_x =
 8493                                display_map.x_for_display_point(range.end, &text_layout_details);
 8494                            start_x.min(end_x)..start_x.max(end_x)
 8495                        };
 8496
 8497                    while row != end_row {
 8498                        if above {
 8499                            row.0 -= 1;
 8500                        } else {
 8501                            row.0 += 1;
 8502                        }
 8503
 8504                        if let Some(new_selection) = self.selections.build_columnar_selection(
 8505                            &display_map,
 8506                            row,
 8507                            &positions,
 8508                            selection.reversed,
 8509                            &text_layout_details,
 8510                        ) {
 8511                            state.stack.push(new_selection.id);
 8512                            if above {
 8513                                new_selections.push(new_selection);
 8514                                new_selections.push(selection);
 8515                            } else {
 8516                                new_selections.push(selection);
 8517                                new_selections.push(new_selection);
 8518                            }
 8519
 8520                            continue 'outer;
 8521                        }
 8522                    }
 8523                }
 8524
 8525                new_selections.push(selection);
 8526            }
 8527        } else {
 8528            new_selections = selections;
 8529            new_selections.retain(|s| s.id != last_added_selection);
 8530            state.stack.pop();
 8531        }
 8532
 8533        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8534            s.select(new_selections);
 8535        });
 8536        if state.stack.len() > 1 {
 8537            self.add_selections_state = Some(state);
 8538        }
 8539    }
 8540
 8541    pub fn select_next_match_internal(
 8542        &mut self,
 8543        display_map: &DisplaySnapshot,
 8544        replace_newest: bool,
 8545        autoscroll: Option<Autoscroll>,
 8546        cx: &mut ViewContext<Self>,
 8547    ) -> Result<()> {
 8548        fn select_next_match_ranges(
 8549            this: &mut Editor,
 8550            range: Range<usize>,
 8551            replace_newest: bool,
 8552            auto_scroll: Option<Autoscroll>,
 8553            cx: &mut ViewContext<Editor>,
 8554        ) {
 8555            this.unfold_ranges(&[range.clone()], false, true, cx);
 8556            this.change_selections(auto_scroll, cx, |s| {
 8557                if replace_newest {
 8558                    s.delete(s.newest_anchor().id);
 8559                }
 8560                s.insert_range(range.clone());
 8561            });
 8562        }
 8563
 8564        let buffer = &display_map.buffer_snapshot;
 8565        let mut selections = self.selections.all::<usize>(cx);
 8566        if let Some(mut select_next_state) = self.select_next_state.take() {
 8567            let query = &select_next_state.query;
 8568            if !select_next_state.done {
 8569                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8570                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8571                let mut next_selected_range = None;
 8572
 8573                let bytes_after_last_selection =
 8574                    buffer.bytes_in_range(last_selection.end..buffer.len());
 8575                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 8576                let query_matches = query
 8577                    .stream_find_iter(bytes_after_last_selection)
 8578                    .map(|result| (last_selection.end, result))
 8579                    .chain(
 8580                        query
 8581                            .stream_find_iter(bytes_before_first_selection)
 8582                            .map(|result| (0, result)),
 8583                    );
 8584
 8585                for (start_offset, query_match) in query_matches {
 8586                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8587                    let offset_range =
 8588                        start_offset + query_match.start()..start_offset + query_match.end();
 8589                    let display_range = offset_range.start.to_display_point(display_map)
 8590                        ..offset_range.end.to_display_point(display_map);
 8591
 8592                    if !select_next_state.wordwise
 8593                        || (!movement::is_inside_word(display_map, display_range.start)
 8594                            && !movement::is_inside_word(display_map, display_range.end))
 8595                    {
 8596                        // TODO: This is n^2, because we might check all the selections
 8597                        if !selections
 8598                            .iter()
 8599                            .any(|selection| selection.range().overlaps(&offset_range))
 8600                        {
 8601                            next_selected_range = Some(offset_range);
 8602                            break;
 8603                        }
 8604                    }
 8605                }
 8606
 8607                if let Some(next_selected_range) = next_selected_range {
 8608                    select_next_match_ranges(
 8609                        self,
 8610                        next_selected_range,
 8611                        replace_newest,
 8612                        autoscroll,
 8613                        cx,
 8614                    );
 8615                } else {
 8616                    select_next_state.done = true;
 8617                }
 8618            }
 8619
 8620            self.select_next_state = Some(select_next_state);
 8621        } else {
 8622            let mut only_carets = true;
 8623            let mut same_text_selected = true;
 8624            let mut selected_text = None;
 8625
 8626            let mut selections_iter = selections.iter().peekable();
 8627            while let Some(selection) = selections_iter.next() {
 8628                if selection.start != selection.end {
 8629                    only_carets = false;
 8630                }
 8631
 8632                if same_text_selected {
 8633                    if selected_text.is_none() {
 8634                        selected_text =
 8635                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8636                    }
 8637
 8638                    if let Some(next_selection) = selections_iter.peek() {
 8639                        if next_selection.range().len() == selection.range().len() {
 8640                            let next_selected_text = buffer
 8641                                .text_for_range(next_selection.range())
 8642                                .collect::<String>();
 8643                            if Some(next_selected_text) != selected_text {
 8644                                same_text_selected = false;
 8645                                selected_text = None;
 8646                            }
 8647                        } else {
 8648                            same_text_selected = false;
 8649                            selected_text = None;
 8650                        }
 8651                    }
 8652                }
 8653            }
 8654
 8655            if only_carets {
 8656                for selection in &mut selections {
 8657                    let word_range = movement::surrounding_word(
 8658                        display_map,
 8659                        selection.start.to_display_point(display_map),
 8660                    );
 8661                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 8662                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 8663                    selection.goal = SelectionGoal::None;
 8664                    selection.reversed = false;
 8665                    select_next_match_ranges(
 8666                        self,
 8667                        selection.start..selection.end,
 8668                        replace_newest,
 8669                        autoscroll,
 8670                        cx,
 8671                    );
 8672                }
 8673
 8674                if selections.len() == 1 {
 8675                    let selection = selections
 8676                        .last()
 8677                        .expect("ensured that there's only one selection");
 8678                    let query = buffer
 8679                        .text_for_range(selection.start..selection.end)
 8680                        .collect::<String>();
 8681                    let is_empty = query.is_empty();
 8682                    let select_state = SelectNextState {
 8683                        query: AhoCorasick::new(&[query])?,
 8684                        wordwise: true,
 8685                        done: is_empty,
 8686                    };
 8687                    self.select_next_state = Some(select_state);
 8688                } else {
 8689                    self.select_next_state = None;
 8690                }
 8691            } else if let Some(selected_text) = selected_text {
 8692                self.select_next_state = Some(SelectNextState {
 8693                    query: AhoCorasick::new(&[selected_text])?,
 8694                    wordwise: false,
 8695                    done: false,
 8696                });
 8697                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 8698            }
 8699        }
 8700        Ok(())
 8701    }
 8702
 8703    pub fn select_all_matches(
 8704        &mut self,
 8705        _action: &SelectAllMatches,
 8706        cx: &mut ViewContext<Self>,
 8707    ) -> Result<()> {
 8708        self.push_to_selection_history();
 8709        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8710
 8711        self.select_next_match_internal(&display_map, false, None, cx)?;
 8712        let Some(select_next_state) = self.select_next_state.as_mut() else {
 8713            return Ok(());
 8714        };
 8715        if select_next_state.done {
 8716            return Ok(());
 8717        }
 8718
 8719        let mut new_selections = self.selections.all::<usize>(cx);
 8720
 8721        let buffer = &display_map.buffer_snapshot;
 8722        let query_matches = select_next_state
 8723            .query
 8724            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 8725
 8726        for query_match in query_matches {
 8727            let query_match = query_match.unwrap(); // can only fail due to I/O
 8728            let offset_range = query_match.start()..query_match.end();
 8729            let display_range = offset_range.start.to_display_point(&display_map)
 8730                ..offset_range.end.to_display_point(&display_map);
 8731
 8732            if !select_next_state.wordwise
 8733                || (!movement::is_inside_word(&display_map, display_range.start)
 8734                    && !movement::is_inside_word(&display_map, display_range.end))
 8735            {
 8736                self.selections.change_with(cx, |selections| {
 8737                    new_selections.push(Selection {
 8738                        id: selections.new_selection_id(),
 8739                        start: offset_range.start,
 8740                        end: offset_range.end,
 8741                        reversed: false,
 8742                        goal: SelectionGoal::None,
 8743                    });
 8744                });
 8745            }
 8746        }
 8747
 8748        new_selections.sort_by_key(|selection| selection.start);
 8749        let mut ix = 0;
 8750        while ix + 1 < new_selections.len() {
 8751            let current_selection = &new_selections[ix];
 8752            let next_selection = &new_selections[ix + 1];
 8753            if current_selection.range().overlaps(&next_selection.range()) {
 8754                if current_selection.id < next_selection.id {
 8755                    new_selections.remove(ix + 1);
 8756                } else {
 8757                    new_selections.remove(ix);
 8758                }
 8759            } else {
 8760                ix += 1;
 8761            }
 8762        }
 8763
 8764        select_next_state.done = true;
 8765        self.unfold_ranges(
 8766            &new_selections
 8767                .iter()
 8768                .map(|selection| selection.range())
 8769                .collect::<Vec<_>>(),
 8770            false,
 8771            false,
 8772            cx,
 8773        );
 8774        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 8775            selections.select(new_selections)
 8776        });
 8777
 8778        Ok(())
 8779    }
 8780
 8781    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 8782        self.push_to_selection_history();
 8783        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8784        self.select_next_match_internal(
 8785            &display_map,
 8786            action.replace_newest,
 8787            Some(Autoscroll::newest()),
 8788            cx,
 8789        )?;
 8790        Ok(())
 8791    }
 8792
 8793    pub fn select_previous(
 8794        &mut self,
 8795        action: &SelectPrevious,
 8796        cx: &mut ViewContext<Self>,
 8797    ) -> Result<()> {
 8798        self.push_to_selection_history();
 8799        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8800        let buffer = &display_map.buffer_snapshot;
 8801        let mut selections = self.selections.all::<usize>(cx);
 8802        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8803            let query = &select_prev_state.query;
 8804            if !select_prev_state.done {
 8805                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8806                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8807                let mut next_selected_range = None;
 8808                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8809                let bytes_before_last_selection =
 8810                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8811                let bytes_after_first_selection =
 8812                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8813                let query_matches = query
 8814                    .stream_find_iter(bytes_before_last_selection)
 8815                    .map(|result| (last_selection.start, result))
 8816                    .chain(
 8817                        query
 8818                            .stream_find_iter(bytes_after_first_selection)
 8819                            .map(|result| (buffer.len(), result)),
 8820                    );
 8821                for (end_offset, query_match) in query_matches {
 8822                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8823                    let offset_range =
 8824                        end_offset - query_match.end()..end_offset - query_match.start();
 8825                    let display_range = offset_range.start.to_display_point(&display_map)
 8826                        ..offset_range.end.to_display_point(&display_map);
 8827
 8828                    if !select_prev_state.wordwise
 8829                        || (!movement::is_inside_word(&display_map, display_range.start)
 8830                            && !movement::is_inside_word(&display_map, display_range.end))
 8831                    {
 8832                        next_selected_range = Some(offset_range);
 8833                        break;
 8834                    }
 8835                }
 8836
 8837                if let Some(next_selected_range) = next_selected_range {
 8838                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 8839                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8840                        if action.replace_newest {
 8841                            s.delete(s.newest_anchor().id);
 8842                        }
 8843                        s.insert_range(next_selected_range);
 8844                    });
 8845                } else {
 8846                    select_prev_state.done = true;
 8847                }
 8848            }
 8849
 8850            self.select_prev_state = Some(select_prev_state);
 8851        } else {
 8852            let mut only_carets = true;
 8853            let mut same_text_selected = true;
 8854            let mut selected_text = None;
 8855
 8856            let mut selections_iter = selections.iter().peekable();
 8857            while let Some(selection) = selections_iter.next() {
 8858                if selection.start != selection.end {
 8859                    only_carets = false;
 8860                }
 8861
 8862                if same_text_selected {
 8863                    if selected_text.is_none() {
 8864                        selected_text =
 8865                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8866                    }
 8867
 8868                    if let Some(next_selection) = selections_iter.peek() {
 8869                        if next_selection.range().len() == selection.range().len() {
 8870                            let next_selected_text = buffer
 8871                                .text_for_range(next_selection.range())
 8872                                .collect::<String>();
 8873                            if Some(next_selected_text) != selected_text {
 8874                                same_text_selected = false;
 8875                                selected_text = None;
 8876                            }
 8877                        } else {
 8878                            same_text_selected = false;
 8879                            selected_text = None;
 8880                        }
 8881                    }
 8882                }
 8883            }
 8884
 8885            if only_carets {
 8886                for selection in &mut selections {
 8887                    let word_range = movement::surrounding_word(
 8888                        &display_map,
 8889                        selection.start.to_display_point(&display_map),
 8890                    );
 8891                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8892                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8893                    selection.goal = SelectionGoal::None;
 8894                    selection.reversed = false;
 8895                }
 8896                if selections.len() == 1 {
 8897                    let selection = selections
 8898                        .last()
 8899                        .expect("ensured that there's only one selection");
 8900                    let query = buffer
 8901                        .text_for_range(selection.start..selection.end)
 8902                        .collect::<String>();
 8903                    let is_empty = query.is_empty();
 8904                    let select_state = SelectNextState {
 8905                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8906                        wordwise: true,
 8907                        done: is_empty,
 8908                    };
 8909                    self.select_prev_state = Some(select_state);
 8910                } else {
 8911                    self.select_prev_state = None;
 8912                }
 8913
 8914                self.unfold_ranges(
 8915                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8916                    false,
 8917                    true,
 8918                    cx,
 8919                );
 8920                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8921                    s.select(selections);
 8922                });
 8923            } else if let Some(selected_text) = selected_text {
 8924                self.select_prev_state = Some(SelectNextState {
 8925                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8926                    wordwise: false,
 8927                    done: false,
 8928                });
 8929                self.select_previous(action, cx)?;
 8930            }
 8931        }
 8932        Ok(())
 8933    }
 8934
 8935    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 8936        if self.read_only(cx) {
 8937            return;
 8938        }
 8939        let text_layout_details = &self.text_layout_details(cx);
 8940        self.transact(cx, |this, cx| {
 8941            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8942            let mut edits = Vec::new();
 8943            let mut selection_edit_ranges = Vec::new();
 8944            let mut last_toggled_row = None;
 8945            let snapshot = this.buffer.read(cx).read(cx);
 8946            let empty_str: Arc<str> = Arc::default();
 8947            let mut suffixes_inserted = Vec::new();
 8948            let ignore_indent = action.ignore_indent;
 8949
 8950            fn comment_prefix_range(
 8951                snapshot: &MultiBufferSnapshot,
 8952                row: MultiBufferRow,
 8953                comment_prefix: &str,
 8954                comment_prefix_whitespace: &str,
 8955                ignore_indent: bool,
 8956            ) -> Range<Point> {
 8957                let indent_size = if ignore_indent {
 8958                    0
 8959                } else {
 8960                    snapshot.indent_size_for_line(row).len
 8961                };
 8962
 8963                let start = Point::new(row.0, indent_size);
 8964
 8965                let mut line_bytes = snapshot
 8966                    .bytes_in_range(start..snapshot.max_point())
 8967                    .flatten()
 8968                    .copied();
 8969
 8970                // If this line currently begins with the line comment prefix, then record
 8971                // the range containing the prefix.
 8972                if line_bytes
 8973                    .by_ref()
 8974                    .take(comment_prefix.len())
 8975                    .eq(comment_prefix.bytes())
 8976                {
 8977                    // Include any whitespace that matches the comment prefix.
 8978                    let matching_whitespace_len = line_bytes
 8979                        .zip(comment_prefix_whitespace.bytes())
 8980                        .take_while(|(a, b)| a == b)
 8981                        .count() as u32;
 8982                    let end = Point::new(
 8983                        start.row,
 8984                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 8985                    );
 8986                    start..end
 8987                } else {
 8988                    start..start
 8989                }
 8990            }
 8991
 8992            fn comment_suffix_range(
 8993                snapshot: &MultiBufferSnapshot,
 8994                row: MultiBufferRow,
 8995                comment_suffix: &str,
 8996                comment_suffix_has_leading_space: bool,
 8997            ) -> Range<Point> {
 8998                let end = Point::new(row.0, snapshot.line_len(row));
 8999                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 9000
 9001                let mut line_end_bytes = snapshot
 9002                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 9003                    .flatten()
 9004                    .copied();
 9005
 9006                let leading_space_len = if suffix_start_column > 0
 9007                    && line_end_bytes.next() == Some(b' ')
 9008                    && comment_suffix_has_leading_space
 9009                {
 9010                    1
 9011                } else {
 9012                    0
 9013                };
 9014
 9015                // If this line currently begins with the line comment prefix, then record
 9016                // the range containing the prefix.
 9017                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 9018                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 9019                    start..end
 9020                } else {
 9021                    end..end
 9022                }
 9023            }
 9024
 9025            // TODO: Handle selections that cross excerpts
 9026            for selection in &mut selections {
 9027                let start_column = snapshot
 9028                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 9029                    .len;
 9030                let language = if let Some(language) =
 9031                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 9032                {
 9033                    language
 9034                } else {
 9035                    continue;
 9036                };
 9037
 9038                selection_edit_ranges.clear();
 9039
 9040                // If multiple selections contain a given row, avoid processing that
 9041                // row more than once.
 9042                let mut start_row = MultiBufferRow(selection.start.row);
 9043                if last_toggled_row == Some(start_row) {
 9044                    start_row = start_row.next_row();
 9045                }
 9046                let end_row =
 9047                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 9048                        MultiBufferRow(selection.end.row - 1)
 9049                    } else {
 9050                        MultiBufferRow(selection.end.row)
 9051                    };
 9052                last_toggled_row = Some(end_row);
 9053
 9054                if start_row > end_row {
 9055                    continue;
 9056                }
 9057
 9058                // If the language has line comments, toggle those.
 9059                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 9060
 9061                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 9062                if ignore_indent {
 9063                    full_comment_prefixes = full_comment_prefixes
 9064                        .into_iter()
 9065                        .map(|s| Arc::from(s.trim_end()))
 9066                        .collect();
 9067                }
 9068
 9069                if !full_comment_prefixes.is_empty() {
 9070                    let first_prefix = full_comment_prefixes
 9071                        .first()
 9072                        .expect("prefixes is non-empty");
 9073                    let prefix_trimmed_lengths = full_comment_prefixes
 9074                        .iter()
 9075                        .map(|p| p.trim_end_matches(' ').len())
 9076                        .collect::<SmallVec<[usize; 4]>>();
 9077
 9078                    let mut all_selection_lines_are_comments = true;
 9079
 9080                    for row in start_row.0..=end_row.0 {
 9081                        let row = MultiBufferRow(row);
 9082                        if start_row < end_row && snapshot.is_line_blank(row) {
 9083                            continue;
 9084                        }
 9085
 9086                        let prefix_range = full_comment_prefixes
 9087                            .iter()
 9088                            .zip(prefix_trimmed_lengths.iter().copied())
 9089                            .map(|(prefix, trimmed_prefix_len)| {
 9090                                comment_prefix_range(
 9091                                    snapshot.deref(),
 9092                                    row,
 9093                                    &prefix[..trimmed_prefix_len],
 9094                                    &prefix[trimmed_prefix_len..],
 9095                                    ignore_indent,
 9096                                )
 9097                            })
 9098                            .max_by_key(|range| range.end.column - range.start.column)
 9099                            .expect("prefixes is non-empty");
 9100
 9101                        if prefix_range.is_empty() {
 9102                            all_selection_lines_are_comments = false;
 9103                        }
 9104
 9105                        selection_edit_ranges.push(prefix_range);
 9106                    }
 9107
 9108                    if all_selection_lines_are_comments {
 9109                        edits.extend(
 9110                            selection_edit_ranges
 9111                                .iter()
 9112                                .cloned()
 9113                                .map(|range| (range, empty_str.clone())),
 9114                        );
 9115                    } else {
 9116                        let min_column = selection_edit_ranges
 9117                            .iter()
 9118                            .map(|range| range.start.column)
 9119                            .min()
 9120                            .unwrap_or(0);
 9121                        edits.extend(selection_edit_ranges.iter().map(|range| {
 9122                            let position = Point::new(range.start.row, min_column);
 9123                            (position..position, first_prefix.clone())
 9124                        }));
 9125                    }
 9126                } else if let Some((full_comment_prefix, comment_suffix)) =
 9127                    language.block_comment_delimiters()
 9128                {
 9129                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 9130                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 9131                    let prefix_range = comment_prefix_range(
 9132                        snapshot.deref(),
 9133                        start_row,
 9134                        comment_prefix,
 9135                        comment_prefix_whitespace,
 9136                        ignore_indent,
 9137                    );
 9138                    let suffix_range = comment_suffix_range(
 9139                        snapshot.deref(),
 9140                        end_row,
 9141                        comment_suffix.trim_start_matches(' '),
 9142                        comment_suffix.starts_with(' '),
 9143                    );
 9144
 9145                    if prefix_range.is_empty() || suffix_range.is_empty() {
 9146                        edits.push((
 9147                            prefix_range.start..prefix_range.start,
 9148                            full_comment_prefix.clone(),
 9149                        ));
 9150                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 9151                        suffixes_inserted.push((end_row, comment_suffix.len()));
 9152                    } else {
 9153                        edits.push((prefix_range, empty_str.clone()));
 9154                        edits.push((suffix_range, empty_str.clone()));
 9155                    }
 9156                } else {
 9157                    continue;
 9158                }
 9159            }
 9160
 9161            drop(snapshot);
 9162            this.buffer.update(cx, |buffer, cx| {
 9163                buffer.edit(edits, None, cx);
 9164            });
 9165
 9166            // Adjust selections so that they end before any comment suffixes that
 9167            // were inserted.
 9168            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 9169            let mut selections = this.selections.all::<Point>(cx);
 9170            let snapshot = this.buffer.read(cx).read(cx);
 9171            for selection in &mut selections {
 9172                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 9173                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 9174                        Ordering::Less => {
 9175                            suffixes_inserted.next();
 9176                            continue;
 9177                        }
 9178                        Ordering::Greater => break,
 9179                        Ordering::Equal => {
 9180                            if selection.end.column == snapshot.line_len(row) {
 9181                                if selection.is_empty() {
 9182                                    selection.start.column -= suffix_len as u32;
 9183                                }
 9184                                selection.end.column -= suffix_len as u32;
 9185                            }
 9186                            break;
 9187                        }
 9188                    }
 9189                }
 9190            }
 9191
 9192            drop(snapshot);
 9193            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 9194
 9195            let selections = this.selections.all::<Point>(cx);
 9196            let selections_on_single_row = selections.windows(2).all(|selections| {
 9197                selections[0].start.row == selections[1].start.row
 9198                    && selections[0].end.row == selections[1].end.row
 9199                    && selections[0].start.row == selections[0].end.row
 9200            });
 9201            let selections_selecting = selections
 9202                .iter()
 9203                .any(|selection| selection.start != selection.end);
 9204            let advance_downwards = action.advance_downwards
 9205                && selections_on_single_row
 9206                && !selections_selecting
 9207                && !matches!(this.mode, EditorMode::SingleLine { .. });
 9208
 9209            if advance_downwards {
 9210                let snapshot = this.buffer.read(cx).snapshot(cx);
 9211
 9212                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9213                    s.move_cursors_with(|display_snapshot, display_point, _| {
 9214                        let mut point = display_point.to_point(display_snapshot);
 9215                        point.row += 1;
 9216                        point = snapshot.clip_point(point, Bias::Left);
 9217                        let display_point = point.to_display_point(display_snapshot);
 9218                        let goal = SelectionGoal::HorizontalPosition(
 9219                            display_snapshot
 9220                                .x_for_display_point(display_point, text_layout_details)
 9221                                .into(),
 9222                        );
 9223                        (display_point, goal)
 9224                    })
 9225                });
 9226            }
 9227        });
 9228    }
 9229
 9230    pub fn select_enclosing_symbol(
 9231        &mut self,
 9232        _: &SelectEnclosingSymbol,
 9233        cx: &mut ViewContext<Self>,
 9234    ) {
 9235        let buffer = self.buffer.read(cx).snapshot(cx);
 9236        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9237
 9238        fn update_selection(
 9239            selection: &Selection<usize>,
 9240            buffer_snap: &MultiBufferSnapshot,
 9241        ) -> Option<Selection<usize>> {
 9242            let cursor = selection.head();
 9243            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 9244            for symbol in symbols.iter().rev() {
 9245                let start = symbol.range.start.to_offset(buffer_snap);
 9246                let end = symbol.range.end.to_offset(buffer_snap);
 9247                let new_range = start..end;
 9248                if start < selection.start || end > selection.end {
 9249                    return Some(Selection {
 9250                        id: selection.id,
 9251                        start: new_range.start,
 9252                        end: new_range.end,
 9253                        goal: SelectionGoal::None,
 9254                        reversed: selection.reversed,
 9255                    });
 9256                }
 9257            }
 9258            None
 9259        }
 9260
 9261        let mut selected_larger_symbol = false;
 9262        let new_selections = old_selections
 9263            .iter()
 9264            .map(|selection| match update_selection(selection, &buffer) {
 9265                Some(new_selection) => {
 9266                    if new_selection.range() != selection.range() {
 9267                        selected_larger_symbol = true;
 9268                    }
 9269                    new_selection
 9270                }
 9271                None => selection.clone(),
 9272            })
 9273            .collect::<Vec<_>>();
 9274
 9275        if selected_larger_symbol {
 9276            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9277                s.select(new_selections);
 9278            });
 9279        }
 9280    }
 9281
 9282    pub fn select_larger_syntax_node(
 9283        &mut self,
 9284        _: &SelectLargerSyntaxNode,
 9285        cx: &mut ViewContext<Self>,
 9286    ) {
 9287        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9288        let buffer = self.buffer.read(cx).snapshot(cx);
 9289        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9290
 9291        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9292        let mut selected_larger_node = false;
 9293        let new_selections = old_selections
 9294            .iter()
 9295            .map(|selection| {
 9296                let old_range = selection.start..selection.end;
 9297                let mut new_range = old_range.clone();
 9298                while let Some(containing_range) =
 9299                    buffer.range_for_syntax_ancestor(new_range.clone())
 9300                {
 9301                    new_range = containing_range;
 9302                    if !display_map.intersects_fold(new_range.start)
 9303                        && !display_map.intersects_fold(new_range.end)
 9304                    {
 9305                        break;
 9306                    }
 9307                }
 9308
 9309                selected_larger_node |= new_range != old_range;
 9310                Selection {
 9311                    id: selection.id,
 9312                    start: new_range.start,
 9313                    end: new_range.end,
 9314                    goal: SelectionGoal::None,
 9315                    reversed: selection.reversed,
 9316                }
 9317            })
 9318            .collect::<Vec<_>>();
 9319
 9320        if selected_larger_node {
 9321            stack.push(old_selections);
 9322            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9323                s.select(new_selections);
 9324            });
 9325        }
 9326        self.select_larger_syntax_node_stack = stack;
 9327    }
 9328
 9329    pub fn select_smaller_syntax_node(
 9330        &mut self,
 9331        _: &SelectSmallerSyntaxNode,
 9332        cx: &mut ViewContext<Self>,
 9333    ) {
 9334        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9335        if let Some(selections) = stack.pop() {
 9336            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9337                s.select(selections.to_vec());
 9338            });
 9339        }
 9340        self.select_larger_syntax_node_stack = stack;
 9341    }
 9342
 9343    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 9344        if !EditorSettings::get_global(cx).gutter.runnables {
 9345            self.clear_tasks();
 9346            return Task::ready(());
 9347        }
 9348        let project = self.project.as_ref().map(Model::downgrade);
 9349        cx.spawn(|this, mut cx| async move {
 9350            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
 9351            let Some(project) = project.and_then(|p| p.upgrade()) else {
 9352                return;
 9353            };
 9354            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 9355                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 9356            }) else {
 9357                return;
 9358            };
 9359
 9360            let hide_runnables = project
 9361                .update(&mut cx, |project, cx| {
 9362                    // Do not display any test indicators in non-dev server remote projects.
 9363                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 9364                })
 9365                .unwrap_or(true);
 9366            if hide_runnables {
 9367                return;
 9368            }
 9369            let new_rows =
 9370                cx.background_executor()
 9371                    .spawn({
 9372                        let snapshot = display_snapshot.clone();
 9373                        async move {
 9374                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 9375                        }
 9376                    })
 9377                    .await;
 9378            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 9379
 9380            this.update(&mut cx, |this, _| {
 9381                this.clear_tasks();
 9382                for (key, value) in rows {
 9383                    this.insert_tasks(key, value);
 9384                }
 9385            })
 9386            .ok();
 9387        })
 9388    }
 9389    fn fetch_runnable_ranges(
 9390        snapshot: &DisplaySnapshot,
 9391        range: Range<Anchor>,
 9392    ) -> Vec<language::RunnableRange> {
 9393        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 9394    }
 9395
 9396    fn runnable_rows(
 9397        project: Model<Project>,
 9398        snapshot: DisplaySnapshot,
 9399        runnable_ranges: Vec<RunnableRange>,
 9400        mut cx: AsyncWindowContext,
 9401    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 9402        runnable_ranges
 9403            .into_iter()
 9404            .filter_map(|mut runnable| {
 9405                let tasks = cx
 9406                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 9407                    .ok()?;
 9408                if tasks.is_empty() {
 9409                    return None;
 9410                }
 9411
 9412                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 9413
 9414                let row = snapshot
 9415                    .buffer_snapshot
 9416                    .buffer_line_for_row(MultiBufferRow(point.row))?
 9417                    .1
 9418                    .start
 9419                    .row;
 9420
 9421                let context_range =
 9422                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 9423                Some((
 9424                    (runnable.buffer_id, row),
 9425                    RunnableTasks {
 9426                        templates: tasks,
 9427                        offset: MultiBufferOffset(runnable.run_range.start),
 9428                        context_range,
 9429                        column: point.column,
 9430                        extra_variables: runnable.extra_captures,
 9431                    },
 9432                ))
 9433            })
 9434            .collect()
 9435    }
 9436
 9437    fn templates_with_tags(
 9438        project: &Model<Project>,
 9439        runnable: &mut Runnable,
 9440        cx: &WindowContext<'_>,
 9441    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 9442        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 9443            let (worktree_id, file) = project
 9444                .buffer_for_id(runnable.buffer, cx)
 9445                .and_then(|buffer| buffer.read(cx).file())
 9446                .map(|file| (file.worktree_id(cx), file.clone()))
 9447                .unzip();
 9448
 9449            (
 9450                project.task_store().read(cx).task_inventory().cloned(),
 9451                worktree_id,
 9452                file,
 9453            )
 9454        });
 9455
 9456        let tags = mem::take(&mut runnable.tags);
 9457        let mut tags: Vec<_> = tags
 9458            .into_iter()
 9459            .flat_map(|tag| {
 9460                let tag = tag.0.clone();
 9461                inventory
 9462                    .as_ref()
 9463                    .into_iter()
 9464                    .flat_map(|inventory| {
 9465                        inventory.read(cx).list_tasks(
 9466                            file.clone(),
 9467                            Some(runnable.language.clone()),
 9468                            worktree_id,
 9469                            cx,
 9470                        )
 9471                    })
 9472                    .filter(move |(_, template)| {
 9473                        template.tags.iter().any(|source_tag| source_tag == &tag)
 9474                    })
 9475            })
 9476            .sorted_by_key(|(kind, _)| kind.to_owned())
 9477            .collect();
 9478        if let Some((leading_tag_source, _)) = tags.first() {
 9479            // Strongest source wins; if we have worktree tag binding, prefer that to
 9480            // global and language bindings;
 9481            // if we have a global binding, prefer that to language binding.
 9482            let first_mismatch = tags
 9483                .iter()
 9484                .position(|(tag_source, _)| tag_source != leading_tag_source);
 9485            if let Some(index) = first_mismatch {
 9486                tags.truncate(index);
 9487            }
 9488        }
 9489
 9490        tags
 9491    }
 9492
 9493    pub fn move_to_enclosing_bracket(
 9494        &mut self,
 9495        _: &MoveToEnclosingBracket,
 9496        cx: &mut ViewContext<Self>,
 9497    ) {
 9498        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9499            s.move_offsets_with(|snapshot, selection| {
 9500                let Some(enclosing_bracket_ranges) =
 9501                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 9502                else {
 9503                    return;
 9504                };
 9505
 9506                let mut best_length = usize::MAX;
 9507                let mut best_inside = false;
 9508                let mut best_in_bracket_range = false;
 9509                let mut best_destination = None;
 9510                for (open, close) in enclosing_bracket_ranges {
 9511                    let close = close.to_inclusive();
 9512                    let length = close.end() - open.start;
 9513                    let inside = selection.start >= open.end && selection.end <= *close.start();
 9514                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 9515                        || close.contains(&selection.head());
 9516
 9517                    // If best is next to a bracket and current isn't, skip
 9518                    if !in_bracket_range && best_in_bracket_range {
 9519                        continue;
 9520                    }
 9521
 9522                    // Prefer smaller lengths unless best is inside and current isn't
 9523                    if length > best_length && (best_inside || !inside) {
 9524                        continue;
 9525                    }
 9526
 9527                    best_length = length;
 9528                    best_inside = inside;
 9529                    best_in_bracket_range = in_bracket_range;
 9530                    best_destination = Some(
 9531                        if close.contains(&selection.start) && close.contains(&selection.end) {
 9532                            if inside {
 9533                                open.end
 9534                            } else {
 9535                                open.start
 9536                            }
 9537                        } else if inside {
 9538                            *close.start()
 9539                        } else {
 9540                            *close.end()
 9541                        },
 9542                    );
 9543                }
 9544
 9545                if let Some(destination) = best_destination {
 9546                    selection.collapse_to(destination, SelectionGoal::None);
 9547                }
 9548            })
 9549        });
 9550    }
 9551
 9552    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 9553        self.end_selection(cx);
 9554        self.selection_history.mode = SelectionHistoryMode::Undoing;
 9555        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 9556            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9557            self.select_next_state = entry.select_next_state;
 9558            self.select_prev_state = entry.select_prev_state;
 9559            self.add_selections_state = entry.add_selections_state;
 9560            self.request_autoscroll(Autoscroll::newest(), cx);
 9561        }
 9562        self.selection_history.mode = SelectionHistoryMode::Normal;
 9563    }
 9564
 9565    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 9566        self.end_selection(cx);
 9567        self.selection_history.mode = SelectionHistoryMode::Redoing;
 9568        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 9569            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9570            self.select_next_state = entry.select_next_state;
 9571            self.select_prev_state = entry.select_prev_state;
 9572            self.add_selections_state = entry.add_selections_state;
 9573            self.request_autoscroll(Autoscroll::newest(), cx);
 9574        }
 9575        self.selection_history.mode = SelectionHistoryMode::Normal;
 9576    }
 9577
 9578    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 9579        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 9580    }
 9581
 9582    pub fn expand_excerpts_down(
 9583        &mut self,
 9584        action: &ExpandExcerptsDown,
 9585        cx: &mut ViewContext<Self>,
 9586    ) {
 9587        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 9588    }
 9589
 9590    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 9591        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 9592    }
 9593
 9594    pub fn expand_excerpts_for_direction(
 9595        &mut self,
 9596        lines: u32,
 9597        direction: ExpandExcerptDirection,
 9598        cx: &mut ViewContext<Self>,
 9599    ) {
 9600        let selections = self.selections.disjoint_anchors();
 9601
 9602        let lines = if lines == 0 {
 9603            EditorSettings::get_global(cx).expand_excerpt_lines
 9604        } else {
 9605            lines
 9606        };
 9607
 9608        self.buffer.update(cx, |buffer, cx| {
 9609            buffer.expand_excerpts(
 9610                selections
 9611                    .iter()
 9612                    .map(|selection| selection.head().excerpt_id)
 9613                    .dedup(),
 9614                lines,
 9615                direction,
 9616                cx,
 9617            )
 9618        })
 9619    }
 9620
 9621    pub fn expand_excerpt(
 9622        &mut self,
 9623        excerpt: ExcerptId,
 9624        direction: ExpandExcerptDirection,
 9625        cx: &mut ViewContext<Self>,
 9626    ) {
 9627        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 9628        self.buffer.update(cx, |buffer, cx| {
 9629            buffer.expand_excerpts([excerpt], lines, direction, cx)
 9630        })
 9631    }
 9632
 9633    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 9634        self.go_to_diagnostic_impl(Direction::Next, cx)
 9635    }
 9636
 9637    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 9638        self.go_to_diagnostic_impl(Direction::Prev, cx)
 9639    }
 9640
 9641    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 9642        let buffer = self.buffer.read(cx).snapshot(cx);
 9643        let selection = self.selections.newest::<usize>(cx);
 9644
 9645        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 9646        if direction == Direction::Next {
 9647            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 9648                let (group_id, jump_to) = popover.activation_info();
 9649                if self.activate_diagnostics(group_id, cx) {
 9650                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9651                        let mut new_selection = s.newest_anchor().clone();
 9652                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 9653                        s.select_anchors(vec![new_selection.clone()]);
 9654                    });
 9655                }
 9656                return;
 9657            }
 9658        }
 9659
 9660        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 9661            active_diagnostics
 9662                .primary_range
 9663                .to_offset(&buffer)
 9664                .to_inclusive()
 9665        });
 9666        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 9667            if active_primary_range.contains(&selection.head()) {
 9668                *active_primary_range.start()
 9669            } else {
 9670                selection.head()
 9671            }
 9672        } else {
 9673            selection.head()
 9674        };
 9675        let snapshot = self.snapshot(cx);
 9676        loop {
 9677            let diagnostics = if direction == Direction::Prev {
 9678                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 9679            } else {
 9680                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 9681            }
 9682            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 9683            let group = diagnostics
 9684                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 9685                // be sorted in a stable way
 9686                // skip until we are at current active diagnostic, if it exists
 9687                .skip_while(|entry| {
 9688                    (match direction {
 9689                        Direction::Prev => entry.range.start >= search_start,
 9690                        Direction::Next => entry.range.start <= search_start,
 9691                    }) && self
 9692                        .active_diagnostics
 9693                        .as_ref()
 9694                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 9695                })
 9696                .find_map(|entry| {
 9697                    if entry.diagnostic.is_primary
 9698                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 9699                        && !entry.range.is_empty()
 9700                        // if we match with the active diagnostic, skip it
 9701                        && Some(entry.diagnostic.group_id)
 9702                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 9703                    {
 9704                        Some((entry.range, entry.diagnostic.group_id))
 9705                    } else {
 9706                        None
 9707                    }
 9708                });
 9709
 9710            if let Some((primary_range, group_id)) = group {
 9711                if self.activate_diagnostics(group_id, cx) {
 9712                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9713                        s.select(vec![Selection {
 9714                            id: selection.id,
 9715                            start: primary_range.start,
 9716                            end: primary_range.start,
 9717                            reversed: false,
 9718                            goal: SelectionGoal::None,
 9719                        }]);
 9720                    });
 9721                }
 9722                break;
 9723            } else {
 9724                // Cycle around to the start of the buffer, potentially moving back to the start of
 9725                // the currently active diagnostic.
 9726                active_primary_range.take();
 9727                if direction == Direction::Prev {
 9728                    if search_start == buffer.len() {
 9729                        break;
 9730                    } else {
 9731                        search_start = buffer.len();
 9732                    }
 9733                } else if search_start == 0 {
 9734                    break;
 9735                } else {
 9736                    search_start = 0;
 9737                }
 9738            }
 9739        }
 9740    }
 9741
 9742    fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 9743        let snapshot = self
 9744            .display_map
 9745            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9746        let selection = self.selections.newest::<Point>(cx);
 9747        self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
 9748    }
 9749
 9750    fn go_to_hunk_after_position(
 9751        &mut self,
 9752        snapshot: &DisplaySnapshot,
 9753        position: Point,
 9754        cx: &mut ViewContext<'_, Editor>,
 9755    ) -> Option<MultiBufferDiffHunk> {
 9756        if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9757            snapshot,
 9758            position,
 9759            false,
 9760            snapshot
 9761                .buffer_snapshot
 9762                .git_diff_hunks_in_range(MultiBufferRow(position.row + 1)..MultiBufferRow::MAX),
 9763            cx,
 9764        ) {
 9765            return Some(hunk);
 9766        }
 9767
 9768        let wrapped_point = Point::zero();
 9769        self.go_to_next_hunk_in_direction(
 9770            snapshot,
 9771            wrapped_point,
 9772            true,
 9773            snapshot.buffer_snapshot.git_diff_hunks_in_range(
 9774                MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
 9775            ),
 9776            cx,
 9777        )
 9778    }
 9779
 9780    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 9781        let snapshot = self
 9782            .display_map
 9783            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9784        let selection = self.selections.newest::<Point>(cx);
 9785
 9786        self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
 9787    }
 9788
 9789    fn go_to_hunk_before_position(
 9790        &mut self,
 9791        snapshot: &DisplaySnapshot,
 9792        position: Point,
 9793        cx: &mut ViewContext<'_, Editor>,
 9794    ) -> Option<MultiBufferDiffHunk> {
 9795        if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9796            snapshot,
 9797            position,
 9798            false,
 9799            snapshot
 9800                .buffer_snapshot
 9801                .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(position.row)),
 9802            cx,
 9803        ) {
 9804            return Some(hunk);
 9805        }
 9806
 9807        let wrapped_point = snapshot.buffer_snapshot.max_point();
 9808        self.go_to_next_hunk_in_direction(
 9809            snapshot,
 9810            wrapped_point,
 9811            true,
 9812            snapshot
 9813                .buffer_snapshot
 9814                .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(wrapped_point.row)),
 9815            cx,
 9816        )
 9817    }
 9818
 9819    fn go_to_next_hunk_in_direction(
 9820        &mut self,
 9821        snapshot: &DisplaySnapshot,
 9822        initial_point: Point,
 9823        is_wrapped: bool,
 9824        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
 9825        cx: &mut ViewContext<Editor>,
 9826    ) -> Option<MultiBufferDiffHunk> {
 9827        let display_point = initial_point.to_display_point(snapshot);
 9828        let mut hunks = hunks
 9829            .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
 9830            .filter(|(display_hunk, _)| {
 9831                is_wrapped || !display_hunk.contains_display_row(display_point.row())
 9832            })
 9833            .dedup();
 9834
 9835        if let Some((display_hunk, hunk)) = hunks.next() {
 9836            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9837                let row = display_hunk.start_display_row();
 9838                let point = DisplayPoint::new(row, 0);
 9839                s.select_display_ranges([point..point]);
 9840            });
 9841
 9842            Some(hunk)
 9843        } else {
 9844            None
 9845        }
 9846    }
 9847
 9848    pub fn go_to_definition(
 9849        &mut self,
 9850        _: &GoToDefinition,
 9851        cx: &mut ViewContext<Self>,
 9852    ) -> Task<Result<Navigated>> {
 9853        let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
 9854        cx.spawn(|editor, mut cx| async move {
 9855            if definition.await? == Navigated::Yes {
 9856                return Ok(Navigated::Yes);
 9857            }
 9858            match editor.update(&mut cx, |editor, cx| {
 9859                editor.find_all_references(&FindAllReferences, cx)
 9860            })? {
 9861                Some(references) => references.await,
 9862                None => Ok(Navigated::No),
 9863            }
 9864        })
 9865    }
 9866
 9867    pub fn go_to_declaration(
 9868        &mut self,
 9869        _: &GoToDeclaration,
 9870        cx: &mut ViewContext<Self>,
 9871    ) -> Task<Result<Navigated>> {
 9872        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
 9873    }
 9874
 9875    pub fn go_to_declaration_split(
 9876        &mut self,
 9877        _: &GoToDeclaration,
 9878        cx: &mut ViewContext<Self>,
 9879    ) -> Task<Result<Navigated>> {
 9880        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
 9881    }
 9882
 9883    pub fn go_to_implementation(
 9884        &mut self,
 9885        _: &GoToImplementation,
 9886        cx: &mut ViewContext<Self>,
 9887    ) -> Task<Result<Navigated>> {
 9888        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 9889    }
 9890
 9891    pub fn go_to_implementation_split(
 9892        &mut self,
 9893        _: &GoToImplementationSplit,
 9894        cx: &mut ViewContext<Self>,
 9895    ) -> Task<Result<Navigated>> {
 9896        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 9897    }
 9898
 9899    pub fn go_to_type_definition(
 9900        &mut self,
 9901        _: &GoToTypeDefinition,
 9902        cx: &mut ViewContext<Self>,
 9903    ) -> Task<Result<Navigated>> {
 9904        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 9905    }
 9906
 9907    pub fn go_to_definition_split(
 9908        &mut self,
 9909        _: &GoToDefinitionSplit,
 9910        cx: &mut ViewContext<Self>,
 9911    ) -> Task<Result<Navigated>> {
 9912        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 9913    }
 9914
 9915    pub fn go_to_type_definition_split(
 9916        &mut self,
 9917        _: &GoToTypeDefinitionSplit,
 9918        cx: &mut ViewContext<Self>,
 9919    ) -> Task<Result<Navigated>> {
 9920        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 9921    }
 9922
 9923    fn go_to_definition_of_kind(
 9924        &mut self,
 9925        kind: GotoDefinitionKind,
 9926        split: bool,
 9927        cx: &mut ViewContext<Self>,
 9928    ) -> Task<Result<Navigated>> {
 9929        let Some(provider) = self.semantics_provider.clone() else {
 9930            return Task::ready(Ok(Navigated::No));
 9931        };
 9932        let head = self.selections.newest::<usize>(cx).head();
 9933        let buffer = self.buffer.read(cx);
 9934        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 9935            text_anchor
 9936        } else {
 9937            return Task::ready(Ok(Navigated::No));
 9938        };
 9939
 9940        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
 9941            return Task::ready(Ok(Navigated::No));
 9942        };
 9943
 9944        cx.spawn(|editor, mut cx| async move {
 9945            let definitions = definitions.await?;
 9946            let navigated = editor
 9947                .update(&mut cx, |editor, cx| {
 9948                    editor.navigate_to_hover_links(
 9949                        Some(kind),
 9950                        definitions
 9951                            .into_iter()
 9952                            .filter(|location| {
 9953                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 9954                            })
 9955                            .map(HoverLink::Text)
 9956                            .collect::<Vec<_>>(),
 9957                        split,
 9958                        cx,
 9959                    )
 9960                })?
 9961                .await?;
 9962            anyhow::Ok(navigated)
 9963        })
 9964    }
 9965
 9966    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 9967        let position = self.selections.newest_anchor().head();
 9968        let Some((buffer, buffer_position)) =
 9969            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9970        else {
 9971            return;
 9972        };
 9973
 9974        cx.spawn(|editor, mut cx| async move {
 9975            if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
 9976                editor.update(&mut cx, |_, cx| {
 9977                    cx.open_url(&url);
 9978                })
 9979            } else {
 9980                Ok(())
 9981            }
 9982        })
 9983        .detach();
 9984    }
 9985
 9986    pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
 9987        let Some(workspace) = self.workspace() else {
 9988            return;
 9989        };
 9990
 9991        let position = self.selections.newest_anchor().head();
 9992
 9993        let Some((buffer, buffer_position)) =
 9994            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9995        else {
 9996            return;
 9997        };
 9998
 9999        let project = self.project.clone();
10000
10001        cx.spawn(|_, mut cx| async move {
10002            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10003
10004            if let Some((_, path)) = result {
10005                workspace
10006                    .update(&mut cx, |workspace, cx| {
10007                        workspace.open_resolved_path(path, cx)
10008                    })?
10009                    .await?;
10010            }
10011            anyhow::Ok(())
10012        })
10013        .detach();
10014    }
10015
10016    pub(crate) fn navigate_to_hover_links(
10017        &mut self,
10018        kind: Option<GotoDefinitionKind>,
10019        mut definitions: Vec<HoverLink>,
10020        split: bool,
10021        cx: &mut ViewContext<Editor>,
10022    ) -> Task<Result<Navigated>> {
10023        // If there is one definition, just open it directly
10024        if definitions.len() == 1 {
10025            let definition = definitions.pop().unwrap();
10026
10027            enum TargetTaskResult {
10028                Location(Option<Location>),
10029                AlreadyNavigated,
10030            }
10031
10032            let target_task = match definition {
10033                HoverLink::Text(link) => {
10034                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10035                }
10036                HoverLink::InlayHint(lsp_location, server_id) => {
10037                    let computation = self.compute_target_location(lsp_location, server_id, cx);
10038                    cx.background_executor().spawn(async move {
10039                        let location = computation.await?;
10040                        Ok(TargetTaskResult::Location(location))
10041                    })
10042                }
10043                HoverLink::Url(url) => {
10044                    cx.open_url(&url);
10045                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10046                }
10047                HoverLink::File(path) => {
10048                    if let Some(workspace) = self.workspace() {
10049                        cx.spawn(|_, mut cx| async move {
10050                            workspace
10051                                .update(&mut cx, |workspace, cx| {
10052                                    workspace.open_resolved_path(path, cx)
10053                                })?
10054                                .await
10055                                .map(|_| TargetTaskResult::AlreadyNavigated)
10056                        })
10057                    } else {
10058                        Task::ready(Ok(TargetTaskResult::Location(None)))
10059                    }
10060                }
10061            };
10062            cx.spawn(|editor, mut cx| async move {
10063                let target = match target_task.await.context("target resolution task")? {
10064                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10065                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
10066                    TargetTaskResult::Location(Some(target)) => target,
10067                };
10068
10069                editor.update(&mut cx, |editor, cx| {
10070                    let Some(workspace) = editor.workspace() else {
10071                        return Navigated::No;
10072                    };
10073                    let pane = workspace.read(cx).active_pane().clone();
10074
10075                    let range = target.range.to_offset(target.buffer.read(cx));
10076                    let range = editor.range_for_match(&range);
10077
10078                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10079                        let buffer = target.buffer.read(cx);
10080                        let range = check_multiline_range(buffer, range);
10081                        editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10082                            s.select_ranges([range]);
10083                        });
10084                    } else {
10085                        cx.window_context().defer(move |cx| {
10086                            let target_editor: View<Self> =
10087                                workspace.update(cx, |workspace, cx| {
10088                                    let pane = if split {
10089                                        workspace.adjacent_pane(cx)
10090                                    } else {
10091                                        workspace.active_pane().clone()
10092                                    };
10093
10094                                    workspace.open_project_item(
10095                                        pane,
10096                                        target.buffer.clone(),
10097                                        true,
10098                                        true,
10099                                        cx,
10100                                    )
10101                                });
10102                            target_editor.update(cx, |target_editor, cx| {
10103                                // When selecting a definition in a different buffer, disable the nav history
10104                                // to avoid creating a history entry at the previous cursor location.
10105                                pane.update(cx, |pane, _| pane.disable_history());
10106                                let buffer = target.buffer.read(cx);
10107                                let range = check_multiline_range(buffer, range);
10108                                target_editor.change_selections(
10109                                    Some(Autoscroll::focused()),
10110                                    cx,
10111                                    |s| {
10112                                        s.select_ranges([range]);
10113                                    },
10114                                );
10115                                pane.update(cx, |pane, _| pane.enable_history());
10116                            });
10117                        });
10118                    }
10119                    Navigated::Yes
10120                })
10121            })
10122        } else if !definitions.is_empty() {
10123            cx.spawn(|editor, mut cx| async move {
10124                let (title, location_tasks, workspace) = editor
10125                    .update(&mut cx, |editor, cx| {
10126                        let tab_kind = match kind {
10127                            Some(GotoDefinitionKind::Implementation) => "Implementations",
10128                            _ => "Definitions",
10129                        };
10130                        let title = definitions
10131                            .iter()
10132                            .find_map(|definition| match definition {
10133                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10134                                    let buffer = origin.buffer.read(cx);
10135                                    format!(
10136                                        "{} for {}",
10137                                        tab_kind,
10138                                        buffer
10139                                            .text_for_range(origin.range.clone())
10140                                            .collect::<String>()
10141                                    )
10142                                }),
10143                                HoverLink::InlayHint(_, _) => None,
10144                                HoverLink::Url(_) => None,
10145                                HoverLink::File(_) => None,
10146                            })
10147                            .unwrap_or(tab_kind.to_string());
10148                        let location_tasks = definitions
10149                            .into_iter()
10150                            .map(|definition| match definition {
10151                                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
10152                                HoverLink::InlayHint(lsp_location, server_id) => {
10153                                    editor.compute_target_location(lsp_location, server_id, cx)
10154                                }
10155                                HoverLink::Url(_) => Task::ready(Ok(None)),
10156                                HoverLink::File(_) => Task::ready(Ok(None)),
10157                            })
10158                            .collect::<Vec<_>>();
10159                        (title, location_tasks, editor.workspace().clone())
10160                    })
10161                    .context("location tasks preparation")?;
10162
10163                let locations = future::join_all(location_tasks)
10164                    .await
10165                    .into_iter()
10166                    .filter_map(|location| location.transpose())
10167                    .collect::<Result<_>>()
10168                    .context("location tasks")?;
10169
10170                let Some(workspace) = workspace else {
10171                    return Ok(Navigated::No);
10172                };
10173                let opened = workspace
10174                    .update(&mut cx, |workspace, cx| {
10175                        Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
10176                    })
10177                    .ok();
10178
10179                anyhow::Ok(Navigated::from_bool(opened.is_some()))
10180            })
10181        } else {
10182            Task::ready(Ok(Navigated::No))
10183        }
10184    }
10185
10186    fn compute_target_location(
10187        &self,
10188        lsp_location: lsp::Location,
10189        server_id: LanguageServerId,
10190        cx: &mut ViewContext<Self>,
10191    ) -> Task<anyhow::Result<Option<Location>>> {
10192        let Some(project) = self.project.clone() else {
10193            return Task::Ready(Some(Ok(None)));
10194        };
10195
10196        cx.spawn(move |editor, mut cx| async move {
10197            let location_task = editor.update(&mut cx, |_, cx| {
10198                project.update(cx, |project, cx| {
10199                    let language_server_name = project
10200                        .language_server_statuses(cx)
10201                        .find(|(id, _)| server_id == *id)
10202                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10203                    language_server_name.map(|language_server_name| {
10204                        project.open_local_buffer_via_lsp(
10205                            lsp_location.uri.clone(),
10206                            server_id,
10207                            language_server_name,
10208                            cx,
10209                        )
10210                    })
10211                })
10212            })?;
10213            let location = match location_task {
10214                Some(task) => Some({
10215                    let target_buffer_handle = task.await.context("open local buffer")?;
10216                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10217                        let target_start = target_buffer
10218                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10219                        let target_end = target_buffer
10220                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10221                        target_buffer.anchor_after(target_start)
10222                            ..target_buffer.anchor_before(target_end)
10223                    })?;
10224                    Location {
10225                        buffer: target_buffer_handle,
10226                        range,
10227                    }
10228                }),
10229                None => None,
10230            };
10231            Ok(location)
10232        })
10233    }
10234
10235    pub fn find_all_references(
10236        &mut self,
10237        _: &FindAllReferences,
10238        cx: &mut ViewContext<Self>,
10239    ) -> Option<Task<Result<Navigated>>> {
10240        let selection = self.selections.newest::<usize>(cx);
10241        let multi_buffer = self.buffer.read(cx);
10242        let head = selection.head();
10243
10244        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10245        let head_anchor = multi_buffer_snapshot.anchor_at(
10246            head,
10247            if head < selection.tail() {
10248                Bias::Right
10249            } else {
10250                Bias::Left
10251            },
10252        );
10253
10254        match self
10255            .find_all_references_task_sources
10256            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10257        {
10258            Ok(_) => {
10259                log::info!(
10260                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
10261                );
10262                return None;
10263            }
10264            Err(i) => {
10265                self.find_all_references_task_sources.insert(i, head_anchor);
10266            }
10267        }
10268
10269        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10270        let workspace = self.workspace()?;
10271        let project = workspace.read(cx).project().clone();
10272        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10273        Some(cx.spawn(|editor, mut cx| async move {
10274            let _cleanup = defer({
10275                let mut cx = cx.clone();
10276                move || {
10277                    let _ = editor.update(&mut cx, |editor, _| {
10278                        if let Ok(i) =
10279                            editor
10280                                .find_all_references_task_sources
10281                                .binary_search_by(|anchor| {
10282                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10283                                })
10284                        {
10285                            editor.find_all_references_task_sources.remove(i);
10286                        }
10287                    });
10288                }
10289            });
10290
10291            let locations = references.await?;
10292            if locations.is_empty() {
10293                return anyhow::Ok(Navigated::No);
10294            }
10295
10296            workspace.update(&mut cx, |workspace, cx| {
10297                let title = locations
10298                    .first()
10299                    .as_ref()
10300                    .map(|location| {
10301                        let buffer = location.buffer.read(cx);
10302                        format!(
10303                            "References to `{}`",
10304                            buffer
10305                                .text_for_range(location.range.clone())
10306                                .collect::<String>()
10307                        )
10308                    })
10309                    .unwrap();
10310                Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
10311                Navigated::Yes
10312            })
10313        }))
10314    }
10315
10316    /// Opens a multibuffer with the given project locations in it
10317    pub fn open_locations_in_multibuffer(
10318        workspace: &mut Workspace,
10319        mut locations: Vec<Location>,
10320        title: String,
10321        split: bool,
10322        cx: &mut ViewContext<Workspace>,
10323    ) {
10324        // If there are multiple definitions, open them in a multibuffer
10325        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10326        let mut locations = locations.into_iter().peekable();
10327        let mut ranges_to_highlight = Vec::new();
10328        let capability = workspace.project().read(cx).capability();
10329
10330        let excerpt_buffer = cx.new_model(|cx| {
10331            let mut multibuffer = MultiBuffer::new(capability);
10332            while let Some(location) = locations.next() {
10333                let buffer = location.buffer.read(cx);
10334                let mut ranges_for_buffer = Vec::new();
10335                let range = location.range.to_offset(buffer);
10336                ranges_for_buffer.push(range.clone());
10337
10338                while let Some(next_location) = locations.peek() {
10339                    if next_location.buffer == location.buffer {
10340                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
10341                        locations.next();
10342                    } else {
10343                        break;
10344                    }
10345                }
10346
10347                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10348                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
10349                    location.buffer.clone(),
10350                    ranges_for_buffer,
10351                    DEFAULT_MULTIBUFFER_CONTEXT,
10352                    cx,
10353                ))
10354            }
10355
10356            multibuffer.with_title(title)
10357        });
10358
10359        let editor = cx.new_view(|cx| {
10360            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
10361        });
10362        editor.update(cx, |editor, cx| {
10363            if let Some(first_range) = ranges_to_highlight.first() {
10364                editor.change_selections(None, cx, |selections| {
10365                    selections.clear_disjoint();
10366                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10367                });
10368            }
10369            editor.highlight_background::<Self>(
10370                &ranges_to_highlight,
10371                |theme| theme.editor_highlighted_line_background,
10372                cx,
10373            );
10374        });
10375
10376        let item = Box::new(editor);
10377        let item_id = item.item_id();
10378
10379        if split {
10380            workspace.split_item(SplitDirection::Right, item.clone(), cx);
10381        } else {
10382            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10383                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10384                    pane.close_current_preview_item(cx)
10385                } else {
10386                    None
10387                }
10388            });
10389            workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
10390        }
10391        workspace.active_pane().update(cx, |pane, cx| {
10392            pane.set_preview_item_id(Some(item_id), cx);
10393        });
10394    }
10395
10396    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10397        use language::ToOffset as _;
10398
10399        let provider = self.semantics_provider.clone()?;
10400        let selection = self.selections.newest_anchor().clone();
10401        let (cursor_buffer, cursor_buffer_position) = self
10402            .buffer
10403            .read(cx)
10404            .text_anchor_for_position(selection.head(), cx)?;
10405        let (tail_buffer, cursor_buffer_position_end) = self
10406            .buffer
10407            .read(cx)
10408            .text_anchor_for_position(selection.tail(), cx)?;
10409        if tail_buffer != cursor_buffer {
10410            return None;
10411        }
10412
10413        let snapshot = cursor_buffer.read(cx).snapshot();
10414        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10415        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10416        let prepare_rename = provider
10417            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10418            .unwrap_or_else(|| Task::ready(Ok(None)));
10419        drop(snapshot);
10420
10421        Some(cx.spawn(|this, mut cx| async move {
10422            let rename_range = if let Some(range) = prepare_rename.await? {
10423                Some(range)
10424            } else {
10425                this.update(&mut cx, |this, cx| {
10426                    let buffer = this.buffer.read(cx).snapshot(cx);
10427                    let mut buffer_highlights = this
10428                        .document_highlights_for_position(selection.head(), &buffer)
10429                        .filter(|highlight| {
10430                            highlight.start.excerpt_id == selection.head().excerpt_id
10431                                && highlight.end.excerpt_id == selection.head().excerpt_id
10432                        });
10433                    buffer_highlights
10434                        .next()
10435                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10436                })?
10437            };
10438            if let Some(rename_range) = rename_range {
10439                this.update(&mut cx, |this, cx| {
10440                    let snapshot = cursor_buffer.read(cx).snapshot();
10441                    let rename_buffer_range = rename_range.to_offset(&snapshot);
10442                    let cursor_offset_in_rename_range =
10443                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10444                    let cursor_offset_in_rename_range_end =
10445                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10446
10447                    this.take_rename(false, cx);
10448                    let buffer = this.buffer.read(cx).read(cx);
10449                    let cursor_offset = selection.head().to_offset(&buffer);
10450                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10451                    let rename_end = rename_start + rename_buffer_range.len();
10452                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10453                    let mut old_highlight_id = None;
10454                    let old_name: Arc<str> = buffer
10455                        .chunks(rename_start..rename_end, true)
10456                        .map(|chunk| {
10457                            if old_highlight_id.is_none() {
10458                                old_highlight_id = chunk.syntax_highlight_id;
10459                            }
10460                            chunk.text
10461                        })
10462                        .collect::<String>()
10463                        .into();
10464
10465                    drop(buffer);
10466
10467                    // Position the selection in the rename editor so that it matches the current selection.
10468                    this.show_local_selections = false;
10469                    let rename_editor = cx.new_view(|cx| {
10470                        let mut editor = Editor::single_line(cx);
10471                        editor.buffer.update(cx, |buffer, cx| {
10472                            buffer.edit([(0..0, old_name.clone())], None, cx)
10473                        });
10474                        let rename_selection_range = match cursor_offset_in_rename_range
10475                            .cmp(&cursor_offset_in_rename_range_end)
10476                        {
10477                            Ordering::Equal => {
10478                                editor.select_all(&SelectAll, cx);
10479                                return editor;
10480                            }
10481                            Ordering::Less => {
10482                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10483                            }
10484                            Ordering::Greater => {
10485                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10486                            }
10487                        };
10488                        if rename_selection_range.end > old_name.len() {
10489                            editor.select_all(&SelectAll, cx);
10490                        } else {
10491                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10492                                s.select_ranges([rename_selection_range]);
10493                            });
10494                        }
10495                        editor
10496                    });
10497                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10498                        if e == &EditorEvent::Focused {
10499                            cx.emit(EditorEvent::FocusedIn)
10500                        }
10501                    })
10502                    .detach();
10503
10504                    let write_highlights =
10505                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10506                    let read_highlights =
10507                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
10508                    let ranges = write_highlights
10509                        .iter()
10510                        .flat_map(|(_, ranges)| ranges.iter())
10511                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10512                        .cloned()
10513                        .collect();
10514
10515                    this.highlight_text::<Rename>(
10516                        ranges,
10517                        HighlightStyle {
10518                            fade_out: Some(0.6),
10519                            ..Default::default()
10520                        },
10521                        cx,
10522                    );
10523                    let rename_focus_handle = rename_editor.focus_handle(cx);
10524                    cx.focus(&rename_focus_handle);
10525                    let block_id = this.insert_blocks(
10526                        [BlockProperties {
10527                            style: BlockStyle::Flex,
10528                            placement: BlockPlacement::Below(range.start),
10529                            height: 1,
10530                            render: Arc::new({
10531                                let rename_editor = rename_editor.clone();
10532                                move |cx: &mut BlockContext| {
10533                                    let mut text_style = cx.editor_style.text.clone();
10534                                    if let Some(highlight_style) = old_highlight_id
10535                                        .and_then(|h| h.style(&cx.editor_style.syntax))
10536                                    {
10537                                        text_style = text_style.highlight(highlight_style);
10538                                    }
10539                                    div()
10540                                        .block_mouse_down()
10541                                        .pl(cx.anchor_x)
10542                                        .child(EditorElement::new(
10543                                            &rename_editor,
10544                                            EditorStyle {
10545                                                background: cx.theme().system().transparent,
10546                                                local_player: cx.editor_style.local_player,
10547                                                text: text_style,
10548                                                scrollbar_width: cx.editor_style.scrollbar_width,
10549                                                syntax: cx.editor_style.syntax.clone(),
10550                                                status: cx.editor_style.status.clone(),
10551                                                inlay_hints_style: HighlightStyle {
10552                                                    font_weight: Some(FontWeight::BOLD),
10553                                                    ..make_inlay_hints_style(cx)
10554                                                },
10555                                                suggestions_style: HighlightStyle {
10556                                                    color: Some(cx.theme().status().predictive),
10557                                                    ..HighlightStyle::default()
10558                                                },
10559                                                ..EditorStyle::default()
10560                                            },
10561                                        ))
10562                                        .into_any_element()
10563                                }
10564                            }),
10565                            priority: 0,
10566                        }],
10567                        Some(Autoscroll::fit()),
10568                        cx,
10569                    )[0];
10570                    this.pending_rename = Some(RenameState {
10571                        range,
10572                        old_name,
10573                        editor: rename_editor,
10574                        block_id,
10575                    });
10576                })?;
10577            }
10578
10579            Ok(())
10580        }))
10581    }
10582
10583    pub fn confirm_rename(
10584        &mut self,
10585        _: &ConfirmRename,
10586        cx: &mut ViewContext<Self>,
10587    ) -> Option<Task<Result<()>>> {
10588        let rename = self.take_rename(false, cx)?;
10589        let workspace = self.workspace()?.downgrade();
10590        let (buffer, start) = self
10591            .buffer
10592            .read(cx)
10593            .text_anchor_for_position(rename.range.start, cx)?;
10594        let (end_buffer, _) = self
10595            .buffer
10596            .read(cx)
10597            .text_anchor_for_position(rename.range.end, cx)?;
10598        if buffer != end_buffer {
10599            return None;
10600        }
10601
10602        let old_name = rename.old_name;
10603        let new_name = rename.editor.read(cx).text(cx);
10604
10605        let rename = self.semantics_provider.as_ref()?.perform_rename(
10606            &buffer,
10607            start,
10608            new_name.clone(),
10609            cx,
10610        )?;
10611
10612        Some(cx.spawn(|editor, mut cx| async move {
10613            let project_transaction = rename.await?;
10614            Self::open_project_transaction(
10615                &editor,
10616                workspace,
10617                project_transaction,
10618                format!("Rename: {}{}", old_name, new_name),
10619                cx.clone(),
10620            )
10621            .await?;
10622
10623            editor.update(&mut cx, |editor, cx| {
10624                editor.refresh_document_highlights(cx);
10625            })?;
10626            Ok(())
10627        }))
10628    }
10629
10630    fn take_rename(
10631        &mut self,
10632        moving_cursor: bool,
10633        cx: &mut ViewContext<Self>,
10634    ) -> Option<RenameState> {
10635        let rename = self.pending_rename.take()?;
10636        if rename.editor.focus_handle(cx).is_focused(cx) {
10637            cx.focus(&self.focus_handle);
10638        }
10639
10640        self.remove_blocks(
10641            [rename.block_id].into_iter().collect(),
10642            Some(Autoscroll::fit()),
10643            cx,
10644        );
10645        self.clear_highlights::<Rename>(cx);
10646        self.show_local_selections = true;
10647
10648        if moving_cursor {
10649            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10650                editor.selections.newest::<usize>(cx).head()
10651            });
10652
10653            // Update the selection to match the position of the selection inside
10654            // the rename editor.
10655            let snapshot = self.buffer.read(cx).read(cx);
10656            let rename_range = rename.range.to_offset(&snapshot);
10657            let cursor_in_editor = snapshot
10658                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10659                .min(rename_range.end);
10660            drop(snapshot);
10661
10662            self.change_selections(None, cx, |s| {
10663                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10664            });
10665        } else {
10666            self.refresh_document_highlights(cx);
10667        }
10668
10669        Some(rename)
10670    }
10671
10672    pub fn pending_rename(&self) -> Option<&RenameState> {
10673        self.pending_rename.as_ref()
10674    }
10675
10676    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10677        let project = match &self.project {
10678            Some(project) => project.clone(),
10679            None => return None,
10680        };
10681
10682        Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10683    }
10684
10685    fn format_selections(
10686        &mut self,
10687        _: &FormatSelections,
10688        cx: &mut ViewContext<Self>,
10689    ) -> Option<Task<Result<()>>> {
10690        let project = match &self.project {
10691            Some(project) => project.clone(),
10692            None => return None,
10693        };
10694
10695        let selections = self
10696            .selections
10697            .all_adjusted(cx)
10698            .into_iter()
10699            .filter(|s| !s.is_empty())
10700            .collect_vec();
10701
10702        Some(self.perform_format(
10703            project,
10704            FormatTrigger::Manual,
10705            FormatTarget::Ranges(selections),
10706            cx,
10707        ))
10708    }
10709
10710    fn perform_format(
10711        &mut self,
10712        project: Model<Project>,
10713        trigger: FormatTrigger,
10714        target: FormatTarget,
10715        cx: &mut ViewContext<Self>,
10716    ) -> Task<Result<()>> {
10717        let buffer = self.buffer().clone();
10718        let mut buffers = buffer.read(cx).all_buffers();
10719        if trigger == FormatTrigger::Save {
10720            buffers.retain(|buffer| buffer.read(cx).is_dirty());
10721        }
10722
10723        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10724        let format = project.update(cx, |project, cx| {
10725            project.format(buffers, true, trigger, target, cx)
10726        });
10727
10728        cx.spawn(|_, mut cx| async move {
10729            let transaction = futures::select_biased! {
10730                () = timeout => {
10731                    log::warn!("timed out waiting for formatting");
10732                    None
10733                }
10734                transaction = format.log_err().fuse() => transaction,
10735            };
10736
10737            buffer
10738                .update(&mut cx, |buffer, cx| {
10739                    if let Some(transaction) = transaction {
10740                        if !buffer.is_singleton() {
10741                            buffer.push_transaction(&transaction.0, cx);
10742                        }
10743                    }
10744
10745                    cx.notify();
10746                })
10747                .ok();
10748
10749            Ok(())
10750        })
10751    }
10752
10753    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10754        if let Some(project) = self.project.clone() {
10755            self.buffer.update(cx, |multi_buffer, cx| {
10756                project.update(cx, |project, cx| {
10757                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10758                });
10759            })
10760        }
10761    }
10762
10763    fn cancel_language_server_work(
10764        &mut self,
10765        _: &actions::CancelLanguageServerWork,
10766        cx: &mut ViewContext<Self>,
10767    ) {
10768        if let Some(project) = self.project.clone() {
10769            self.buffer.update(cx, |multi_buffer, cx| {
10770                project.update(cx, |project, cx| {
10771                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10772                });
10773            })
10774        }
10775    }
10776
10777    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10778        cx.show_character_palette();
10779    }
10780
10781    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10782        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10783            let buffer = self.buffer.read(cx).snapshot(cx);
10784            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10785            let is_valid = buffer
10786                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10787                .any(|entry| {
10788                    entry.diagnostic.is_primary
10789                        && !entry.range.is_empty()
10790                        && entry.range.start == primary_range_start
10791                        && entry.diagnostic.message == active_diagnostics.primary_message
10792                });
10793
10794            if is_valid != active_diagnostics.is_valid {
10795                active_diagnostics.is_valid = is_valid;
10796                let mut new_styles = HashMap::default();
10797                for (block_id, diagnostic) in &active_diagnostics.blocks {
10798                    new_styles.insert(
10799                        *block_id,
10800                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10801                    );
10802                }
10803                self.display_map.update(cx, |display_map, _cx| {
10804                    display_map.replace_blocks(new_styles)
10805                });
10806            }
10807        }
10808    }
10809
10810    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10811        self.dismiss_diagnostics(cx);
10812        let snapshot = self.snapshot(cx);
10813        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10814            let buffer = self.buffer.read(cx).snapshot(cx);
10815
10816            let mut primary_range = None;
10817            let mut primary_message = None;
10818            let mut group_end = Point::zero();
10819            let diagnostic_group = buffer
10820                .diagnostic_group::<MultiBufferPoint>(group_id)
10821                .filter_map(|entry| {
10822                    if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10823                        && (entry.range.start.row == entry.range.end.row
10824                            || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10825                    {
10826                        return None;
10827                    }
10828                    if entry.range.end > group_end {
10829                        group_end = entry.range.end;
10830                    }
10831                    if entry.diagnostic.is_primary {
10832                        primary_range = Some(entry.range.clone());
10833                        primary_message = Some(entry.diagnostic.message.clone());
10834                    }
10835                    Some(entry)
10836                })
10837                .collect::<Vec<_>>();
10838            let primary_range = primary_range?;
10839            let primary_message = primary_message?;
10840            let primary_range =
10841                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10842
10843            let blocks = display_map
10844                .insert_blocks(
10845                    diagnostic_group.iter().map(|entry| {
10846                        let diagnostic = entry.diagnostic.clone();
10847                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10848                        BlockProperties {
10849                            style: BlockStyle::Fixed,
10850                            placement: BlockPlacement::Below(
10851                                buffer.anchor_after(entry.range.start),
10852                            ),
10853                            height: message_height,
10854                            render: diagnostic_block_renderer(diagnostic, None, true, true),
10855                            priority: 0,
10856                        }
10857                    }),
10858                    cx,
10859                )
10860                .into_iter()
10861                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10862                .collect();
10863
10864            Some(ActiveDiagnosticGroup {
10865                primary_range,
10866                primary_message,
10867                group_id,
10868                blocks,
10869                is_valid: true,
10870            })
10871        });
10872        self.active_diagnostics.is_some()
10873    }
10874
10875    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10876        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10877            self.display_map.update(cx, |display_map, cx| {
10878                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10879            });
10880            cx.notify();
10881        }
10882    }
10883
10884    pub fn set_selections_from_remote(
10885        &mut self,
10886        selections: Vec<Selection<Anchor>>,
10887        pending_selection: Option<Selection<Anchor>>,
10888        cx: &mut ViewContext<Self>,
10889    ) {
10890        let old_cursor_position = self.selections.newest_anchor().head();
10891        self.selections.change_with(cx, |s| {
10892            s.select_anchors(selections);
10893            if let Some(pending_selection) = pending_selection {
10894                s.set_pending(pending_selection, SelectMode::Character);
10895            } else {
10896                s.clear_pending();
10897            }
10898        });
10899        self.selections_did_change(false, &old_cursor_position, true, cx);
10900    }
10901
10902    fn push_to_selection_history(&mut self) {
10903        self.selection_history.push(SelectionHistoryEntry {
10904            selections: self.selections.disjoint_anchors(),
10905            select_next_state: self.select_next_state.clone(),
10906            select_prev_state: self.select_prev_state.clone(),
10907            add_selections_state: self.add_selections_state.clone(),
10908        });
10909    }
10910
10911    pub fn transact(
10912        &mut self,
10913        cx: &mut ViewContext<Self>,
10914        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10915    ) -> Option<TransactionId> {
10916        self.start_transaction_at(Instant::now(), cx);
10917        update(self, cx);
10918        self.end_transaction_at(Instant::now(), cx)
10919    }
10920
10921    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10922        self.end_selection(cx);
10923        if let Some(tx_id) = self
10924            .buffer
10925            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10926        {
10927            self.selection_history
10928                .insert_transaction(tx_id, self.selections.disjoint_anchors());
10929            cx.emit(EditorEvent::TransactionBegun {
10930                transaction_id: tx_id,
10931            })
10932        }
10933    }
10934
10935    fn end_transaction_at(
10936        &mut self,
10937        now: Instant,
10938        cx: &mut ViewContext<Self>,
10939    ) -> Option<TransactionId> {
10940        if let Some(transaction_id) = self
10941            .buffer
10942            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10943        {
10944            if let Some((_, end_selections)) =
10945                self.selection_history.transaction_mut(transaction_id)
10946            {
10947                *end_selections = Some(self.selections.disjoint_anchors());
10948            } else {
10949                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10950            }
10951
10952            cx.emit(EditorEvent::Edited { transaction_id });
10953            Some(transaction_id)
10954        } else {
10955            None
10956        }
10957    }
10958
10959    pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10960        let selection = self.selections.newest::<Point>(cx);
10961
10962        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10963        let range = if selection.is_empty() {
10964            let point = selection.head().to_display_point(&display_map);
10965            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10966            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10967                .to_point(&display_map);
10968            start..end
10969        } else {
10970            selection.range()
10971        };
10972        if display_map.folds_in_range(range).next().is_some() {
10973            self.unfold_lines(&Default::default(), cx)
10974        } else {
10975            self.fold(&Default::default(), cx)
10976        }
10977    }
10978
10979    pub fn toggle_fold_recursive(
10980        &mut self,
10981        _: &actions::ToggleFoldRecursive,
10982        cx: &mut ViewContext<Self>,
10983    ) {
10984        let selection = self.selections.newest::<Point>(cx);
10985
10986        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10987        let range = if selection.is_empty() {
10988            let point = selection.head().to_display_point(&display_map);
10989            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10990            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10991                .to_point(&display_map);
10992            start..end
10993        } else {
10994            selection.range()
10995        };
10996        if display_map.folds_in_range(range).next().is_some() {
10997            self.unfold_recursive(&Default::default(), cx)
10998        } else {
10999            self.fold_recursive(&Default::default(), cx)
11000        }
11001    }
11002
11003    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
11004        let mut to_fold = Vec::new();
11005        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11006        let selections = self.selections.all_adjusted(cx);
11007
11008        for selection in selections {
11009            let range = selection.range().sorted();
11010            let buffer_start_row = range.start.row;
11011
11012            if range.start.row != range.end.row {
11013                let mut found = false;
11014                let mut row = range.start.row;
11015                while row <= range.end.row {
11016                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11017                        found = true;
11018                        row = crease.range().end.row + 1;
11019                        to_fold.push(crease);
11020                    } else {
11021                        row += 1
11022                    }
11023                }
11024                if found {
11025                    continue;
11026                }
11027            }
11028
11029            for row in (0..=range.start.row).rev() {
11030                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11031                    if crease.range().end.row >= buffer_start_row {
11032                        to_fold.push(crease);
11033                        if row <= range.start.row {
11034                            break;
11035                        }
11036                    }
11037                }
11038            }
11039        }
11040
11041        self.fold_creases(to_fold, true, cx);
11042    }
11043
11044    fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
11045        if !self.buffer.read(cx).is_singleton() {
11046            return;
11047        }
11048
11049        let fold_at_level = fold_at.level;
11050        let snapshot = self.buffer.read(cx).snapshot(cx);
11051        let mut to_fold = Vec::new();
11052        let mut stack = vec![(0, snapshot.max_row().0, 1)];
11053
11054        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
11055            while start_row < end_row {
11056                match self
11057                    .snapshot(cx)
11058                    .crease_for_buffer_row(MultiBufferRow(start_row))
11059                {
11060                    Some(crease) => {
11061                        let nested_start_row = crease.range().start.row + 1;
11062                        let nested_end_row = crease.range().end.row;
11063
11064                        if current_level < fold_at_level {
11065                            stack.push((nested_start_row, nested_end_row, current_level + 1));
11066                        } else if current_level == fold_at_level {
11067                            to_fold.push(crease);
11068                        }
11069
11070                        start_row = nested_end_row + 1;
11071                    }
11072                    None => start_row += 1,
11073                }
11074            }
11075        }
11076
11077        self.fold_creases(to_fold, true, cx);
11078    }
11079
11080    pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
11081        if !self.buffer.read(cx).is_singleton() {
11082            return;
11083        }
11084
11085        let mut fold_ranges = Vec::new();
11086        let snapshot = self.buffer.read(cx).snapshot(cx);
11087
11088        for row in 0..snapshot.max_row().0 {
11089            if let Some(foldable_range) =
11090                self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
11091            {
11092                fold_ranges.push(foldable_range);
11093            }
11094        }
11095
11096        self.fold_creases(fold_ranges, true, cx);
11097    }
11098
11099    pub fn fold_function_bodies(
11100        &mut self,
11101        _: &actions::FoldFunctionBodies,
11102        cx: &mut ViewContext<Self>,
11103    ) {
11104        let snapshot = self.buffer.read(cx).snapshot(cx);
11105        let Some((_, _, buffer)) = snapshot.as_singleton() else {
11106            return;
11107        };
11108        let creases = buffer
11109            .function_body_fold_ranges(0..buffer.len())
11110            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
11111            .collect();
11112
11113        self.fold_creases(creases, true, cx);
11114    }
11115
11116    pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
11117        let mut to_fold = Vec::new();
11118        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11119        let selections = self.selections.all_adjusted(cx);
11120
11121        for selection in selections {
11122            let range = selection.range().sorted();
11123            let buffer_start_row = range.start.row;
11124
11125            if range.start.row != range.end.row {
11126                let mut found = false;
11127                for row in range.start.row..=range.end.row {
11128                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11129                        found = true;
11130                        to_fold.push(crease);
11131                    }
11132                }
11133                if found {
11134                    continue;
11135                }
11136            }
11137
11138            for row in (0..=range.start.row).rev() {
11139                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11140                    if crease.range().end.row >= buffer_start_row {
11141                        to_fold.push(crease);
11142                    } else {
11143                        break;
11144                    }
11145                }
11146            }
11147        }
11148
11149        self.fold_creases(to_fold, true, cx);
11150    }
11151
11152    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
11153        let buffer_row = fold_at.buffer_row;
11154        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11155
11156        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
11157            let autoscroll = self
11158                .selections
11159                .all::<Point>(cx)
11160                .iter()
11161                .any(|selection| crease.range().overlaps(&selection.range()));
11162
11163            self.fold_creases(vec![crease], autoscroll, cx);
11164        }
11165    }
11166
11167    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
11168        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11169        let buffer = &display_map.buffer_snapshot;
11170        let selections = self.selections.all::<Point>(cx);
11171        let ranges = selections
11172            .iter()
11173            .map(|s| {
11174                let range = s.display_range(&display_map).sorted();
11175                let mut start = range.start.to_point(&display_map);
11176                let mut end = range.end.to_point(&display_map);
11177                start.column = 0;
11178                end.column = buffer.line_len(MultiBufferRow(end.row));
11179                start..end
11180            })
11181            .collect::<Vec<_>>();
11182
11183        self.unfold_ranges(&ranges, true, true, cx);
11184    }
11185
11186    pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
11187        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11188        let selections = self.selections.all::<Point>(cx);
11189        let ranges = selections
11190            .iter()
11191            .map(|s| {
11192                let mut range = s.display_range(&display_map).sorted();
11193                *range.start.column_mut() = 0;
11194                *range.end.column_mut() = display_map.line_len(range.end.row());
11195                let start = range.start.to_point(&display_map);
11196                let end = range.end.to_point(&display_map);
11197                start..end
11198            })
11199            .collect::<Vec<_>>();
11200
11201        self.unfold_ranges(&ranges, true, true, cx);
11202    }
11203
11204    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
11205        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11206
11207        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
11208            ..Point::new(
11209                unfold_at.buffer_row.0,
11210                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
11211            );
11212
11213        let autoscroll = self
11214            .selections
11215            .all::<Point>(cx)
11216            .iter()
11217            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
11218
11219        self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
11220    }
11221
11222    pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
11223        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11224        self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
11225    }
11226
11227    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
11228        let selections = self.selections.all::<Point>(cx);
11229        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11230        let line_mode = self.selections.line_mode;
11231        let ranges = selections
11232            .into_iter()
11233            .map(|s| {
11234                if line_mode {
11235                    let start = Point::new(s.start.row, 0);
11236                    let end = Point::new(
11237                        s.end.row,
11238                        display_map
11239                            .buffer_snapshot
11240                            .line_len(MultiBufferRow(s.end.row)),
11241                    );
11242                    Crease::simple(start..end, display_map.fold_placeholder.clone())
11243                } else {
11244                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
11245                }
11246            })
11247            .collect::<Vec<_>>();
11248        self.fold_creases(ranges, true, cx);
11249    }
11250
11251    pub fn fold_creases<T: ToOffset + Clone>(
11252        &mut self,
11253        creases: Vec<Crease<T>>,
11254        auto_scroll: bool,
11255        cx: &mut ViewContext<Self>,
11256    ) {
11257        if creases.is_empty() {
11258            return;
11259        }
11260
11261        let mut buffers_affected = HashMap::default();
11262        let multi_buffer = self.buffer().read(cx);
11263        for crease in &creases {
11264            if let Some((_, buffer, _)) =
11265                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
11266            {
11267                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
11268            };
11269        }
11270
11271        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
11272
11273        if auto_scroll {
11274            self.request_autoscroll(Autoscroll::fit(), cx);
11275        }
11276
11277        for buffer in buffers_affected.into_values() {
11278            self.sync_expanded_diff_hunks(buffer, cx);
11279        }
11280
11281        cx.notify();
11282
11283        if let Some(active_diagnostics) = self.active_diagnostics.take() {
11284            // Clear diagnostics block when folding a range that contains it.
11285            let snapshot = self.snapshot(cx);
11286            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
11287                drop(snapshot);
11288                self.active_diagnostics = Some(active_diagnostics);
11289                self.dismiss_diagnostics(cx);
11290            } else {
11291                self.active_diagnostics = Some(active_diagnostics);
11292            }
11293        }
11294
11295        self.scrollbar_marker_state.dirty = true;
11296    }
11297
11298    /// Removes any folds whose ranges intersect any of the given ranges.
11299    pub fn unfold_ranges<T: ToOffset + Clone>(
11300        &mut self,
11301        ranges: &[Range<T>],
11302        inclusive: bool,
11303        auto_scroll: bool,
11304        cx: &mut ViewContext<Self>,
11305    ) {
11306        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11307            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
11308        });
11309    }
11310
11311    /// Removes any folds with the given ranges.
11312    pub fn remove_folds_with_type<T: ToOffset + Clone>(
11313        &mut self,
11314        ranges: &[Range<T>],
11315        type_id: TypeId,
11316        auto_scroll: bool,
11317        cx: &mut ViewContext<Self>,
11318    ) {
11319        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11320            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
11321        });
11322    }
11323
11324    fn remove_folds_with<T: ToOffset + Clone>(
11325        &mut self,
11326        ranges: &[Range<T>],
11327        auto_scroll: bool,
11328        cx: &mut ViewContext<Self>,
11329        update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
11330    ) {
11331        if ranges.is_empty() {
11332            return;
11333        }
11334
11335        let mut buffers_affected = HashMap::default();
11336        let multi_buffer = self.buffer().read(cx);
11337        for range in ranges {
11338            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11339                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
11340            };
11341        }
11342
11343        self.display_map.update(cx, update);
11344
11345        if auto_scroll {
11346            self.request_autoscroll(Autoscroll::fit(), cx);
11347        }
11348
11349        for buffer in buffers_affected.into_values() {
11350            self.sync_expanded_diff_hunks(buffer, cx);
11351        }
11352
11353        cx.notify();
11354        self.scrollbar_marker_state.dirty = true;
11355        self.active_indent_guides_state.dirty = true;
11356    }
11357
11358    pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
11359        self.display_map.read(cx).fold_placeholder.clone()
11360    }
11361
11362    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11363        if hovered != self.gutter_hovered {
11364            self.gutter_hovered = hovered;
11365            cx.notify();
11366        }
11367    }
11368
11369    pub fn insert_blocks(
11370        &mut self,
11371        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11372        autoscroll: Option<Autoscroll>,
11373        cx: &mut ViewContext<Self>,
11374    ) -> Vec<CustomBlockId> {
11375        let blocks = self
11376            .display_map
11377            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11378        if let Some(autoscroll) = autoscroll {
11379            self.request_autoscroll(autoscroll, cx);
11380        }
11381        cx.notify();
11382        blocks
11383    }
11384
11385    pub fn resize_blocks(
11386        &mut self,
11387        heights: HashMap<CustomBlockId, u32>,
11388        autoscroll: Option<Autoscroll>,
11389        cx: &mut ViewContext<Self>,
11390    ) {
11391        self.display_map
11392            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11393        if let Some(autoscroll) = autoscroll {
11394            self.request_autoscroll(autoscroll, cx);
11395        }
11396        cx.notify();
11397    }
11398
11399    pub fn replace_blocks(
11400        &mut self,
11401        renderers: HashMap<CustomBlockId, RenderBlock>,
11402        autoscroll: Option<Autoscroll>,
11403        cx: &mut ViewContext<Self>,
11404    ) {
11405        self.display_map
11406            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11407        if let Some(autoscroll) = autoscroll {
11408            self.request_autoscroll(autoscroll, cx);
11409        }
11410        cx.notify();
11411    }
11412
11413    pub fn remove_blocks(
11414        &mut self,
11415        block_ids: HashSet<CustomBlockId>,
11416        autoscroll: Option<Autoscroll>,
11417        cx: &mut ViewContext<Self>,
11418    ) {
11419        self.display_map.update(cx, |display_map, cx| {
11420            display_map.remove_blocks(block_ids, cx)
11421        });
11422        if let Some(autoscroll) = autoscroll {
11423            self.request_autoscroll(autoscroll, cx);
11424        }
11425        cx.notify();
11426    }
11427
11428    pub fn row_for_block(
11429        &self,
11430        block_id: CustomBlockId,
11431        cx: &mut ViewContext<Self>,
11432    ) -> Option<DisplayRow> {
11433        self.display_map
11434            .update(cx, |map, cx| map.row_for_block(block_id, cx))
11435    }
11436
11437    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11438        self.focused_block = Some(focused_block);
11439    }
11440
11441    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11442        self.focused_block.take()
11443    }
11444
11445    pub fn insert_creases(
11446        &mut self,
11447        creases: impl IntoIterator<Item = Crease<Anchor>>,
11448        cx: &mut ViewContext<Self>,
11449    ) -> Vec<CreaseId> {
11450        self.display_map
11451            .update(cx, |map, cx| map.insert_creases(creases, cx))
11452    }
11453
11454    pub fn remove_creases(
11455        &mut self,
11456        ids: impl IntoIterator<Item = CreaseId>,
11457        cx: &mut ViewContext<Self>,
11458    ) {
11459        self.display_map
11460            .update(cx, |map, cx| map.remove_creases(ids, cx));
11461    }
11462
11463    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11464        self.display_map
11465            .update(cx, |map, cx| map.snapshot(cx))
11466            .longest_row()
11467    }
11468
11469    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11470        self.display_map
11471            .update(cx, |map, cx| map.snapshot(cx))
11472            .max_point()
11473    }
11474
11475    pub fn text(&self, cx: &AppContext) -> String {
11476        self.buffer.read(cx).read(cx).text()
11477    }
11478
11479    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11480        let text = self.text(cx);
11481        let text = text.trim();
11482
11483        if text.is_empty() {
11484            return None;
11485        }
11486
11487        Some(text.to_string())
11488    }
11489
11490    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11491        self.transact(cx, |this, cx| {
11492            this.buffer
11493                .read(cx)
11494                .as_singleton()
11495                .expect("you can only call set_text on editors for singleton buffers")
11496                .update(cx, |buffer, cx| buffer.set_text(text, cx));
11497        });
11498    }
11499
11500    pub fn display_text(&self, cx: &mut AppContext) -> String {
11501        self.display_map
11502            .update(cx, |map, cx| map.snapshot(cx))
11503            .text()
11504    }
11505
11506    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11507        let mut wrap_guides = smallvec::smallvec![];
11508
11509        if self.show_wrap_guides == Some(false) {
11510            return wrap_guides;
11511        }
11512
11513        let settings = self.buffer.read(cx).settings_at(0, cx);
11514        if settings.show_wrap_guides {
11515            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11516                wrap_guides.push((soft_wrap as usize, true));
11517            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11518                wrap_guides.push((soft_wrap as usize, true));
11519            }
11520            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11521        }
11522
11523        wrap_guides
11524    }
11525
11526    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11527        let settings = self.buffer.read(cx).settings_at(0, cx);
11528        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11529        match mode {
11530            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11531                SoftWrap::None
11532            }
11533            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11534            language_settings::SoftWrap::PreferredLineLength => {
11535                SoftWrap::Column(settings.preferred_line_length)
11536            }
11537            language_settings::SoftWrap::Bounded => {
11538                SoftWrap::Bounded(settings.preferred_line_length)
11539            }
11540        }
11541    }
11542
11543    pub fn set_soft_wrap_mode(
11544        &mut self,
11545        mode: language_settings::SoftWrap,
11546        cx: &mut ViewContext<Self>,
11547    ) {
11548        self.soft_wrap_mode_override = Some(mode);
11549        cx.notify();
11550    }
11551
11552    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11553        self.text_style_refinement = Some(style);
11554    }
11555
11556    /// called by the Element so we know what style we were most recently rendered with.
11557    pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11558        let rem_size = cx.rem_size();
11559        self.display_map.update(cx, |map, cx| {
11560            map.set_font(
11561                style.text.font(),
11562                style.text.font_size.to_pixels(rem_size),
11563                cx,
11564            )
11565        });
11566        self.style = Some(style);
11567    }
11568
11569    pub fn style(&self) -> Option<&EditorStyle> {
11570        self.style.as_ref()
11571    }
11572
11573    // Called by the element. This method is not designed to be called outside of the editor
11574    // element's layout code because it does not notify when rewrapping is computed synchronously.
11575    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11576        self.display_map
11577            .update(cx, |map, cx| map.set_wrap_width(width, cx))
11578    }
11579
11580    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11581        if self.soft_wrap_mode_override.is_some() {
11582            self.soft_wrap_mode_override.take();
11583        } else {
11584            let soft_wrap = match self.soft_wrap_mode(cx) {
11585                SoftWrap::GitDiff => return,
11586                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11587                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11588                    language_settings::SoftWrap::None
11589                }
11590            };
11591            self.soft_wrap_mode_override = Some(soft_wrap);
11592        }
11593        cx.notify();
11594    }
11595
11596    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11597        let Some(workspace) = self.workspace() else {
11598            return;
11599        };
11600        let fs = workspace.read(cx).app_state().fs.clone();
11601        let current_show = TabBarSettings::get_global(cx).show;
11602        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11603            setting.show = Some(!current_show);
11604        });
11605    }
11606
11607    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11608        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11609            self.buffer
11610                .read(cx)
11611                .settings_at(0, cx)
11612                .indent_guides
11613                .enabled
11614        });
11615        self.show_indent_guides = Some(!currently_enabled);
11616        cx.notify();
11617    }
11618
11619    fn should_show_indent_guides(&self) -> Option<bool> {
11620        self.show_indent_guides
11621    }
11622
11623    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11624        let mut editor_settings = EditorSettings::get_global(cx).clone();
11625        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11626        EditorSettings::override_global(editor_settings, cx);
11627    }
11628
11629    pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11630        self.use_relative_line_numbers
11631            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11632    }
11633
11634    pub fn toggle_relative_line_numbers(
11635        &mut self,
11636        _: &ToggleRelativeLineNumbers,
11637        cx: &mut ViewContext<Self>,
11638    ) {
11639        let is_relative = self.should_use_relative_line_numbers(cx);
11640        self.set_relative_line_number(Some(!is_relative), cx)
11641    }
11642
11643    pub fn set_relative_line_number(
11644        &mut self,
11645        is_relative: Option<bool>,
11646        cx: &mut ViewContext<Self>,
11647    ) {
11648        self.use_relative_line_numbers = is_relative;
11649        cx.notify();
11650    }
11651
11652    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11653        self.show_gutter = show_gutter;
11654        cx.notify();
11655    }
11656
11657    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11658        self.show_line_numbers = Some(show_line_numbers);
11659        cx.notify();
11660    }
11661
11662    pub fn set_show_git_diff_gutter(
11663        &mut self,
11664        show_git_diff_gutter: bool,
11665        cx: &mut ViewContext<Self>,
11666    ) {
11667        self.show_git_diff_gutter = Some(show_git_diff_gutter);
11668        cx.notify();
11669    }
11670
11671    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11672        self.show_code_actions = Some(show_code_actions);
11673        cx.notify();
11674    }
11675
11676    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11677        self.show_runnables = Some(show_runnables);
11678        cx.notify();
11679    }
11680
11681    pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11682        if self.display_map.read(cx).masked != masked {
11683            self.display_map.update(cx, |map, _| map.masked = masked);
11684        }
11685        cx.notify()
11686    }
11687
11688    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11689        self.show_wrap_guides = Some(show_wrap_guides);
11690        cx.notify();
11691    }
11692
11693    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11694        self.show_indent_guides = Some(show_indent_guides);
11695        cx.notify();
11696    }
11697
11698    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11699        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11700            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11701                if let Some(dir) = file.abs_path(cx).parent() {
11702                    return Some(dir.to_owned());
11703                }
11704            }
11705
11706            if let Some(project_path) = buffer.read(cx).project_path(cx) {
11707                return Some(project_path.path.to_path_buf());
11708            }
11709        }
11710
11711        None
11712    }
11713
11714    fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11715        self.active_excerpt(cx)?
11716            .1
11717            .read(cx)
11718            .file()
11719            .and_then(|f| f.as_local())
11720    }
11721
11722    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11723        if let Some(target) = self.target_file(cx) {
11724            cx.reveal_path(&target.abs_path(cx));
11725        }
11726    }
11727
11728    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11729        if let Some(file) = self.target_file(cx) {
11730            if let Some(path) = file.abs_path(cx).to_str() {
11731                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11732            }
11733        }
11734    }
11735
11736    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11737        if let Some(file) = self.target_file(cx) {
11738            if let Some(path) = file.path().to_str() {
11739                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11740            }
11741        }
11742    }
11743
11744    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11745        self.show_git_blame_gutter = !self.show_git_blame_gutter;
11746
11747        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11748            self.start_git_blame(true, cx);
11749        }
11750
11751        cx.notify();
11752    }
11753
11754    pub fn toggle_git_blame_inline(
11755        &mut self,
11756        _: &ToggleGitBlameInline,
11757        cx: &mut ViewContext<Self>,
11758    ) {
11759        self.toggle_git_blame_inline_internal(true, cx);
11760        cx.notify();
11761    }
11762
11763    pub fn git_blame_inline_enabled(&self) -> bool {
11764        self.git_blame_inline_enabled
11765    }
11766
11767    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11768        self.show_selection_menu = self
11769            .show_selection_menu
11770            .map(|show_selections_menu| !show_selections_menu)
11771            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11772
11773        cx.notify();
11774    }
11775
11776    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11777        self.show_selection_menu
11778            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11779    }
11780
11781    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11782        if let Some(project) = self.project.as_ref() {
11783            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11784                return;
11785            };
11786
11787            if buffer.read(cx).file().is_none() {
11788                return;
11789            }
11790
11791            let focused = self.focus_handle(cx).contains_focused(cx);
11792
11793            let project = project.clone();
11794            let blame =
11795                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11796            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11797            self.blame = Some(blame);
11798        }
11799    }
11800
11801    fn toggle_git_blame_inline_internal(
11802        &mut self,
11803        user_triggered: bool,
11804        cx: &mut ViewContext<Self>,
11805    ) {
11806        if self.git_blame_inline_enabled {
11807            self.git_blame_inline_enabled = false;
11808            self.show_git_blame_inline = false;
11809            self.show_git_blame_inline_delay_task.take();
11810        } else {
11811            self.git_blame_inline_enabled = true;
11812            self.start_git_blame_inline(user_triggered, cx);
11813        }
11814
11815        cx.notify();
11816    }
11817
11818    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11819        self.start_git_blame(user_triggered, cx);
11820
11821        if ProjectSettings::get_global(cx)
11822            .git
11823            .inline_blame_delay()
11824            .is_some()
11825        {
11826            self.start_inline_blame_timer(cx);
11827        } else {
11828            self.show_git_blame_inline = true
11829        }
11830    }
11831
11832    pub fn blame(&self) -> Option<&Model<GitBlame>> {
11833        self.blame.as_ref()
11834    }
11835
11836    pub fn show_git_blame_gutter(&self) -> bool {
11837        self.show_git_blame_gutter
11838    }
11839
11840    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11841        self.show_git_blame_gutter && self.has_blame_entries(cx)
11842    }
11843
11844    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11845        self.show_git_blame_inline
11846            && self.focus_handle.is_focused(cx)
11847            && !self.newest_selection_head_on_empty_line(cx)
11848            && self.has_blame_entries(cx)
11849    }
11850
11851    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11852        self.blame()
11853            .map_or(false, |blame| blame.read(cx).has_generated_entries())
11854    }
11855
11856    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11857        let cursor_anchor = self.selections.newest_anchor().head();
11858
11859        let snapshot = self.buffer.read(cx).snapshot(cx);
11860        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11861
11862        snapshot.line_len(buffer_row) == 0
11863    }
11864
11865    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11866        let buffer_and_selection = maybe!({
11867            let selection = self.selections.newest::<Point>(cx);
11868            let selection_range = selection.range();
11869
11870            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11871                (buffer, selection_range.start.row..selection_range.end.row)
11872            } else {
11873                let buffer_ranges = self
11874                    .buffer()
11875                    .read(cx)
11876                    .range_to_buffer_ranges(selection_range, cx);
11877
11878                let (buffer, range, _) = if selection.reversed {
11879                    buffer_ranges.first()
11880                } else {
11881                    buffer_ranges.last()
11882                }?;
11883
11884                let snapshot = buffer.read(cx).snapshot();
11885                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11886                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
11887                (buffer.clone(), selection)
11888            };
11889
11890            Some((buffer, selection))
11891        });
11892
11893        let Some((buffer, selection)) = buffer_and_selection else {
11894            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11895        };
11896
11897        let Some(project) = self.project.as_ref() else {
11898            return Task::ready(Err(anyhow!("editor does not have project")));
11899        };
11900
11901        project.update(cx, |project, cx| {
11902            project.get_permalink_to_line(&buffer, selection, cx)
11903        })
11904    }
11905
11906    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11907        let permalink_task = self.get_permalink_to_line(cx);
11908        let workspace = self.workspace();
11909
11910        cx.spawn(|_, mut cx| async move {
11911            match permalink_task.await {
11912                Ok(permalink) => {
11913                    cx.update(|cx| {
11914                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11915                    })
11916                    .ok();
11917                }
11918                Err(err) => {
11919                    let message = format!("Failed to copy permalink: {err}");
11920
11921                    Err::<(), anyhow::Error>(err).log_err();
11922
11923                    if let Some(workspace) = workspace {
11924                        workspace
11925                            .update(&mut cx, |workspace, cx| {
11926                                struct CopyPermalinkToLine;
11927
11928                                workspace.show_toast(
11929                                    Toast::new(
11930                                        NotificationId::unique::<CopyPermalinkToLine>(),
11931                                        message,
11932                                    ),
11933                                    cx,
11934                                )
11935                            })
11936                            .ok();
11937                    }
11938                }
11939            }
11940        })
11941        .detach();
11942    }
11943
11944    pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11945        let selection = self.selections.newest::<Point>(cx).start.row + 1;
11946        if let Some(file) = self.target_file(cx) {
11947            if let Some(path) = file.path().to_str() {
11948                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11949            }
11950        }
11951    }
11952
11953    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11954        let permalink_task = self.get_permalink_to_line(cx);
11955        let workspace = self.workspace();
11956
11957        cx.spawn(|_, mut cx| async move {
11958            match permalink_task.await {
11959                Ok(permalink) => {
11960                    cx.update(|cx| {
11961                        cx.open_url(permalink.as_ref());
11962                    })
11963                    .ok();
11964                }
11965                Err(err) => {
11966                    let message = format!("Failed to open permalink: {err}");
11967
11968                    Err::<(), anyhow::Error>(err).log_err();
11969
11970                    if let Some(workspace) = workspace {
11971                        workspace
11972                            .update(&mut cx, |workspace, cx| {
11973                                struct OpenPermalinkToLine;
11974
11975                                workspace.show_toast(
11976                                    Toast::new(
11977                                        NotificationId::unique::<OpenPermalinkToLine>(),
11978                                        message,
11979                                    ),
11980                                    cx,
11981                                )
11982                            })
11983                            .ok();
11984                    }
11985                }
11986            }
11987        })
11988        .detach();
11989    }
11990
11991    /// Adds a row highlight for the given range. If a row has multiple highlights, the
11992    /// last highlight added will be used.
11993    ///
11994    /// If the range ends at the beginning of a line, then that line will not be highlighted.
11995    pub fn highlight_rows<T: 'static>(
11996        &mut self,
11997        range: Range<Anchor>,
11998        color: Hsla,
11999        should_autoscroll: bool,
12000        cx: &mut ViewContext<Self>,
12001    ) {
12002        let snapshot = self.buffer().read(cx).snapshot(cx);
12003        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
12004        let ix = row_highlights.binary_search_by(|highlight| {
12005            Ordering::Equal
12006                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
12007                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
12008        });
12009
12010        if let Err(mut ix) = ix {
12011            let index = post_inc(&mut self.highlight_order);
12012
12013            // If this range intersects with the preceding highlight, then merge it with
12014            // the preceding highlight. Otherwise insert a new highlight.
12015            let mut merged = false;
12016            if ix > 0 {
12017                let prev_highlight = &mut row_highlights[ix - 1];
12018                if prev_highlight
12019                    .range
12020                    .end
12021                    .cmp(&range.start, &snapshot)
12022                    .is_ge()
12023                {
12024                    ix -= 1;
12025                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
12026                        prev_highlight.range.end = range.end;
12027                    }
12028                    merged = true;
12029                    prev_highlight.index = index;
12030                    prev_highlight.color = color;
12031                    prev_highlight.should_autoscroll = should_autoscroll;
12032                }
12033            }
12034
12035            if !merged {
12036                row_highlights.insert(
12037                    ix,
12038                    RowHighlight {
12039                        range: range.clone(),
12040                        index,
12041                        color,
12042                        should_autoscroll,
12043                    },
12044                );
12045            }
12046
12047            // If any of the following highlights intersect with this one, merge them.
12048            while let Some(next_highlight) = row_highlights.get(ix + 1) {
12049                let highlight = &row_highlights[ix];
12050                if next_highlight
12051                    .range
12052                    .start
12053                    .cmp(&highlight.range.end, &snapshot)
12054                    .is_le()
12055                {
12056                    if next_highlight
12057                        .range
12058                        .end
12059                        .cmp(&highlight.range.end, &snapshot)
12060                        .is_gt()
12061                    {
12062                        row_highlights[ix].range.end = next_highlight.range.end;
12063                    }
12064                    row_highlights.remove(ix + 1);
12065                } else {
12066                    break;
12067                }
12068            }
12069        }
12070    }
12071
12072    /// Remove any highlighted row ranges of the given type that intersect the
12073    /// given ranges.
12074    pub fn remove_highlighted_rows<T: 'static>(
12075        &mut self,
12076        ranges_to_remove: Vec<Range<Anchor>>,
12077        cx: &mut ViewContext<Self>,
12078    ) {
12079        let snapshot = self.buffer().read(cx).snapshot(cx);
12080        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
12081        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
12082        row_highlights.retain(|highlight| {
12083            while let Some(range_to_remove) = ranges_to_remove.peek() {
12084                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
12085                    Ordering::Less | Ordering::Equal => {
12086                        ranges_to_remove.next();
12087                    }
12088                    Ordering::Greater => {
12089                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
12090                            Ordering::Less | Ordering::Equal => {
12091                                return false;
12092                            }
12093                            Ordering::Greater => break,
12094                        }
12095                    }
12096                }
12097            }
12098
12099            true
12100        })
12101    }
12102
12103    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
12104    pub fn clear_row_highlights<T: 'static>(&mut self) {
12105        self.highlighted_rows.remove(&TypeId::of::<T>());
12106    }
12107
12108    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
12109    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
12110        self.highlighted_rows
12111            .get(&TypeId::of::<T>())
12112            .map_or(&[] as &[_], |vec| vec.as_slice())
12113            .iter()
12114            .map(|highlight| (highlight.range.clone(), highlight.color))
12115    }
12116
12117    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
12118    /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
12119    /// Allows to ignore certain kinds of highlights.
12120    pub fn highlighted_display_rows(
12121        &mut self,
12122        cx: &mut WindowContext,
12123    ) -> BTreeMap<DisplayRow, Hsla> {
12124        let snapshot = self.snapshot(cx);
12125        let mut used_highlight_orders = HashMap::default();
12126        self.highlighted_rows
12127            .iter()
12128            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
12129            .fold(
12130                BTreeMap::<DisplayRow, Hsla>::new(),
12131                |mut unique_rows, highlight| {
12132                    let start = highlight.range.start.to_display_point(&snapshot);
12133                    let end = highlight.range.end.to_display_point(&snapshot);
12134                    let start_row = start.row().0;
12135                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
12136                        && end.column() == 0
12137                    {
12138                        end.row().0.saturating_sub(1)
12139                    } else {
12140                        end.row().0
12141                    };
12142                    for row in start_row..=end_row {
12143                        let used_index =
12144                            used_highlight_orders.entry(row).or_insert(highlight.index);
12145                        if highlight.index >= *used_index {
12146                            *used_index = highlight.index;
12147                            unique_rows.insert(DisplayRow(row), highlight.color);
12148                        }
12149                    }
12150                    unique_rows
12151                },
12152            )
12153    }
12154
12155    pub fn highlighted_display_row_for_autoscroll(
12156        &self,
12157        snapshot: &DisplaySnapshot,
12158    ) -> Option<DisplayRow> {
12159        self.highlighted_rows
12160            .values()
12161            .flat_map(|highlighted_rows| highlighted_rows.iter())
12162            .filter_map(|highlight| {
12163                if highlight.should_autoscroll {
12164                    Some(highlight.range.start.to_display_point(snapshot).row())
12165                } else {
12166                    None
12167                }
12168            })
12169            .min()
12170    }
12171
12172    pub fn set_search_within_ranges(
12173        &mut self,
12174        ranges: &[Range<Anchor>],
12175        cx: &mut ViewContext<Self>,
12176    ) {
12177        self.highlight_background::<SearchWithinRange>(
12178            ranges,
12179            |colors| colors.editor_document_highlight_read_background,
12180            cx,
12181        )
12182    }
12183
12184    pub fn set_breadcrumb_header(&mut self, new_header: String) {
12185        self.breadcrumb_header = Some(new_header);
12186    }
12187
12188    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
12189        self.clear_background_highlights::<SearchWithinRange>(cx);
12190    }
12191
12192    pub fn highlight_background<T: 'static>(
12193        &mut self,
12194        ranges: &[Range<Anchor>],
12195        color_fetcher: fn(&ThemeColors) -> Hsla,
12196        cx: &mut ViewContext<Self>,
12197    ) {
12198        self.background_highlights
12199            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12200        self.scrollbar_marker_state.dirty = true;
12201        cx.notify();
12202    }
12203
12204    pub fn clear_background_highlights<T: 'static>(
12205        &mut self,
12206        cx: &mut ViewContext<Self>,
12207    ) -> Option<BackgroundHighlight> {
12208        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
12209        if !text_highlights.1.is_empty() {
12210            self.scrollbar_marker_state.dirty = true;
12211            cx.notify();
12212        }
12213        Some(text_highlights)
12214    }
12215
12216    pub fn highlight_gutter<T: 'static>(
12217        &mut self,
12218        ranges: &[Range<Anchor>],
12219        color_fetcher: fn(&AppContext) -> Hsla,
12220        cx: &mut ViewContext<Self>,
12221    ) {
12222        self.gutter_highlights
12223            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12224        cx.notify();
12225    }
12226
12227    pub fn clear_gutter_highlights<T: 'static>(
12228        &mut self,
12229        cx: &mut ViewContext<Self>,
12230    ) -> Option<GutterHighlight> {
12231        cx.notify();
12232        self.gutter_highlights.remove(&TypeId::of::<T>())
12233    }
12234
12235    #[cfg(feature = "test-support")]
12236    pub fn all_text_background_highlights(
12237        &mut self,
12238        cx: &mut ViewContext<Self>,
12239    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12240        let snapshot = self.snapshot(cx);
12241        let buffer = &snapshot.buffer_snapshot;
12242        let start = buffer.anchor_before(0);
12243        let end = buffer.anchor_after(buffer.len());
12244        let theme = cx.theme().colors();
12245        self.background_highlights_in_range(start..end, &snapshot, theme)
12246    }
12247
12248    #[cfg(feature = "test-support")]
12249    pub fn search_background_highlights(
12250        &mut self,
12251        cx: &mut ViewContext<Self>,
12252    ) -> Vec<Range<Point>> {
12253        let snapshot = self.buffer().read(cx).snapshot(cx);
12254
12255        let highlights = self
12256            .background_highlights
12257            .get(&TypeId::of::<items::BufferSearchHighlights>());
12258
12259        if let Some((_color, ranges)) = highlights {
12260            ranges
12261                .iter()
12262                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
12263                .collect_vec()
12264        } else {
12265            vec![]
12266        }
12267    }
12268
12269    fn document_highlights_for_position<'a>(
12270        &'a self,
12271        position: Anchor,
12272        buffer: &'a MultiBufferSnapshot,
12273    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
12274        let read_highlights = self
12275            .background_highlights
12276            .get(&TypeId::of::<DocumentHighlightRead>())
12277            .map(|h| &h.1);
12278        let write_highlights = self
12279            .background_highlights
12280            .get(&TypeId::of::<DocumentHighlightWrite>())
12281            .map(|h| &h.1);
12282        let left_position = position.bias_left(buffer);
12283        let right_position = position.bias_right(buffer);
12284        read_highlights
12285            .into_iter()
12286            .chain(write_highlights)
12287            .flat_map(move |ranges| {
12288                let start_ix = match ranges.binary_search_by(|probe| {
12289                    let cmp = probe.end.cmp(&left_position, buffer);
12290                    if cmp.is_ge() {
12291                        Ordering::Greater
12292                    } else {
12293                        Ordering::Less
12294                    }
12295                }) {
12296                    Ok(i) | Err(i) => i,
12297                };
12298
12299                ranges[start_ix..]
12300                    .iter()
12301                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
12302            })
12303    }
12304
12305    pub fn has_background_highlights<T: 'static>(&self) -> bool {
12306        self.background_highlights
12307            .get(&TypeId::of::<T>())
12308            .map_or(false, |(_, highlights)| !highlights.is_empty())
12309    }
12310
12311    pub fn background_highlights_in_range(
12312        &self,
12313        search_range: Range<Anchor>,
12314        display_snapshot: &DisplaySnapshot,
12315        theme: &ThemeColors,
12316    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12317        let mut results = Vec::new();
12318        for (color_fetcher, ranges) in self.background_highlights.values() {
12319            let color = color_fetcher(theme);
12320            let start_ix = match ranges.binary_search_by(|probe| {
12321                let cmp = probe
12322                    .end
12323                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12324                if cmp.is_gt() {
12325                    Ordering::Greater
12326                } else {
12327                    Ordering::Less
12328                }
12329            }) {
12330                Ok(i) | Err(i) => i,
12331            };
12332            for range in &ranges[start_ix..] {
12333                if range
12334                    .start
12335                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12336                    .is_ge()
12337                {
12338                    break;
12339                }
12340
12341                let start = range.start.to_display_point(display_snapshot);
12342                let end = range.end.to_display_point(display_snapshot);
12343                results.push((start..end, color))
12344            }
12345        }
12346        results
12347    }
12348
12349    pub fn background_highlight_row_ranges<T: 'static>(
12350        &self,
12351        search_range: Range<Anchor>,
12352        display_snapshot: &DisplaySnapshot,
12353        count: usize,
12354    ) -> Vec<RangeInclusive<DisplayPoint>> {
12355        let mut results = Vec::new();
12356        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12357            return vec![];
12358        };
12359
12360        let start_ix = match ranges.binary_search_by(|probe| {
12361            let cmp = probe
12362                .end
12363                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12364            if cmp.is_gt() {
12365                Ordering::Greater
12366            } else {
12367                Ordering::Less
12368            }
12369        }) {
12370            Ok(i) | Err(i) => i,
12371        };
12372        let mut push_region = |start: Option<Point>, end: Option<Point>| {
12373            if let (Some(start_display), Some(end_display)) = (start, end) {
12374                results.push(
12375                    start_display.to_display_point(display_snapshot)
12376                        ..=end_display.to_display_point(display_snapshot),
12377                );
12378            }
12379        };
12380        let mut start_row: Option<Point> = None;
12381        let mut end_row: Option<Point> = None;
12382        if ranges.len() > count {
12383            return Vec::new();
12384        }
12385        for range in &ranges[start_ix..] {
12386            if range
12387                .start
12388                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12389                .is_ge()
12390            {
12391                break;
12392            }
12393            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12394            if let Some(current_row) = &end_row {
12395                if end.row == current_row.row {
12396                    continue;
12397                }
12398            }
12399            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12400            if start_row.is_none() {
12401                assert_eq!(end_row, None);
12402                start_row = Some(start);
12403                end_row = Some(end);
12404                continue;
12405            }
12406            if let Some(current_end) = end_row.as_mut() {
12407                if start.row > current_end.row + 1 {
12408                    push_region(start_row, end_row);
12409                    start_row = Some(start);
12410                    end_row = Some(end);
12411                } else {
12412                    // Merge two hunks.
12413                    *current_end = end;
12414                }
12415            } else {
12416                unreachable!();
12417            }
12418        }
12419        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12420        push_region(start_row, end_row);
12421        results
12422    }
12423
12424    pub fn gutter_highlights_in_range(
12425        &self,
12426        search_range: Range<Anchor>,
12427        display_snapshot: &DisplaySnapshot,
12428        cx: &AppContext,
12429    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12430        let mut results = Vec::new();
12431        for (color_fetcher, ranges) in self.gutter_highlights.values() {
12432            let color = color_fetcher(cx);
12433            let start_ix = match ranges.binary_search_by(|probe| {
12434                let cmp = probe
12435                    .end
12436                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12437                if cmp.is_gt() {
12438                    Ordering::Greater
12439                } else {
12440                    Ordering::Less
12441                }
12442            }) {
12443                Ok(i) | Err(i) => i,
12444            };
12445            for range in &ranges[start_ix..] {
12446                if range
12447                    .start
12448                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12449                    .is_ge()
12450                {
12451                    break;
12452                }
12453
12454                let start = range.start.to_display_point(display_snapshot);
12455                let end = range.end.to_display_point(display_snapshot);
12456                results.push((start..end, color))
12457            }
12458        }
12459        results
12460    }
12461
12462    /// Get the text ranges corresponding to the redaction query
12463    pub fn redacted_ranges(
12464        &self,
12465        search_range: Range<Anchor>,
12466        display_snapshot: &DisplaySnapshot,
12467        cx: &WindowContext,
12468    ) -> Vec<Range<DisplayPoint>> {
12469        display_snapshot
12470            .buffer_snapshot
12471            .redacted_ranges(search_range, |file| {
12472                if let Some(file) = file {
12473                    file.is_private()
12474                        && EditorSettings::get(
12475                            Some(SettingsLocation {
12476                                worktree_id: file.worktree_id(cx),
12477                                path: file.path().as_ref(),
12478                            }),
12479                            cx,
12480                        )
12481                        .redact_private_values
12482                } else {
12483                    false
12484                }
12485            })
12486            .map(|range| {
12487                range.start.to_display_point(display_snapshot)
12488                    ..range.end.to_display_point(display_snapshot)
12489            })
12490            .collect()
12491    }
12492
12493    pub fn highlight_text<T: 'static>(
12494        &mut self,
12495        ranges: Vec<Range<Anchor>>,
12496        style: HighlightStyle,
12497        cx: &mut ViewContext<Self>,
12498    ) {
12499        self.display_map.update(cx, |map, _| {
12500            map.highlight_text(TypeId::of::<T>(), ranges, style)
12501        });
12502        cx.notify();
12503    }
12504
12505    pub(crate) fn highlight_inlays<T: 'static>(
12506        &mut self,
12507        highlights: Vec<InlayHighlight>,
12508        style: HighlightStyle,
12509        cx: &mut ViewContext<Self>,
12510    ) {
12511        self.display_map.update(cx, |map, _| {
12512            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12513        });
12514        cx.notify();
12515    }
12516
12517    pub fn text_highlights<'a, T: 'static>(
12518        &'a self,
12519        cx: &'a AppContext,
12520    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12521        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12522    }
12523
12524    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12525        let cleared = self
12526            .display_map
12527            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12528        if cleared {
12529            cx.notify();
12530        }
12531    }
12532
12533    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12534        (self.read_only(cx) || self.blink_manager.read(cx).visible())
12535            && self.focus_handle.is_focused(cx)
12536    }
12537
12538    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12539        self.show_cursor_when_unfocused = is_enabled;
12540        cx.notify();
12541    }
12542
12543    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12544        cx.notify();
12545    }
12546
12547    fn on_buffer_event(
12548        &mut self,
12549        multibuffer: Model<MultiBuffer>,
12550        event: &multi_buffer::Event,
12551        cx: &mut ViewContext<Self>,
12552    ) {
12553        match event {
12554            multi_buffer::Event::Edited {
12555                singleton_buffer_edited,
12556            } => {
12557                self.scrollbar_marker_state.dirty = true;
12558                self.active_indent_guides_state.dirty = true;
12559                self.refresh_active_diagnostics(cx);
12560                self.refresh_code_actions(cx);
12561                if self.has_active_inline_completion(cx) {
12562                    self.update_visible_inline_completion(cx);
12563                }
12564                cx.emit(EditorEvent::BufferEdited);
12565                cx.emit(SearchEvent::MatchesInvalidated);
12566                if *singleton_buffer_edited {
12567                    if let Some(project) = &self.project {
12568                        let project = project.read(cx);
12569                        #[allow(clippy::mutable_key_type)]
12570                        let languages_affected = multibuffer
12571                            .read(cx)
12572                            .all_buffers()
12573                            .into_iter()
12574                            .filter_map(|buffer| {
12575                                let buffer = buffer.read(cx);
12576                                let language = buffer.language()?;
12577                                if project.is_local()
12578                                    && project.language_servers_for_buffer(buffer, cx).count() == 0
12579                                {
12580                                    None
12581                                } else {
12582                                    Some(language)
12583                                }
12584                            })
12585                            .cloned()
12586                            .collect::<HashSet<_>>();
12587                        if !languages_affected.is_empty() {
12588                            self.refresh_inlay_hints(
12589                                InlayHintRefreshReason::BufferEdited(languages_affected),
12590                                cx,
12591                            );
12592                        }
12593                    }
12594                }
12595
12596                let Some(project) = &self.project else { return };
12597                let (telemetry, is_via_ssh) = {
12598                    let project = project.read(cx);
12599                    let telemetry = project.client().telemetry().clone();
12600                    let is_via_ssh = project.is_via_ssh();
12601                    (telemetry, is_via_ssh)
12602                };
12603                refresh_linked_ranges(self, cx);
12604                telemetry.log_edit_event("editor", is_via_ssh);
12605            }
12606            multi_buffer::Event::ExcerptsAdded {
12607                buffer,
12608                predecessor,
12609                excerpts,
12610            } => {
12611                self.tasks_update_task = Some(self.refresh_runnables(cx));
12612                cx.emit(EditorEvent::ExcerptsAdded {
12613                    buffer: buffer.clone(),
12614                    predecessor: *predecessor,
12615                    excerpts: excerpts.clone(),
12616                });
12617                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12618            }
12619            multi_buffer::Event::ExcerptsRemoved { ids } => {
12620                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12621                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12622            }
12623            multi_buffer::Event::ExcerptsEdited { ids } => {
12624                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12625            }
12626            multi_buffer::Event::ExcerptsExpanded { ids } => {
12627                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12628            }
12629            multi_buffer::Event::Reparsed(buffer_id) => {
12630                self.tasks_update_task = Some(self.refresh_runnables(cx));
12631
12632                cx.emit(EditorEvent::Reparsed(*buffer_id));
12633            }
12634            multi_buffer::Event::LanguageChanged(buffer_id) => {
12635                linked_editing_ranges::refresh_linked_ranges(self, cx);
12636                cx.emit(EditorEvent::Reparsed(*buffer_id));
12637                cx.notify();
12638            }
12639            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12640            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12641            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12642                cx.emit(EditorEvent::TitleChanged)
12643            }
12644            multi_buffer::Event::DiffBaseChanged => {
12645                self.scrollbar_marker_state.dirty = true;
12646                cx.emit(EditorEvent::DiffBaseChanged);
12647                cx.notify();
12648            }
12649            multi_buffer::Event::DiffUpdated { buffer } => {
12650                self.sync_expanded_diff_hunks(buffer.clone(), cx);
12651                cx.notify();
12652            }
12653            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12654            multi_buffer::Event::DiagnosticsUpdated => {
12655                self.refresh_active_diagnostics(cx);
12656                self.scrollbar_marker_state.dirty = true;
12657                cx.notify();
12658            }
12659            _ => {}
12660        };
12661    }
12662
12663    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12664        cx.notify();
12665    }
12666
12667    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12668        self.tasks_update_task = Some(self.refresh_runnables(cx));
12669        self.refresh_inline_completion(true, false, cx);
12670        self.refresh_inlay_hints(
12671            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12672                self.selections.newest_anchor().head(),
12673                &self.buffer.read(cx).snapshot(cx),
12674                cx,
12675            )),
12676            cx,
12677        );
12678
12679        let old_cursor_shape = self.cursor_shape;
12680
12681        {
12682            let editor_settings = EditorSettings::get_global(cx);
12683            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12684            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12685            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12686        }
12687
12688        if old_cursor_shape != self.cursor_shape {
12689            cx.emit(EditorEvent::CursorShapeChanged);
12690        }
12691
12692        let project_settings = ProjectSettings::get_global(cx);
12693        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12694
12695        if self.mode == EditorMode::Full {
12696            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12697            if self.git_blame_inline_enabled != inline_blame_enabled {
12698                self.toggle_git_blame_inline_internal(false, cx);
12699            }
12700        }
12701
12702        cx.notify();
12703    }
12704
12705    pub fn set_searchable(&mut self, searchable: bool) {
12706        self.searchable = searchable;
12707    }
12708
12709    pub fn searchable(&self) -> bool {
12710        self.searchable
12711    }
12712
12713    fn open_proposed_changes_editor(
12714        &mut self,
12715        _: &OpenProposedChangesEditor,
12716        cx: &mut ViewContext<Self>,
12717    ) {
12718        let Some(workspace) = self.workspace() else {
12719            cx.propagate();
12720            return;
12721        };
12722
12723        let selections = self.selections.all::<usize>(cx);
12724        let buffer = self.buffer.read(cx);
12725        let mut new_selections_by_buffer = HashMap::default();
12726        for selection in selections {
12727            for (buffer, range, _) in
12728                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12729            {
12730                let mut range = range.to_point(buffer.read(cx));
12731                range.start.column = 0;
12732                range.end.column = buffer.read(cx).line_len(range.end.row);
12733                new_selections_by_buffer
12734                    .entry(buffer)
12735                    .or_insert(Vec::new())
12736                    .push(range)
12737            }
12738        }
12739
12740        let proposed_changes_buffers = new_selections_by_buffer
12741            .into_iter()
12742            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12743            .collect::<Vec<_>>();
12744        let proposed_changes_editor = cx.new_view(|cx| {
12745            ProposedChangesEditor::new(
12746                "Proposed changes",
12747                proposed_changes_buffers,
12748                self.project.clone(),
12749                cx,
12750            )
12751        });
12752
12753        cx.window_context().defer(move |cx| {
12754            workspace.update(cx, |workspace, cx| {
12755                workspace.active_pane().update(cx, |pane, cx| {
12756                    pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12757                });
12758            });
12759        });
12760    }
12761
12762    pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12763        self.open_excerpts_common(None, true, cx)
12764    }
12765
12766    pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12767        self.open_excerpts_common(None, false, cx)
12768    }
12769
12770    fn open_excerpts_common(
12771        &mut self,
12772        jump_data: Option<JumpData>,
12773        split: bool,
12774        cx: &mut ViewContext<Self>,
12775    ) {
12776        let Some(workspace) = self.workspace() else {
12777            cx.propagate();
12778            return;
12779        };
12780
12781        if self.buffer.read(cx).is_singleton() {
12782            cx.propagate();
12783            return;
12784        }
12785
12786        let mut new_selections_by_buffer = HashMap::default();
12787        match &jump_data {
12788            Some(jump_data) => {
12789                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12790                if let Some(buffer) = multi_buffer_snapshot
12791                    .buffer_id_for_excerpt(jump_data.excerpt_id)
12792                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12793                {
12794                    let buffer_snapshot = buffer.read(cx).snapshot();
12795                    let jump_to_point = if buffer_snapshot.can_resolve(&jump_data.anchor) {
12796                        language::ToPoint::to_point(&jump_data.anchor, &buffer_snapshot)
12797                    } else {
12798                        buffer_snapshot.clip_point(jump_data.position, Bias::Left)
12799                    };
12800                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12801                    new_selections_by_buffer.insert(
12802                        buffer,
12803                        (
12804                            vec![jump_to_offset..jump_to_offset],
12805                            Some(jump_data.line_offset_from_top),
12806                        ),
12807                    );
12808                }
12809            }
12810            None => {
12811                let selections = self.selections.all::<usize>(cx);
12812                let buffer = self.buffer.read(cx);
12813                for selection in selections {
12814                    for (mut buffer_handle, mut range, _) in
12815                        buffer.range_to_buffer_ranges(selection.range(), cx)
12816                    {
12817                        // When editing branch buffers, jump to the corresponding location
12818                        // in their base buffer.
12819                        let buffer = buffer_handle.read(cx);
12820                        if let Some(base_buffer) = buffer.diff_base_buffer() {
12821                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12822                            buffer_handle = base_buffer;
12823                        }
12824
12825                        if selection.reversed {
12826                            mem::swap(&mut range.start, &mut range.end);
12827                        }
12828                        new_selections_by_buffer
12829                            .entry(buffer_handle)
12830                            .or_insert((Vec::new(), None))
12831                            .0
12832                            .push(range)
12833                    }
12834                }
12835            }
12836        }
12837
12838        if new_selections_by_buffer.is_empty() {
12839            return;
12840        }
12841
12842        // We defer the pane interaction because we ourselves are a workspace item
12843        // and activating a new item causes the pane to call a method on us reentrantly,
12844        // which panics if we're on the stack.
12845        cx.window_context().defer(move |cx| {
12846            workspace.update(cx, |workspace, cx| {
12847                let pane = if split {
12848                    workspace.adjacent_pane(cx)
12849                } else {
12850                    workspace.active_pane().clone()
12851                };
12852
12853                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12854                    let editor = buffer
12855                        .read(cx)
12856                        .file()
12857                        .is_none()
12858                        .then(|| {
12859                            // Handle file-less buffers separately: those are not really the project items, so won't have a paroject path or entity id,
12860                            // so `workspace.open_project_item` will never find them, always opening a new editor.
12861                            // Instead, we try to activate the existing editor in the pane first.
12862                            let (editor, pane_item_index) =
12863                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
12864                                    let editor = item.downcast::<Editor>()?;
12865                                    let singleton_buffer =
12866                                        editor.read(cx).buffer().read(cx).as_singleton()?;
12867                                    if singleton_buffer == buffer {
12868                                        Some((editor, i))
12869                                    } else {
12870                                        None
12871                                    }
12872                                })?;
12873                            pane.update(cx, |pane, cx| {
12874                                pane.activate_item(pane_item_index, true, true, cx)
12875                            });
12876                            Some(editor)
12877                        })
12878                        .flatten()
12879                        .unwrap_or_else(|| {
12880                            workspace.open_project_item::<Self>(
12881                                pane.clone(),
12882                                buffer,
12883                                true,
12884                                true,
12885                                cx,
12886                            )
12887                        });
12888
12889                    editor.update(cx, |editor, cx| {
12890                        let autoscroll = match scroll_offset {
12891                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12892                            None => Autoscroll::newest(),
12893                        };
12894                        let nav_history = editor.nav_history.take();
12895                        editor.change_selections(Some(autoscroll), cx, |s| {
12896                            s.select_ranges(ranges);
12897                        });
12898                        editor.nav_history = nav_history;
12899                    });
12900                }
12901            })
12902        });
12903    }
12904
12905    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12906        let snapshot = self.buffer.read(cx).read(cx);
12907        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12908        Some(
12909            ranges
12910                .iter()
12911                .map(move |range| {
12912                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12913                })
12914                .collect(),
12915        )
12916    }
12917
12918    fn selection_replacement_ranges(
12919        &self,
12920        range: Range<OffsetUtf16>,
12921        cx: &mut AppContext,
12922    ) -> Vec<Range<OffsetUtf16>> {
12923        let selections = self.selections.all::<OffsetUtf16>(cx);
12924        let newest_selection = selections
12925            .iter()
12926            .max_by_key(|selection| selection.id)
12927            .unwrap();
12928        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12929        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12930        let snapshot = self.buffer.read(cx).read(cx);
12931        selections
12932            .into_iter()
12933            .map(|mut selection| {
12934                selection.start.0 =
12935                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
12936                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12937                snapshot.clip_offset_utf16(selection.start, Bias::Left)
12938                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12939            })
12940            .collect()
12941    }
12942
12943    fn report_editor_event(
12944        &self,
12945        operation: &'static str,
12946        file_extension: Option<String>,
12947        cx: &AppContext,
12948    ) {
12949        if cfg!(any(test, feature = "test-support")) {
12950            return;
12951        }
12952
12953        let Some(project) = &self.project else { return };
12954
12955        // If None, we are in a file without an extension
12956        let file = self
12957            .buffer
12958            .read(cx)
12959            .as_singleton()
12960            .and_then(|b| b.read(cx).file());
12961        let file_extension = file_extension.or(file
12962            .as_ref()
12963            .and_then(|file| Path::new(file.file_name(cx)).extension())
12964            .and_then(|e| e.to_str())
12965            .map(|a| a.to_string()));
12966
12967        let vim_mode = cx
12968            .global::<SettingsStore>()
12969            .raw_user_settings()
12970            .get("vim_mode")
12971            == Some(&serde_json::Value::Bool(true));
12972
12973        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12974            == language::language_settings::InlineCompletionProvider::Copilot;
12975        let copilot_enabled_for_language = self
12976            .buffer
12977            .read(cx)
12978            .settings_at(0, cx)
12979            .show_inline_completions;
12980
12981        let project = project.read(cx);
12982        let telemetry = project.client().telemetry().clone();
12983        telemetry.report_editor_event(
12984            file_extension,
12985            vim_mode,
12986            operation,
12987            copilot_enabled,
12988            copilot_enabled_for_language,
12989            project.is_via_ssh(),
12990        )
12991    }
12992
12993    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12994    /// with each line being an array of {text, highlight} objects.
12995    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12996        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12997            return;
12998        };
12999
13000        #[derive(Serialize)]
13001        struct Chunk<'a> {
13002            text: String,
13003            highlight: Option<&'a str>,
13004        }
13005
13006        let snapshot = buffer.read(cx).snapshot();
13007        let range = self
13008            .selected_text_range(false, cx)
13009            .and_then(|selection| {
13010                if selection.range.is_empty() {
13011                    None
13012                } else {
13013                    Some(selection.range)
13014                }
13015            })
13016            .unwrap_or_else(|| 0..snapshot.len());
13017
13018        let chunks = snapshot.chunks(range, true);
13019        let mut lines = Vec::new();
13020        let mut line: VecDeque<Chunk> = VecDeque::new();
13021
13022        let Some(style) = self.style.as_ref() else {
13023            return;
13024        };
13025
13026        for chunk in chunks {
13027            let highlight = chunk
13028                .syntax_highlight_id
13029                .and_then(|id| id.name(&style.syntax));
13030            let mut chunk_lines = chunk.text.split('\n').peekable();
13031            while let Some(text) = chunk_lines.next() {
13032                let mut merged_with_last_token = false;
13033                if let Some(last_token) = line.back_mut() {
13034                    if last_token.highlight == highlight {
13035                        last_token.text.push_str(text);
13036                        merged_with_last_token = true;
13037                    }
13038                }
13039
13040                if !merged_with_last_token {
13041                    line.push_back(Chunk {
13042                        text: text.into(),
13043                        highlight,
13044                    });
13045                }
13046
13047                if chunk_lines.peek().is_some() {
13048                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
13049                        line.pop_front();
13050                    }
13051                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
13052                        line.pop_back();
13053                    }
13054
13055                    lines.push(mem::take(&mut line));
13056                }
13057            }
13058        }
13059
13060        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
13061            return;
13062        };
13063        cx.write_to_clipboard(ClipboardItem::new_string(lines));
13064    }
13065
13066    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
13067        &self.inlay_hint_cache
13068    }
13069
13070    pub fn replay_insert_event(
13071        &mut self,
13072        text: &str,
13073        relative_utf16_range: Option<Range<isize>>,
13074        cx: &mut ViewContext<Self>,
13075    ) {
13076        if !self.input_enabled {
13077            cx.emit(EditorEvent::InputIgnored { text: text.into() });
13078            return;
13079        }
13080        if let Some(relative_utf16_range) = relative_utf16_range {
13081            let selections = self.selections.all::<OffsetUtf16>(cx);
13082            self.change_selections(None, cx, |s| {
13083                let new_ranges = selections.into_iter().map(|range| {
13084                    let start = OffsetUtf16(
13085                        range
13086                            .head()
13087                            .0
13088                            .saturating_add_signed(relative_utf16_range.start),
13089                    );
13090                    let end = OffsetUtf16(
13091                        range
13092                            .head()
13093                            .0
13094                            .saturating_add_signed(relative_utf16_range.end),
13095                    );
13096                    start..end
13097                });
13098                s.select_ranges(new_ranges);
13099            });
13100        }
13101
13102        self.handle_input(text, cx);
13103    }
13104
13105    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
13106        let Some(provider) = self.semantics_provider.as_ref() else {
13107            return false;
13108        };
13109
13110        let mut supports = false;
13111        self.buffer().read(cx).for_each_buffer(|buffer| {
13112            supports |= provider.supports_inlay_hints(buffer, cx);
13113        });
13114        supports
13115    }
13116
13117    pub fn focus(&self, cx: &mut WindowContext) {
13118        cx.focus(&self.focus_handle)
13119    }
13120
13121    pub fn is_focused(&self, cx: &WindowContext) -> bool {
13122        self.focus_handle.is_focused(cx)
13123    }
13124
13125    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
13126        cx.emit(EditorEvent::Focused);
13127
13128        if let Some(descendant) = self
13129            .last_focused_descendant
13130            .take()
13131            .and_then(|descendant| descendant.upgrade())
13132        {
13133            cx.focus(&descendant);
13134        } else {
13135            if let Some(blame) = self.blame.as_ref() {
13136                blame.update(cx, GitBlame::focus)
13137            }
13138
13139            self.blink_manager.update(cx, BlinkManager::enable);
13140            self.show_cursor_names(cx);
13141            self.buffer.update(cx, |buffer, cx| {
13142                buffer.finalize_last_transaction(cx);
13143                if self.leader_peer_id.is_none() {
13144                    buffer.set_active_selections(
13145                        &self.selections.disjoint_anchors(),
13146                        self.selections.line_mode,
13147                        self.cursor_shape,
13148                        cx,
13149                    );
13150                }
13151            });
13152        }
13153    }
13154
13155    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
13156        cx.emit(EditorEvent::FocusedIn)
13157    }
13158
13159    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
13160        if event.blurred != self.focus_handle {
13161            self.last_focused_descendant = Some(event.blurred);
13162        }
13163    }
13164
13165    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
13166        self.blink_manager.update(cx, BlinkManager::disable);
13167        self.buffer
13168            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
13169
13170        if let Some(blame) = self.blame.as_ref() {
13171            blame.update(cx, GitBlame::blur)
13172        }
13173        if !self.hover_state.focused(cx) {
13174            hide_hover(self, cx);
13175        }
13176
13177        self.hide_context_menu(cx);
13178        cx.emit(EditorEvent::Blurred);
13179        cx.notify();
13180    }
13181
13182    pub fn register_action<A: Action>(
13183        &mut self,
13184        listener: impl Fn(&A, &mut WindowContext) + 'static,
13185    ) -> Subscription {
13186        let id = self.next_editor_action_id.post_inc();
13187        let listener = Arc::new(listener);
13188        self.editor_actions.borrow_mut().insert(
13189            id,
13190            Box::new(move |cx| {
13191                let cx = cx.window_context();
13192                let listener = listener.clone();
13193                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
13194                    let action = action.downcast_ref().unwrap();
13195                    if phase == DispatchPhase::Bubble {
13196                        listener(action, cx)
13197                    }
13198                })
13199            }),
13200        );
13201
13202        let editor_actions = self.editor_actions.clone();
13203        Subscription::new(move || {
13204            editor_actions.borrow_mut().remove(&id);
13205        })
13206    }
13207
13208    pub fn file_header_size(&self) -> u32 {
13209        FILE_HEADER_HEIGHT
13210    }
13211
13212    pub fn revert(
13213        &mut self,
13214        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
13215        cx: &mut ViewContext<Self>,
13216    ) {
13217        self.buffer().update(cx, |multi_buffer, cx| {
13218            for (buffer_id, changes) in revert_changes {
13219                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13220                    buffer.update(cx, |buffer, cx| {
13221                        buffer.edit(
13222                            changes.into_iter().map(|(range, text)| {
13223                                (range, text.to_string().map(Arc::<str>::from))
13224                            }),
13225                            None,
13226                            cx,
13227                        );
13228                    });
13229                }
13230            }
13231        });
13232        self.change_selections(None, cx, |selections| selections.refresh());
13233    }
13234
13235    pub fn to_pixel_point(
13236        &mut self,
13237        source: multi_buffer::Anchor,
13238        editor_snapshot: &EditorSnapshot,
13239        cx: &mut ViewContext<Self>,
13240    ) -> Option<gpui::Point<Pixels>> {
13241        let source_point = source.to_display_point(editor_snapshot);
13242        self.display_to_pixel_point(source_point, editor_snapshot, cx)
13243    }
13244
13245    pub fn display_to_pixel_point(
13246        &mut self,
13247        source: DisplayPoint,
13248        editor_snapshot: &EditorSnapshot,
13249        cx: &mut ViewContext<Self>,
13250    ) -> Option<gpui::Point<Pixels>> {
13251        let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
13252        let text_layout_details = self.text_layout_details(cx);
13253        let scroll_top = text_layout_details
13254            .scroll_anchor
13255            .scroll_position(editor_snapshot)
13256            .y;
13257
13258        if source.row().as_f32() < scroll_top.floor() {
13259            return None;
13260        }
13261        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
13262        let source_y = line_height * (source.row().as_f32() - scroll_top);
13263        Some(gpui::Point::new(source_x, source_y))
13264    }
13265
13266    pub fn has_active_completions_menu(&self) -> bool {
13267        self.context_menu.read().as_ref().map_or(false, |menu| {
13268            menu.visible() && matches!(menu, ContextMenu::Completions(_))
13269        })
13270    }
13271
13272    pub fn register_addon<T: Addon>(&mut self, instance: T) {
13273        self.addons
13274            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
13275    }
13276
13277    pub fn unregister_addon<T: Addon>(&mut self) {
13278        self.addons.remove(&std::any::TypeId::of::<T>());
13279    }
13280
13281    pub fn addon<T: Addon>(&self) -> Option<&T> {
13282        let type_id = std::any::TypeId::of::<T>();
13283        self.addons
13284            .get(&type_id)
13285            .and_then(|item| item.to_any().downcast_ref::<T>())
13286    }
13287}
13288
13289fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13290    let tab_size = tab_size.get() as usize;
13291    let mut width = offset;
13292
13293    for ch in text.chars() {
13294        width += if ch == '\t' {
13295            tab_size - (width % tab_size)
13296        } else {
13297            1
13298        };
13299    }
13300
13301    width - offset
13302}
13303
13304#[cfg(test)]
13305mod tests {
13306    use super::*;
13307
13308    #[test]
13309    fn test_string_size_with_expanded_tabs() {
13310        let nz = |val| NonZeroU32::new(val).unwrap();
13311        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13312        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13313        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13314        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13315        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13316        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13317        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13318        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13319    }
13320}
13321
13322/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13323struct WordBreakingTokenizer<'a> {
13324    input: &'a str,
13325}
13326
13327impl<'a> WordBreakingTokenizer<'a> {
13328    fn new(input: &'a str) -> Self {
13329        Self { input }
13330    }
13331}
13332
13333fn is_char_ideographic(ch: char) -> bool {
13334    use unicode_script::Script::*;
13335    use unicode_script::UnicodeScript;
13336    matches!(ch.script(), Han | Tangut | Yi)
13337}
13338
13339fn is_grapheme_ideographic(text: &str) -> bool {
13340    text.chars().any(is_char_ideographic)
13341}
13342
13343fn is_grapheme_whitespace(text: &str) -> bool {
13344    text.chars().any(|x| x.is_whitespace())
13345}
13346
13347fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13348    text.chars().next().map_or(false, |ch| {
13349        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13350    })
13351}
13352
13353#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13354struct WordBreakToken<'a> {
13355    token: &'a str,
13356    grapheme_len: usize,
13357    is_whitespace: bool,
13358}
13359
13360impl<'a> Iterator for WordBreakingTokenizer<'a> {
13361    /// Yields a span, the count of graphemes in the token, and whether it was
13362    /// whitespace. Note that it also breaks at word boundaries.
13363    type Item = WordBreakToken<'a>;
13364
13365    fn next(&mut self) -> Option<Self::Item> {
13366        use unicode_segmentation::UnicodeSegmentation;
13367        if self.input.is_empty() {
13368            return None;
13369        }
13370
13371        let mut iter = self.input.graphemes(true).peekable();
13372        let mut offset = 0;
13373        let mut graphemes = 0;
13374        if let Some(first_grapheme) = iter.next() {
13375            let is_whitespace = is_grapheme_whitespace(first_grapheme);
13376            offset += first_grapheme.len();
13377            graphemes += 1;
13378            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13379                if let Some(grapheme) = iter.peek().copied() {
13380                    if should_stay_with_preceding_ideograph(grapheme) {
13381                        offset += grapheme.len();
13382                        graphemes += 1;
13383                    }
13384                }
13385            } else {
13386                let mut words = self.input[offset..].split_word_bound_indices().peekable();
13387                let mut next_word_bound = words.peek().copied();
13388                if next_word_bound.map_or(false, |(i, _)| i == 0) {
13389                    next_word_bound = words.next();
13390                }
13391                while let Some(grapheme) = iter.peek().copied() {
13392                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
13393                        break;
13394                    };
13395                    if is_grapheme_whitespace(grapheme) != is_whitespace {
13396                        break;
13397                    };
13398                    offset += grapheme.len();
13399                    graphemes += 1;
13400                    iter.next();
13401                }
13402            }
13403            let token = &self.input[..offset];
13404            self.input = &self.input[offset..];
13405            if is_whitespace {
13406                Some(WordBreakToken {
13407                    token: " ",
13408                    grapheme_len: 1,
13409                    is_whitespace: true,
13410                })
13411            } else {
13412                Some(WordBreakToken {
13413                    token,
13414                    grapheme_len: graphemes,
13415                    is_whitespace: false,
13416                })
13417            }
13418        } else {
13419            None
13420        }
13421    }
13422}
13423
13424#[test]
13425fn test_word_breaking_tokenizer() {
13426    let tests: &[(&str, &[(&str, usize, bool)])] = &[
13427        ("", &[]),
13428        ("  ", &[(" ", 1, true)]),
13429        ("Ʒ", &[("Ʒ", 1, false)]),
13430        ("Ǽ", &[("Ǽ", 1, false)]),
13431        ("", &[("", 1, false)]),
13432        ("⋑⋑", &[("⋑⋑", 2, false)]),
13433        (
13434            "原理,进而",
13435            &[
13436                ("", 1, false),
13437                ("理,", 2, false),
13438                ("", 1, false),
13439                ("", 1, false),
13440            ],
13441        ),
13442        (
13443            "hello world",
13444            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13445        ),
13446        (
13447            "hello, world",
13448            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13449        ),
13450        (
13451            "  hello world",
13452            &[
13453                (" ", 1, true),
13454                ("hello", 5, false),
13455                (" ", 1, true),
13456                ("world", 5, false),
13457            ],
13458        ),
13459        (
13460            "这是什么 \n 钢笔",
13461            &[
13462                ("", 1, false),
13463                ("", 1, false),
13464                ("", 1, false),
13465                ("", 1, false),
13466                (" ", 1, true),
13467                ("", 1, false),
13468                ("", 1, false),
13469            ],
13470        ),
13471        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13472    ];
13473
13474    for (input, result) in tests {
13475        assert_eq!(
13476            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13477            result
13478                .iter()
13479                .copied()
13480                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13481                    token,
13482                    grapheme_len,
13483                    is_whitespace,
13484                })
13485                .collect::<Vec<_>>()
13486        );
13487    }
13488}
13489
13490fn wrap_with_prefix(
13491    line_prefix: String,
13492    unwrapped_text: String,
13493    wrap_column: usize,
13494    tab_size: NonZeroU32,
13495) -> String {
13496    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13497    let mut wrapped_text = String::new();
13498    let mut current_line = line_prefix.clone();
13499
13500    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13501    let mut current_line_len = line_prefix_len;
13502    for WordBreakToken {
13503        token,
13504        grapheme_len,
13505        is_whitespace,
13506    } in tokenizer
13507    {
13508        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13509            wrapped_text.push_str(current_line.trim_end());
13510            wrapped_text.push('\n');
13511            current_line.truncate(line_prefix.len());
13512            current_line_len = line_prefix_len;
13513            if !is_whitespace {
13514                current_line.push_str(token);
13515                current_line_len += grapheme_len;
13516            }
13517        } else if !is_whitespace {
13518            current_line.push_str(token);
13519            current_line_len += grapheme_len;
13520        } else if current_line_len != line_prefix_len {
13521            current_line.push(' ');
13522            current_line_len += 1;
13523        }
13524    }
13525
13526    if !current_line.is_empty() {
13527        wrapped_text.push_str(&current_line);
13528    }
13529    wrapped_text
13530}
13531
13532#[test]
13533fn test_wrap_with_prefix() {
13534    assert_eq!(
13535        wrap_with_prefix(
13536            "# ".to_string(),
13537            "abcdefg".to_string(),
13538            4,
13539            NonZeroU32::new(4).unwrap()
13540        ),
13541        "# abcdefg"
13542    );
13543    assert_eq!(
13544        wrap_with_prefix(
13545            "".to_string(),
13546            "\thello world".to_string(),
13547            8,
13548            NonZeroU32::new(4).unwrap()
13549        ),
13550        "hello\nworld"
13551    );
13552    assert_eq!(
13553        wrap_with_prefix(
13554            "// ".to_string(),
13555            "xx \nyy zz aa bb cc".to_string(),
13556            12,
13557            NonZeroU32::new(4).unwrap()
13558        ),
13559        "// xx yy zz\n// aa bb cc"
13560    );
13561    assert_eq!(
13562        wrap_with_prefix(
13563            String::new(),
13564            "这是什么 \n 钢笔".to_string(),
13565            3,
13566            NonZeroU32::new(4).unwrap()
13567        ),
13568        "这是什\n么 钢\n"
13569    );
13570}
13571
13572fn hunks_for_selections(
13573    multi_buffer_snapshot: &MultiBufferSnapshot,
13574    selections: &[Selection<Anchor>],
13575) -> Vec<MultiBufferDiffHunk> {
13576    let buffer_rows_for_selections = selections.iter().map(|selection| {
13577        let head = selection.head();
13578        let tail = selection.tail();
13579        let start = MultiBufferRow(tail.to_point(multi_buffer_snapshot).row);
13580        let end = MultiBufferRow(head.to_point(multi_buffer_snapshot).row);
13581        if start > end {
13582            end..start
13583        } else {
13584            start..end
13585        }
13586    });
13587
13588    hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
13589}
13590
13591pub fn hunks_for_rows(
13592    rows: impl Iterator<Item = Range<MultiBufferRow>>,
13593    multi_buffer_snapshot: &MultiBufferSnapshot,
13594) -> Vec<MultiBufferDiffHunk> {
13595    let mut hunks = Vec::new();
13596    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13597        HashMap::default();
13598    for selected_multi_buffer_rows in rows {
13599        let query_rows =
13600            selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
13601        for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
13602            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13603            // when the caret is just above or just below the deleted hunk.
13604            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13605            let related_to_selection = if allow_adjacent {
13606                hunk.row_range.overlaps(&query_rows)
13607                    || hunk.row_range.start == query_rows.end
13608                    || hunk.row_range.end == query_rows.start
13609            } else {
13610                // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
13611                // `hunk.row_range` is exclusive (e.g. [2..3] means 2nd row is selected)
13612                hunk.row_range.overlaps(&selected_multi_buffer_rows)
13613                    || selected_multi_buffer_rows.end == hunk.row_range.start
13614            };
13615            if related_to_selection {
13616                if !processed_buffer_rows
13617                    .entry(hunk.buffer_id)
13618                    .or_default()
13619                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13620                {
13621                    continue;
13622                }
13623                hunks.push(hunk);
13624            }
13625        }
13626    }
13627
13628    hunks
13629}
13630
13631pub trait CollaborationHub {
13632    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13633    fn user_participant_indices<'a>(
13634        &self,
13635        cx: &'a AppContext,
13636    ) -> &'a HashMap<u64, ParticipantIndex>;
13637    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13638}
13639
13640impl CollaborationHub for Model<Project> {
13641    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13642        self.read(cx).collaborators()
13643    }
13644
13645    fn user_participant_indices<'a>(
13646        &self,
13647        cx: &'a AppContext,
13648    ) -> &'a HashMap<u64, ParticipantIndex> {
13649        self.read(cx).user_store().read(cx).participant_indices()
13650    }
13651
13652    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13653        let this = self.read(cx);
13654        let user_ids = this.collaborators().values().map(|c| c.user_id);
13655        this.user_store().read_with(cx, |user_store, cx| {
13656            user_store.participant_names(user_ids, cx)
13657        })
13658    }
13659}
13660
13661pub trait SemanticsProvider {
13662    fn hover(
13663        &self,
13664        buffer: &Model<Buffer>,
13665        position: text::Anchor,
13666        cx: &mut AppContext,
13667    ) -> Option<Task<Vec<project::Hover>>>;
13668
13669    fn inlay_hints(
13670        &self,
13671        buffer_handle: Model<Buffer>,
13672        range: Range<text::Anchor>,
13673        cx: &mut AppContext,
13674    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13675
13676    fn resolve_inlay_hint(
13677        &self,
13678        hint: InlayHint,
13679        buffer_handle: Model<Buffer>,
13680        server_id: LanguageServerId,
13681        cx: &mut AppContext,
13682    ) -> Option<Task<anyhow::Result<InlayHint>>>;
13683
13684    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13685
13686    fn document_highlights(
13687        &self,
13688        buffer: &Model<Buffer>,
13689        position: text::Anchor,
13690        cx: &mut AppContext,
13691    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13692
13693    fn definitions(
13694        &self,
13695        buffer: &Model<Buffer>,
13696        position: text::Anchor,
13697        kind: GotoDefinitionKind,
13698        cx: &mut AppContext,
13699    ) -> Option<Task<Result<Vec<LocationLink>>>>;
13700
13701    fn range_for_rename(
13702        &self,
13703        buffer: &Model<Buffer>,
13704        position: text::Anchor,
13705        cx: &mut AppContext,
13706    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13707
13708    fn perform_rename(
13709        &self,
13710        buffer: &Model<Buffer>,
13711        position: text::Anchor,
13712        new_name: String,
13713        cx: &mut AppContext,
13714    ) -> Option<Task<Result<ProjectTransaction>>>;
13715}
13716
13717pub trait CompletionProvider {
13718    fn completions(
13719        &self,
13720        buffer: &Model<Buffer>,
13721        buffer_position: text::Anchor,
13722        trigger: CompletionContext,
13723        cx: &mut ViewContext<Editor>,
13724    ) -> Task<Result<Vec<Completion>>>;
13725
13726    fn resolve_completions(
13727        &self,
13728        buffer: Model<Buffer>,
13729        completion_indices: Vec<usize>,
13730        completions: Arc<RwLock<Box<[Completion]>>>,
13731        cx: &mut ViewContext<Editor>,
13732    ) -> Task<Result<bool>>;
13733
13734    fn apply_additional_edits_for_completion(
13735        &self,
13736        buffer: Model<Buffer>,
13737        completion: Completion,
13738        push_to_history: bool,
13739        cx: &mut ViewContext<Editor>,
13740    ) -> Task<Result<Option<language::Transaction>>>;
13741
13742    fn is_completion_trigger(
13743        &self,
13744        buffer: &Model<Buffer>,
13745        position: language::Anchor,
13746        text: &str,
13747        trigger_in_words: bool,
13748        cx: &mut ViewContext<Editor>,
13749    ) -> bool;
13750
13751    fn sort_completions(&self) -> bool {
13752        true
13753    }
13754}
13755
13756pub trait CodeActionProvider {
13757    fn code_actions(
13758        &self,
13759        buffer: &Model<Buffer>,
13760        range: Range<text::Anchor>,
13761        cx: &mut WindowContext,
13762    ) -> Task<Result<Vec<CodeAction>>>;
13763
13764    fn apply_code_action(
13765        &self,
13766        buffer_handle: Model<Buffer>,
13767        action: CodeAction,
13768        excerpt_id: ExcerptId,
13769        push_to_history: bool,
13770        cx: &mut WindowContext,
13771    ) -> Task<Result<ProjectTransaction>>;
13772}
13773
13774impl CodeActionProvider for Model<Project> {
13775    fn code_actions(
13776        &self,
13777        buffer: &Model<Buffer>,
13778        range: Range<text::Anchor>,
13779        cx: &mut WindowContext,
13780    ) -> Task<Result<Vec<CodeAction>>> {
13781        self.update(cx, |project, cx| {
13782            project.code_actions(buffer, range, None, cx)
13783        })
13784    }
13785
13786    fn apply_code_action(
13787        &self,
13788        buffer_handle: Model<Buffer>,
13789        action: CodeAction,
13790        _excerpt_id: ExcerptId,
13791        push_to_history: bool,
13792        cx: &mut WindowContext,
13793    ) -> Task<Result<ProjectTransaction>> {
13794        self.update(cx, |project, cx| {
13795            project.apply_code_action(buffer_handle, action, push_to_history, cx)
13796        })
13797    }
13798}
13799
13800fn snippet_completions(
13801    project: &Project,
13802    buffer: &Model<Buffer>,
13803    buffer_position: text::Anchor,
13804    cx: &mut AppContext,
13805) -> Task<Result<Vec<Completion>>> {
13806    let language = buffer.read(cx).language_at(buffer_position);
13807    let language_name = language.as_ref().map(|language| language.lsp_id());
13808    let snippet_store = project.snippets().read(cx);
13809    let snippets = snippet_store.snippets_for(language_name, cx);
13810
13811    if snippets.is_empty() {
13812        return Task::ready(Ok(vec![]));
13813    }
13814    let snapshot = buffer.read(cx).text_snapshot();
13815    let chars: String = snapshot
13816        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
13817        .collect();
13818
13819    let scope = language.map(|language| language.default_scope());
13820    let executor = cx.background_executor().clone();
13821
13822    cx.background_executor().spawn(async move {
13823        let classifier = CharClassifier::new(scope).for_completion(true);
13824        let mut last_word = chars
13825            .chars()
13826            .take_while(|c| classifier.is_word(*c))
13827            .collect::<String>();
13828        last_word = last_word.chars().rev().collect();
13829
13830        if last_word.is_empty() {
13831            return Ok(vec![]);
13832        }
13833
13834        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13835        let to_lsp = |point: &text::Anchor| {
13836            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13837            point_to_lsp(end)
13838        };
13839        let lsp_end = to_lsp(&buffer_position);
13840
13841        let candidates = snippets
13842            .iter()
13843            .enumerate()
13844            .flat_map(|(ix, snippet)| {
13845                snippet
13846                    .prefix
13847                    .iter()
13848                    .map(move |prefix| StringMatchCandidate::new(ix, prefix.clone()))
13849            })
13850            .collect::<Vec<StringMatchCandidate>>();
13851
13852        let mut matches = fuzzy::match_strings(
13853            &candidates,
13854            &last_word,
13855            last_word.chars().any(|c| c.is_uppercase()),
13856            100,
13857            &Default::default(),
13858            executor,
13859        )
13860        .await;
13861
13862        // Remove all candidates where the query's start does not match the start of any word in the candidate
13863        if let Some(query_start) = last_word.chars().next() {
13864            matches.retain(|string_match| {
13865                split_words(&string_match.string).any(|word| {
13866                    // Check that the first codepoint of the word as lowercase matches the first
13867                    // codepoint of the query as lowercase
13868                    word.chars()
13869                        .flat_map(|codepoint| codepoint.to_lowercase())
13870                        .zip(query_start.to_lowercase())
13871                        .all(|(word_cp, query_cp)| word_cp == query_cp)
13872                })
13873            });
13874        }
13875
13876        let matched_strings = matches
13877            .into_iter()
13878            .map(|m| m.string)
13879            .collect::<HashSet<_>>();
13880
13881        let result: Vec<Completion> = snippets
13882            .into_iter()
13883            .filter_map(|snippet| {
13884                let matching_prefix = snippet
13885                    .prefix
13886                    .iter()
13887                    .find(|prefix| matched_strings.contains(*prefix))?;
13888                let start = as_offset - last_word.len();
13889                let start = snapshot.anchor_before(start);
13890                let range = start..buffer_position;
13891                let lsp_start = to_lsp(&start);
13892                let lsp_range = lsp::Range {
13893                    start: lsp_start,
13894                    end: lsp_end,
13895                };
13896                Some(Completion {
13897                    old_range: range,
13898                    new_text: snippet.body.clone(),
13899                    label: CodeLabel {
13900                        text: matching_prefix.clone(),
13901                        runs: vec![],
13902                        filter_range: 0..matching_prefix.len(),
13903                    },
13904                    server_id: LanguageServerId(usize::MAX),
13905                    documentation: snippet.description.clone().map(Documentation::SingleLine),
13906                    lsp_completion: lsp::CompletionItem {
13907                        label: snippet.prefix.first().unwrap().clone(),
13908                        kind: Some(CompletionItemKind::SNIPPET),
13909                        label_details: snippet.description.as_ref().map(|description| {
13910                            lsp::CompletionItemLabelDetails {
13911                                detail: Some(description.clone()),
13912                                description: None,
13913                            }
13914                        }),
13915                        insert_text_format: Some(InsertTextFormat::SNIPPET),
13916                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13917                            lsp::InsertReplaceEdit {
13918                                new_text: snippet.body.clone(),
13919                                insert: lsp_range,
13920                                replace: lsp_range,
13921                            },
13922                        )),
13923                        filter_text: Some(snippet.body.clone()),
13924                        sort_text: Some(char::MAX.to_string()),
13925                        ..Default::default()
13926                    },
13927                    confirm: None,
13928                })
13929            })
13930            .collect();
13931
13932        Ok(result)
13933    })
13934}
13935
13936impl CompletionProvider for Model<Project> {
13937    fn completions(
13938        &self,
13939        buffer: &Model<Buffer>,
13940        buffer_position: text::Anchor,
13941        options: CompletionContext,
13942        cx: &mut ViewContext<Editor>,
13943    ) -> Task<Result<Vec<Completion>>> {
13944        self.update(cx, |project, cx| {
13945            let snippets = snippet_completions(project, buffer, buffer_position, cx);
13946            let project_completions = project.completions(buffer, buffer_position, options, cx);
13947            cx.background_executor().spawn(async move {
13948                let mut completions = project_completions.await?;
13949                let snippets_completions = snippets.await?;
13950                completions.extend(snippets_completions);
13951                Ok(completions)
13952            })
13953        })
13954    }
13955
13956    fn resolve_completions(
13957        &self,
13958        buffer: Model<Buffer>,
13959        completion_indices: Vec<usize>,
13960        completions: Arc<RwLock<Box<[Completion]>>>,
13961        cx: &mut ViewContext<Editor>,
13962    ) -> Task<Result<bool>> {
13963        self.update(cx, |project, cx| {
13964            project.resolve_completions(buffer, completion_indices, completions, cx)
13965        })
13966    }
13967
13968    fn apply_additional_edits_for_completion(
13969        &self,
13970        buffer: Model<Buffer>,
13971        completion: Completion,
13972        push_to_history: bool,
13973        cx: &mut ViewContext<Editor>,
13974    ) -> Task<Result<Option<language::Transaction>>> {
13975        self.update(cx, |project, cx| {
13976            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13977        })
13978    }
13979
13980    fn is_completion_trigger(
13981        &self,
13982        buffer: &Model<Buffer>,
13983        position: language::Anchor,
13984        text: &str,
13985        trigger_in_words: bool,
13986        cx: &mut ViewContext<Editor>,
13987    ) -> bool {
13988        if !EditorSettings::get_global(cx).show_completions_on_input {
13989            return false;
13990        }
13991
13992        let mut chars = text.chars();
13993        let char = if let Some(char) = chars.next() {
13994            char
13995        } else {
13996            return false;
13997        };
13998        if chars.next().is_some() {
13999            return false;
14000        }
14001
14002        let buffer = buffer.read(cx);
14003        let classifier = buffer
14004            .snapshot()
14005            .char_classifier_at(position)
14006            .for_completion(true);
14007        if trigger_in_words && classifier.is_word(char) {
14008            return true;
14009        }
14010
14011        buffer.completion_triggers().contains(text)
14012    }
14013}
14014
14015impl SemanticsProvider for Model<Project> {
14016    fn hover(
14017        &self,
14018        buffer: &Model<Buffer>,
14019        position: text::Anchor,
14020        cx: &mut AppContext,
14021    ) -> Option<Task<Vec<project::Hover>>> {
14022        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
14023    }
14024
14025    fn document_highlights(
14026        &self,
14027        buffer: &Model<Buffer>,
14028        position: text::Anchor,
14029        cx: &mut AppContext,
14030    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
14031        Some(self.update(cx, |project, cx| {
14032            project.document_highlights(buffer, position, cx)
14033        }))
14034    }
14035
14036    fn definitions(
14037        &self,
14038        buffer: &Model<Buffer>,
14039        position: text::Anchor,
14040        kind: GotoDefinitionKind,
14041        cx: &mut AppContext,
14042    ) -> Option<Task<Result<Vec<LocationLink>>>> {
14043        Some(self.update(cx, |project, cx| match kind {
14044            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
14045            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
14046            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
14047            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
14048        }))
14049    }
14050
14051    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
14052        // TODO: make this work for remote projects
14053        self.read(cx)
14054            .language_servers_for_buffer(buffer.read(cx), cx)
14055            .any(
14056                |(_, server)| match server.capabilities().inlay_hint_provider {
14057                    Some(lsp::OneOf::Left(enabled)) => enabled,
14058                    Some(lsp::OneOf::Right(_)) => true,
14059                    None => false,
14060                },
14061            )
14062    }
14063
14064    fn inlay_hints(
14065        &self,
14066        buffer_handle: Model<Buffer>,
14067        range: Range<text::Anchor>,
14068        cx: &mut AppContext,
14069    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
14070        Some(self.update(cx, |project, cx| {
14071            project.inlay_hints(buffer_handle, range, cx)
14072        }))
14073    }
14074
14075    fn resolve_inlay_hint(
14076        &self,
14077        hint: InlayHint,
14078        buffer_handle: Model<Buffer>,
14079        server_id: LanguageServerId,
14080        cx: &mut AppContext,
14081    ) -> Option<Task<anyhow::Result<InlayHint>>> {
14082        Some(self.update(cx, |project, cx| {
14083            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
14084        }))
14085    }
14086
14087    fn range_for_rename(
14088        &self,
14089        buffer: &Model<Buffer>,
14090        position: text::Anchor,
14091        cx: &mut AppContext,
14092    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
14093        Some(self.update(cx, |project, cx| {
14094            project.prepare_rename(buffer.clone(), position, cx)
14095        }))
14096    }
14097
14098    fn perform_rename(
14099        &self,
14100        buffer: &Model<Buffer>,
14101        position: text::Anchor,
14102        new_name: String,
14103        cx: &mut AppContext,
14104    ) -> Option<Task<Result<ProjectTransaction>>> {
14105        Some(self.update(cx, |project, cx| {
14106            project.perform_rename(buffer.clone(), position, new_name, cx)
14107        }))
14108    }
14109}
14110
14111fn inlay_hint_settings(
14112    location: Anchor,
14113    snapshot: &MultiBufferSnapshot,
14114    cx: &mut ViewContext<'_, Editor>,
14115) -> InlayHintSettings {
14116    let file = snapshot.file_at(location);
14117    let language = snapshot.language_at(location).map(|l| l.name());
14118    language_settings(language, file, cx).inlay_hints
14119}
14120
14121fn consume_contiguous_rows(
14122    contiguous_row_selections: &mut Vec<Selection<Point>>,
14123    selection: &Selection<Point>,
14124    display_map: &DisplaySnapshot,
14125    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
14126) -> (MultiBufferRow, MultiBufferRow) {
14127    contiguous_row_selections.push(selection.clone());
14128    let start_row = MultiBufferRow(selection.start.row);
14129    let mut end_row = ending_row(selection, display_map);
14130
14131    while let Some(next_selection) = selections.peek() {
14132        if next_selection.start.row <= end_row.0 {
14133            end_row = ending_row(next_selection, display_map);
14134            contiguous_row_selections.push(selections.next().unwrap().clone());
14135        } else {
14136            break;
14137        }
14138    }
14139    (start_row, end_row)
14140}
14141
14142fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
14143    if next_selection.end.column > 0 || next_selection.is_empty() {
14144        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
14145    } else {
14146        MultiBufferRow(next_selection.end.row)
14147    }
14148}
14149
14150impl EditorSnapshot {
14151    pub fn remote_selections_in_range<'a>(
14152        &'a self,
14153        range: &'a Range<Anchor>,
14154        collaboration_hub: &dyn CollaborationHub,
14155        cx: &'a AppContext,
14156    ) -> impl 'a + Iterator<Item = RemoteSelection> {
14157        let participant_names = collaboration_hub.user_names(cx);
14158        let participant_indices = collaboration_hub.user_participant_indices(cx);
14159        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
14160        let collaborators_by_replica_id = collaborators_by_peer_id
14161            .iter()
14162            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
14163            .collect::<HashMap<_, _>>();
14164        self.buffer_snapshot
14165            .selections_in_range(range, false)
14166            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
14167                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
14168                let participant_index = participant_indices.get(&collaborator.user_id).copied();
14169                let user_name = participant_names.get(&collaborator.user_id).cloned();
14170                Some(RemoteSelection {
14171                    replica_id,
14172                    selection,
14173                    cursor_shape,
14174                    line_mode,
14175                    participant_index,
14176                    peer_id: collaborator.peer_id,
14177                    user_name,
14178                })
14179            })
14180    }
14181
14182    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
14183        self.display_snapshot.buffer_snapshot.language_at(position)
14184    }
14185
14186    pub fn is_focused(&self) -> bool {
14187        self.is_focused
14188    }
14189
14190    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
14191        self.placeholder_text.as_ref()
14192    }
14193
14194    pub fn scroll_position(&self) -> gpui::Point<f32> {
14195        self.scroll_anchor.scroll_position(&self.display_snapshot)
14196    }
14197
14198    fn gutter_dimensions(
14199        &self,
14200        font_id: FontId,
14201        font_size: Pixels,
14202        em_width: Pixels,
14203        em_advance: Pixels,
14204        max_line_number_width: Pixels,
14205        cx: &AppContext,
14206    ) -> GutterDimensions {
14207        if !self.show_gutter {
14208            return GutterDimensions::default();
14209        }
14210        let descent = cx.text_system().descent(font_id, font_size);
14211
14212        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
14213            matches!(
14214                ProjectSettings::get_global(cx).git.git_gutter,
14215                Some(GitGutterSetting::TrackedFiles)
14216            )
14217        });
14218        let gutter_settings = EditorSettings::get_global(cx).gutter;
14219        let show_line_numbers = self
14220            .show_line_numbers
14221            .unwrap_or(gutter_settings.line_numbers);
14222        let line_gutter_width = if show_line_numbers {
14223            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
14224            let min_width_for_number_on_gutter = em_advance * 4.0;
14225            max_line_number_width.max(min_width_for_number_on_gutter)
14226        } else {
14227            0.0.into()
14228        };
14229
14230        let show_code_actions = self
14231            .show_code_actions
14232            .unwrap_or(gutter_settings.code_actions);
14233
14234        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
14235
14236        let git_blame_entries_width =
14237            self.git_blame_gutter_max_author_length
14238                .map(|max_author_length| {
14239                    // Length of the author name, but also space for the commit hash,
14240                    // the spacing and the timestamp.
14241                    let max_char_count = max_author_length
14242                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
14243                        + 7 // length of commit sha
14244                        + 14 // length of max relative timestamp ("60 minutes ago")
14245                        + 4; // gaps and margins
14246
14247                    em_advance * max_char_count
14248                });
14249
14250        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
14251        left_padding += if show_code_actions || show_runnables {
14252            em_width * 3.0
14253        } else if show_git_gutter && show_line_numbers {
14254            em_width * 2.0
14255        } else if show_git_gutter || show_line_numbers {
14256            em_width
14257        } else {
14258            px(0.)
14259        };
14260
14261        let right_padding = if gutter_settings.folds && show_line_numbers {
14262            em_width * 4.0
14263        } else if gutter_settings.folds {
14264            em_width * 3.0
14265        } else if show_line_numbers {
14266            em_width
14267        } else {
14268            px(0.)
14269        };
14270
14271        GutterDimensions {
14272            left_padding,
14273            right_padding,
14274            width: line_gutter_width + left_padding + right_padding,
14275            margin: -descent,
14276            git_blame_entries_width,
14277        }
14278    }
14279
14280    pub fn render_crease_toggle(
14281        &self,
14282        buffer_row: MultiBufferRow,
14283        row_contains_cursor: bool,
14284        editor: View<Editor>,
14285        cx: &mut WindowContext,
14286    ) -> Option<AnyElement> {
14287        let folded = self.is_line_folded(buffer_row);
14288        let mut is_foldable = false;
14289
14290        if let Some(crease) = self
14291            .crease_snapshot
14292            .query_row(buffer_row, &self.buffer_snapshot)
14293        {
14294            is_foldable = true;
14295            match crease {
14296                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
14297                    if let Some(render_toggle) = render_toggle {
14298                        let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14299                            if folded {
14300                                editor.update(cx, |editor, cx| {
14301                                    editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14302                                });
14303                            } else {
14304                                editor.update(cx, |editor, cx| {
14305                                    editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14306                                });
14307                            }
14308                        });
14309                        return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
14310                    }
14311                }
14312            }
14313        }
14314
14315        is_foldable |= self.starts_indent(buffer_row);
14316
14317        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
14318            Some(
14319                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
14320                    .selected(folded)
14321                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14322                        if folded {
14323                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
14324                        } else {
14325                            this.fold_at(&FoldAt { buffer_row }, cx);
14326                        }
14327                    }))
14328                    .into_any_element(),
14329            )
14330        } else {
14331            None
14332        }
14333    }
14334
14335    pub fn render_crease_trailer(
14336        &self,
14337        buffer_row: MultiBufferRow,
14338        cx: &mut WindowContext,
14339    ) -> Option<AnyElement> {
14340        let folded = self.is_line_folded(buffer_row);
14341        if let Crease::Inline { render_trailer, .. } = self
14342            .crease_snapshot
14343            .query_row(buffer_row, &self.buffer_snapshot)?
14344        {
14345            let render_trailer = render_trailer.as_ref()?;
14346            Some(render_trailer(buffer_row, folded, cx))
14347        } else {
14348            None
14349        }
14350    }
14351}
14352
14353impl Deref for EditorSnapshot {
14354    type Target = DisplaySnapshot;
14355
14356    fn deref(&self) -> &Self::Target {
14357        &self.display_snapshot
14358    }
14359}
14360
14361#[derive(Clone, Debug, PartialEq, Eq)]
14362pub enum EditorEvent {
14363    InputIgnored {
14364        text: Arc<str>,
14365    },
14366    InputHandled {
14367        utf16_range_to_replace: Option<Range<isize>>,
14368        text: Arc<str>,
14369    },
14370    ExcerptsAdded {
14371        buffer: Model<Buffer>,
14372        predecessor: ExcerptId,
14373        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14374    },
14375    ExcerptsRemoved {
14376        ids: Vec<ExcerptId>,
14377    },
14378    ExcerptsEdited {
14379        ids: Vec<ExcerptId>,
14380    },
14381    ExcerptsExpanded {
14382        ids: Vec<ExcerptId>,
14383    },
14384    BufferEdited,
14385    Edited {
14386        transaction_id: clock::Lamport,
14387    },
14388    Reparsed(BufferId),
14389    Focused,
14390    FocusedIn,
14391    Blurred,
14392    DirtyChanged,
14393    Saved,
14394    TitleChanged,
14395    DiffBaseChanged,
14396    SelectionsChanged {
14397        local: bool,
14398    },
14399    ScrollPositionChanged {
14400        local: bool,
14401        autoscroll: bool,
14402    },
14403    Closed,
14404    TransactionUndone {
14405        transaction_id: clock::Lamport,
14406    },
14407    TransactionBegun {
14408        transaction_id: clock::Lamport,
14409    },
14410    Reloaded,
14411    CursorShapeChanged,
14412}
14413
14414impl EventEmitter<EditorEvent> for Editor {}
14415
14416impl FocusableView for Editor {
14417    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14418        self.focus_handle.clone()
14419    }
14420}
14421
14422impl Render for Editor {
14423    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14424        let settings = ThemeSettings::get_global(cx);
14425
14426        let mut text_style = match self.mode {
14427            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14428                color: cx.theme().colors().editor_foreground,
14429                font_family: settings.ui_font.family.clone(),
14430                font_features: settings.ui_font.features.clone(),
14431                font_fallbacks: settings.ui_font.fallbacks.clone(),
14432                font_size: rems(0.875).into(),
14433                font_weight: settings.ui_font.weight,
14434                line_height: relative(settings.buffer_line_height.value()),
14435                ..Default::default()
14436            },
14437            EditorMode::Full => TextStyle {
14438                color: cx.theme().colors().editor_foreground,
14439                font_family: settings.buffer_font.family.clone(),
14440                font_features: settings.buffer_font.features.clone(),
14441                font_fallbacks: settings.buffer_font.fallbacks.clone(),
14442                font_size: settings.buffer_font_size(cx).into(),
14443                font_weight: settings.buffer_font.weight,
14444                line_height: relative(settings.buffer_line_height.value()),
14445                ..Default::default()
14446            },
14447        };
14448        if let Some(text_style_refinement) = &self.text_style_refinement {
14449            text_style.refine(text_style_refinement)
14450        }
14451
14452        let background = match self.mode {
14453            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14454            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14455            EditorMode::Full => cx.theme().colors().editor_background,
14456        };
14457
14458        EditorElement::new(
14459            cx.view(),
14460            EditorStyle {
14461                background,
14462                local_player: cx.theme().players().local(),
14463                text: text_style,
14464                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14465                syntax: cx.theme().syntax().clone(),
14466                status: cx.theme().status().clone(),
14467                inlay_hints_style: make_inlay_hints_style(cx),
14468                suggestions_style: HighlightStyle {
14469                    color: Some(cx.theme().status().predictive),
14470                    ..HighlightStyle::default()
14471                },
14472                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14473            },
14474        )
14475    }
14476}
14477
14478impl ViewInputHandler for Editor {
14479    fn text_for_range(
14480        &mut self,
14481        range_utf16: Range<usize>,
14482        adjusted_range: &mut Option<Range<usize>>,
14483        cx: &mut ViewContext<Self>,
14484    ) -> Option<String> {
14485        let snapshot = self.buffer.read(cx).read(cx);
14486        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
14487        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
14488        if (start.0..end.0) != range_utf16 {
14489            adjusted_range.replace(start.0..end.0);
14490        }
14491        Some(snapshot.text_for_range(start..end).collect())
14492    }
14493
14494    fn selected_text_range(
14495        &mut self,
14496        ignore_disabled_input: bool,
14497        cx: &mut ViewContext<Self>,
14498    ) -> Option<UTF16Selection> {
14499        // Prevent the IME menu from appearing when holding down an alphabetic key
14500        // while input is disabled.
14501        if !ignore_disabled_input && !self.input_enabled {
14502            return None;
14503        }
14504
14505        let selection = self.selections.newest::<OffsetUtf16>(cx);
14506        let range = selection.range();
14507
14508        Some(UTF16Selection {
14509            range: range.start.0..range.end.0,
14510            reversed: selection.reversed,
14511        })
14512    }
14513
14514    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14515        let snapshot = self.buffer.read(cx).read(cx);
14516        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14517        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14518    }
14519
14520    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14521        self.clear_highlights::<InputComposition>(cx);
14522        self.ime_transaction.take();
14523    }
14524
14525    fn replace_text_in_range(
14526        &mut self,
14527        range_utf16: Option<Range<usize>>,
14528        text: &str,
14529        cx: &mut ViewContext<Self>,
14530    ) {
14531        if !self.input_enabled {
14532            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14533            return;
14534        }
14535
14536        self.transact(cx, |this, cx| {
14537            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14538                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14539                Some(this.selection_replacement_ranges(range_utf16, cx))
14540            } else {
14541                this.marked_text_ranges(cx)
14542            };
14543
14544            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14545                let newest_selection_id = this.selections.newest_anchor().id;
14546                this.selections
14547                    .all::<OffsetUtf16>(cx)
14548                    .iter()
14549                    .zip(ranges_to_replace.iter())
14550                    .find_map(|(selection, range)| {
14551                        if selection.id == newest_selection_id {
14552                            Some(
14553                                (range.start.0 as isize - selection.head().0 as isize)
14554                                    ..(range.end.0 as isize - selection.head().0 as isize),
14555                            )
14556                        } else {
14557                            None
14558                        }
14559                    })
14560            });
14561
14562            cx.emit(EditorEvent::InputHandled {
14563                utf16_range_to_replace: range_to_replace,
14564                text: text.into(),
14565            });
14566
14567            if let Some(new_selected_ranges) = new_selected_ranges {
14568                this.change_selections(None, cx, |selections| {
14569                    selections.select_ranges(new_selected_ranges)
14570                });
14571                this.backspace(&Default::default(), cx);
14572            }
14573
14574            this.handle_input(text, cx);
14575        });
14576
14577        if let Some(transaction) = self.ime_transaction {
14578            self.buffer.update(cx, |buffer, cx| {
14579                buffer.group_until_transaction(transaction, cx);
14580            });
14581        }
14582
14583        self.unmark_text(cx);
14584    }
14585
14586    fn replace_and_mark_text_in_range(
14587        &mut self,
14588        range_utf16: Option<Range<usize>>,
14589        text: &str,
14590        new_selected_range_utf16: Option<Range<usize>>,
14591        cx: &mut ViewContext<Self>,
14592    ) {
14593        if !self.input_enabled {
14594            return;
14595        }
14596
14597        let transaction = self.transact(cx, |this, cx| {
14598            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14599                let snapshot = this.buffer.read(cx).read(cx);
14600                if let Some(relative_range_utf16) = range_utf16.as_ref() {
14601                    for marked_range in &mut marked_ranges {
14602                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14603                        marked_range.start.0 += relative_range_utf16.start;
14604                        marked_range.start =
14605                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14606                        marked_range.end =
14607                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14608                    }
14609                }
14610                Some(marked_ranges)
14611            } else if let Some(range_utf16) = range_utf16 {
14612                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14613                Some(this.selection_replacement_ranges(range_utf16, cx))
14614            } else {
14615                None
14616            };
14617
14618            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14619                let newest_selection_id = this.selections.newest_anchor().id;
14620                this.selections
14621                    .all::<OffsetUtf16>(cx)
14622                    .iter()
14623                    .zip(ranges_to_replace.iter())
14624                    .find_map(|(selection, range)| {
14625                        if selection.id == newest_selection_id {
14626                            Some(
14627                                (range.start.0 as isize - selection.head().0 as isize)
14628                                    ..(range.end.0 as isize - selection.head().0 as isize),
14629                            )
14630                        } else {
14631                            None
14632                        }
14633                    })
14634            });
14635
14636            cx.emit(EditorEvent::InputHandled {
14637                utf16_range_to_replace: range_to_replace,
14638                text: text.into(),
14639            });
14640
14641            if let Some(ranges) = ranges_to_replace {
14642                this.change_selections(None, cx, |s| s.select_ranges(ranges));
14643            }
14644
14645            let marked_ranges = {
14646                let snapshot = this.buffer.read(cx).read(cx);
14647                this.selections
14648                    .disjoint_anchors()
14649                    .iter()
14650                    .map(|selection| {
14651                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14652                    })
14653                    .collect::<Vec<_>>()
14654            };
14655
14656            if text.is_empty() {
14657                this.unmark_text(cx);
14658            } else {
14659                this.highlight_text::<InputComposition>(
14660                    marked_ranges.clone(),
14661                    HighlightStyle {
14662                        underline: Some(UnderlineStyle {
14663                            thickness: px(1.),
14664                            color: None,
14665                            wavy: false,
14666                        }),
14667                        ..Default::default()
14668                    },
14669                    cx,
14670                );
14671            }
14672
14673            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14674            let use_autoclose = this.use_autoclose;
14675            let use_auto_surround = this.use_auto_surround;
14676            this.set_use_autoclose(false);
14677            this.set_use_auto_surround(false);
14678            this.handle_input(text, cx);
14679            this.set_use_autoclose(use_autoclose);
14680            this.set_use_auto_surround(use_auto_surround);
14681
14682            if let Some(new_selected_range) = new_selected_range_utf16 {
14683                let snapshot = this.buffer.read(cx).read(cx);
14684                let new_selected_ranges = marked_ranges
14685                    .into_iter()
14686                    .map(|marked_range| {
14687                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14688                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14689                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14690                        snapshot.clip_offset_utf16(new_start, Bias::Left)
14691                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14692                    })
14693                    .collect::<Vec<_>>();
14694
14695                drop(snapshot);
14696                this.change_selections(None, cx, |selections| {
14697                    selections.select_ranges(new_selected_ranges)
14698                });
14699            }
14700        });
14701
14702        self.ime_transaction = self.ime_transaction.or(transaction);
14703        if let Some(transaction) = self.ime_transaction {
14704            self.buffer.update(cx, |buffer, cx| {
14705                buffer.group_until_transaction(transaction, cx);
14706            });
14707        }
14708
14709        if self.text_highlights::<InputComposition>(cx).is_none() {
14710            self.ime_transaction.take();
14711        }
14712    }
14713
14714    fn bounds_for_range(
14715        &mut self,
14716        range_utf16: Range<usize>,
14717        element_bounds: gpui::Bounds<Pixels>,
14718        cx: &mut ViewContext<Self>,
14719    ) -> Option<gpui::Bounds<Pixels>> {
14720        let text_layout_details = self.text_layout_details(cx);
14721        let style = &text_layout_details.editor_style;
14722        let font_id = cx.text_system().resolve_font(&style.text.font());
14723        let font_size = style.text.font_size.to_pixels(cx.rem_size());
14724        let line_height = style.text.line_height_in_pixels(cx.rem_size());
14725
14726        let em_width = cx
14727            .text_system()
14728            .typographic_bounds(font_id, font_size, 'm')
14729            .unwrap()
14730            .size
14731            .width;
14732
14733        let snapshot = self.snapshot(cx);
14734        let scroll_position = snapshot.scroll_position();
14735        let scroll_left = scroll_position.x * em_width;
14736
14737        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14738        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14739            + self.gutter_dimensions.width
14740            + self.gutter_dimensions.margin;
14741        let y = line_height * (start.row().as_f32() - scroll_position.y);
14742
14743        Some(Bounds {
14744            origin: element_bounds.origin + point(x, y),
14745            size: size(em_width, line_height),
14746        })
14747    }
14748}
14749
14750trait SelectionExt {
14751    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14752    fn spanned_rows(
14753        &self,
14754        include_end_if_at_line_start: bool,
14755        map: &DisplaySnapshot,
14756    ) -> Range<MultiBufferRow>;
14757}
14758
14759impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14760    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14761        let start = self
14762            .start
14763            .to_point(&map.buffer_snapshot)
14764            .to_display_point(map);
14765        let end = self
14766            .end
14767            .to_point(&map.buffer_snapshot)
14768            .to_display_point(map);
14769        if self.reversed {
14770            end..start
14771        } else {
14772            start..end
14773        }
14774    }
14775
14776    fn spanned_rows(
14777        &self,
14778        include_end_if_at_line_start: bool,
14779        map: &DisplaySnapshot,
14780    ) -> Range<MultiBufferRow> {
14781        let start = self.start.to_point(&map.buffer_snapshot);
14782        let mut end = self.end.to_point(&map.buffer_snapshot);
14783        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14784            end.row -= 1;
14785        }
14786
14787        let buffer_start = map.prev_line_boundary(start).0;
14788        let buffer_end = map.next_line_boundary(end).0;
14789        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14790    }
14791}
14792
14793impl<T: InvalidationRegion> InvalidationStack<T> {
14794    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14795    where
14796        S: Clone + ToOffset,
14797    {
14798        while let Some(region) = self.last() {
14799            let all_selections_inside_invalidation_ranges =
14800                if selections.len() == region.ranges().len() {
14801                    selections
14802                        .iter()
14803                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14804                        .all(|(selection, invalidation_range)| {
14805                            let head = selection.head().to_offset(buffer);
14806                            invalidation_range.start <= head && invalidation_range.end >= head
14807                        })
14808                } else {
14809                    false
14810                };
14811
14812            if all_selections_inside_invalidation_ranges {
14813                break;
14814            } else {
14815                self.pop();
14816            }
14817        }
14818    }
14819}
14820
14821impl<T> Default for InvalidationStack<T> {
14822    fn default() -> Self {
14823        Self(Default::default())
14824    }
14825}
14826
14827impl<T> Deref for InvalidationStack<T> {
14828    type Target = Vec<T>;
14829
14830    fn deref(&self) -> &Self::Target {
14831        &self.0
14832    }
14833}
14834
14835impl<T> DerefMut for InvalidationStack<T> {
14836    fn deref_mut(&mut self) -> &mut Self::Target {
14837        &mut self.0
14838    }
14839}
14840
14841impl InvalidationRegion for SnippetState {
14842    fn ranges(&self) -> &[Range<Anchor>] {
14843        &self.ranges[self.active_index]
14844    }
14845}
14846
14847pub fn diagnostic_block_renderer(
14848    diagnostic: Diagnostic,
14849    max_message_rows: Option<u8>,
14850    allow_closing: bool,
14851    _is_valid: bool,
14852) -> RenderBlock {
14853    let (text_without_backticks, code_ranges) =
14854        highlight_diagnostic_message(&diagnostic, max_message_rows);
14855
14856    Arc::new(move |cx: &mut BlockContext| {
14857        let group_id: SharedString = cx.block_id.to_string().into();
14858
14859        let mut text_style = cx.text_style().clone();
14860        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14861        let theme_settings = ThemeSettings::get_global(cx);
14862        text_style.font_family = theme_settings.buffer_font.family.clone();
14863        text_style.font_style = theme_settings.buffer_font.style;
14864        text_style.font_features = theme_settings.buffer_font.features.clone();
14865        text_style.font_weight = theme_settings.buffer_font.weight;
14866
14867        let multi_line_diagnostic = diagnostic.message.contains('\n');
14868
14869        let buttons = |diagnostic: &Diagnostic| {
14870            if multi_line_diagnostic {
14871                v_flex()
14872            } else {
14873                h_flex()
14874            }
14875            .when(allow_closing, |div| {
14876                div.children(diagnostic.is_primary.then(|| {
14877                    IconButton::new("close-block", IconName::XCircle)
14878                        .icon_color(Color::Muted)
14879                        .size(ButtonSize::Compact)
14880                        .style(ButtonStyle::Transparent)
14881                        .visible_on_hover(group_id.clone())
14882                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14883                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14884                }))
14885            })
14886            .child(
14887                IconButton::new("copy-block", IconName::Copy)
14888                    .icon_color(Color::Muted)
14889                    .size(ButtonSize::Compact)
14890                    .style(ButtonStyle::Transparent)
14891                    .visible_on_hover(group_id.clone())
14892                    .on_click({
14893                        let message = diagnostic.message.clone();
14894                        move |_click, cx| {
14895                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14896                        }
14897                    })
14898                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14899            )
14900        };
14901
14902        let icon_size = buttons(&diagnostic)
14903            .into_any_element()
14904            .layout_as_root(AvailableSpace::min_size(), cx);
14905
14906        h_flex()
14907            .id(cx.block_id)
14908            .group(group_id.clone())
14909            .relative()
14910            .size_full()
14911            .block_mouse_down()
14912            .pl(cx.gutter_dimensions.width)
14913            .w(cx.max_width - cx.gutter_dimensions.full_width())
14914            .child(
14915                div()
14916                    .flex()
14917                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14918                    .flex_shrink(),
14919            )
14920            .child(buttons(&diagnostic))
14921            .child(div().flex().flex_shrink_0().child(
14922                StyledText::new(text_without_backticks.clone()).with_highlights(
14923                    &text_style,
14924                    code_ranges.iter().map(|range| {
14925                        (
14926                            range.clone(),
14927                            HighlightStyle {
14928                                font_weight: Some(FontWeight::BOLD),
14929                                ..Default::default()
14930                            },
14931                        )
14932                    }),
14933                ),
14934            ))
14935            .into_any_element()
14936    })
14937}
14938
14939pub fn highlight_diagnostic_message(
14940    diagnostic: &Diagnostic,
14941    mut max_message_rows: Option<u8>,
14942) -> (SharedString, Vec<Range<usize>>) {
14943    let mut text_without_backticks = String::new();
14944    let mut code_ranges = Vec::new();
14945
14946    if let Some(source) = &diagnostic.source {
14947        text_without_backticks.push_str(source);
14948        code_ranges.push(0..source.len());
14949        text_without_backticks.push_str(": ");
14950    }
14951
14952    let mut prev_offset = 0;
14953    let mut in_code_block = false;
14954    let has_row_limit = max_message_rows.is_some();
14955    let mut newline_indices = diagnostic
14956        .message
14957        .match_indices('\n')
14958        .filter(|_| has_row_limit)
14959        .map(|(ix, _)| ix)
14960        .fuse()
14961        .peekable();
14962
14963    for (quote_ix, _) in diagnostic
14964        .message
14965        .match_indices('`')
14966        .chain([(diagnostic.message.len(), "")])
14967    {
14968        let mut first_newline_ix = None;
14969        let mut last_newline_ix = None;
14970        while let Some(newline_ix) = newline_indices.peek() {
14971            if *newline_ix < quote_ix {
14972                if first_newline_ix.is_none() {
14973                    first_newline_ix = Some(*newline_ix);
14974                }
14975                last_newline_ix = Some(*newline_ix);
14976
14977                if let Some(rows_left) = &mut max_message_rows {
14978                    if *rows_left == 0 {
14979                        break;
14980                    } else {
14981                        *rows_left -= 1;
14982                    }
14983                }
14984                let _ = newline_indices.next();
14985            } else {
14986                break;
14987            }
14988        }
14989        let prev_len = text_without_backticks.len();
14990        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14991        text_without_backticks.push_str(new_text);
14992        if in_code_block {
14993            code_ranges.push(prev_len..text_without_backticks.len());
14994        }
14995        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14996        in_code_block = !in_code_block;
14997        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14998            text_without_backticks.push_str("...");
14999            break;
15000        }
15001    }
15002
15003    (text_without_backticks.into(), code_ranges)
15004}
15005
15006fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
15007    match severity {
15008        DiagnosticSeverity::ERROR => colors.error,
15009        DiagnosticSeverity::WARNING => colors.warning,
15010        DiagnosticSeverity::INFORMATION => colors.info,
15011        DiagnosticSeverity::HINT => colors.info,
15012        _ => colors.ignored,
15013    }
15014}
15015
15016pub fn styled_runs_for_code_label<'a>(
15017    label: &'a CodeLabel,
15018    syntax_theme: &'a theme::SyntaxTheme,
15019) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
15020    let fade_out = HighlightStyle {
15021        fade_out: Some(0.35),
15022        ..Default::default()
15023    };
15024
15025    let mut prev_end = label.filter_range.end;
15026    label
15027        .runs
15028        .iter()
15029        .enumerate()
15030        .flat_map(move |(ix, (range, highlight_id))| {
15031            let style = if let Some(style) = highlight_id.style(syntax_theme) {
15032                style
15033            } else {
15034                return Default::default();
15035            };
15036            let mut muted_style = style;
15037            muted_style.highlight(fade_out);
15038
15039            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
15040            if range.start >= label.filter_range.end {
15041                if range.start > prev_end {
15042                    runs.push((prev_end..range.start, fade_out));
15043                }
15044                runs.push((range.clone(), muted_style));
15045            } else if range.end <= label.filter_range.end {
15046                runs.push((range.clone(), style));
15047            } else {
15048                runs.push((range.start..label.filter_range.end, style));
15049                runs.push((label.filter_range.end..range.end, muted_style));
15050            }
15051            prev_end = cmp::max(prev_end, range.end);
15052
15053            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
15054                runs.push((prev_end..label.text.len(), fade_out));
15055            }
15056
15057            runs
15058        })
15059}
15060
15061pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
15062    let mut prev_index = 0;
15063    let mut prev_codepoint: Option<char> = None;
15064    text.char_indices()
15065        .chain([(text.len(), '\0')])
15066        .filter_map(move |(index, codepoint)| {
15067            let prev_codepoint = prev_codepoint.replace(codepoint)?;
15068            let is_boundary = index == text.len()
15069                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
15070                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
15071            if is_boundary {
15072                let chunk = &text[prev_index..index];
15073                prev_index = index;
15074                Some(chunk)
15075            } else {
15076                None
15077            }
15078        })
15079}
15080
15081pub trait RangeToAnchorExt: Sized {
15082    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
15083
15084    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
15085        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
15086        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
15087    }
15088}
15089
15090impl<T: ToOffset> RangeToAnchorExt for Range<T> {
15091    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
15092        let start_offset = self.start.to_offset(snapshot);
15093        let end_offset = self.end.to_offset(snapshot);
15094        if start_offset == end_offset {
15095            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
15096        } else {
15097            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
15098        }
15099    }
15100}
15101
15102pub trait RowExt {
15103    fn as_f32(&self) -> f32;
15104
15105    fn next_row(&self) -> Self;
15106
15107    fn previous_row(&self) -> Self;
15108
15109    fn minus(&self, other: Self) -> u32;
15110}
15111
15112impl RowExt for DisplayRow {
15113    fn as_f32(&self) -> f32 {
15114        self.0 as f32
15115    }
15116
15117    fn next_row(&self) -> Self {
15118        Self(self.0 + 1)
15119    }
15120
15121    fn previous_row(&self) -> Self {
15122        Self(self.0.saturating_sub(1))
15123    }
15124
15125    fn minus(&self, other: Self) -> u32 {
15126        self.0 - other.0
15127    }
15128}
15129
15130impl RowExt for MultiBufferRow {
15131    fn as_f32(&self) -> f32 {
15132        self.0 as f32
15133    }
15134
15135    fn next_row(&self) -> Self {
15136        Self(self.0 + 1)
15137    }
15138
15139    fn previous_row(&self) -> Self {
15140        Self(self.0.saturating_sub(1))
15141    }
15142
15143    fn minus(&self, other: Self) -> u32 {
15144        self.0 - other.0
15145    }
15146}
15147
15148trait RowRangeExt {
15149    type Row;
15150
15151    fn len(&self) -> usize;
15152
15153    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
15154}
15155
15156impl RowRangeExt for Range<MultiBufferRow> {
15157    type Row = MultiBufferRow;
15158
15159    fn len(&self) -> usize {
15160        (self.end.0 - self.start.0) as usize
15161    }
15162
15163    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
15164        (self.start.0..self.end.0).map(MultiBufferRow)
15165    }
15166}
15167
15168impl RowRangeExt for Range<DisplayRow> {
15169    type Row = DisplayRow;
15170
15171    fn len(&self) -> usize {
15172        (self.end.0 - self.start.0) as usize
15173    }
15174
15175    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
15176        (self.start.0..self.end.0).map(DisplayRow)
15177    }
15178}
15179
15180fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
15181    if hunk.diff_base_byte_range.is_empty() {
15182        DiffHunkStatus::Added
15183    } else if hunk.row_range.is_empty() {
15184        DiffHunkStatus::Removed
15185    } else {
15186        DiffHunkStatus::Modified
15187    }
15188}
15189
15190/// If select range has more than one line, we
15191/// just point the cursor to range.start.
15192fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
15193    if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
15194        range
15195    } else {
15196        range.start..range.start
15197    }
15198}
15199
15200pub struct KillRing(ClipboardItem);
15201impl Global for KillRing {}
15202
15203const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);