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, DiffMap, DiffMapSnapshot};
   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    git::project_diff::init(cx);
  331}
  332
  333pub struct SearchWithinRange;
  334
  335trait InvalidationRegion {
  336    fn ranges(&self) -> &[Range<Anchor>];
  337}
  338
  339#[derive(Clone, Debug, PartialEq)]
  340pub enum SelectPhase {
  341    Begin {
  342        position: DisplayPoint,
  343        add: bool,
  344        click_count: usize,
  345    },
  346    BeginColumnar {
  347        position: DisplayPoint,
  348        reset: bool,
  349        goal_column: u32,
  350    },
  351    Extend {
  352        position: DisplayPoint,
  353        click_count: usize,
  354    },
  355    Update {
  356        position: DisplayPoint,
  357        goal_column: u32,
  358        scroll_delta: gpui::Point<f32>,
  359    },
  360    End,
  361}
  362
  363#[derive(Clone, Debug)]
  364pub enum SelectMode {
  365    Character,
  366    Word(Range<Anchor>),
  367    Line(Range<Anchor>),
  368    All,
  369}
  370
  371#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  372pub enum EditorMode {
  373    SingleLine { auto_width: bool },
  374    AutoHeight { max_lines: usize },
  375    Full,
  376}
  377
  378#[derive(Copy, Clone, Debug)]
  379pub enum SoftWrap {
  380    /// Prefer not to wrap at all.
  381    ///
  382    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  383    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  384    GitDiff,
  385    /// Prefer a single line generally, unless an overly long line is encountered.
  386    None,
  387    /// Soft wrap lines that exceed the editor width.
  388    EditorWidth,
  389    /// Soft wrap lines at the preferred line length.
  390    Column(u32),
  391    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  392    Bounded(u32),
  393}
  394
  395#[derive(Clone)]
  396pub struct EditorStyle {
  397    pub background: Hsla,
  398    pub local_player: PlayerColor,
  399    pub text: TextStyle,
  400    pub scrollbar_width: Pixels,
  401    pub syntax: Arc<SyntaxTheme>,
  402    pub status: StatusColors,
  403    pub inlay_hints_style: HighlightStyle,
  404    pub suggestions_style: HighlightStyle,
  405    pub unnecessary_code_fade: f32,
  406}
  407
  408impl Default for EditorStyle {
  409    fn default() -> Self {
  410        Self {
  411            background: Hsla::default(),
  412            local_player: PlayerColor::default(),
  413            text: TextStyle::default(),
  414            scrollbar_width: Pixels::default(),
  415            syntax: Default::default(),
  416            // HACK: Status colors don't have a real default.
  417            // We should look into removing the status colors from the editor
  418            // style and retrieve them directly from the theme.
  419            status: StatusColors::dark(),
  420            inlay_hints_style: HighlightStyle::default(),
  421            suggestions_style: HighlightStyle::default(),
  422            unnecessary_code_fade: Default::default(),
  423        }
  424    }
  425}
  426
  427pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
  428    let show_background = language_settings::language_settings(None, None, cx)
  429        .inlay_hints
  430        .show_background;
  431
  432    HighlightStyle {
  433        color: Some(cx.theme().status().hint),
  434        background_color: show_background.then(|| cx.theme().status().hint_background),
  435        ..HighlightStyle::default()
  436    }
  437}
  438
  439type CompletionId = usize;
  440
  441#[derive(Clone, Debug)]
  442struct CompletionState {
  443    // render_inlay_ids represents the inlay hints that are inserted
  444    // for rendering the inline completions. They may be discontinuous
  445    // in the event that the completion provider returns some intersection
  446    // with the existing content.
  447    render_inlay_ids: Vec<InlayId>,
  448    // text is the resulting rope that is inserted when the user accepts a completion.
  449    text: Rope,
  450    // position is the position of the cursor when the completion was triggered.
  451    position: multi_buffer::Anchor,
  452    // delete_range is the range of text that this completion state covers.
  453    // if the completion is accepted, this range should be deleted.
  454    delete_range: Option<Range<multi_buffer::Anchor>>,
  455}
  456
  457#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  458struct EditorActionId(usize);
  459
  460impl EditorActionId {
  461    pub fn post_inc(&mut self) -> Self {
  462        let answer = self.0;
  463
  464        *self = Self(answer + 1);
  465
  466        Self(answer)
  467    }
  468}
  469
  470// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  471// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  472
  473type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  474type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
  475
  476#[derive(Default)]
  477struct ScrollbarMarkerState {
  478    scrollbar_size: Size<Pixels>,
  479    dirty: bool,
  480    markers: Arc<[PaintQuad]>,
  481    pending_refresh: Option<Task<Result<()>>>,
  482}
  483
  484impl ScrollbarMarkerState {
  485    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  486        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  487    }
  488}
  489
  490#[derive(Clone, Debug)]
  491struct RunnableTasks {
  492    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  493    offset: MultiBufferOffset,
  494    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  495    column: u32,
  496    // Values of all named captures, including those starting with '_'
  497    extra_variables: HashMap<String, String>,
  498    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  499    context_range: Range<BufferOffset>,
  500}
  501
  502impl RunnableTasks {
  503    fn resolve<'a>(
  504        &'a self,
  505        cx: &'a task::TaskContext,
  506    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  507        self.templates.iter().filter_map(|(kind, template)| {
  508            template
  509                .resolve_task(&kind.to_id_base(), cx)
  510                .map(|task| (kind.clone(), task))
  511        })
  512    }
  513}
  514
  515#[derive(Clone)]
  516struct ResolvedTasks {
  517    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  518    position: Anchor,
  519}
  520#[derive(Copy, Clone, Debug)]
  521struct MultiBufferOffset(usize);
  522#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  523struct BufferOffset(usize);
  524
  525// Addons allow storing per-editor state in other crates (e.g. Vim)
  526pub trait Addon: 'static {
  527    fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
  528
  529    fn to_any(&self) -> &dyn std::any::Any;
  530}
  531
  532#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  533pub enum IsVimMode {
  534    Yes,
  535    No,
  536}
  537
  538/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
  539///
  540/// See the [module level documentation](self) for more information.
  541pub struct Editor {
  542    focus_handle: FocusHandle,
  543    last_focused_descendant: Option<WeakFocusHandle>,
  544    /// The text buffer being edited
  545    buffer: Model<MultiBuffer>,
  546    /// Map of how text in the buffer should be displayed.
  547    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  548    pub display_map: Model<DisplayMap>,
  549    pub selections: SelectionsCollection,
  550    pub scroll_manager: ScrollManager,
  551    /// When inline assist editors are linked, they all render cursors because
  552    /// typing enters text into each of them, even the ones that aren't focused.
  553    pub(crate) show_cursor_when_unfocused: bool,
  554    columnar_selection_tail: Option<Anchor>,
  555    add_selections_state: Option<AddSelectionsState>,
  556    select_next_state: Option<SelectNextState>,
  557    select_prev_state: Option<SelectNextState>,
  558    selection_history: SelectionHistory,
  559    autoclose_regions: Vec<AutocloseRegion>,
  560    snippet_stack: InvalidationStack<SnippetState>,
  561    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  562    ime_transaction: Option<TransactionId>,
  563    active_diagnostics: Option<ActiveDiagnosticGroup>,
  564    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  565
  566    project: Option<Model<Project>>,
  567    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  568    completion_provider: Option<Box<dyn CompletionProvider>>,
  569    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  570    blink_manager: Model<BlinkManager>,
  571    show_cursor_names: bool,
  572    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  573    pub show_local_selections: bool,
  574    mode: EditorMode,
  575    show_breadcrumbs: bool,
  576    show_gutter: bool,
  577    show_line_numbers: Option<bool>,
  578    use_relative_line_numbers: Option<bool>,
  579    show_git_diff_gutter: Option<bool>,
  580    show_code_actions: Option<bool>,
  581    show_runnables: Option<bool>,
  582    show_wrap_guides: Option<bool>,
  583    show_indent_guides: Option<bool>,
  584    placeholder_text: Option<Arc<str>>,
  585    highlight_order: usize,
  586    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  587    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  588    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  589    scrollbar_marker_state: ScrollbarMarkerState,
  590    active_indent_guides_state: ActiveIndentGuidesState,
  591    nav_history: Option<ItemNavHistory>,
  592    context_menu: RwLock<Option<ContextMenu>>,
  593    mouse_context_menu: Option<MouseContextMenu>,
  594    hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
  595    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  596    signature_help_state: SignatureHelpState,
  597    auto_signature_help: Option<bool>,
  598    find_all_references_task_sources: Vec<Anchor>,
  599    next_completion_id: CompletionId,
  600    available_code_actions: Option<(Location, Arc<[AvailableCodeAction]>)>,
  601    code_actions_task: Option<Task<Result<()>>>,
  602    document_highlights_task: Option<Task<()>>,
  603    linked_editing_range_task: Option<Task<Option<()>>>,
  604    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  605    pending_rename: Option<RenameState>,
  606    searchable: bool,
  607    cursor_shape: CursorShape,
  608    current_line_highlight: Option<CurrentLineHighlight>,
  609    collapse_matches: bool,
  610    autoindent_mode: Option<AutoindentMode>,
  611    workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
  612    input_enabled: bool,
  613    use_modal_editing: bool,
  614    read_only: bool,
  615    leader_peer_id: Option<PeerId>,
  616    remote_id: Option<ViewId>,
  617    hover_state: HoverState,
  618    gutter_hovered: bool,
  619    hovered_link_state: Option<HoveredLinkState>,
  620    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  621    code_action_providers: Vec<Arc<dyn CodeActionProvider>>,
  622    active_inline_completion: Option<CompletionState>,
  623    // enable_inline_completions is a switch that Vim can use to disable
  624    // inline completions based on its mode.
  625    enable_inline_completions: bool,
  626    show_inline_completions_override: Option<bool>,
  627    inlay_hint_cache: InlayHintCache,
  628    diff_map: DiffMap,
  629    next_inlay_id: usize,
  630    _subscriptions: Vec<Subscription>,
  631    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  632    gutter_dimensions: GutterDimensions,
  633    style: Option<EditorStyle>,
  634    text_style_refinement: Option<TextStyleRefinement>,
  635    next_editor_action_id: EditorActionId,
  636    editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
  637    use_autoclose: bool,
  638    use_auto_surround: bool,
  639    auto_replace_emoji_shortcode: bool,
  640    show_git_blame_gutter: bool,
  641    show_git_blame_inline: bool,
  642    show_git_blame_inline_delay_task: Option<Task<()>>,
  643    git_blame_inline_enabled: bool,
  644    serialize_dirty_buffers: bool,
  645    show_selection_menu: Option<bool>,
  646    blame: Option<Model<GitBlame>>,
  647    blame_subscription: Option<Subscription>,
  648    custom_context_menu: Option<
  649        Box<
  650            dyn 'static
  651                + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
  652        >,
  653    >,
  654    last_bounds: Option<Bounds<Pixels>>,
  655    expect_bounds_change: Option<Bounds<Pixels>>,
  656    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  657    tasks_update_task: Option<Task<()>>,
  658    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  659    breadcrumb_header: Option<String>,
  660    focused_block: Option<FocusedBlock>,
  661    next_scroll_position: NextScrollCursorCenterTopBottom,
  662    addons: HashMap<TypeId, Box<dyn Addon>>,
  663    _scroll_cursor_center_top_bottom_task: Task<()>,
  664}
  665
  666#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  667enum NextScrollCursorCenterTopBottom {
  668    #[default]
  669    Center,
  670    Top,
  671    Bottom,
  672}
  673
  674impl NextScrollCursorCenterTopBottom {
  675    fn next(&self) -> Self {
  676        match self {
  677            Self::Center => Self::Top,
  678            Self::Top => Self::Bottom,
  679            Self::Bottom => Self::Center,
  680        }
  681    }
  682}
  683
  684#[derive(Clone)]
  685pub struct EditorSnapshot {
  686    pub mode: EditorMode,
  687    show_gutter: bool,
  688    show_line_numbers: Option<bool>,
  689    show_git_diff_gutter: Option<bool>,
  690    show_code_actions: Option<bool>,
  691    show_runnables: Option<bool>,
  692    git_blame_gutter_max_author_length: Option<usize>,
  693    pub display_snapshot: DisplaySnapshot,
  694    pub placeholder_text: Option<Arc<str>>,
  695    diff_map: DiffMapSnapshot,
  696    is_focused: bool,
  697    scroll_anchor: ScrollAnchor,
  698    ongoing_scroll: OngoingScroll,
  699    current_line_highlight: CurrentLineHighlight,
  700    gutter_hovered: bool,
  701}
  702
  703const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  704
  705#[derive(Default, Debug, Clone, Copy)]
  706pub struct GutterDimensions {
  707    pub left_padding: Pixels,
  708    pub right_padding: Pixels,
  709    pub width: Pixels,
  710    pub margin: Pixels,
  711    pub git_blame_entries_width: Option<Pixels>,
  712}
  713
  714impl GutterDimensions {
  715    /// The full width of the space taken up by the gutter.
  716    pub fn full_width(&self) -> Pixels {
  717        self.margin + self.width
  718    }
  719
  720    /// The width of the space reserved for the fold indicators,
  721    /// use alongside 'justify_end' and `gutter_width` to
  722    /// right align content with the line numbers
  723    pub fn fold_area_width(&self) -> Pixels {
  724        self.margin + self.right_padding
  725    }
  726}
  727
  728#[derive(Debug)]
  729pub struct RemoteSelection {
  730    pub replica_id: ReplicaId,
  731    pub selection: Selection<Anchor>,
  732    pub cursor_shape: CursorShape,
  733    pub peer_id: PeerId,
  734    pub line_mode: bool,
  735    pub participant_index: Option<ParticipantIndex>,
  736    pub user_name: Option<SharedString>,
  737}
  738
  739#[derive(Clone, Debug)]
  740struct SelectionHistoryEntry {
  741    selections: Arc<[Selection<Anchor>]>,
  742    select_next_state: Option<SelectNextState>,
  743    select_prev_state: Option<SelectNextState>,
  744    add_selections_state: Option<AddSelectionsState>,
  745}
  746
  747enum SelectionHistoryMode {
  748    Normal,
  749    Undoing,
  750    Redoing,
  751}
  752
  753#[derive(Clone, PartialEq, Eq, Hash)]
  754struct HoveredCursor {
  755    replica_id: u16,
  756    selection_id: usize,
  757}
  758
  759impl Default for SelectionHistoryMode {
  760    fn default() -> Self {
  761        Self::Normal
  762    }
  763}
  764
  765#[derive(Default)]
  766struct SelectionHistory {
  767    #[allow(clippy::type_complexity)]
  768    selections_by_transaction:
  769        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  770    mode: SelectionHistoryMode,
  771    undo_stack: VecDeque<SelectionHistoryEntry>,
  772    redo_stack: VecDeque<SelectionHistoryEntry>,
  773}
  774
  775impl SelectionHistory {
  776    fn insert_transaction(
  777        &mut self,
  778        transaction_id: TransactionId,
  779        selections: Arc<[Selection<Anchor>]>,
  780    ) {
  781        self.selections_by_transaction
  782            .insert(transaction_id, (selections, None));
  783    }
  784
  785    #[allow(clippy::type_complexity)]
  786    fn transaction(
  787        &self,
  788        transaction_id: TransactionId,
  789    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  790        self.selections_by_transaction.get(&transaction_id)
  791    }
  792
  793    #[allow(clippy::type_complexity)]
  794    fn transaction_mut(
  795        &mut self,
  796        transaction_id: TransactionId,
  797    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  798        self.selections_by_transaction.get_mut(&transaction_id)
  799    }
  800
  801    fn push(&mut self, entry: SelectionHistoryEntry) {
  802        if !entry.selections.is_empty() {
  803            match self.mode {
  804                SelectionHistoryMode::Normal => {
  805                    self.push_undo(entry);
  806                    self.redo_stack.clear();
  807                }
  808                SelectionHistoryMode::Undoing => self.push_redo(entry),
  809                SelectionHistoryMode::Redoing => self.push_undo(entry),
  810            }
  811        }
  812    }
  813
  814    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  815        if self
  816            .undo_stack
  817            .back()
  818            .map_or(true, |e| e.selections != entry.selections)
  819        {
  820            self.undo_stack.push_back(entry);
  821            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  822                self.undo_stack.pop_front();
  823            }
  824        }
  825    }
  826
  827    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  828        if self
  829            .redo_stack
  830            .back()
  831            .map_or(true, |e| e.selections != entry.selections)
  832        {
  833            self.redo_stack.push_back(entry);
  834            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  835                self.redo_stack.pop_front();
  836            }
  837        }
  838    }
  839}
  840
  841struct RowHighlight {
  842    index: usize,
  843    range: Range<Anchor>,
  844    color: Hsla,
  845    should_autoscroll: bool,
  846}
  847
  848#[derive(Clone, Debug)]
  849struct AddSelectionsState {
  850    above: bool,
  851    stack: Vec<usize>,
  852}
  853
  854#[derive(Clone)]
  855struct SelectNextState {
  856    query: AhoCorasick,
  857    wordwise: bool,
  858    done: bool,
  859}
  860
  861impl std::fmt::Debug for SelectNextState {
  862    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  863        f.debug_struct(std::any::type_name::<Self>())
  864            .field("wordwise", &self.wordwise)
  865            .field("done", &self.done)
  866            .finish()
  867    }
  868}
  869
  870#[derive(Debug)]
  871struct AutocloseRegion {
  872    selection_id: usize,
  873    range: Range<Anchor>,
  874    pair: BracketPair,
  875}
  876
  877#[derive(Debug)]
  878struct SnippetState {
  879    ranges: Vec<Vec<Range<Anchor>>>,
  880    active_index: usize,
  881    choices: Vec<Option<Vec<String>>>,
  882}
  883
  884#[doc(hidden)]
  885pub struct RenameState {
  886    pub range: Range<Anchor>,
  887    pub old_name: Arc<str>,
  888    pub editor: View<Editor>,
  889    block_id: CustomBlockId,
  890}
  891
  892struct InvalidationStack<T>(Vec<T>);
  893
  894struct RegisteredInlineCompletionProvider {
  895    provider: Arc<dyn InlineCompletionProviderHandle>,
  896    _subscription: Subscription,
  897}
  898
  899enum ContextMenu {
  900    Completions(CompletionsMenu),
  901    CodeActions(CodeActionsMenu),
  902}
  903
  904impl ContextMenu {
  905    fn select_first(
  906        &mut self,
  907        provider: Option<&dyn CompletionProvider>,
  908        cx: &mut ViewContext<Editor>,
  909    ) -> bool {
  910        if self.visible() {
  911            match self {
  912                ContextMenu::Completions(menu) => menu.select_first(provider, cx),
  913                ContextMenu::CodeActions(menu) => menu.select_first(cx),
  914            }
  915            true
  916        } else {
  917            false
  918        }
  919    }
  920
  921    fn select_prev(
  922        &mut self,
  923        provider: Option<&dyn CompletionProvider>,
  924        cx: &mut ViewContext<Editor>,
  925    ) -> bool {
  926        if self.visible() {
  927            match self {
  928                ContextMenu::Completions(menu) => menu.select_prev(provider, cx),
  929                ContextMenu::CodeActions(menu) => menu.select_prev(cx),
  930            }
  931            true
  932        } else {
  933            false
  934        }
  935    }
  936
  937    fn select_next(
  938        &mut self,
  939        provider: Option<&dyn CompletionProvider>,
  940        cx: &mut ViewContext<Editor>,
  941    ) -> bool {
  942        if self.visible() {
  943            match self {
  944                ContextMenu::Completions(menu) => menu.select_next(provider, cx),
  945                ContextMenu::CodeActions(menu) => menu.select_next(cx),
  946            }
  947            true
  948        } else {
  949            false
  950        }
  951    }
  952
  953    fn select_last(
  954        &mut self,
  955        provider: Option<&dyn CompletionProvider>,
  956        cx: &mut ViewContext<Editor>,
  957    ) -> bool {
  958        if self.visible() {
  959            match self {
  960                ContextMenu::Completions(menu) => menu.select_last(provider, cx),
  961                ContextMenu::CodeActions(menu) => menu.select_last(cx),
  962            }
  963            true
  964        } else {
  965            false
  966        }
  967    }
  968
  969    fn visible(&self) -> bool {
  970        match self {
  971            ContextMenu::Completions(menu) => menu.visible(),
  972            ContextMenu::CodeActions(menu) => menu.visible(),
  973        }
  974    }
  975
  976    fn render(
  977        &self,
  978        cursor_position: DisplayPoint,
  979        style: &EditorStyle,
  980        max_height: Pixels,
  981        workspace: Option<WeakView<Workspace>>,
  982        cx: &mut ViewContext<Editor>,
  983    ) -> (ContextMenuOrigin, AnyElement) {
  984        match self {
  985            ContextMenu::Completions(menu) => (
  986                ContextMenuOrigin::EditorPoint(cursor_position),
  987                menu.render(style, max_height, workspace, cx),
  988            ),
  989            ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
  990        }
  991    }
  992}
  993
  994enum ContextMenuOrigin {
  995    EditorPoint(DisplayPoint),
  996    GutterIndicator(DisplayRow),
  997}
  998
  999#[derive(Clone, Debug)]
 1000struct CompletionsMenu {
 1001    id: CompletionId,
 1002    sort_completions: bool,
 1003    initial_position: Anchor,
 1004    buffer: Model<Buffer>,
 1005    completions: Arc<RwLock<Box<[Completion]>>>,
 1006    match_candidates: Arc<[StringMatchCandidate]>,
 1007    matches: Arc<[StringMatch]>,
 1008    selected_item: usize,
 1009    scroll_handle: UniformListScrollHandle,
 1010    selected_completion_resolve_debounce: Option<Arc<Mutex<DebouncedDelay>>>,
 1011}
 1012
 1013impl CompletionsMenu {
 1014    fn new(
 1015        id: CompletionId,
 1016        sort_completions: bool,
 1017        initial_position: Anchor,
 1018        buffer: Model<Buffer>,
 1019        completions: Box<[Completion]>,
 1020    ) -> Self {
 1021        let match_candidates = completions
 1022            .iter()
 1023            .enumerate()
 1024            .map(|(id, completion)| {
 1025                StringMatchCandidate::new(
 1026                    id,
 1027                    completion.label.text[completion.label.filter_range.clone()].into(),
 1028                )
 1029            })
 1030            .collect();
 1031
 1032        Self {
 1033            id,
 1034            sort_completions,
 1035            initial_position,
 1036            buffer,
 1037            completions: Arc::new(RwLock::new(completions)),
 1038            match_candidates,
 1039            matches: Vec::new().into(),
 1040            selected_item: 0,
 1041            scroll_handle: UniformListScrollHandle::new(),
 1042            selected_completion_resolve_debounce: Some(Arc::new(Mutex::new(DebouncedDelay::new()))),
 1043        }
 1044    }
 1045
 1046    fn new_snippet_choices(
 1047        id: CompletionId,
 1048        sort_completions: bool,
 1049        choices: &Vec<String>,
 1050        selection: Range<Anchor>,
 1051        buffer: Model<Buffer>,
 1052    ) -> Self {
 1053        let completions = choices
 1054            .iter()
 1055            .map(|choice| Completion {
 1056                old_range: selection.start.text_anchor..selection.end.text_anchor,
 1057                new_text: choice.to_string(),
 1058                label: CodeLabel {
 1059                    text: choice.to_string(),
 1060                    runs: Default::default(),
 1061                    filter_range: Default::default(),
 1062                },
 1063                server_id: LanguageServerId(usize::MAX),
 1064                documentation: None,
 1065                lsp_completion: Default::default(),
 1066                confirm: None,
 1067            })
 1068            .collect();
 1069
 1070        let match_candidates = choices
 1071            .iter()
 1072            .enumerate()
 1073            .map(|(id, completion)| StringMatchCandidate::new(id, completion.to_string()))
 1074            .collect();
 1075        let matches = choices
 1076            .iter()
 1077            .enumerate()
 1078            .map(|(id, completion)| StringMatch {
 1079                candidate_id: id,
 1080                score: 1.,
 1081                positions: vec![],
 1082                string: completion.clone(),
 1083            })
 1084            .collect();
 1085        Self {
 1086            id,
 1087            sort_completions,
 1088            initial_position: selection.start,
 1089            buffer,
 1090            completions: Arc::new(RwLock::new(completions)),
 1091            match_candidates,
 1092            matches,
 1093            selected_item: 0,
 1094            scroll_handle: UniformListScrollHandle::new(),
 1095            selected_completion_resolve_debounce: Some(Arc::new(Mutex::new(DebouncedDelay::new()))),
 1096        }
 1097    }
 1098
 1099    fn suppress_documentation_resolution(mut self) -> Self {
 1100        self.selected_completion_resolve_debounce.take();
 1101        self
 1102    }
 1103
 1104    fn select_first(
 1105        &mut self,
 1106        provider: Option<&dyn CompletionProvider>,
 1107        cx: &mut ViewContext<Editor>,
 1108    ) {
 1109        self.selected_item = 0;
 1110        self.scroll_handle
 1111            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1112        self.resolve_selected_completion(provider, cx);
 1113        cx.notify();
 1114    }
 1115
 1116    fn select_prev(
 1117        &mut self,
 1118        provider: Option<&dyn CompletionProvider>,
 1119        cx: &mut ViewContext<Editor>,
 1120    ) {
 1121        if self.selected_item > 0 {
 1122            self.selected_item -= 1;
 1123        } else {
 1124            self.selected_item = self.matches.len() - 1;
 1125        }
 1126        self.scroll_handle
 1127            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1128        self.resolve_selected_completion(provider, cx);
 1129        cx.notify();
 1130    }
 1131
 1132    fn select_next(
 1133        &mut self,
 1134        provider: Option<&dyn CompletionProvider>,
 1135        cx: &mut ViewContext<Editor>,
 1136    ) {
 1137        if self.selected_item + 1 < self.matches.len() {
 1138            self.selected_item += 1;
 1139        } else {
 1140            self.selected_item = 0;
 1141        }
 1142        self.scroll_handle
 1143            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1144        self.resolve_selected_completion(provider, cx);
 1145        cx.notify();
 1146    }
 1147
 1148    fn select_last(
 1149        &mut self,
 1150        provider: Option<&dyn CompletionProvider>,
 1151        cx: &mut ViewContext<Editor>,
 1152    ) {
 1153        self.selected_item = self.matches.len() - 1;
 1154        self.scroll_handle
 1155            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1156        self.resolve_selected_completion(provider, cx);
 1157        cx.notify();
 1158    }
 1159
 1160    fn resolve_selected_completion(
 1161        &mut self,
 1162        provider: Option<&dyn CompletionProvider>,
 1163        cx: &mut ViewContext<Editor>,
 1164    ) {
 1165        let completion_index = self.matches[self.selected_item].candidate_id;
 1166        let Some(provider) = provider else {
 1167            return;
 1168        };
 1169        let Some(completion_resolve) = self.selected_completion_resolve_debounce.as_ref() else {
 1170            return;
 1171        };
 1172
 1173        let resolve_task = provider.resolve_completions(
 1174            self.buffer.clone(),
 1175            vec![completion_index],
 1176            self.completions.clone(),
 1177            cx,
 1178        );
 1179
 1180        let delay_ms =
 1181            EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
 1182        let delay = Duration::from_millis(delay_ms);
 1183
 1184        completion_resolve.lock().fire_new(delay, cx, |_, cx| {
 1185            cx.spawn(move |editor, mut cx| async move {
 1186                if let Some(true) = resolve_task.await.log_err() {
 1187                    editor.update(&mut cx, |_, cx| cx.notify()).ok();
 1188                }
 1189            })
 1190        });
 1191    }
 1192
 1193    fn visible(&self) -> bool {
 1194        !self.matches.is_empty()
 1195    }
 1196
 1197    fn render(
 1198        &self,
 1199        style: &EditorStyle,
 1200        max_height: Pixels,
 1201        workspace: Option<WeakView<Workspace>>,
 1202        cx: &mut ViewContext<Editor>,
 1203    ) -> AnyElement {
 1204        let settings = EditorSettings::get_global(cx);
 1205        let show_completion_documentation = settings.show_completion_documentation;
 1206
 1207        let widest_completion_ix = self
 1208            .matches
 1209            .iter()
 1210            .enumerate()
 1211            .max_by_key(|(_, mat)| {
 1212                let completions = self.completions.read();
 1213                let completion = &completions[mat.candidate_id];
 1214                let documentation = &completion.documentation;
 1215
 1216                let mut len = completion.label.text.chars().count();
 1217                if let Some(Documentation::SingleLine(text)) = documentation {
 1218                    if show_completion_documentation {
 1219                        len += text.chars().count();
 1220                    }
 1221                }
 1222
 1223                len
 1224            })
 1225            .map(|(ix, _)| ix);
 1226
 1227        let completions = self.completions.clone();
 1228        let matches = self.matches.clone();
 1229        let selected_item = self.selected_item;
 1230        let style = style.clone();
 1231
 1232        let multiline_docs = if show_completion_documentation {
 1233            let mat = &self.matches[selected_item];
 1234            let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
 1235                Some(Documentation::MultiLinePlainText(text)) => {
 1236                    Some(div().child(SharedString::from(text.clone())))
 1237                }
 1238                Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
 1239                    Some(div().child(render_parsed_markdown(
 1240                        "completions_markdown",
 1241                        parsed,
 1242                        &style,
 1243                        workspace,
 1244                        cx,
 1245                    )))
 1246                }
 1247                _ => None,
 1248            };
 1249            multiline_docs.map(|div| {
 1250                div.id("multiline_docs")
 1251                    .max_h(max_height)
 1252                    .flex_1()
 1253                    .px_1p5()
 1254                    .py_1()
 1255                    .min_w(px(260.))
 1256                    .max_w(px(640.))
 1257                    .w(px(500.))
 1258                    .overflow_y_scroll()
 1259                    .occlude()
 1260            })
 1261        } else {
 1262            None
 1263        };
 1264
 1265        let list = uniform_list(
 1266            cx.view().clone(),
 1267            "completions",
 1268            matches.len(),
 1269            move |_editor, range, cx| {
 1270                let start_ix = range.start;
 1271                let completions_guard = completions.read();
 1272
 1273                matches[range]
 1274                    .iter()
 1275                    .enumerate()
 1276                    .map(|(ix, mat)| {
 1277                        let item_ix = start_ix + ix;
 1278                        let candidate_id = mat.candidate_id;
 1279                        let completion = &completions_guard[candidate_id];
 1280
 1281                        let documentation = if show_completion_documentation {
 1282                            &completion.documentation
 1283                        } else {
 1284                            &None
 1285                        };
 1286
 1287                        let highlights = gpui::combine_highlights(
 1288                            mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
 1289                            styled_runs_for_code_label(&completion.label, &style.syntax).map(
 1290                                |(range, mut highlight)| {
 1291                                    // Ignore font weight for syntax highlighting, as we'll use it
 1292                                    // for fuzzy matches.
 1293                                    highlight.font_weight = None;
 1294
 1295                                    if completion.lsp_completion.deprecated.unwrap_or(false) {
 1296                                        highlight.strikethrough = Some(StrikethroughStyle {
 1297                                            thickness: 1.0.into(),
 1298                                            ..Default::default()
 1299                                        });
 1300                                        highlight.color = Some(cx.theme().colors().text_muted);
 1301                                    }
 1302
 1303                                    (range, highlight)
 1304                                },
 1305                            ),
 1306                        );
 1307                        let completion_label = StyledText::new(completion.label.text.clone())
 1308                            .with_highlights(&style.text, highlights);
 1309                        let documentation_label =
 1310                            if let Some(Documentation::SingleLine(text)) = documentation {
 1311                                if text.trim().is_empty() {
 1312                                    None
 1313                                } else {
 1314                                    Some(
 1315                                        Label::new(text.clone())
 1316                                            .ml_4()
 1317                                            .size(LabelSize::Small)
 1318                                            .color(Color::Muted),
 1319                                    )
 1320                                }
 1321                            } else {
 1322                                None
 1323                            };
 1324
 1325                        let color_swatch = completion
 1326                            .color()
 1327                            .map(|color| div().size_4().bg(color).rounded_sm());
 1328
 1329                        div().min_w(px(220.)).max_w(px(540.)).child(
 1330                            ListItem::new(mat.candidate_id)
 1331                                .inset(true)
 1332                                .selected(item_ix == selected_item)
 1333                                .on_click(cx.listener(move |editor, _event, cx| {
 1334                                    cx.stop_propagation();
 1335                                    if let Some(task) = editor.confirm_completion(
 1336                                        &ConfirmCompletion {
 1337                                            item_ix: Some(item_ix),
 1338                                        },
 1339                                        cx,
 1340                                    ) {
 1341                                        task.detach_and_log_err(cx)
 1342                                    }
 1343                                }))
 1344                                .start_slot::<Div>(color_swatch)
 1345                                .child(h_flex().overflow_hidden().child(completion_label))
 1346                                .end_slot::<Label>(documentation_label),
 1347                        )
 1348                    })
 1349                    .collect()
 1350            },
 1351        )
 1352        .occlude()
 1353        .max_h(max_height)
 1354        .track_scroll(self.scroll_handle.clone())
 1355        .with_width_from_item(widest_completion_ix)
 1356        .with_sizing_behavior(ListSizingBehavior::Infer);
 1357
 1358        Popover::new()
 1359            .child(list)
 1360            .when_some(multiline_docs, |popover, multiline_docs| {
 1361                popover.aside(multiline_docs)
 1362            })
 1363            .into_any_element()
 1364    }
 1365
 1366    pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
 1367        let mut matches = if let Some(query) = query {
 1368            fuzzy::match_strings(
 1369                &self.match_candidates,
 1370                query,
 1371                query.chars().any(|c| c.is_uppercase()),
 1372                100,
 1373                &Default::default(),
 1374                executor,
 1375            )
 1376            .await
 1377        } else {
 1378            self.match_candidates
 1379                .iter()
 1380                .enumerate()
 1381                .map(|(candidate_id, candidate)| StringMatch {
 1382                    candidate_id,
 1383                    score: Default::default(),
 1384                    positions: Default::default(),
 1385                    string: candidate.string.clone(),
 1386                })
 1387                .collect()
 1388        };
 1389
 1390        // Remove all candidates where the query's start does not match the start of any word in the candidate
 1391        if let Some(query) = query {
 1392            if let Some(query_start) = query.chars().next() {
 1393                matches.retain(|string_match| {
 1394                    split_words(&string_match.string).any(|word| {
 1395                        // Check that the first codepoint of the word as lowercase matches the first
 1396                        // codepoint of the query as lowercase
 1397                        word.chars()
 1398                            .flat_map(|codepoint| codepoint.to_lowercase())
 1399                            .zip(query_start.to_lowercase())
 1400                            .all(|(word_cp, query_cp)| word_cp == query_cp)
 1401                    })
 1402                });
 1403            }
 1404        }
 1405
 1406        let completions = self.completions.read();
 1407        if self.sort_completions {
 1408            matches.sort_unstable_by_key(|mat| {
 1409                // We do want to strike a balance here between what the language server tells us
 1410                // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
 1411                // `Creat` and there is a local variable called `CreateComponent`).
 1412                // So what we do is: we bucket all matches into two buckets
 1413                // - Strong matches
 1414                // - Weak matches
 1415                // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
 1416                // and the Weak matches are the rest.
 1417                //
 1418                // For the strong matches, we sort by our fuzzy-finder score first and for the weak
 1419                // matches, we prefer language-server sort_text first.
 1420                //
 1421                // The thinking behind that: we want to show strong matches first in order of relevance(fuzzy score).
 1422                // Rest of the matches(weak) can be sorted as language-server expects.
 1423
 1424                #[derive(PartialEq, Eq, PartialOrd, Ord)]
 1425                enum MatchScore<'a> {
 1426                    Strong {
 1427                        score: Reverse<OrderedFloat<f64>>,
 1428                        sort_text: Option<&'a str>,
 1429                        sort_key: (usize, &'a str),
 1430                    },
 1431                    Weak {
 1432                        sort_text: Option<&'a str>,
 1433                        score: Reverse<OrderedFloat<f64>>,
 1434                        sort_key: (usize, &'a str),
 1435                    },
 1436                }
 1437
 1438                let completion = &completions[mat.candidate_id];
 1439                let sort_key = completion.sort_key();
 1440                let sort_text = completion.lsp_completion.sort_text.as_deref();
 1441                let score = Reverse(OrderedFloat(mat.score));
 1442
 1443                if mat.score >= 0.2 {
 1444                    MatchScore::Strong {
 1445                        score,
 1446                        sort_text,
 1447                        sort_key,
 1448                    }
 1449                } else {
 1450                    MatchScore::Weak {
 1451                        sort_text,
 1452                        score,
 1453                        sort_key,
 1454                    }
 1455                }
 1456            });
 1457        }
 1458
 1459        for mat in &mut matches {
 1460            let completion = &completions[mat.candidate_id];
 1461            mat.string.clone_from(&completion.label.text);
 1462            for position in &mut mat.positions {
 1463                *position += completion.label.filter_range.start;
 1464            }
 1465        }
 1466        drop(completions);
 1467
 1468        self.matches = matches.into();
 1469        self.selected_item = 0;
 1470    }
 1471}
 1472
 1473#[derive(Clone)]
 1474struct AvailableCodeAction {
 1475    excerpt_id: ExcerptId,
 1476    action: CodeAction,
 1477    provider: Arc<dyn CodeActionProvider>,
 1478}
 1479
 1480#[derive(Clone)]
 1481struct CodeActionContents {
 1482    tasks: Option<Arc<ResolvedTasks>>,
 1483    actions: Option<Arc<[AvailableCodeAction]>>,
 1484}
 1485
 1486impl CodeActionContents {
 1487    fn len(&self) -> usize {
 1488        match (&self.tasks, &self.actions) {
 1489            (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
 1490            (Some(tasks), None) => tasks.templates.len(),
 1491            (None, Some(actions)) => actions.len(),
 1492            (None, None) => 0,
 1493        }
 1494    }
 1495
 1496    fn is_empty(&self) -> bool {
 1497        match (&self.tasks, &self.actions) {
 1498            (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
 1499            (Some(tasks), None) => tasks.templates.is_empty(),
 1500            (None, Some(actions)) => actions.is_empty(),
 1501            (None, None) => true,
 1502        }
 1503    }
 1504
 1505    fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
 1506        self.tasks
 1507            .iter()
 1508            .flat_map(|tasks| {
 1509                tasks
 1510                    .templates
 1511                    .iter()
 1512                    .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
 1513            })
 1514            .chain(self.actions.iter().flat_map(|actions| {
 1515                actions.iter().map(|available| CodeActionsItem::CodeAction {
 1516                    excerpt_id: available.excerpt_id,
 1517                    action: available.action.clone(),
 1518                    provider: available.provider.clone(),
 1519                })
 1520            }))
 1521    }
 1522    fn get(&self, index: usize) -> Option<CodeActionsItem> {
 1523        match (&self.tasks, &self.actions) {
 1524            (Some(tasks), Some(actions)) => {
 1525                if index < tasks.templates.len() {
 1526                    tasks
 1527                        .templates
 1528                        .get(index)
 1529                        .cloned()
 1530                        .map(|(kind, task)| CodeActionsItem::Task(kind, task))
 1531                } else {
 1532                    actions.get(index - tasks.templates.len()).map(|available| {
 1533                        CodeActionsItem::CodeAction {
 1534                            excerpt_id: available.excerpt_id,
 1535                            action: available.action.clone(),
 1536                            provider: available.provider.clone(),
 1537                        }
 1538                    })
 1539                }
 1540            }
 1541            (Some(tasks), None) => tasks
 1542                .templates
 1543                .get(index)
 1544                .cloned()
 1545                .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
 1546            (None, Some(actions)) => {
 1547                actions
 1548                    .get(index)
 1549                    .map(|available| CodeActionsItem::CodeAction {
 1550                        excerpt_id: available.excerpt_id,
 1551                        action: available.action.clone(),
 1552                        provider: available.provider.clone(),
 1553                    })
 1554            }
 1555            (None, None) => None,
 1556        }
 1557    }
 1558}
 1559
 1560#[allow(clippy::large_enum_variant)]
 1561#[derive(Clone)]
 1562enum CodeActionsItem {
 1563    Task(TaskSourceKind, ResolvedTask),
 1564    CodeAction {
 1565        excerpt_id: ExcerptId,
 1566        action: CodeAction,
 1567        provider: Arc<dyn CodeActionProvider>,
 1568    },
 1569}
 1570
 1571impl CodeActionsItem {
 1572    fn as_task(&self) -> Option<&ResolvedTask> {
 1573        let Self::Task(_, task) = self else {
 1574            return None;
 1575        };
 1576        Some(task)
 1577    }
 1578    fn as_code_action(&self) -> Option<&CodeAction> {
 1579        let Self::CodeAction { action, .. } = self else {
 1580            return None;
 1581        };
 1582        Some(action)
 1583    }
 1584    fn label(&self) -> String {
 1585        match self {
 1586            Self::CodeAction { action, .. } => action.lsp_action.title.clone(),
 1587            Self::Task(_, task) => task.resolved_label.clone(),
 1588        }
 1589    }
 1590}
 1591
 1592struct CodeActionsMenu {
 1593    actions: CodeActionContents,
 1594    buffer: Model<Buffer>,
 1595    selected_item: usize,
 1596    scroll_handle: UniformListScrollHandle,
 1597    deployed_from_indicator: Option<DisplayRow>,
 1598}
 1599
 1600impl CodeActionsMenu {
 1601    fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
 1602        self.selected_item = 0;
 1603        self.scroll_handle
 1604            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1605        cx.notify()
 1606    }
 1607
 1608    fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
 1609        if self.selected_item > 0 {
 1610            self.selected_item -= 1;
 1611        } else {
 1612            self.selected_item = self.actions.len() - 1;
 1613        }
 1614        self.scroll_handle
 1615            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1616        cx.notify();
 1617    }
 1618
 1619    fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
 1620        if self.selected_item + 1 < self.actions.len() {
 1621            self.selected_item += 1;
 1622        } else {
 1623            self.selected_item = 0;
 1624        }
 1625        self.scroll_handle
 1626            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1627        cx.notify();
 1628    }
 1629
 1630    fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
 1631        self.selected_item = self.actions.len() - 1;
 1632        self.scroll_handle
 1633            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1634        cx.notify()
 1635    }
 1636
 1637    fn visible(&self) -> bool {
 1638        !self.actions.is_empty()
 1639    }
 1640
 1641    fn render(
 1642        &self,
 1643        cursor_position: DisplayPoint,
 1644        _style: &EditorStyle,
 1645        max_height: Pixels,
 1646        cx: &mut ViewContext<Editor>,
 1647    ) -> (ContextMenuOrigin, AnyElement) {
 1648        let actions = self.actions.clone();
 1649        let selected_item = self.selected_item;
 1650        let element = uniform_list(
 1651            cx.view().clone(),
 1652            "code_actions_menu",
 1653            self.actions.len(),
 1654            move |_this, range, cx| {
 1655                actions
 1656                    .iter()
 1657                    .skip(range.start)
 1658                    .take(range.end - range.start)
 1659                    .enumerate()
 1660                    .map(|(ix, action)| {
 1661                        let item_ix = range.start + ix;
 1662                        let selected = selected_item == item_ix;
 1663                        let colors = cx.theme().colors();
 1664                        div()
 1665                            .px_1()
 1666                            .rounded_md()
 1667                            .text_color(colors.text)
 1668                            .when(selected, |style| {
 1669                                style
 1670                                    .bg(colors.element_active)
 1671                                    .text_color(colors.text_accent)
 1672                            })
 1673                            .hover(|style| {
 1674                                style
 1675                                    .bg(colors.element_hover)
 1676                                    .text_color(colors.text_accent)
 1677                            })
 1678                            .whitespace_nowrap()
 1679                            .when_some(action.as_code_action(), |this, action| {
 1680                                this.on_mouse_down(
 1681                                    MouseButton::Left,
 1682                                    cx.listener(move |editor, _, cx| {
 1683                                        cx.stop_propagation();
 1684                                        if let Some(task) = editor.confirm_code_action(
 1685                                            &ConfirmCodeAction {
 1686                                                item_ix: Some(item_ix),
 1687                                            },
 1688                                            cx,
 1689                                        ) {
 1690                                            task.detach_and_log_err(cx)
 1691                                        }
 1692                                    }),
 1693                                )
 1694                                // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
 1695                                .child(SharedString::from(
 1696                                    action.lsp_action.title.replace("\n", ""),
 1697                                ))
 1698                            })
 1699                            .when_some(action.as_task(), |this, task| {
 1700                                this.on_mouse_down(
 1701                                    MouseButton::Left,
 1702                                    cx.listener(move |editor, _, cx| {
 1703                                        cx.stop_propagation();
 1704                                        if let Some(task) = editor.confirm_code_action(
 1705                                            &ConfirmCodeAction {
 1706                                                item_ix: Some(item_ix),
 1707                                            },
 1708                                            cx,
 1709                                        ) {
 1710                                            task.detach_and_log_err(cx)
 1711                                        }
 1712                                    }),
 1713                                )
 1714                                .child(SharedString::from(task.resolved_label.replace("\n", "")))
 1715                            })
 1716                    })
 1717                    .collect()
 1718            },
 1719        )
 1720        .elevation_1(cx)
 1721        .p_1()
 1722        .max_h(max_height)
 1723        .occlude()
 1724        .track_scroll(self.scroll_handle.clone())
 1725        .with_width_from_item(
 1726            self.actions
 1727                .iter()
 1728                .enumerate()
 1729                .max_by_key(|(_, action)| match action {
 1730                    CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
 1731                    CodeActionsItem::CodeAction { action, .. } => {
 1732                        action.lsp_action.title.chars().count()
 1733                    }
 1734                })
 1735                .map(|(ix, _)| ix),
 1736        )
 1737        .with_sizing_behavior(ListSizingBehavior::Infer)
 1738        .into_any_element();
 1739
 1740        let cursor_position = if let Some(row) = self.deployed_from_indicator {
 1741            ContextMenuOrigin::GutterIndicator(row)
 1742        } else {
 1743            ContextMenuOrigin::EditorPoint(cursor_position)
 1744        };
 1745
 1746        (cursor_position, element)
 1747    }
 1748}
 1749
 1750#[derive(Debug)]
 1751struct ActiveDiagnosticGroup {
 1752    primary_range: Range<Anchor>,
 1753    primary_message: String,
 1754    group_id: usize,
 1755    blocks: HashMap<CustomBlockId, Diagnostic>,
 1756    is_valid: bool,
 1757}
 1758
 1759#[derive(Serialize, Deserialize, Clone, Debug)]
 1760pub struct ClipboardSelection {
 1761    pub len: usize,
 1762    pub is_entire_line: bool,
 1763    pub first_line_indent: u32,
 1764}
 1765
 1766#[derive(Debug)]
 1767pub(crate) struct NavigationData {
 1768    cursor_anchor: Anchor,
 1769    cursor_position: Point,
 1770    scroll_anchor: ScrollAnchor,
 1771    scroll_top_row: u32,
 1772}
 1773
 1774#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1775pub enum GotoDefinitionKind {
 1776    Symbol,
 1777    Declaration,
 1778    Type,
 1779    Implementation,
 1780}
 1781
 1782#[derive(Debug, Clone)]
 1783enum InlayHintRefreshReason {
 1784    Toggle(bool),
 1785    SettingsChange(InlayHintSettings),
 1786    NewLinesShown,
 1787    BufferEdited(HashSet<Arc<Language>>),
 1788    RefreshRequested,
 1789    ExcerptsRemoved(Vec<ExcerptId>),
 1790}
 1791
 1792impl InlayHintRefreshReason {
 1793    fn description(&self) -> &'static str {
 1794        match self {
 1795            Self::Toggle(_) => "toggle",
 1796            Self::SettingsChange(_) => "settings change",
 1797            Self::NewLinesShown => "new lines shown",
 1798            Self::BufferEdited(_) => "buffer edited",
 1799            Self::RefreshRequested => "refresh requested",
 1800            Self::ExcerptsRemoved(_) => "excerpts removed",
 1801        }
 1802    }
 1803}
 1804
 1805pub(crate) struct FocusedBlock {
 1806    id: BlockId,
 1807    focus_handle: WeakFocusHandle,
 1808}
 1809
 1810#[derive(Clone)]
 1811struct JumpData {
 1812    excerpt_id: ExcerptId,
 1813    position: Point,
 1814    anchor: text::Anchor,
 1815    path: Option<project::ProjectPath>,
 1816    line_offset_from_top: u32,
 1817}
 1818
 1819impl Editor {
 1820    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
 1821        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1822        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1823        Self::new(
 1824            EditorMode::SingleLine { auto_width: false },
 1825            buffer,
 1826            None,
 1827            false,
 1828            cx,
 1829        )
 1830    }
 1831
 1832    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
 1833        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1834        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1835        Self::new(EditorMode::Full, buffer, None, false, cx)
 1836    }
 1837
 1838    pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
 1839        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1840        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1841        Self::new(
 1842            EditorMode::SingleLine { auto_width: true },
 1843            buffer,
 1844            None,
 1845            false,
 1846            cx,
 1847        )
 1848    }
 1849
 1850    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
 1851        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1852        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1853        Self::new(
 1854            EditorMode::AutoHeight { max_lines },
 1855            buffer,
 1856            None,
 1857            false,
 1858            cx,
 1859        )
 1860    }
 1861
 1862    pub fn for_buffer(
 1863        buffer: Model<Buffer>,
 1864        project: Option<Model<Project>>,
 1865        cx: &mut ViewContext<Self>,
 1866    ) -> Self {
 1867        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1868        Self::new(EditorMode::Full, buffer, project, false, cx)
 1869    }
 1870
 1871    pub fn for_multibuffer(
 1872        buffer: Model<MultiBuffer>,
 1873        project: Option<Model<Project>>,
 1874        show_excerpt_controls: bool,
 1875        cx: &mut ViewContext<Self>,
 1876    ) -> Self {
 1877        Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
 1878    }
 1879
 1880    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 1881        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1882        let mut clone = Self::new(
 1883            self.mode,
 1884            self.buffer.clone(),
 1885            self.project.clone(),
 1886            show_excerpt_controls,
 1887            cx,
 1888        );
 1889        self.display_map.update(cx, |display_map, cx| {
 1890            let snapshot = display_map.snapshot(cx);
 1891            clone.display_map.update(cx, |display_map, cx| {
 1892                display_map.set_state(&snapshot, cx);
 1893            });
 1894        });
 1895        clone.selections.clone_state(&self.selections);
 1896        clone.scroll_manager.clone_state(&self.scroll_manager);
 1897        clone.searchable = self.searchable;
 1898        clone
 1899    }
 1900
 1901    pub fn new(
 1902        mode: EditorMode,
 1903        buffer: Model<MultiBuffer>,
 1904        project: Option<Model<Project>>,
 1905        show_excerpt_controls: bool,
 1906        cx: &mut ViewContext<Self>,
 1907    ) -> Self {
 1908        let style = cx.text_style();
 1909        let font_size = style.font_size.to_pixels(cx.rem_size());
 1910        let editor = cx.view().downgrade();
 1911        let fold_placeholder = FoldPlaceholder {
 1912            constrain_width: true,
 1913            render: Arc::new(move |fold_id, fold_range, cx| {
 1914                let editor = editor.clone();
 1915                div()
 1916                    .id(fold_id)
 1917                    .bg(cx.theme().colors().ghost_element_background)
 1918                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1919                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1920                    .rounded_sm()
 1921                    .size_full()
 1922                    .cursor_pointer()
 1923                    .child("")
 1924                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 1925                    .on_click(move |_, cx| {
 1926                        editor
 1927                            .update(cx, |editor, cx| {
 1928                                editor.unfold_ranges(
 1929                                    &[fold_range.start..fold_range.end],
 1930                                    true,
 1931                                    false,
 1932                                    cx,
 1933                                );
 1934                                cx.stop_propagation();
 1935                            })
 1936                            .ok();
 1937                    })
 1938                    .into_any()
 1939            }),
 1940            merge_adjacent: true,
 1941            ..Default::default()
 1942        };
 1943        let display_map = cx.new_model(|cx| {
 1944            DisplayMap::new(
 1945                buffer.clone(),
 1946                style.font(),
 1947                font_size,
 1948                None,
 1949                show_excerpt_controls,
 1950                FILE_HEADER_HEIGHT,
 1951                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1952                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1953                fold_placeholder,
 1954                cx,
 1955            )
 1956        });
 1957
 1958        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1959
 1960        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1961
 1962        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1963            .then(|| language_settings::SoftWrap::None);
 1964
 1965        let mut project_subscriptions = Vec::new();
 1966        if mode == EditorMode::Full {
 1967            if let Some(project) = project.as_ref() {
 1968                if buffer.read(cx).is_singleton() {
 1969                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
 1970                        cx.emit(EditorEvent::TitleChanged);
 1971                    }));
 1972                }
 1973                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
 1974                    if let project::Event::RefreshInlayHints = event {
 1975                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1976                    } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1977                        if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1978                            let focus_handle = editor.focus_handle(cx);
 1979                            if focus_handle.is_focused(cx) {
 1980                                let snapshot = buffer.read(cx).snapshot();
 1981                                for (range, snippet) in snippet_edits {
 1982                                    let editor_range =
 1983                                        language::range_from_lsp(*range).to_offset(&snapshot);
 1984                                    editor
 1985                                        .insert_snippet(&[editor_range], snippet.clone(), cx)
 1986                                        .ok();
 1987                                }
 1988                            }
 1989                        }
 1990                    }
 1991                }));
 1992                if let Some(task_inventory) = project
 1993                    .read(cx)
 1994                    .task_store()
 1995                    .read(cx)
 1996                    .task_inventory()
 1997                    .cloned()
 1998                {
 1999                    project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
 2000                        editor.tasks_update_task = Some(editor.refresh_runnables(cx));
 2001                    }));
 2002                }
 2003            }
 2004        }
 2005
 2006        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 2007
 2008        let inlay_hint_settings =
 2009            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 2010        let focus_handle = cx.focus_handle();
 2011        cx.on_focus(&focus_handle, Self::handle_focus).detach();
 2012        cx.on_focus_in(&focus_handle, Self::handle_focus_in)
 2013            .detach();
 2014        cx.on_focus_out(&focus_handle, Self::handle_focus_out)
 2015            .detach();
 2016        cx.on_blur(&focus_handle, Self::handle_blur).detach();
 2017
 2018        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 2019            Some(false)
 2020        } else {
 2021            None
 2022        };
 2023
 2024        let mut code_action_providers = Vec::new();
 2025        if let Some(project) = project.clone() {
 2026            get_unstaged_changes_for_buffers(&project, buffer.read(cx).all_buffers(), cx);
 2027            code_action_providers.push(Arc::new(project) as Arc<_>);
 2028        }
 2029
 2030        let mut this = Self {
 2031            focus_handle,
 2032            show_cursor_when_unfocused: false,
 2033            last_focused_descendant: None,
 2034            buffer: buffer.clone(),
 2035            display_map: display_map.clone(),
 2036            selections,
 2037            scroll_manager: ScrollManager::new(cx),
 2038            columnar_selection_tail: None,
 2039            add_selections_state: None,
 2040            select_next_state: None,
 2041            select_prev_state: None,
 2042            selection_history: Default::default(),
 2043            autoclose_regions: Default::default(),
 2044            snippet_stack: Default::default(),
 2045            select_larger_syntax_node_stack: Vec::new(),
 2046            ime_transaction: Default::default(),
 2047            active_diagnostics: None,
 2048            soft_wrap_mode_override,
 2049            completion_provider: project.clone().map(|project| Box::new(project) as _),
 2050            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 2051            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 2052            project,
 2053            blink_manager: blink_manager.clone(),
 2054            show_local_selections: true,
 2055            mode,
 2056            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 2057            show_gutter: mode == EditorMode::Full,
 2058            show_line_numbers: None,
 2059            use_relative_line_numbers: None,
 2060            show_git_diff_gutter: None,
 2061            show_code_actions: None,
 2062            show_runnables: None,
 2063            show_wrap_guides: None,
 2064            show_indent_guides,
 2065            placeholder_text: None,
 2066            highlight_order: 0,
 2067            highlighted_rows: HashMap::default(),
 2068            background_highlights: Default::default(),
 2069            gutter_highlights: TreeMap::default(),
 2070            scrollbar_marker_state: ScrollbarMarkerState::default(),
 2071            active_indent_guides_state: ActiveIndentGuidesState::default(),
 2072            nav_history: None,
 2073            context_menu: RwLock::new(None),
 2074            mouse_context_menu: None,
 2075            hunk_controls_menu_handle: PopoverMenuHandle::default(),
 2076            completion_tasks: Default::default(),
 2077            signature_help_state: SignatureHelpState::default(),
 2078            auto_signature_help: None,
 2079            find_all_references_task_sources: Vec::new(),
 2080            next_completion_id: 0,
 2081            next_inlay_id: 0,
 2082            code_action_providers,
 2083            available_code_actions: Default::default(),
 2084            code_actions_task: Default::default(),
 2085            document_highlights_task: Default::default(),
 2086            linked_editing_range_task: Default::default(),
 2087            pending_rename: Default::default(),
 2088            searchable: true,
 2089            cursor_shape: EditorSettings::get_global(cx)
 2090                .cursor_shape
 2091                .unwrap_or_default(),
 2092            current_line_highlight: None,
 2093            autoindent_mode: Some(AutoindentMode::EachLine),
 2094            collapse_matches: false,
 2095            workspace: None,
 2096            input_enabled: true,
 2097            use_modal_editing: mode == EditorMode::Full,
 2098            read_only: false,
 2099            use_autoclose: true,
 2100            use_auto_surround: true,
 2101            auto_replace_emoji_shortcode: false,
 2102            leader_peer_id: None,
 2103            remote_id: None,
 2104            hover_state: Default::default(),
 2105            hovered_link_state: Default::default(),
 2106            inline_completion_provider: None,
 2107            active_inline_completion: None,
 2108            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 2109            diff_map: DiffMap::default(),
 2110            gutter_hovered: false,
 2111            pixel_position_of_newest_cursor: None,
 2112            last_bounds: None,
 2113            expect_bounds_change: None,
 2114            gutter_dimensions: GutterDimensions::default(),
 2115            style: None,
 2116            show_cursor_names: false,
 2117            hovered_cursors: Default::default(),
 2118            next_editor_action_id: EditorActionId::default(),
 2119            editor_actions: Rc::default(),
 2120            show_inline_completions_override: None,
 2121            enable_inline_completions: true,
 2122            custom_context_menu: None,
 2123            show_git_blame_gutter: false,
 2124            show_git_blame_inline: false,
 2125            show_selection_menu: None,
 2126            show_git_blame_inline_delay_task: None,
 2127            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 2128            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 2129                .session
 2130                .restore_unsaved_buffers,
 2131            blame: None,
 2132            blame_subscription: None,
 2133            tasks: Default::default(),
 2134            _subscriptions: vec![
 2135                cx.observe(&buffer, Self::on_buffer_changed),
 2136                cx.subscribe(&buffer, Self::on_buffer_event),
 2137                cx.observe(&display_map, Self::on_display_map_changed),
 2138                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 2139                cx.observe_global::<SettingsStore>(Self::settings_changed),
 2140                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 2141                cx.observe_window_activation(|editor, cx| {
 2142                    let active = cx.is_window_active();
 2143                    editor.blink_manager.update(cx, |blink_manager, cx| {
 2144                        if active {
 2145                            blink_manager.enable(cx);
 2146                        } else {
 2147                            blink_manager.disable(cx);
 2148                        }
 2149                    });
 2150                }),
 2151            ],
 2152            tasks_update_task: None,
 2153            linked_edit_ranges: Default::default(),
 2154            previous_search_ranges: None,
 2155            breadcrumb_header: None,
 2156            focused_block: None,
 2157            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 2158            addons: HashMap::default(),
 2159            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 2160            text_style_refinement: None,
 2161        };
 2162        this.tasks_update_task = Some(this.refresh_runnables(cx));
 2163        this._subscriptions.extend(project_subscriptions);
 2164
 2165        this.end_selection(cx);
 2166        this.scroll_manager.show_scrollbar(cx);
 2167
 2168        if mode == EditorMode::Full {
 2169            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 2170            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 2171
 2172            if this.git_blame_inline_enabled {
 2173                this.git_blame_inline_enabled = true;
 2174                this.start_git_blame_inline(false, cx);
 2175            }
 2176        }
 2177
 2178        this.report_editor_event("open", None, cx);
 2179        this
 2180    }
 2181
 2182    pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
 2183        self.mouse_context_menu
 2184            .as_ref()
 2185            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
 2186    }
 2187
 2188    fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
 2189        let mut key_context = KeyContext::new_with_defaults();
 2190        key_context.add("Editor");
 2191        let mode = match self.mode {
 2192            EditorMode::SingleLine { .. } => "single_line",
 2193            EditorMode::AutoHeight { .. } => "auto_height",
 2194            EditorMode::Full => "full",
 2195        };
 2196
 2197        if EditorSettings::jupyter_enabled(cx) {
 2198            key_context.add("jupyter");
 2199        }
 2200
 2201        key_context.set("mode", mode);
 2202        if self.pending_rename.is_some() {
 2203            key_context.add("renaming");
 2204        }
 2205        if self.context_menu_visible() {
 2206            match self.context_menu.read().as_ref() {
 2207                Some(ContextMenu::Completions(_)) => {
 2208                    key_context.add("menu");
 2209                    key_context.add("showing_completions")
 2210                }
 2211                Some(ContextMenu::CodeActions(_)) => {
 2212                    key_context.add("menu");
 2213                    key_context.add("showing_code_actions")
 2214                }
 2215                None => {}
 2216            }
 2217        }
 2218
 2219        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 2220        if !self.focus_handle(cx).contains_focused(cx)
 2221            || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
 2222        {
 2223            for addon in self.addons.values() {
 2224                addon.extend_key_context(&mut key_context, cx)
 2225            }
 2226        }
 2227
 2228        if let Some(extension) = self
 2229            .buffer
 2230            .read(cx)
 2231            .as_singleton()
 2232            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 2233        {
 2234            key_context.set("extension", extension.to_string());
 2235        }
 2236
 2237        if self.has_active_inline_completion(cx) {
 2238            key_context.add("copilot_suggestion");
 2239            key_context.add("inline_completion");
 2240        }
 2241
 2242        key_context
 2243    }
 2244
 2245    pub fn new_file(
 2246        workspace: &mut Workspace,
 2247        _: &workspace::NewFile,
 2248        cx: &mut ViewContext<Workspace>,
 2249    ) {
 2250        Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
 2251            "Failed to create buffer",
 2252            cx,
 2253            |e, _| match e.error_code() {
 2254                ErrorCode::RemoteUpgradeRequired => Some(format!(
 2255                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2256                e.error_tag("required").unwrap_or("the latest version")
 2257            )),
 2258                _ => None,
 2259            },
 2260        );
 2261    }
 2262
 2263    pub fn new_in_workspace(
 2264        workspace: &mut Workspace,
 2265        cx: &mut ViewContext<Workspace>,
 2266    ) -> Task<Result<View<Editor>>> {
 2267        let project = workspace.project().clone();
 2268        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2269
 2270        cx.spawn(|workspace, mut cx| async move {
 2271            let buffer = create.await?;
 2272            workspace.update(&mut cx, |workspace, cx| {
 2273                let editor =
 2274                    cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
 2275                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 2276                editor
 2277            })
 2278        })
 2279    }
 2280
 2281    fn new_file_vertical(
 2282        workspace: &mut Workspace,
 2283        _: &workspace::NewFileSplitVertical,
 2284        cx: &mut ViewContext<Workspace>,
 2285    ) {
 2286        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
 2287    }
 2288
 2289    fn new_file_horizontal(
 2290        workspace: &mut Workspace,
 2291        _: &workspace::NewFileSplitHorizontal,
 2292        cx: &mut ViewContext<Workspace>,
 2293    ) {
 2294        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
 2295    }
 2296
 2297    fn new_file_in_direction(
 2298        workspace: &mut Workspace,
 2299        direction: SplitDirection,
 2300        cx: &mut ViewContext<Workspace>,
 2301    ) {
 2302        let project = workspace.project().clone();
 2303        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2304
 2305        cx.spawn(|workspace, mut cx| async move {
 2306            let buffer = create.await?;
 2307            workspace.update(&mut cx, move |workspace, cx| {
 2308                workspace.split_item(
 2309                    direction,
 2310                    Box::new(
 2311                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 2312                    ),
 2313                    cx,
 2314                )
 2315            })?;
 2316            anyhow::Ok(())
 2317        })
 2318        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 2319            ErrorCode::RemoteUpgradeRequired => Some(format!(
 2320                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2321                e.error_tag("required").unwrap_or("the latest version")
 2322            )),
 2323            _ => None,
 2324        });
 2325    }
 2326
 2327    pub fn leader_peer_id(&self) -> Option<PeerId> {
 2328        self.leader_peer_id
 2329    }
 2330
 2331    pub fn buffer(&self) -> &Model<MultiBuffer> {
 2332        &self.buffer
 2333    }
 2334
 2335    pub fn workspace(&self) -> Option<View<Workspace>> {
 2336        self.workspace.as_ref()?.0.upgrade()
 2337    }
 2338
 2339    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
 2340        self.buffer().read(cx).title(cx)
 2341    }
 2342
 2343    pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
 2344        let git_blame_gutter_max_author_length = self
 2345            .render_git_blame_gutter(cx)
 2346            .then(|| {
 2347                if let Some(blame) = self.blame.as_ref() {
 2348                    let max_author_length =
 2349                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 2350                    Some(max_author_length)
 2351                } else {
 2352                    None
 2353                }
 2354            })
 2355            .flatten();
 2356
 2357        EditorSnapshot {
 2358            mode: self.mode,
 2359            show_gutter: self.show_gutter,
 2360            show_line_numbers: self.show_line_numbers,
 2361            show_git_diff_gutter: self.show_git_diff_gutter,
 2362            show_code_actions: self.show_code_actions,
 2363            show_runnables: self.show_runnables,
 2364            git_blame_gutter_max_author_length,
 2365            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 2366            scroll_anchor: self.scroll_manager.anchor(),
 2367            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 2368            placeholder_text: self.placeholder_text.clone(),
 2369            diff_map: self.diff_map.snapshot(),
 2370            is_focused: self.focus_handle.is_focused(cx),
 2371            current_line_highlight: self
 2372                .current_line_highlight
 2373                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 2374            gutter_hovered: self.gutter_hovered,
 2375        }
 2376    }
 2377
 2378    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
 2379        self.buffer.read(cx).language_at(point, cx)
 2380    }
 2381
 2382    pub fn file_at<T: ToOffset>(
 2383        &self,
 2384        point: T,
 2385        cx: &AppContext,
 2386    ) -> Option<Arc<dyn language::File>> {
 2387        self.buffer.read(cx).read(cx).file_at(point).cloned()
 2388    }
 2389
 2390    pub fn active_excerpt(
 2391        &self,
 2392        cx: &AppContext,
 2393    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
 2394        self.buffer
 2395            .read(cx)
 2396            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 2397    }
 2398
 2399    pub fn mode(&self) -> EditorMode {
 2400        self.mode
 2401    }
 2402
 2403    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 2404        self.collaboration_hub.as_deref()
 2405    }
 2406
 2407    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 2408        self.collaboration_hub = Some(hub);
 2409    }
 2410
 2411    pub fn set_custom_context_menu(
 2412        &mut self,
 2413        f: impl 'static
 2414            + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
 2415    ) {
 2416        self.custom_context_menu = Some(Box::new(f))
 2417    }
 2418
 2419    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 2420        self.completion_provider = provider;
 2421    }
 2422
 2423    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 2424        self.semantics_provider.clone()
 2425    }
 2426
 2427    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 2428        self.semantics_provider = provider;
 2429    }
 2430
 2431    pub fn set_inline_completion_provider<T>(
 2432        &mut self,
 2433        provider: Option<Model<T>>,
 2434        cx: &mut ViewContext<Self>,
 2435    ) where
 2436        T: InlineCompletionProvider,
 2437    {
 2438        self.inline_completion_provider =
 2439            provider.map(|provider| RegisteredInlineCompletionProvider {
 2440                _subscription: cx.observe(&provider, |this, _, cx| {
 2441                    if this.focus_handle.is_focused(cx) {
 2442                        this.update_visible_inline_completion(cx);
 2443                    }
 2444                }),
 2445                provider: Arc::new(provider),
 2446            });
 2447        self.refresh_inline_completion(false, false, cx);
 2448    }
 2449
 2450    pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
 2451        self.placeholder_text.as_deref()
 2452    }
 2453
 2454    pub fn set_placeholder_text(
 2455        &mut self,
 2456        placeholder_text: impl Into<Arc<str>>,
 2457        cx: &mut ViewContext<Self>,
 2458    ) {
 2459        let placeholder_text = Some(placeholder_text.into());
 2460        if self.placeholder_text != placeholder_text {
 2461            self.placeholder_text = placeholder_text;
 2462            cx.notify();
 2463        }
 2464    }
 2465
 2466    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
 2467        self.cursor_shape = cursor_shape;
 2468
 2469        // Disrupt blink for immediate user feedback that the cursor shape has changed
 2470        self.blink_manager.update(cx, BlinkManager::show_cursor);
 2471
 2472        cx.notify();
 2473    }
 2474
 2475    pub fn set_current_line_highlight(
 2476        &mut self,
 2477        current_line_highlight: Option<CurrentLineHighlight>,
 2478    ) {
 2479        self.current_line_highlight = current_line_highlight;
 2480    }
 2481
 2482    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 2483        self.collapse_matches = collapse_matches;
 2484    }
 2485
 2486    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 2487        if self.collapse_matches {
 2488            return range.start..range.start;
 2489        }
 2490        range.clone()
 2491    }
 2492
 2493    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
 2494        if self.display_map.read(cx).clip_at_line_ends != clip {
 2495            self.display_map
 2496                .update(cx, |map, _| map.clip_at_line_ends = clip);
 2497        }
 2498    }
 2499
 2500    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 2501        self.input_enabled = input_enabled;
 2502    }
 2503
 2504    pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
 2505        self.enable_inline_completions = enabled;
 2506    }
 2507
 2508    pub fn set_autoindent(&mut self, autoindent: bool) {
 2509        if autoindent {
 2510            self.autoindent_mode = Some(AutoindentMode::EachLine);
 2511        } else {
 2512            self.autoindent_mode = None;
 2513        }
 2514    }
 2515
 2516    pub fn read_only(&self, cx: &AppContext) -> bool {
 2517        self.read_only || self.buffer.read(cx).read_only()
 2518    }
 2519
 2520    pub fn set_read_only(&mut self, read_only: bool) {
 2521        self.read_only = read_only;
 2522    }
 2523
 2524    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 2525        self.use_autoclose = autoclose;
 2526    }
 2527
 2528    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 2529        self.use_auto_surround = auto_surround;
 2530    }
 2531
 2532    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 2533        self.auto_replace_emoji_shortcode = auto_replace;
 2534    }
 2535
 2536    pub fn toggle_inline_completions(
 2537        &mut self,
 2538        _: &ToggleInlineCompletions,
 2539        cx: &mut ViewContext<Self>,
 2540    ) {
 2541        if self.show_inline_completions_override.is_some() {
 2542            self.set_show_inline_completions(None, cx);
 2543        } else {
 2544            let cursor = self.selections.newest_anchor().head();
 2545            if let Some((buffer, cursor_buffer_position)) =
 2546                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 2547            {
 2548                let show_inline_completions =
 2549                    !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
 2550                self.set_show_inline_completions(Some(show_inline_completions), cx);
 2551            }
 2552        }
 2553    }
 2554
 2555    pub fn set_show_inline_completions(
 2556        &mut self,
 2557        show_inline_completions: Option<bool>,
 2558        cx: &mut ViewContext<Self>,
 2559    ) {
 2560        self.show_inline_completions_override = show_inline_completions;
 2561        self.refresh_inline_completion(false, true, cx);
 2562    }
 2563
 2564    fn should_show_inline_completions(
 2565        &self,
 2566        buffer: &Model<Buffer>,
 2567        buffer_position: language::Anchor,
 2568        cx: &AppContext,
 2569    ) -> bool {
 2570        if !self.snippet_stack.is_empty() {
 2571            return false;
 2572        }
 2573
 2574        if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
 2575            return false;
 2576        }
 2577
 2578        if let Some(provider) = self.inline_completion_provider() {
 2579            if let Some(show_inline_completions) = self.show_inline_completions_override {
 2580                show_inline_completions
 2581            } else {
 2582                self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
 2583            }
 2584        } else {
 2585            false
 2586        }
 2587    }
 2588
 2589    fn inline_completions_disabled_in_scope(
 2590        &self,
 2591        buffer: &Model<Buffer>,
 2592        buffer_position: language::Anchor,
 2593        cx: &AppContext,
 2594    ) -> bool {
 2595        let snapshot = buffer.read(cx).snapshot();
 2596        let settings = snapshot.settings_at(buffer_position, cx);
 2597
 2598        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 2599            return false;
 2600        };
 2601
 2602        scope.override_name().map_or(false, |scope_name| {
 2603            settings
 2604                .inline_completions_disabled_in
 2605                .iter()
 2606                .any(|s| s == scope_name)
 2607        })
 2608    }
 2609
 2610    pub fn set_use_modal_editing(&mut self, to: bool) {
 2611        self.use_modal_editing = to;
 2612    }
 2613
 2614    pub fn use_modal_editing(&self) -> bool {
 2615        self.use_modal_editing
 2616    }
 2617
 2618    fn selections_did_change(
 2619        &mut self,
 2620        local: bool,
 2621        old_cursor_position: &Anchor,
 2622        show_completions: bool,
 2623        cx: &mut ViewContext<Self>,
 2624    ) {
 2625        cx.invalidate_character_coordinates();
 2626
 2627        // Copy selections to primary selection buffer
 2628        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 2629        if local {
 2630            let selections = self.selections.all::<usize>(cx);
 2631            let buffer_handle = self.buffer.read(cx).read(cx);
 2632
 2633            let mut text = String::new();
 2634            for (index, selection) in selections.iter().enumerate() {
 2635                let text_for_selection = buffer_handle
 2636                    .text_for_range(selection.start..selection.end)
 2637                    .collect::<String>();
 2638
 2639                text.push_str(&text_for_selection);
 2640                if index != selections.len() - 1 {
 2641                    text.push('\n');
 2642                }
 2643            }
 2644
 2645            if !text.is_empty() {
 2646                cx.write_to_primary(ClipboardItem::new_string(text));
 2647            }
 2648        }
 2649
 2650        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
 2651            self.buffer.update(cx, |buffer, cx| {
 2652                buffer.set_active_selections(
 2653                    &self.selections.disjoint_anchors(),
 2654                    self.selections.line_mode,
 2655                    self.cursor_shape,
 2656                    cx,
 2657                )
 2658            });
 2659        }
 2660        let display_map = self
 2661            .display_map
 2662            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2663        let buffer = &display_map.buffer_snapshot;
 2664        self.add_selections_state = None;
 2665        self.select_next_state = None;
 2666        self.select_prev_state = None;
 2667        self.select_larger_syntax_node_stack.clear();
 2668        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2669        self.snippet_stack
 2670            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2671        self.take_rename(false, cx);
 2672
 2673        let new_cursor_position = self.selections.newest_anchor().head();
 2674
 2675        self.push_to_nav_history(
 2676            *old_cursor_position,
 2677            Some(new_cursor_position.to_point(buffer)),
 2678            cx,
 2679        );
 2680
 2681        if local {
 2682            let new_cursor_position = self.selections.newest_anchor().head();
 2683            let mut context_menu = self.context_menu.write();
 2684            let completion_menu = match context_menu.as_ref() {
 2685                Some(ContextMenu::Completions(menu)) => Some(menu),
 2686
 2687                _ => {
 2688                    *context_menu = None;
 2689                    None
 2690                }
 2691            };
 2692
 2693            if let Some(completion_menu) = completion_menu {
 2694                let cursor_position = new_cursor_position.to_offset(buffer);
 2695                let (word_range, kind) =
 2696                    buffer.surrounding_word(completion_menu.initial_position, true);
 2697                if kind == Some(CharKind::Word)
 2698                    && word_range.to_inclusive().contains(&cursor_position)
 2699                {
 2700                    let mut completion_menu = completion_menu.clone();
 2701                    drop(context_menu);
 2702
 2703                    let query = Self::completion_query(buffer, cursor_position);
 2704                    cx.spawn(move |this, mut cx| async move {
 2705                        completion_menu
 2706                            .filter(query.as_deref(), cx.background_executor().clone())
 2707                            .await;
 2708
 2709                        this.update(&mut cx, |this, cx| {
 2710                            let mut context_menu = this.context_menu.write();
 2711                            let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
 2712                                return;
 2713                            };
 2714
 2715                            if menu.id > completion_menu.id {
 2716                                return;
 2717                            }
 2718
 2719                            *context_menu = Some(ContextMenu::Completions(completion_menu));
 2720                            drop(context_menu);
 2721                            cx.notify();
 2722                        })
 2723                    })
 2724                    .detach();
 2725
 2726                    if show_completions {
 2727                        self.show_completions(&ShowCompletions { trigger: None }, cx);
 2728                    }
 2729                } else {
 2730                    drop(context_menu);
 2731                    self.hide_context_menu(cx);
 2732                }
 2733            } else {
 2734                drop(context_menu);
 2735            }
 2736
 2737            hide_hover(self, cx);
 2738
 2739            if old_cursor_position.to_display_point(&display_map).row()
 2740                != new_cursor_position.to_display_point(&display_map).row()
 2741            {
 2742                self.available_code_actions.take();
 2743            }
 2744            self.refresh_code_actions(cx);
 2745            self.refresh_document_highlights(cx);
 2746            refresh_matching_bracket_highlights(self, cx);
 2747            self.discard_inline_completion(false, cx);
 2748            linked_editing_ranges::refresh_linked_ranges(self, cx);
 2749            if self.git_blame_inline_enabled {
 2750                self.start_inline_blame_timer(cx);
 2751            }
 2752        }
 2753
 2754        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2755        cx.emit(EditorEvent::SelectionsChanged { local });
 2756
 2757        if self.selections.disjoint_anchors().len() == 1 {
 2758            cx.emit(SearchEvent::ActiveMatchChanged)
 2759        }
 2760        cx.notify();
 2761    }
 2762
 2763    pub fn change_selections<R>(
 2764        &mut self,
 2765        autoscroll: Option<Autoscroll>,
 2766        cx: &mut ViewContext<Self>,
 2767        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2768    ) -> R {
 2769        self.change_selections_inner(autoscroll, true, cx, change)
 2770    }
 2771
 2772    pub fn change_selections_inner<R>(
 2773        &mut self,
 2774        autoscroll: Option<Autoscroll>,
 2775        request_completions: bool,
 2776        cx: &mut ViewContext<Self>,
 2777        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2778    ) -> R {
 2779        let old_cursor_position = self.selections.newest_anchor().head();
 2780        self.push_to_selection_history();
 2781
 2782        let (changed, result) = self.selections.change_with(cx, change);
 2783
 2784        if changed {
 2785            if let Some(autoscroll) = autoscroll {
 2786                self.request_autoscroll(autoscroll, cx);
 2787            }
 2788            self.selections_did_change(true, &old_cursor_position, request_completions, cx);
 2789
 2790            if self.should_open_signature_help_automatically(
 2791                &old_cursor_position,
 2792                self.signature_help_state.backspace_pressed(),
 2793                cx,
 2794            ) {
 2795                self.show_signature_help(&ShowSignatureHelp, cx);
 2796            }
 2797            self.signature_help_state.set_backspace_pressed(false);
 2798        }
 2799
 2800        result
 2801    }
 2802
 2803    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2804    where
 2805        I: IntoIterator<Item = (Range<S>, T)>,
 2806        S: ToOffset,
 2807        T: Into<Arc<str>>,
 2808    {
 2809        if self.read_only(cx) {
 2810            return;
 2811        }
 2812
 2813        self.buffer
 2814            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2815    }
 2816
 2817    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2818    where
 2819        I: IntoIterator<Item = (Range<S>, T)>,
 2820        S: ToOffset,
 2821        T: Into<Arc<str>>,
 2822    {
 2823        if self.read_only(cx) {
 2824            return;
 2825        }
 2826
 2827        self.buffer.update(cx, |buffer, cx| {
 2828            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2829        });
 2830    }
 2831
 2832    pub fn edit_with_block_indent<I, S, T>(
 2833        &mut self,
 2834        edits: I,
 2835        original_indent_columns: Vec<u32>,
 2836        cx: &mut ViewContext<Self>,
 2837    ) where
 2838        I: IntoIterator<Item = (Range<S>, T)>,
 2839        S: ToOffset,
 2840        T: Into<Arc<str>>,
 2841    {
 2842        if self.read_only(cx) {
 2843            return;
 2844        }
 2845
 2846        self.buffer.update(cx, |buffer, cx| {
 2847            buffer.edit(
 2848                edits,
 2849                Some(AutoindentMode::Block {
 2850                    original_indent_columns,
 2851                }),
 2852                cx,
 2853            )
 2854        });
 2855    }
 2856
 2857    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
 2858        self.hide_context_menu(cx);
 2859
 2860        match phase {
 2861            SelectPhase::Begin {
 2862                position,
 2863                add,
 2864                click_count,
 2865            } => self.begin_selection(position, add, click_count, cx),
 2866            SelectPhase::BeginColumnar {
 2867                position,
 2868                goal_column,
 2869                reset,
 2870            } => self.begin_columnar_selection(position, goal_column, reset, cx),
 2871            SelectPhase::Extend {
 2872                position,
 2873                click_count,
 2874            } => self.extend_selection(position, click_count, cx),
 2875            SelectPhase::Update {
 2876                position,
 2877                goal_column,
 2878                scroll_delta,
 2879            } => self.update_selection(position, goal_column, scroll_delta, cx),
 2880            SelectPhase::End => self.end_selection(cx),
 2881        }
 2882    }
 2883
 2884    fn extend_selection(
 2885        &mut self,
 2886        position: DisplayPoint,
 2887        click_count: usize,
 2888        cx: &mut ViewContext<Self>,
 2889    ) {
 2890        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2891        let tail = self.selections.newest::<usize>(cx).tail();
 2892        self.begin_selection(position, false, click_count, cx);
 2893
 2894        let position = position.to_offset(&display_map, Bias::Left);
 2895        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2896
 2897        let mut pending_selection = self
 2898            .selections
 2899            .pending_anchor()
 2900            .expect("extend_selection not called with pending selection");
 2901        if position >= tail {
 2902            pending_selection.start = tail_anchor;
 2903        } else {
 2904            pending_selection.end = tail_anchor;
 2905            pending_selection.reversed = true;
 2906        }
 2907
 2908        let mut pending_mode = self.selections.pending_mode().unwrap();
 2909        match &mut pending_mode {
 2910            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2911            _ => {}
 2912        }
 2913
 2914        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 2915            s.set_pending(pending_selection, pending_mode)
 2916        });
 2917    }
 2918
 2919    fn begin_selection(
 2920        &mut self,
 2921        position: DisplayPoint,
 2922        add: bool,
 2923        click_count: usize,
 2924        cx: &mut ViewContext<Self>,
 2925    ) {
 2926        if !self.focus_handle.is_focused(cx) {
 2927            self.last_focused_descendant = None;
 2928            cx.focus(&self.focus_handle);
 2929        }
 2930
 2931        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2932        let buffer = &display_map.buffer_snapshot;
 2933        let newest_selection = self.selections.newest_anchor().clone();
 2934        let position = display_map.clip_point(position, Bias::Left);
 2935
 2936        let start;
 2937        let end;
 2938        let mode;
 2939        let mut auto_scroll;
 2940        match click_count {
 2941            1 => {
 2942                start = buffer.anchor_before(position.to_point(&display_map));
 2943                end = start;
 2944                mode = SelectMode::Character;
 2945                auto_scroll = true;
 2946            }
 2947            2 => {
 2948                let range = movement::surrounding_word(&display_map, position);
 2949                start = buffer.anchor_before(range.start.to_point(&display_map));
 2950                end = buffer.anchor_before(range.end.to_point(&display_map));
 2951                mode = SelectMode::Word(start..end);
 2952                auto_scroll = true;
 2953            }
 2954            3 => {
 2955                let position = display_map
 2956                    .clip_point(position, Bias::Left)
 2957                    .to_point(&display_map);
 2958                let line_start = display_map.prev_line_boundary(position).0;
 2959                let next_line_start = buffer.clip_point(
 2960                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2961                    Bias::Left,
 2962                );
 2963                start = buffer.anchor_before(line_start);
 2964                end = buffer.anchor_before(next_line_start);
 2965                mode = SelectMode::Line(start..end);
 2966                auto_scroll = true;
 2967            }
 2968            _ => {
 2969                start = buffer.anchor_before(0);
 2970                end = buffer.anchor_before(buffer.len());
 2971                mode = SelectMode::All;
 2972                auto_scroll = false;
 2973            }
 2974        }
 2975        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2976
 2977        let point_to_delete: Option<usize> = {
 2978            let selected_points: Vec<Selection<Point>> =
 2979                self.selections.disjoint_in_range(start..end, cx);
 2980
 2981            if !add || click_count > 1 {
 2982                None
 2983            } else if !selected_points.is_empty() {
 2984                Some(selected_points[0].id)
 2985            } else {
 2986                let clicked_point_already_selected =
 2987                    self.selections.disjoint.iter().find(|selection| {
 2988                        selection.start.to_point(buffer) == start.to_point(buffer)
 2989                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2990                    });
 2991
 2992                clicked_point_already_selected.map(|selection| selection.id)
 2993            }
 2994        };
 2995
 2996        let selections_count = self.selections.count();
 2997
 2998        self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
 2999            if let Some(point_to_delete) = point_to_delete {
 3000                s.delete(point_to_delete);
 3001
 3002                if selections_count == 1 {
 3003                    s.set_pending_anchor_range(start..end, mode);
 3004                }
 3005            } else {
 3006                if !add {
 3007                    s.clear_disjoint();
 3008                } else if click_count > 1 {
 3009                    s.delete(newest_selection.id)
 3010                }
 3011
 3012                s.set_pending_anchor_range(start..end, mode);
 3013            }
 3014        });
 3015    }
 3016
 3017    fn begin_columnar_selection(
 3018        &mut self,
 3019        position: DisplayPoint,
 3020        goal_column: u32,
 3021        reset: bool,
 3022        cx: &mut ViewContext<Self>,
 3023    ) {
 3024        if !self.focus_handle.is_focused(cx) {
 3025            self.last_focused_descendant = None;
 3026            cx.focus(&self.focus_handle);
 3027        }
 3028
 3029        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 3030
 3031        if reset {
 3032            let pointer_position = display_map
 3033                .buffer_snapshot
 3034                .anchor_before(position.to_point(&display_map));
 3035
 3036            self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 3037                s.clear_disjoint();
 3038                s.set_pending_anchor_range(
 3039                    pointer_position..pointer_position,
 3040                    SelectMode::Character,
 3041                );
 3042            });
 3043        }
 3044
 3045        let tail = self.selections.newest::<Point>(cx).tail();
 3046        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 3047
 3048        if !reset {
 3049            self.select_columns(
 3050                tail.to_display_point(&display_map),
 3051                position,
 3052                goal_column,
 3053                &display_map,
 3054                cx,
 3055            );
 3056        }
 3057    }
 3058
 3059    fn update_selection(
 3060        &mut self,
 3061        position: DisplayPoint,
 3062        goal_column: u32,
 3063        scroll_delta: gpui::Point<f32>,
 3064        cx: &mut ViewContext<Self>,
 3065    ) {
 3066        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 3067
 3068        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 3069            let tail = tail.to_display_point(&display_map);
 3070            self.select_columns(tail, position, goal_column, &display_map, cx);
 3071        } else if let Some(mut pending) = self.selections.pending_anchor() {
 3072            let buffer = self.buffer.read(cx).snapshot(cx);
 3073            let head;
 3074            let tail;
 3075            let mode = self.selections.pending_mode().unwrap();
 3076            match &mode {
 3077                SelectMode::Character => {
 3078                    head = position.to_point(&display_map);
 3079                    tail = pending.tail().to_point(&buffer);
 3080                }
 3081                SelectMode::Word(original_range) => {
 3082                    let original_display_range = original_range.start.to_display_point(&display_map)
 3083                        ..original_range.end.to_display_point(&display_map);
 3084                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 3085                        ..original_display_range.end.to_point(&display_map);
 3086                    if movement::is_inside_word(&display_map, position)
 3087                        || original_display_range.contains(&position)
 3088                    {
 3089                        let word_range = movement::surrounding_word(&display_map, position);
 3090                        if word_range.start < original_display_range.start {
 3091                            head = word_range.start.to_point(&display_map);
 3092                        } else {
 3093                            head = word_range.end.to_point(&display_map);
 3094                        }
 3095                    } else {
 3096                        head = position.to_point(&display_map);
 3097                    }
 3098
 3099                    if head <= original_buffer_range.start {
 3100                        tail = original_buffer_range.end;
 3101                    } else {
 3102                        tail = original_buffer_range.start;
 3103                    }
 3104                }
 3105                SelectMode::Line(original_range) => {
 3106                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 3107
 3108                    let position = display_map
 3109                        .clip_point(position, Bias::Left)
 3110                        .to_point(&display_map);
 3111                    let line_start = display_map.prev_line_boundary(position).0;
 3112                    let next_line_start = buffer.clip_point(
 3113                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 3114                        Bias::Left,
 3115                    );
 3116
 3117                    if line_start < original_range.start {
 3118                        head = line_start
 3119                    } else {
 3120                        head = next_line_start
 3121                    }
 3122
 3123                    if head <= original_range.start {
 3124                        tail = original_range.end;
 3125                    } else {
 3126                        tail = original_range.start;
 3127                    }
 3128                }
 3129                SelectMode::All => {
 3130                    return;
 3131                }
 3132            };
 3133
 3134            if head < tail {
 3135                pending.start = buffer.anchor_before(head);
 3136                pending.end = buffer.anchor_before(tail);
 3137                pending.reversed = true;
 3138            } else {
 3139                pending.start = buffer.anchor_before(tail);
 3140                pending.end = buffer.anchor_before(head);
 3141                pending.reversed = false;
 3142            }
 3143
 3144            self.change_selections(None, cx, |s| {
 3145                s.set_pending(pending, mode);
 3146            });
 3147        } else {
 3148            log::error!("update_selection dispatched with no pending selection");
 3149            return;
 3150        }
 3151
 3152        self.apply_scroll_delta(scroll_delta, cx);
 3153        cx.notify();
 3154    }
 3155
 3156    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 3157        self.columnar_selection_tail.take();
 3158        if self.selections.pending_anchor().is_some() {
 3159            let selections = self.selections.all::<usize>(cx);
 3160            self.change_selections(None, cx, |s| {
 3161                s.select(selections);
 3162                s.clear_pending();
 3163            });
 3164        }
 3165    }
 3166
 3167    fn select_columns(
 3168        &mut self,
 3169        tail: DisplayPoint,
 3170        head: DisplayPoint,
 3171        goal_column: u32,
 3172        display_map: &DisplaySnapshot,
 3173        cx: &mut ViewContext<Self>,
 3174    ) {
 3175        let start_row = cmp::min(tail.row(), head.row());
 3176        let end_row = cmp::max(tail.row(), head.row());
 3177        let start_column = cmp::min(tail.column(), goal_column);
 3178        let end_column = cmp::max(tail.column(), goal_column);
 3179        let reversed = start_column < tail.column();
 3180
 3181        let selection_ranges = (start_row.0..=end_row.0)
 3182            .map(DisplayRow)
 3183            .filter_map(|row| {
 3184                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 3185                    let start = display_map
 3186                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 3187                        .to_point(display_map);
 3188                    let end = display_map
 3189                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 3190                        .to_point(display_map);
 3191                    if reversed {
 3192                        Some(end..start)
 3193                    } else {
 3194                        Some(start..end)
 3195                    }
 3196                } else {
 3197                    None
 3198                }
 3199            })
 3200            .collect::<Vec<_>>();
 3201
 3202        self.change_selections(None, cx, |s| {
 3203            s.select_ranges(selection_ranges);
 3204        });
 3205        cx.notify();
 3206    }
 3207
 3208    pub fn has_pending_nonempty_selection(&self) -> bool {
 3209        let pending_nonempty_selection = match self.selections.pending_anchor() {
 3210            Some(Selection { start, end, .. }) => start != end,
 3211            None => false,
 3212        };
 3213
 3214        pending_nonempty_selection
 3215            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 3216    }
 3217
 3218    pub fn has_pending_selection(&self) -> bool {
 3219        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 3220    }
 3221
 3222    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 3223        if self.clear_expanded_diff_hunks(cx) {
 3224            cx.notify();
 3225            return;
 3226        }
 3227        if self.dismiss_menus_and_popups(true, cx) {
 3228            return;
 3229        }
 3230
 3231        if self.mode == EditorMode::Full
 3232            && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
 3233        {
 3234            return;
 3235        }
 3236
 3237        cx.propagate();
 3238    }
 3239
 3240    pub fn dismiss_menus_and_popups(
 3241        &mut self,
 3242        should_report_inline_completion_event: bool,
 3243        cx: &mut ViewContext<Self>,
 3244    ) -> bool {
 3245        if self.take_rename(false, cx).is_some() {
 3246            return true;
 3247        }
 3248
 3249        if hide_hover(self, cx) {
 3250            return true;
 3251        }
 3252
 3253        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 3254            return true;
 3255        }
 3256
 3257        if self.hide_context_menu(cx).is_some() {
 3258            return true;
 3259        }
 3260
 3261        if self.mouse_context_menu.take().is_some() {
 3262            return true;
 3263        }
 3264
 3265        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 3266            return true;
 3267        }
 3268
 3269        if self.snippet_stack.pop().is_some() {
 3270            return true;
 3271        }
 3272
 3273        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 3274            self.dismiss_diagnostics(cx);
 3275            return true;
 3276        }
 3277
 3278        false
 3279    }
 3280
 3281    fn linked_editing_ranges_for(
 3282        &self,
 3283        selection: Range<text::Anchor>,
 3284        cx: &AppContext,
 3285    ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
 3286        if self.linked_edit_ranges.is_empty() {
 3287            return None;
 3288        }
 3289        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 3290            selection.end.buffer_id.and_then(|end_buffer_id| {
 3291                if selection.start.buffer_id != Some(end_buffer_id) {
 3292                    return None;
 3293                }
 3294                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 3295                let snapshot = buffer.read(cx).snapshot();
 3296                self.linked_edit_ranges
 3297                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 3298                    .map(|ranges| (ranges, snapshot, buffer))
 3299            })?;
 3300        use text::ToOffset as TO;
 3301        // find offset from the start of current range to current cursor position
 3302        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 3303
 3304        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 3305        let start_difference = start_offset - start_byte_offset;
 3306        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 3307        let end_difference = end_offset - start_byte_offset;
 3308        // Current range has associated linked ranges.
 3309        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3310        for range in linked_ranges.iter() {
 3311            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 3312            let end_offset = start_offset + end_difference;
 3313            let start_offset = start_offset + start_difference;
 3314            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 3315                continue;
 3316            }
 3317            if self.selections.disjoint_anchor_ranges().iter().any(|s| {
 3318                if s.start.buffer_id != selection.start.buffer_id
 3319                    || s.end.buffer_id != selection.end.buffer_id
 3320                {
 3321                    return false;
 3322                }
 3323                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 3324                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 3325            }) {
 3326                continue;
 3327            }
 3328            let start = buffer_snapshot.anchor_after(start_offset);
 3329            let end = buffer_snapshot.anchor_after(end_offset);
 3330            linked_edits
 3331                .entry(buffer.clone())
 3332                .or_default()
 3333                .push(start..end);
 3334        }
 3335        Some(linked_edits)
 3336    }
 3337
 3338    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3339        let text: Arc<str> = text.into();
 3340
 3341        if self.read_only(cx) {
 3342            return;
 3343        }
 3344
 3345        let selections = self.selections.all_adjusted(cx);
 3346        let mut bracket_inserted = false;
 3347        let mut edits = Vec::new();
 3348        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3349        let mut new_selections = Vec::with_capacity(selections.len());
 3350        let mut new_autoclose_regions = Vec::new();
 3351        let snapshot = self.buffer.read(cx).read(cx);
 3352
 3353        for (selection, autoclose_region) in
 3354            self.selections_with_autoclose_regions(selections, &snapshot)
 3355        {
 3356            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 3357                // Determine if the inserted text matches the opening or closing
 3358                // bracket of any of this language's bracket pairs.
 3359                let mut bracket_pair = None;
 3360                let mut is_bracket_pair_start = false;
 3361                let mut is_bracket_pair_end = false;
 3362                if !text.is_empty() {
 3363                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 3364                    //  and they are removing the character that triggered IME popup.
 3365                    for (pair, enabled) in scope.brackets() {
 3366                        if !pair.close && !pair.surround {
 3367                            continue;
 3368                        }
 3369
 3370                        if enabled && pair.start.ends_with(text.as_ref()) {
 3371                            let prefix_len = pair.start.len() - text.len();
 3372                            let preceding_text_matches_prefix = prefix_len == 0
 3373                                || (selection.start.column >= (prefix_len as u32)
 3374                                    && snapshot.contains_str_at(
 3375                                        Point::new(
 3376                                            selection.start.row,
 3377                                            selection.start.column - (prefix_len as u32),
 3378                                        ),
 3379                                        &pair.start[..prefix_len],
 3380                                    ));
 3381                            if preceding_text_matches_prefix {
 3382                                bracket_pair = Some(pair.clone());
 3383                                is_bracket_pair_start = true;
 3384                                break;
 3385                            }
 3386                        }
 3387                        if pair.end.as_str() == text.as_ref() {
 3388                            bracket_pair = Some(pair.clone());
 3389                            is_bracket_pair_end = true;
 3390                            break;
 3391                        }
 3392                    }
 3393                }
 3394
 3395                if let Some(bracket_pair) = bracket_pair {
 3396                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 3397                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 3398                    let auto_surround =
 3399                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 3400                    if selection.is_empty() {
 3401                        if is_bracket_pair_start {
 3402                            // If the inserted text is a suffix of an opening bracket and the
 3403                            // selection is preceded by the rest of the opening bracket, then
 3404                            // insert the closing bracket.
 3405                            let following_text_allows_autoclose = snapshot
 3406                                .chars_at(selection.start)
 3407                                .next()
 3408                                .map_or(true, |c| scope.should_autoclose_before(c));
 3409
 3410                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 3411                                && bracket_pair.start.len() == 1
 3412                            {
 3413                                let target = bracket_pair.start.chars().next().unwrap();
 3414                                let current_line_count = snapshot
 3415                                    .reversed_chars_at(selection.start)
 3416                                    .take_while(|&c| c != '\n')
 3417                                    .filter(|&c| c == target)
 3418                                    .count();
 3419                                current_line_count % 2 == 1
 3420                            } else {
 3421                                false
 3422                            };
 3423
 3424                            if autoclose
 3425                                && bracket_pair.close
 3426                                && following_text_allows_autoclose
 3427                                && !is_closing_quote
 3428                            {
 3429                                let anchor = snapshot.anchor_before(selection.end);
 3430                                new_selections.push((selection.map(|_| anchor), text.len()));
 3431                                new_autoclose_regions.push((
 3432                                    anchor,
 3433                                    text.len(),
 3434                                    selection.id,
 3435                                    bracket_pair.clone(),
 3436                                ));
 3437                                edits.push((
 3438                                    selection.range(),
 3439                                    format!("{}{}", text, bracket_pair.end).into(),
 3440                                ));
 3441                                bracket_inserted = true;
 3442                                continue;
 3443                            }
 3444                        }
 3445
 3446                        if let Some(region) = autoclose_region {
 3447                            // If the selection is followed by an auto-inserted closing bracket,
 3448                            // then don't insert that closing bracket again; just move the selection
 3449                            // past the closing bracket.
 3450                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3451                                && text.as_ref() == region.pair.end.as_str();
 3452                            if should_skip {
 3453                                let anchor = snapshot.anchor_after(selection.end);
 3454                                new_selections
 3455                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3456                                continue;
 3457                            }
 3458                        }
 3459
 3460                        let always_treat_brackets_as_autoclosed = snapshot
 3461                            .settings_at(selection.start, cx)
 3462                            .always_treat_brackets_as_autoclosed;
 3463                        if always_treat_brackets_as_autoclosed
 3464                            && is_bracket_pair_end
 3465                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3466                        {
 3467                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3468                            // and the inserted text is a closing bracket and the selection is followed
 3469                            // by the closing bracket then move the selection past the closing bracket.
 3470                            let anchor = snapshot.anchor_after(selection.end);
 3471                            new_selections.push((selection.map(|_| anchor), text.len()));
 3472                            continue;
 3473                        }
 3474                    }
 3475                    // If an opening bracket is 1 character long and is typed while
 3476                    // text is selected, then surround that text with the bracket pair.
 3477                    else if auto_surround
 3478                        && bracket_pair.surround
 3479                        && is_bracket_pair_start
 3480                        && bracket_pair.start.chars().count() == 1
 3481                    {
 3482                        edits.push((selection.start..selection.start, text.clone()));
 3483                        edits.push((
 3484                            selection.end..selection.end,
 3485                            bracket_pair.end.as_str().into(),
 3486                        ));
 3487                        bracket_inserted = true;
 3488                        new_selections.push((
 3489                            Selection {
 3490                                id: selection.id,
 3491                                start: snapshot.anchor_after(selection.start),
 3492                                end: snapshot.anchor_before(selection.end),
 3493                                reversed: selection.reversed,
 3494                                goal: selection.goal,
 3495                            },
 3496                            0,
 3497                        ));
 3498                        continue;
 3499                    }
 3500                }
 3501            }
 3502
 3503            if self.auto_replace_emoji_shortcode
 3504                && selection.is_empty()
 3505                && text.as_ref().ends_with(':')
 3506            {
 3507                if let Some(possible_emoji_short_code) =
 3508                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3509                {
 3510                    if !possible_emoji_short_code.is_empty() {
 3511                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3512                            let emoji_shortcode_start = Point::new(
 3513                                selection.start.row,
 3514                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3515                            );
 3516
 3517                            // Remove shortcode from buffer
 3518                            edits.push((
 3519                                emoji_shortcode_start..selection.start,
 3520                                "".to_string().into(),
 3521                            ));
 3522                            new_selections.push((
 3523                                Selection {
 3524                                    id: selection.id,
 3525                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3526                                    end: snapshot.anchor_before(selection.start),
 3527                                    reversed: selection.reversed,
 3528                                    goal: selection.goal,
 3529                                },
 3530                                0,
 3531                            ));
 3532
 3533                            // Insert emoji
 3534                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3535                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3536                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3537
 3538                            continue;
 3539                        }
 3540                    }
 3541                }
 3542            }
 3543
 3544            // If not handling any auto-close operation, then just replace the selected
 3545            // text with the given input and move the selection to the end of the
 3546            // newly inserted text.
 3547            let anchor = snapshot.anchor_after(selection.end);
 3548            if !self.linked_edit_ranges.is_empty() {
 3549                let start_anchor = snapshot.anchor_before(selection.start);
 3550
 3551                let is_word_char = text.chars().next().map_or(true, |char| {
 3552                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3553                    classifier.is_word(char)
 3554                });
 3555
 3556                if is_word_char {
 3557                    if let Some(ranges) = self
 3558                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3559                    {
 3560                        for (buffer, edits) in ranges {
 3561                            linked_edits
 3562                                .entry(buffer.clone())
 3563                                .or_default()
 3564                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3565                        }
 3566                    }
 3567                }
 3568            }
 3569
 3570            new_selections.push((selection.map(|_| anchor), 0));
 3571            edits.push((selection.start..selection.end, text.clone()));
 3572        }
 3573
 3574        drop(snapshot);
 3575
 3576        self.transact(cx, |this, cx| {
 3577            this.buffer.update(cx, |buffer, cx| {
 3578                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3579            });
 3580            for (buffer, edits) in linked_edits {
 3581                buffer.update(cx, |buffer, cx| {
 3582                    let snapshot = buffer.snapshot();
 3583                    let edits = edits
 3584                        .into_iter()
 3585                        .map(|(range, text)| {
 3586                            use text::ToPoint as TP;
 3587                            let end_point = TP::to_point(&range.end, &snapshot);
 3588                            let start_point = TP::to_point(&range.start, &snapshot);
 3589                            (start_point..end_point, text)
 3590                        })
 3591                        .sorted_by_key(|(range, _)| range.start)
 3592                        .collect::<Vec<_>>();
 3593                    buffer.edit(edits, None, cx);
 3594                })
 3595            }
 3596            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3597            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3598            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3599            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3600                .zip(new_selection_deltas)
 3601                .map(|(selection, delta)| Selection {
 3602                    id: selection.id,
 3603                    start: selection.start + delta,
 3604                    end: selection.end + delta,
 3605                    reversed: selection.reversed,
 3606                    goal: SelectionGoal::None,
 3607                })
 3608                .collect::<Vec<_>>();
 3609
 3610            let mut i = 0;
 3611            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3612                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3613                let start = map.buffer_snapshot.anchor_before(position);
 3614                let end = map.buffer_snapshot.anchor_after(position);
 3615                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3616                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3617                        Ordering::Less => i += 1,
 3618                        Ordering::Greater => break,
 3619                        Ordering::Equal => {
 3620                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3621                                Ordering::Less => i += 1,
 3622                                Ordering::Equal => break,
 3623                                Ordering::Greater => break,
 3624                            }
 3625                        }
 3626                    }
 3627                }
 3628                this.autoclose_regions.insert(
 3629                    i,
 3630                    AutocloseRegion {
 3631                        selection_id,
 3632                        range: start..end,
 3633                        pair,
 3634                    },
 3635                );
 3636            }
 3637
 3638            let had_active_inline_completion = this.has_active_inline_completion(cx);
 3639            this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
 3640                s.select(new_selections)
 3641            });
 3642
 3643            if !bracket_inserted {
 3644                if let Some(on_type_format_task) =
 3645                    this.trigger_on_type_formatting(text.to_string(), cx)
 3646                {
 3647                    on_type_format_task.detach_and_log_err(cx);
 3648                }
 3649            }
 3650
 3651            let editor_settings = EditorSettings::get_global(cx);
 3652            if bracket_inserted
 3653                && (editor_settings.auto_signature_help
 3654                    || editor_settings.show_signature_help_after_edits)
 3655            {
 3656                this.show_signature_help(&ShowSignatureHelp, cx);
 3657            }
 3658
 3659            let trigger_in_words = !had_active_inline_completion;
 3660            this.trigger_completion_on_input(&text, trigger_in_words, cx);
 3661            linked_editing_ranges::refresh_linked_ranges(this, cx);
 3662            this.refresh_inline_completion(true, false, cx);
 3663        });
 3664    }
 3665
 3666    fn find_possible_emoji_shortcode_at_position(
 3667        snapshot: &MultiBufferSnapshot,
 3668        position: Point,
 3669    ) -> Option<String> {
 3670        let mut chars = Vec::new();
 3671        let mut found_colon = false;
 3672        for char in snapshot.reversed_chars_at(position).take(100) {
 3673            // Found a possible emoji shortcode in the middle of the buffer
 3674            if found_colon {
 3675                if char.is_whitespace() {
 3676                    chars.reverse();
 3677                    return Some(chars.iter().collect());
 3678                }
 3679                // If the previous character is not a whitespace, we are in the middle of a word
 3680                // and we only want to complete the shortcode if the word is made up of other emojis
 3681                let mut containing_word = String::new();
 3682                for ch in snapshot
 3683                    .reversed_chars_at(position)
 3684                    .skip(chars.len() + 1)
 3685                    .take(100)
 3686                {
 3687                    if ch.is_whitespace() {
 3688                        break;
 3689                    }
 3690                    containing_word.push(ch);
 3691                }
 3692                let containing_word = containing_word.chars().rev().collect::<String>();
 3693                if util::word_consists_of_emojis(containing_word.as_str()) {
 3694                    chars.reverse();
 3695                    return Some(chars.iter().collect());
 3696                }
 3697            }
 3698
 3699            if char.is_whitespace() || !char.is_ascii() {
 3700                return None;
 3701            }
 3702            if char == ':' {
 3703                found_colon = true;
 3704            } else {
 3705                chars.push(char);
 3706            }
 3707        }
 3708        // Found a possible emoji shortcode at the beginning of the buffer
 3709        chars.reverse();
 3710        Some(chars.iter().collect())
 3711    }
 3712
 3713    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 3714        self.transact(cx, |this, cx| {
 3715            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3716                let selections = this.selections.all::<usize>(cx);
 3717                let multi_buffer = this.buffer.read(cx);
 3718                let buffer = multi_buffer.snapshot(cx);
 3719                selections
 3720                    .iter()
 3721                    .map(|selection| {
 3722                        let start_point = selection.start.to_point(&buffer);
 3723                        let mut indent =
 3724                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3725                        indent.len = cmp::min(indent.len, start_point.column);
 3726                        let start = selection.start;
 3727                        let end = selection.end;
 3728                        let selection_is_empty = start == end;
 3729                        let language_scope = buffer.language_scope_at(start);
 3730                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3731                            &language_scope
 3732                        {
 3733                            let leading_whitespace_len = buffer
 3734                                .reversed_chars_at(start)
 3735                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3736                                .map(|c| c.len_utf8())
 3737                                .sum::<usize>();
 3738
 3739                            let trailing_whitespace_len = buffer
 3740                                .chars_at(end)
 3741                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3742                                .map(|c| c.len_utf8())
 3743                                .sum::<usize>();
 3744
 3745                            let insert_extra_newline =
 3746                                language.brackets().any(|(pair, enabled)| {
 3747                                    let pair_start = pair.start.trim_end();
 3748                                    let pair_end = pair.end.trim_start();
 3749
 3750                                    enabled
 3751                                        && pair.newline
 3752                                        && buffer.contains_str_at(
 3753                                            end + trailing_whitespace_len,
 3754                                            pair_end,
 3755                                        )
 3756                                        && buffer.contains_str_at(
 3757                                            (start - leading_whitespace_len)
 3758                                                .saturating_sub(pair_start.len()),
 3759                                            pair_start,
 3760                                        )
 3761                                });
 3762
 3763                            // Comment extension on newline is allowed only for cursor selections
 3764                            let comment_delimiter = maybe!({
 3765                                if !selection_is_empty {
 3766                                    return None;
 3767                                }
 3768
 3769                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3770                                    return None;
 3771                                }
 3772
 3773                                let delimiters = language.line_comment_prefixes();
 3774                                let max_len_of_delimiter =
 3775                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3776                                let (snapshot, range) =
 3777                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3778
 3779                                let mut index_of_first_non_whitespace = 0;
 3780                                let comment_candidate = snapshot
 3781                                    .chars_for_range(range)
 3782                                    .skip_while(|c| {
 3783                                        let should_skip = c.is_whitespace();
 3784                                        if should_skip {
 3785                                            index_of_first_non_whitespace += 1;
 3786                                        }
 3787                                        should_skip
 3788                                    })
 3789                                    .take(max_len_of_delimiter)
 3790                                    .collect::<String>();
 3791                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3792                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3793                                })?;
 3794                                let cursor_is_placed_after_comment_marker =
 3795                                    index_of_first_non_whitespace + comment_prefix.len()
 3796                                        <= start_point.column as usize;
 3797                                if cursor_is_placed_after_comment_marker {
 3798                                    Some(comment_prefix.clone())
 3799                                } else {
 3800                                    None
 3801                                }
 3802                            });
 3803                            (comment_delimiter, insert_extra_newline)
 3804                        } else {
 3805                            (None, false)
 3806                        };
 3807
 3808                        let capacity_for_delimiter = comment_delimiter
 3809                            .as_deref()
 3810                            .map(str::len)
 3811                            .unwrap_or_default();
 3812                        let mut new_text =
 3813                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3814                        new_text.push('\n');
 3815                        new_text.extend(indent.chars());
 3816                        if let Some(delimiter) = &comment_delimiter {
 3817                            new_text.push_str(delimiter);
 3818                        }
 3819                        if insert_extra_newline {
 3820                            new_text = new_text.repeat(2);
 3821                        }
 3822
 3823                        let anchor = buffer.anchor_after(end);
 3824                        let new_selection = selection.map(|_| anchor);
 3825                        (
 3826                            (start..end, new_text),
 3827                            (insert_extra_newline, new_selection),
 3828                        )
 3829                    })
 3830                    .unzip()
 3831            };
 3832
 3833            this.edit_with_autoindent(edits, cx);
 3834            let buffer = this.buffer.read(cx).snapshot(cx);
 3835            let new_selections = selection_fixup_info
 3836                .into_iter()
 3837                .map(|(extra_newline_inserted, new_selection)| {
 3838                    let mut cursor = new_selection.end.to_point(&buffer);
 3839                    if extra_newline_inserted {
 3840                        cursor.row -= 1;
 3841                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3842                    }
 3843                    new_selection.map(|_| cursor)
 3844                })
 3845                .collect();
 3846
 3847            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3848            this.refresh_inline_completion(true, false, cx);
 3849        });
 3850    }
 3851
 3852    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3853        let buffer = self.buffer.read(cx);
 3854        let snapshot = buffer.snapshot(cx);
 3855
 3856        let mut edits = Vec::new();
 3857        let mut rows = Vec::new();
 3858
 3859        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3860            let cursor = selection.head();
 3861            let row = cursor.row;
 3862
 3863            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3864
 3865            let newline = "\n".to_string();
 3866            edits.push((start_of_line..start_of_line, newline));
 3867
 3868            rows.push(row + rows_inserted as u32);
 3869        }
 3870
 3871        self.transact(cx, |editor, cx| {
 3872            editor.edit(edits, cx);
 3873
 3874            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3875                let mut index = 0;
 3876                s.move_cursors_with(|map, _, _| {
 3877                    let row = rows[index];
 3878                    index += 1;
 3879
 3880                    let point = Point::new(row, 0);
 3881                    let boundary = map.next_line_boundary(point).1;
 3882                    let clipped = map.clip_point(boundary, Bias::Left);
 3883
 3884                    (clipped, SelectionGoal::None)
 3885                });
 3886            });
 3887
 3888            let mut indent_edits = Vec::new();
 3889            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3890            for row in rows {
 3891                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3892                for (row, indent) in indents {
 3893                    if indent.len == 0 {
 3894                        continue;
 3895                    }
 3896
 3897                    let text = match indent.kind {
 3898                        IndentKind::Space => " ".repeat(indent.len as usize),
 3899                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3900                    };
 3901                    let point = Point::new(row.0, 0);
 3902                    indent_edits.push((point..point, text));
 3903                }
 3904            }
 3905            editor.edit(indent_edits, cx);
 3906        });
 3907    }
 3908
 3909    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3910        let buffer = self.buffer.read(cx);
 3911        let snapshot = buffer.snapshot(cx);
 3912
 3913        let mut edits = Vec::new();
 3914        let mut rows = Vec::new();
 3915        let mut rows_inserted = 0;
 3916
 3917        for selection in self.selections.all_adjusted(cx) {
 3918            let cursor = selection.head();
 3919            let row = cursor.row;
 3920
 3921            let point = Point::new(row + 1, 0);
 3922            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3923
 3924            let newline = "\n".to_string();
 3925            edits.push((start_of_line..start_of_line, newline));
 3926
 3927            rows_inserted += 1;
 3928            rows.push(row + rows_inserted);
 3929        }
 3930
 3931        self.transact(cx, |editor, cx| {
 3932            editor.edit(edits, cx);
 3933
 3934            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3935                let mut index = 0;
 3936                s.move_cursors_with(|map, _, _| {
 3937                    let row = rows[index];
 3938                    index += 1;
 3939
 3940                    let point = Point::new(row, 0);
 3941                    let boundary = map.next_line_boundary(point).1;
 3942                    let clipped = map.clip_point(boundary, Bias::Left);
 3943
 3944                    (clipped, SelectionGoal::None)
 3945                });
 3946            });
 3947
 3948            let mut indent_edits = Vec::new();
 3949            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3950            for row in rows {
 3951                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3952                for (row, indent) in indents {
 3953                    if indent.len == 0 {
 3954                        continue;
 3955                    }
 3956
 3957                    let text = match indent.kind {
 3958                        IndentKind::Space => " ".repeat(indent.len as usize),
 3959                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3960                    };
 3961                    let point = Point::new(row.0, 0);
 3962                    indent_edits.push((point..point, text));
 3963                }
 3964            }
 3965            editor.edit(indent_edits, cx);
 3966        });
 3967    }
 3968
 3969    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3970        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3971            original_indent_columns: Vec::new(),
 3972        });
 3973        self.insert_with_autoindent_mode(text, autoindent, cx);
 3974    }
 3975
 3976    fn insert_with_autoindent_mode(
 3977        &mut self,
 3978        text: &str,
 3979        autoindent_mode: Option<AutoindentMode>,
 3980        cx: &mut ViewContext<Self>,
 3981    ) {
 3982        if self.read_only(cx) {
 3983            return;
 3984        }
 3985
 3986        let text: Arc<str> = text.into();
 3987        self.transact(cx, |this, cx| {
 3988            let old_selections = this.selections.all_adjusted(cx);
 3989            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3990                let anchors = {
 3991                    let snapshot = buffer.read(cx);
 3992                    old_selections
 3993                        .iter()
 3994                        .map(|s| {
 3995                            let anchor = snapshot.anchor_after(s.head());
 3996                            s.map(|_| anchor)
 3997                        })
 3998                        .collect::<Vec<_>>()
 3999                };
 4000                buffer.edit(
 4001                    old_selections
 4002                        .iter()
 4003                        .map(|s| (s.start..s.end, text.clone())),
 4004                    autoindent_mode,
 4005                    cx,
 4006                );
 4007                anchors
 4008            });
 4009
 4010            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 4011                s.select_anchors(selection_anchors);
 4012            })
 4013        });
 4014    }
 4015
 4016    fn trigger_completion_on_input(
 4017        &mut self,
 4018        text: &str,
 4019        trigger_in_words: bool,
 4020        cx: &mut ViewContext<Self>,
 4021    ) {
 4022        if self.is_completion_trigger(text, trigger_in_words, cx) {
 4023            self.show_completions(
 4024                &ShowCompletions {
 4025                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 4026                },
 4027                cx,
 4028            );
 4029        } else {
 4030            self.hide_context_menu(cx);
 4031        }
 4032    }
 4033
 4034    fn is_completion_trigger(
 4035        &self,
 4036        text: &str,
 4037        trigger_in_words: bool,
 4038        cx: &mut ViewContext<Self>,
 4039    ) -> bool {
 4040        let position = self.selections.newest_anchor().head();
 4041        let multibuffer = self.buffer.read(cx);
 4042        let Some(buffer) = position
 4043            .buffer_id
 4044            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 4045        else {
 4046            return false;
 4047        };
 4048
 4049        if let Some(completion_provider) = &self.completion_provider {
 4050            completion_provider.is_completion_trigger(
 4051                &buffer,
 4052                position.text_anchor,
 4053                text,
 4054                trigger_in_words,
 4055                cx,
 4056            )
 4057        } else {
 4058            false
 4059        }
 4060    }
 4061
 4062    /// If any empty selections is touching the start of its innermost containing autoclose
 4063    /// region, expand it to select the brackets.
 4064    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 4065        let selections = self.selections.all::<usize>(cx);
 4066        let buffer = self.buffer.read(cx).read(cx);
 4067        let new_selections = self
 4068            .selections_with_autoclose_regions(selections, &buffer)
 4069            .map(|(mut selection, region)| {
 4070                if !selection.is_empty() {
 4071                    return selection;
 4072                }
 4073
 4074                if let Some(region) = region {
 4075                    let mut range = region.range.to_offset(&buffer);
 4076                    if selection.start == range.start && range.start >= region.pair.start.len() {
 4077                        range.start -= region.pair.start.len();
 4078                        if buffer.contains_str_at(range.start, &region.pair.start)
 4079                            && buffer.contains_str_at(range.end, &region.pair.end)
 4080                        {
 4081                            range.end += region.pair.end.len();
 4082                            selection.start = range.start;
 4083                            selection.end = range.end;
 4084
 4085                            return selection;
 4086                        }
 4087                    }
 4088                }
 4089
 4090                let always_treat_brackets_as_autoclosed = buffer
 4091                    .settings_at(selection.start, cx)
 4092                    .always_treat_brackets_as_autoclosed;
 4093
 4094                if !always_treat_brackets_as_autoclosed {
 4095                    return selection;
 4096                }
 4097
 4098                if let Some(scope) = buffer.language_scope_at(selection.start) {
 4099                    for (pair, enabled) in scope.brackets() {
 4100                        if !enabled || !pair.close {
 4101                            continue;
 4102                        }
 4103
 4104                        if buffer.contains_str_at(selection.start, &pair.end) {
 4105                            let pair_start_len = pair.start.len();
 4106                            if buffer.contains_str_at(
 4107                                selection.start.saturating_sub(pair_start_len),
 4108                                &pair.start,
 4109                            ) {
 4110                                selection.start -= pair_start_len;
 4111                                selection.end += pair.end.len();
 4112
 4113                                return selection;
 4114                            }
 4115                        }
 4116                    }
 4117                }
 4118
 4119                selection
 4120            })
 4121            .collect();
 4122
 4123        drop(buffer);
 4124        self.change_selections(None, cx, |selections| selections.select(new_selections));
 4125    }
 4126
 4127    /// Iterate the given selections, and for each one, find the smallest surrounding
 4128    /// autoclose region. This uses the ordering of the selections and the autoclose
 4129    /// regions to avoid repeated comparisons.
 4130    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 4131        &'a self,
 4132        selections: impl IntoIterator<Item = Selection<D>>,
 4133        buffer: &'a MultiBufferSnapshot,
 4134    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 4135        let mut i = 0;
 4136        let mut regions = self.autoclose_regions.as_slice();
 4137        selections.into_iter().map(move |selection| {
 4138            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 4139
 4140            let mut enclosing = None;
 4141            while let Some(pair_state) = regions.get(i) {
 4142                if pair_state.range.end.to_offset(buffer) < range.start {
 4143                    regions = &regions[i + 1..];
 4144                    i = 0;
 4145                } else if pair_state.range.start.to_offset(buffer) > range.end {
 4146                    break;
 4147                } else {
 4148                    if pair_state.selection_id == selection.id {
 4149                        enclosing = Some(pair_state);
 4150                    }
 4151                    i += 1;
 4152                }
 4153            }
 4154
 4155            (selection, enclosing)
 4156        })
 4157    }
 4158
 4159    /// Remove any autoclose regions that no longer contain their selection.
 4160    fn invalidate_autoclose_regions(
 4161        &mut self,
 4162        mut selections: &[Selection<Anchor>],
 4163        buffer: &MultiBufferSnapshot,
 4164    ) {
 4165        self.autoclose_regions.retain(|state| {
 4166            let mut i = 0;
 4167            while let Some(selection) = selections.get(i) {
 4168                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 4169                    selections = &selections[1..];
 4170                    continue;
 4171                }
 4172                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 4173                    break;
 4174                }
 4175                if selection.id == state.selection_id {
 4176                    return true;
 4177                } else {
 4178                    i += 1;
 4179                }
 4180            }
 4181            false
 4182        });
 4183    }
 4184
 4185    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 4186        let offset = position.to_offset(buffer);
 4187        let (word_range, kind) = buffer.surrounding_word(offset, true);
 4188        if offset > word_range.start && kind == Some(CharKind::Word) {
 4189            Some(
 4190                buffer
 4191                    .text_for_range(word_range.start..offset)
 4192                    .collect::<String>(),
 4193            )
 4194        } else {
 4195            None
 4196        }
 4197    }
 4198
 4199    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 4200        self.refresh_inlay_hints(
 4201            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 4202            cx,
 4203        );
 4204    }
 4205
 4206    pub fn inlay_hints_enabled(&self) -> bool {
 4207        self.inlay_hint_cache.enabled
 4208    }
 4209
 4210    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 4211        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 4212            return;
 4213        }
 4214
 4215        let reason_description = reason.description();
 4216        let ignore_debounce = matches!(
 4217            reason,
 4218            InlayHintRefreshReason::SettingsChange(_)
 4219                | InlayHintRefreshReason::Toggle(_)
 4220                | InlayHintRefreshReason::ExcerptsRemoved(_)
 4221        );
 4222        let (invalidate_cache, required_languages) = match reason {
 4223            InlayHintRefreshReason::Toggle(enabled) => {
 4224                self.inlay_hint_cache.enabled = enabled;
 4225                if enabled {
 4226                    (InvalidationStrategy::RefreshRequested, None)
 4227                } else {
 4228                    self.inlay_hint_cache.clear();
 4229                    self.splice_inlays(
 4230                        self.visible_inlay_hints(cx)
 4231                            .iter()
 4232                            .map(|inlay| inlay.id)
 4233                            .collect(),
 4234                        Vec::new(),
 4235                        cx,
 4236                    );
 4237                    return;
 4238                }
 4239            }
 4240            InlayHintRefreshReason::SettingsChange(new_settings) => {
 4241                match self.inlay_hint_cache.update_settings(
 4242                    &self.buffer,
 4243                    new_settings,
 4244                    self.visible_inlay_hints(cx),
 4245                    cx,
 4246                ) {
 4247                    ControlFlow::Break(Some(InlaySplice {
 4248                        to_remove,
 4249                        to_insert,
 4250                    })) => {
 4251                        self.splice_inlays(to_remove, to_insert, cx);
 4252                        return;
 4253                    }
 4254                    ControlFlow::Break(None) => return,
 4255                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 4256                }
 4257            }
 4258            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 4259                if let Some(InlaySplice {
 4260                    to_remove,
 4261                    to_insert,
 4262                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 4263                {
 4264                    self.splice_inlays(to_remove, to_insert, cx);
 4265                }
 4266                return;
 4267            }
 4268            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 4269            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 4270                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 4271            }
 4272            InlayHintRefreshReason::RefreshRequested => {
 4273                (InvalidationStrategy::RefreshRequested, None)
 4274            }
 4275        };
 4276
 4277        if let Some(InlaySplice {
 4278            to_remove,
 4279            to_insert,
 4280        }) = self.inlay_hint_cache.spawn_hint_refresh(
 4281            reason_description,
 4282            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 4283            invalidate_cache,
 4284            ignore_debounce,
 4285            cx,
 4286        ) {
 4287            self.splice_inlays(to_remove, to_insert, cx);
 4288        }
 4289    }
 4290
 4291    fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
 4292        self.display_map
 4293            .read(cx)
 4294            .current_inlays()
 4295            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 4296            .cloned()
 4297            .collect()
 4298    }
 4299
 4300    pub fn excerpts_for_inlay_hints_query(
 4301        &self,
 4302        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 4303        cx: &mut ViewContext<Editor>,
 4304    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 4305        let Some(project) = self.project.as_ref() else {
 4306            return HashMap::default();
 4307        };
 4308        let project = project.read(cx);
 4309        let multi_buffer = self.buffer().read(cx);
 4310        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 4311        let multi_buffer_visible_start = self
 4312            .scroll_manager
 4313            .anchor()
 4314            .anchor
 4315            .to_point(&multi_buffer_snapshot);
 4316        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 4317            multi_buffer_visible_start
 4318                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 4319            Bias::Left,
 4320        );
 4321        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 4322        multi_buffer
 4323            .range_to_buffer_ranges(multi_buffer_visible_range, cx)
 4324            .into_iter()
 4325            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 4326            .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
 4327                let buffer = buffer_handle.read(cx);
 4328                let buffer_file = project::File::from_dyn(buffer.file())?;
 4329                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 4330                let worktree_entry = buffer_worktree
 4331                    .read(cx)
 4332                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 4333                if worktree_entry.is_ignored {
 4334                    return None;
 4335                }
 4336
 4337                let language = buffer.language()?;
 4338                if let Some(restrict_to_languages) = restrict_to_languages {
 4339                    if !restrict_to_languages.contains(language) {
 4340                        return None;
 4341                    }
 4342                }
 4343                Some((
 4344                    excerpt_id,
 4345                    (
 4346                        buffer_handle,
 4347                        buffer.version().clone(),
 4348                        excerpt_visible_range,
 4349                    ),
 4350                ))
 4351            })
 4352            .collect()
 4353    }
 4354
 4355    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 4356        TextLayoutDetails {
 4357            text_system: cx.text_system().clone(),
 4358            editor_style: self.style.clone().unwrap(),
 4359            rem_size: cx.rem_size(),
 4360            scroll_anchor: self.scroll_manager.anchor(),
 4361            visible_rows: self.visible_line_count(),
 4362            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 4363        }
 4364    }
 4365
 4366    fn splice_inlays(
 4367        &self,
 4368        to_remove: Vec<InlayId>,
 4369        to_insert: Vec<Inlay>,
 4370        cx: &mut ViewContext<Self>,
 4371    ) {
 4372        self.display_map.update(cx, |display_map, cx| {
 4373            display_map.splice_inlays(to_remove, to_insert, cx);
 4374        });
 4375        cx.notify();
 4376    }
 4377
 4378    fn trigger_on_type_formatting(
 4379        &self,
 4380        input: String,
 4381        cx: &mut ViewContext<Self>,
 4382    ) -> Option<Task<Result<()>>> {
 4383        if input.len() != 1 {
 4384            return None;
 4385        }
 4386
 4387        let project = self.project.as_ref()?;
 4388        let position = self.selections.newest_anchor().head();
 4389        let (buffer, buffer_position) = self
 4390            .buffer
 4391            .read(cx)
 4392            .text_anchor_for_position(position, cx)?;
 4393
 4394        let settings = language_settings::language_settings(
 4395            buffer
 4396                .read(cx)
 4397                .language_at(buffer_position)
 4398                .map(|l| l.name()),
 4399            buffer.read(cx).file(),
 4400            cx,
 4401        );
 4402        if !settings.use_on_type_format {
 4403            return None;
 4404        }
 4405
 4406        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 4407        // hence we do LSP request & edit on host side only — add formats to host's history.
 4408        let push_to_lsp_host_history = true;
 4409        // If this is not the host, append its history with new edits.
 4410        let push_to_client_history = project.read(cx).is_via_collab();
 4411
 4412        let on_type_formatting = project.update(cx, |project, cx| {
 4413            project.on_type_format(
 4414                buffer.clone(),
 4415                buffer_position,
 4416                input,
 4417                push_to_lsp_host_history,
 4418                cx,
 4419            )
 4420        });
 4421        Some(cx.spawn(|editor, mut cx| async move {
 4422            if let Some(transaction) = on_type_formatting.await? {
 4423                if push_to_client_history {
 4424                    buffer
 4425                        .update(&mut cx, |buffer, _| {
 4426                            buffer.push_transaction(transaction, Instant::now());
 4427                        })
 4428                        .ok();
 4429                }
 4430                editor.update(&mut cx, |editor, cx| {
 4431                    editor.refresh_document_highlights(cx);
 4432                })?;
 4433            }
 4434            Ok(())
 4435        }))
 4436    }
 4437
 4438    pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
 4439        if self.pending_rename.is_some() {
 4440            return;
 4441        }
 4442
 4443        let Some(provider) = self.completion_provider.as_ref() else {
 4444            return;
 4445        };
 4446
 4447        if !self.snippet_stack.is_empty() && self.context_menu.read().as_ref().is_some() {
 4448            return;
 4449        }
 4450
 4451        let position = self.selections.newest_anchor().head();
 4452        let (buffer, buffer_position) =
 4453            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4454                output
 4455            } else {
 4456                return;
 4457            };
 4458
 4459        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4460        let is_followup_invoke = {
 4461            let context_menu_state = self.context_menu.read();
 4462            matches!(
 4463                context_menu_state.deref(),
 4464                Some(ContextMenu::Completions(_))
 4465            )
 4466        };
 4467        let trigger_kind = match (&options.trigger, is_followup_invoke) {
 4468            (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
 4469            (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4470                CompletionTriggerKind::TRIGGER_CHARACTER
 4471            }
 4472
 4473            _ => CompletionTriggerKind::INVOKED,
 4474        };
 4475        let completion_context = CompletionContext {
 4476            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 4477                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4478                    Some(String::from(trigger))
 4479                } else {
 4480                    None
 4481                }
 4482            }),
 4483            trigger_kind,
 4484        };
 4485        let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
 4486        let sort_completions = provider.sort_completions();
 4487
 4488        let id = post_inc(&mut self.next_completion_id);
 4489        let task = cx.spawn(|editor, mut cx| {
 4490            async move {
 4491                editor.update(&mut cx, |this, _| {
 4492                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4493                })?;
 4494                let completions = completions.await.log_err();
 4495                let menu = if let Some(completions) = completions {
 4496                    let mut menu = CompletionsMenu::new(
 4497                        id,
 4498                        sort_completions,
 4499                        position,
 4500                        buffer.clone(),
 4501                        completions.into(),
 4502                    );
 4503                    menu.filter(query.as_deref(), cx.background_executor().clone())
 4504                        .await;
 4505
 4506                    if menu.matches.is_empty() {
 4507                        None
 4508                    } else {
 4509                        Some(menu)
 4510                    }
 4511                } else {
 4512                    None
 4513                };
 4514
 4515                editor.update(&mut cx, |editor, cx| {
 4516                    let mut context_menu = editor.context_menu.write();
 4517                    match context_menu.as_ref() {
 4518                        None => {}
 4519
 4520                        Some(ContextMenu::Completions(prev_menu)) => {
 4521                            if prev_menu.id > id {
 4522                                return;
 4523                            }
 4524                        }
 4525
 4526                        _ => return,
 4527                    }
 4528
 4529                    if editor.focus_handle.is_focused(cx) && menu.is_some() {
 4530                        let mut menu = menu.unwrap();
 4531                        menu.resolve_selected_completion(editor.completion_provider.as_deref(), cx);
 4532                        *context_menu = Some(ContextMenu::Completions(menu));
 4533                        drop(context_menu);
 4534                        editor.discard_inline_completion(false, cx);
 4535                        cx.notify();
 4536                    } else if editor.completion_tasks.len() <= 1 {
 4537                        // If there are no more completion tasks and the last menu was
 4538                        // empty, we should hide it. If it was already hidden, we should
 4539                        // also show the copilot completion when available.
 4540                        drop(context_menu);
 4541                        if editor.hide_context_menu(cx).is_none() {
 4542                            editor.update_visible_inline_completion(cx);
 4543                        }
 4544                    }
 4545                })?;
 4546
 4547                Ok::<_, anyhow::Error>(())
 4548            }
 4549            .log_err()
 4550        });
 4551
 4552        self.completion_tasks.push((id, task));
 4553    }
 4554
 4555    pub fn confirm_completion(
 4556        &mut self,
 4557        action: &ConfirmCompletion,
 4558        cx: &mut ViewContext<Self>,
 4559    ) -> Option<Task<Result<()>>> {
 4560        self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
 4561    }
 4562
 4563    pub fn compose_completion(
 4564        &mut self,
 4565        action: &ComposeCompletion,
 4566        cx: &mut ViewContext<Self>,
 4567    ) -> Option<Task<Result<()>>> {
 4568        self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
 4569    }
 4570
 4571    fn do_completion(
 4572        &mut self,
 4573        item_ix: Option<usize>,
 4574        intent: CompletionIntent,
 4575        cx: &mut ViewContext<Editor>,
 4576    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 4577        use language::ToOffset as _;
 4578
 4579        let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 4580            menu
 4581        } else {
 4582            return None;
 4583        };
 4584
 4585        let mat = completions_menu
 4586            .matches
 4587            .get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4588        let buffer_handle = completions_menu.buffer;
 4589        let completions = completions_menu.completions.read();
 4590        let completion = completions.get(mat.candidate_id)?;
 4591        cx.stop_propagation();
 4592
 4593        let snippet;
 4594        let text;
 4595
 4596        if completion.is_snippet() {
 4597            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4598            text = snippet.as_ref().unwrap().text.clone();
 4599        } else {
 4600            snippet = None;
 4601            text = completion.new_text.clone();
 4602        };
 4603        let selections = self.selections.all::<usize>(cx);
 4604        let buffer = buffer_handle.read(cx);
 4605        let old_range = completion.old_range.to_offset(buffer);
 4606        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4607
 4608        let newest_selection = self.selections.newest_anchor();
 4609        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4610            return None;
 4611        }
 4612
 4613        let lookbehind = newest_selection
 4614            .start
 4615            .text_anchor
 4616            .to_offset(buffer)
 4617            .saturating_sub(old_range.start);
 4618        let lookahead = old_range
 4619            .end
 4620            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4621        let mut common_prefix_len = old_text
 4622            .bytes()
 4623            .zip(text.bytes())
 4624            .take_while(|(a, b)| a == b)
 4625            .count();
 4626
 4627        let snapshot = self.buffer.read(cx).snapshot(cx);
 4628        let mut range_to_replace: Option<Range<isize>> = None;
 4629        let mut ranges = Vec::new();
 4630        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4631        for selection in &selections {
 4632            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4633                let start = selection.start.saturating_sub(lookbehind);
 4634                let end = selection.end + lookahead;
 4635                if selection.id == newest_selection.id {
 4636                    range_to_replace = Some(
 4637                        ((start + common_prefix_len) as isize - selection.start as isize)
 4638                            ..(end as isize - selection.start as isize),
 4639                    );
 4640                }
 4641                ranges.push(start + common_prefix_len..end);
 4642            } else {
 4643                common_prefix_len = 0;
 4644                ranges.clear();
 4645                ranges.extend(selections.iter().map(|s| {
 4646                    if s.id == newest_selection.id {
 4647                        range_to_replace = Some(
 4648                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4649                                - selection.start as isize
 4650                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4651                                    - selection.start as isize,
 4652                        );
 4653                        old_range.clone()
 4654                    } else {
 4655                        s.start..s.end
 4656                    }
 4657                }));
 4658                break;
 4659            }
 4660            if !self.linked_edit_ranges.is_empty() {
 4661                let start_anchor = snapshot.anchor_before(selection.head());
 4662                let end_anchor = snapshot.anchor_after(selection.tail());
 4663                if let Some(ranges) = self
 4664                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4665                {
 4666                    for (buffer, edits) in ranges {
 4667                        linked_edits.entry(buffer.clone()).or_default().extend(
 4668                            edits
 4669                                .into_iter()
 4670                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4671                        );
 4672                    }
 4673                }
 4674            }
 4675        }
 4676        let text = &text[common_prefix_len..];
 4677
 4678        cx.emit(EditorEvent::InputHandled {
 4679            utf16_range_to_replace: range_to_replace,
 4680            text: text.into(),
 4681        });
 4682
 4683        self.transact(cx, |this, cx| {
 4684            if let Some(mut snippet) = snippet {
 4685                snippet.text = text.to_string();
 4686                for tabstop in snippet
 4687                    .tabstops
 4688                    .iter_mut()
 4689                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4690                {
 4691                    tabstop.start -= common_prefix_len as isize;
 4692                    tabstop.end -= common_prefix_len as isize;
 4693                }
 4694
 4695                this.insert_snippet(&ranges, snippet, cx).log_err();
 4696            } else {
 4697                this.buffer.update(cx, |buffer, cx| {
 4698                    buffer.edit(
 4699                        ranges.iter().map(|range| (range.clone(), text)),
 4700                        this.autoindent_mode.clone(),
 4701                        cx,
 4702                    );
 4703                });
 4704            }
 4705            for (buffer, edits) in linked_edits {
 4706                buffer.update(cx, |buffer, cx| {
 4707                    let snapshot = buffer.snapshot();
 4708                    let edits = edits
 4709                        .into_iter()
 4710                        .map(|(range, text)| {
 4711                            use text::ToPoint as TP;
 4712                            let end_point = TP::to_point(&range.end, &snapshot);
 4713                            let start_point = TP::to_point(&range.start, &snapshot);
 4714                            (start_point..end_point, text)
 4715                        })
 4716                        .sorted_by_key(|(range, _)| range.start)
 4717                        .collect::<Vec<_>>();
 4718                    buffer.edit(edits, None, cx);
 4719                })
 4720            }
 4721
 4722            this.refresh_inline_completion(true, false, cx);
 4723        });
 4724
 4725        let show_new_completions_on_confirm = completion
 4726            .confirm
 4727            .as_ref()
 4728            .map_or(false, |confirm| confirm(intent, cx));
 4729        if show_new_completions_on_confirm {
 4730            self.show_completions(&ShowCompletions { trigger: None }, cx);
 4731        }
 4732
 4733        let provider = self.completion_provider.as_ref()?;
 4734        let apply_edits = provider.apply_additional_edits_for_completion(
 4735            buffer_handle,
 4736            completion.clone(),
 4737            true,
 4738            cx,
 4739        );
 4740
 4741        let editor_settings = EditorSettings::get_global(cx);
 4742        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4743            // After the code completion is finished, users often want to know what signatures are needed.
 4744            // so we should automatically call signature_help
 4745            self.show_signature_help(&ShowSignatureHelp, cx);
 4746        }
 4747
 4748        Some(cx.foreground_executor().spawn(async move {
 4749            apply_edits.await?;
 4750            Ok(())
 4751        }))
 4752    }
 4753
 4754    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 4755        let mut context_menu = self.context_menu.write();
 4756        if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4757            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4758                // Toggle if we're selecting the same one
 4759                *context_menu = None;
 4760                cx.notify();
 4761                return;
 4762            } else {
 4763                // Otherwise, clear it and start a new one
 4764                *context_menu = None;
 4765                cx.notify();
 4766            }
 4767        }
 4768        drop(context_menu);
 4769        let snapshot = self.snapshot(cx);
 4770        let deployed_from_indicator = action.deployed_from_indicator;
 4771        let mut task = self.code_actions_task.take();
 4772        let action = action.clone();
 4773        cx.spawn(|editor, mut cx| async move {
 4774            while let Some(prev_task) = task {
 4775                prev_task.await.log_err();
 4776                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4777            }
 4778
 4779            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 4780                if editor.focus_handle.is_focused(cx) {
 4781                    let multibuffer_point = action
 4782                        .deployed_from_indicator
 4783                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4784                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4785                    let (buffer, buffer_row) = snapshot
 4786                        .buffer_snapshot
 4787                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4788                        .and_then(|(buffer_snapshot, range)| {
 4789                            editor
 4790                                .buffer
 4791                                .read(cx)
 4792                                .buffer(buffer_snapshot.remote_id())
 4793                                .map(|buffer| (buffer, range.start.row))
 4794                        })?;
 4795                    let (_, code_actions) = editor
 4796                        .available_code_actions
 4797                        .clone()
 4798                        .and_then(|(location, code_actions)| {
 4799                            let snapshot = location.buffer.read(cx).snapshot();
 4800                            let point_range = location.range.to_point(&snapshot);
 4801                            let point_range = point_range.start.row..=point_range.end.row;
 4802                            if point_range.contains(&buffer_row) {
 4803                                Some((location, code_actions))
 4804                            } else {
 4805                                None
 4806                            }
 4807                        })
 4808                        .unzip();
 4809                    let buffer_id = buffer.read(cx).remote_id();
 4810                    let tasks = editor
 4811                        .tasks
 4812                        .get(&(buffer_id, buffer_row))
 4813                        .map(|t| Arc::new(t.to_owned()));
 4814                    if tasks.is_none() && code_actions.is_none() {
 4815                        return None;
 4816                    }
 4817
 4818                    editor.completion_tasks.clear();
 4819                    editor.discard_inline_completion(false, cx);
 4820                    let task_context =
 4821                        tasks
 4822                            .as_ref()
 4823                            .zip(editor.project.clone())
 4824                            .map(|(tasks, project)| {
 4825                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4826                            });
 4827
 4828                    Some(cx.spawn(|editor, mut cx| async move {
 4829                        let task_context = match task_context {
 4830                            Some(task_context) => task_context.await,
 4831                            None => None,
 4832                        };
 4833                        let resolved_tasks =
 4834                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4835                                Arc::new(ResolvedTasks {
 4836                                    templates: tasks.resolve(&task_context).collect(),
 4837                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4838                                        multibuffer_point.row,
 4839                                        tasks.column,
 4840                                    )),
 4841                                })
 4842                            });
 4843                        let spawn_straight_away = resolved_tasks
 4844                            .as_ref()
 4845                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4846                            && code_actions
 4847                                .as_ref()
 4848                                .map_or(true, |actions| actions.is_empty());
 4849                        if let Ok(task) = editor.update(&mut cx, |editor, cx| {
 4850                            *editor.context_menu.write() =
 4851                                Some(ContextMenu::CodeActions(CodeActionsMenu {
 4852                                    buffer,
 4853                                    actions: CodeActionContents {
 4854                                        tasks: resolved_tasks,
 4855                                        actions: code_actions,
 4856                                    },
 4857                                    selected_item: Default::default(),
 4858                                    scroll_handle: UniformListScrollHandle::default(),
 4859                                    deployed_from_indicator,
 4860                                }));
 4861                            if spawn_straight_away {
 4862                                if let Some(task) = editor.confirm_code_action(
 4863                                    &ConfirmCodeAction { item_ix: Some(0) },
 4864                                    cx,
 4865                                ) {
 4866                                    cx.notify();
 4867                                    return task;
 4868                                }
 4869                            }
 4870                            cx.notify();
 4871                            Task::ready(Ok(()))
 4872                        }) {
 4873                            task.await
 4874                        } else {
 4875                            Ok(())
 4876                        }
 4877                    }))
 4878                } else {
 4879                    Some(Task::ready(Ok(())))
 4880                }
 4881            })?;
 4882            if let Some(task) = spawned_test_task {
 4883                task.await?;
 4884            }
 4885
 4886            Ok::<_, anyhow::Error>(())
 4887        })
 4888        .detach_and_log_err(cx);
 4889    }
 4890
 4891    pub fn confirm_code_action(
 4892        &mut self,
 4893        action: &ConfirmCodeAction,
 4894        cx: &mut ViewContext<Self>,
 4895    ) -> Option<Task<Result<()>>> {
 4896        let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4897            menu
 4898        } else {
 4899            return None;
 4900        };
 4901        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4902        let action = actions_menu.actions.get(action_ix)?;
 4903        let title = action.label();
 4904        let buffer = actions_menu.buffer;
 4905        let workspace = self.workspace()?;
 4906
 4907        match action {
 4908            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4909                workspace.update(cx, |workspace, cx| {
 4910                    workspace::tasks::schedule_resolved_task(
 4911                        workspace,
 4912                        task_source_kind,
 4913                        resolved_task,
 4914                        false,
 4915                        cx,
 4916                    );
 4917
 4918                    Some(Task::ready(Ok(())))
 4919                })
 4920            }
 4921            CodeActionsItem::CodeAction {
 4922                excerpt_id,
 4923                action,
 4924                provider,
 4925            } => {
 4926                let apply_code_action =
 4927                    provider.apply_code_action(buffer, action, excerpt_id, true, cx);
 4928                let workspace = workspace.downgrade();
 4929                Some(cx.spawn(|editor, cx| async move {
 4930                    let project_transaction = apply_code_action.await?;
 4931                    Self::open_project_transaction(
 4932                        &editor,
 4933                        workspace,
 4934                        project_transaction,
 4935                        title,
 4936                        cx,
 4937                    )
 4938                    .await
 4939                }))
 4940            }
 4941        }
 4942    }
 4943
 4944    pub async fn open_project_transaction(
 4945        this: &WeakView<Editor>,
 4946        workspace: WeakView<Workspace>,
 4947        transaction: ProjectTransaction,
 4948        title: String,
 4949        mut cx: AsyncWindowContext,
 4950    ) -> Result<()> {
 4951        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4952        cx.update(|cx| {
 4953            entries.sort_unstable_by_key(|(buffer, _)| {
 4954                buffer.read(cx).file().map(|f| f.path().clone())
 4955            });
 4956        })?;
 4957
 4958        // If the project transaction's edits are all contained within this editor, then
 4959        // avoid opening a new editor to display them.
 4960
 4961        if let Some((buffer, transaction)) = entries.first() {
 4962            if entries.len() == 1 {
 4963                let excerpt = this.update(&mut cx, |editor, cx| {
 4964                    editor
 4965                        .buffer()
 4966                        .read(cx)
 4967                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4968                })?;
 4969                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4970                    if excerpted_buffer == *buffer {
 4971                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4972                            let excerpt_range = excerpt_range.to_offset(buffer);
 4973                            buffer
 4974                                .edited_ranges_for_transaction::<usize>(transaction)
 4975                                .all(|range| {
 4976                                    excerpt_range.start <= range.start
 4977                                        && excerpt_range.end >= range.end
 4978                                })
 4979                        })?;
 4980
 4981                        if all_edits_within_excerpt {
 4982                            return Ok(());
 4983                        }
 4984                    }
 4985                }
 4986            }
 4987        } else {
 4988            return Ok(());
 4989        }
 4990
 4991        let mut ranges_to_highlight = Vec::new();
 4992        let excerpt_buffer = cx.new_model(|cx| {
 4993            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4994            for (buffer_handle, transaction) in &entries {
 4995                let buffer = buffer_handle.read(cx);
 4996                ranges_to_highlight.extend(
 4997                    multibuffer.push_excerpts_with_context_lines(
 4998                        buffer_handle.clone(),
 4999                        buffer
 5000                            .edited_ranges_for_transaction::<usize>(transaction)
 5001                            .collect(),
 5002                        DEFAULT_MULTIBUFFER_CONTEXT,
 5003                        cx,
 5004                    ),
 5005                );
 5006            }
 5007            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 5008            multibuffer
 5009        })?;
 5010
 5011        workspace.update(&mut cx, |workspace, cx| {
 5012            let project = workspace.project().clone();
 5013            let editor =
 5014                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 5015            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 5016            editor.update(cx, |editor, cx| {
 5017                editor.highlight_background::<Self>(
 5018                    &ranges_to_highlight,
 5019                    |theme| theme.editor_highlighted_line_background,
 5020                    cx,
 5021                );
 5022            });
 5023        })?;
 5024
 5025        Ok(())
 5026    }
 5027
 5028    pub fn clear_code_action_providers(&mut self) {
 5029        self.code_action_providers.clear();
 5030        self.available_code_actions.take();
 5031    }
 5032
 5033    pub fn push_code_action_provider(
 5034        &mut self,
 5035        provider: Arc<dyn CodeActionProvider>,
 5036        cx: &mut ViewContext<Self>,
 5037    ) {
 5038        self.code_action_providers.push(provider);
 5039        self.refresh_code_actions(cx);
 5040    }
 5041
 5042    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 5043        let buffer = self.buffer.read(cx);
 5044        let newest_selection = self.selections.newest_anchor().clone();
 5045        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 5046        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 5047        if start_buffer != end_buffer {
 5048            return None;
 5049        }
 5050
 5051        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 5052            cx.background_executor()
 5053                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 5054                .await;
 5055
 5056            let (providers, tasks) = this.update(&mut cx, |this, cx| {
 5057                let providers = this.code_action_providers.clone();
 5058                let tasks = this
 5059                    .code_action_providers
 5060                    .iter()
 5061                    .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
 5062                    .collect::<Vec<_>>();
 5063                (providers, tasks)
 5064            })?;
 5065
 5066            let mut actions = Vec::new();
 5067            for (provider, provider_actions) in
 5068                providers.into_iter().zip(future::join_all(tasks).await)
 5069            {
 5070                if let Some(provider_actions) = provider_actions.log_err() {
 5071                    actions.extend(provider_actions.into_iter().map(|action| {
 5072                        AvailableCodeAction {
 5073                            excerpt_id: newest_selection.start.excerpt_id,
 5074                            action,
 5075                            provider: provider.clone(),
 5076                        }
 5077                    }));
 5078                }
 5079            }
 5080
 5081            this.update(&mut cx, |this, cx| {
 5082                this.available_code_actions = if actions.is_empty() {
 5083                    None
 5084                } else {
 5085                    Some((
 5086                        Location {
 5087                            buffer: start_buffer,
 5088                            range: start..end,
 5089                        },
 5090                        actions.into(),
 5091                    ))
 5092                };
 5093                cx.notify();
 5094            })
 5095        }));
 5096        None
 5097    }
 5098
 5099    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 5100        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 5101            self.show_git_blame_inline = false;
 5102
 5103            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 5104                cx.background_executor().timer(delay).await;
 5105
 5106                this.update(&mut cx, |this, cx| {
 5107                    this.show_git_blame_inline = true;
 5108                    cx.notify();
 5109                })
 5110                .log_err();
 5111            }));
 5112        }
 5113    }
 5114
 5115    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 5116        if self.pending_rename.is_some() {
 5117            return None;
 5118        }
 5119
 5120        let provider = self.semantics_provider.clone()?;
 5121        let buffer = self.buffer.read(cx);
 5122        let newest_selection = self.selections.newest_anchor().clone();
 5123        let cursor_position = newest_selection.head();
 5124        let (cursor_buffer, cursor_buffer_position) =
 5125            buffer.text_anchor_for_position(cursor_position, cx)?;
 5126        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 5127        if cursor_buffer != tail_buffer {
 5128            return None;
 5129        }
 5130
 5131        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 5132            cx.background_executor()
 5133                .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
 5134                .await;
 5135
 5136            let highlights = if let Some(highlights) = cx
 5137                .update(|cx| {
 5138                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 5139                })
 5140                .ok()
 5141                .flatten()
 5142            {
 5143                highlights.await.log_err()
 5144            } else {
 5145                None
 5146            };
 5147
 5148            if let Some(highlights) = highlights {
 5149                this.update(&mut cx, |this, cx| {
 5150                    if this.pending_rename.is_some() {
 5151                        return;
 5152                    }
 5153
 5154                    let buffer_id = cursor_position.buffer_id;
 5155                    let buffer = this.buffer.read(cx);
 5156                    if !buffer
 5157                        .text_anchor_for_position(cursor_position, cx)
 5158                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 5159                    {
 5160                        return;
 5161                    }
 5162
 5163                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 5164                    let mut write_ranges = Vec::new();
 5165                    let mut read_ranges = Vec::new();
 5166                    for highlight in highlights {
 5167                        for (excerpt_id, excerpt_range) in
 5168                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 5169                        {
 5170                            let start = highlight
 5171                                .range
 5172                                .start
 5173                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 5174                            let end = highlight
 5175                                .range
 5176                                .end
 5177                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 5178                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 5179                                continue;
 5180                            }
 5181
 5182                            let range = Anchor {
 5183                                buffer_id,
 5184                                excerpt_id,
 5185                                text_anchor: start,
 5186                            }..Anchor {
 5187                                buffer_id,
 5188                                excerpt_id,
 5189                                text_anchor: end,
 5190                            };
 5191                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 5192                                write_ranges.push(range);
 5193                            } else {
 5194                                read_ranges.push(range);
 5195                            }
 5196                        }
 5197                    }
 5198
 5199                    this.highlight_background::<DocumentHighlightRead>(
 5200                        &read_ranges,
 5201                        |theme| theme.editor_document_highlight_read_background,
 5202                        cx,
 5203                    );
 5204                    this.highlight_background::<DocumentHighlightWrite>(
 5205                        &write_ranges,
 5206                        |theme| theme.editor_document_highlight_write_background,
 5207                        cx,
 5208                    );
 5209                    cx.notify();
 5210                })
 5211                .log_err();
 5212            }
 5213        }));
 5214        None
 5215    }
 5216
 5217    pub fn refresh_inline_completion(
 5218        &mut self,
 5219        debounce: bool,
 5220        user_requested: bool,
 5221        cx: &mut ViewContext<Self>,
 5222    ) -> Option<()> {
 5223        let provider = self.inline_completion_provider()?;
 5224        let cursor = self.selections.newest_anchor().head();
 5225        let (buffer, cursor_buffer_position) =
 5226            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5227
 5228        if !user_requested
 5229            && (!self.enable_inline_completions
 5230                || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx))
 5231        {
 5232            self.discard_inline_completion(false, cx);
 5233            return None;
 5234        }
 5235
 5236        self.update_visible_inline_completion(cx);
 5237        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 5238        Some(())
 5239    }
 5240
 5241    fn cycle_inline_completion(
 5242        &mut self,
 5243        direction: Direction,
 5244        cx: &mut ViewContext<Self>,
 5245    ) -> Option<()> {
 5246        let provider = self.inline_completion_provider()?;
 5247        let cursor = self.selections.newest_anchor().head();
 5248        let (buffer, cursor_buffer_position) =
 5249            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5250        if !self.enable_inline_completions
 5251            || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 5252        {
 5253            return None;
 5254        }
 5255
 5256        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5257        self.update_visible_inline_completion(cx);
 5258
 5259        Some(())
 5260    }
 5261
 5262    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 5263        if !self.has_active_inline_completion(cx) {
 5264            self.refresh_inline_completion(false, true, cx);
 5265            return;
 5266        }
 5267
 5268        self.update_visible_inline_completion(cx);
 5269    }
 5270
 5271    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 5272        self.show_cursor_names(cx);
 5273    }
 5274
 5275    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 5276        self.show_cursor_names = true;
 5277        cx.notify();
 5278        cx.spawn(|this, mut cx| async move {
 5279            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5280            this.update(&mut cx, |this, cx| {
 5281                this.show_cursor_names = false;
 5282                cx.notify()
 5283            })
 5284            .ok()
 5285        })
 5286        .detach();
 5287    }
 5288
 5289    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 5290        if self.has_active_inline_completion(cx) {
 5291            self.cycle_inline_completion(Direction::Next, cx);
 5292        } else {
 5293            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5294            if is_copilot_disabled {
 5295                cx.propagate();
 5296            }
 5297        }
 5298    }
 5299
 5300    pub fn previous_inline_completion(
 5301        &mut self,
 5302        _: &PreviousInlineCompletion,
 5303        cx: &mut ViewContext<Self>,
 5304    ) {
 5305        if self.has_active_inline_completion(cx) {
 5306            self.cycle_inline_completion(Direction::Prev, cx);
 5307        } else {
 5308            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5309            if is_copilot_disabled {
 5310                cx.propagate();
 5311            }
 5312        }
 5313    }
 5314
 5315    pub fn accept_inline_completion(
 5316        &mut self,
 5317        _: &AcceptInlineCompletion,
 5318        cx: &mut ViewContext<Self>,
 5319    ) {
 5320        let Some(completion) = self.take_active_inline_completion(cx) else {
 5321            return;
 5322        };
 5323        if let Some(provider) = self.inline_completion_provider() {
 5324            provider.accept(cx);
 5325        }
 5326
 5327        cx.emit(EditorEvent::InputHandled {
 5328            utf16_range_to_replace: None,
 5329            text: completion.text.to_string().into(),
 5330        });
 5331
 5332        if let Some(range) = completion.delete_range {
 5333            self.change_selections(None, cx, |s| s.select_ranges([range]))
 5334        }
 5335        self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
 5336        self.refresh_inline_completion(true, true, cx);
 5337        cx.notify();
 5338    }
 5339
 5340    pub fn accept_partial_inline_completion(
 5341        &mut self,
 5342        _: &AcceptPartialInlineCompletion,
 5343        cx: &mut ViewContext<Self>,
 5344    ) {
 5345        if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
 5346            if let Some(completion) = self.take_active_inline_completion(cx) {
 5347                let mut partial_completion = completion
 5348                    .text
 5349                    .chars()
 5350                    .by_ref()
 5351                    .take_while(|c| c.is_alphabetic())
 5352                    .collect::<String>();
 5353                if partial_completion.is_empty() {
 5354                    partial_completion = completion
 5355                        .text
 5356                        .chars()
 5357                        .by_ref()
 5358                        .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5359                        .collect::<String>();
 5360                }
 5361
 5362                cx.emit(EditorEvent::InputHandled {
 5363                    utf16_range_to_replace: None,
 5364                    text: partial_completion.clone().into(),
 5365                });
 5366
 5367                if let Some(range) = completion.delete_range {
 5368                    self.change_selections(None, cx, |s| s.select_ranges([range]))
 5369                }
 5370                self.insert_with_autoindent_mode(&partial_completion, None, cx);
 5371
 5372                self.refresh_inline_completion(true, true, cx);
 5373                cx.notify();
 5374            }
 5375        }
 5376    }
 5377
 5378    fn discard_inline_completion(
 5379        &mut self,
 5380        should_report_inline_completion_event: bool,
 5381        cx: &mut ViewContext<Self>,
 5382    ) -> bool {
 5383        if let Some(provider) = self.inline_completion_provider() {
 5384            provider.discard(should_report_inline_completion_event, cx);
 5385        }
 5386
 5387        self.take_active_inline_completion(cx).is_some()
 5388    }
 5389
 5390    pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
 5391        if let Some(completion) = self.active_inline_completion.as_ref() {
 5392            let buffer = self.buffer.read(cx).read(cx);
 5393            completion.position.is_valid(&buffer)
 5394        } else {
 5395            false
 5396        }
 5397    }
 5398
 5399    fn take_active_inline_completion(
 5400        &mut self,
 5401        cx: &mut ViewContext<Self>,
 5402    ) -> Option<CompletionState> {
 5403        let completion = self.active_inline_completion.take()?;
 5404        let render_inlay_ids = completion.render_inlay_ids.clone();
 5405        self.display_map.update(cx, |map, cx| {
 5406            map.splice_inlays(render_inlay_ids, Default::default(), cx);
 5407        });
 5408        let buffer = self.buffer.read(cx).read(cx);
 5409
 5410        if completion.position.is_valid(&buffer) {
 5411            Some(completion)
 5412        } else {
 5413            None
 5414        }
 5415    }
 5416
 5417    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
 5418        let selection = self.selections.newest_anchor();
 5419        let cursor = selection.head();
 5420
 5421        let excerpt_id = cursor.excerpt_id;
 5422
 5423        if self.context_menu.read().is_none()
 5424            && self.completion_tasks.is_empty()
 5425            && selection.start == selection.end
 5426        {
 5427            if let Some(provider) = self.inline_completion_provider() {
 5428                if let Some((buffer, cursor_buffer_position)) =
 5429                    self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5430                {
 5431                    if let Some(proposal) =
 5432                        provider.active_completion_text(&buffer, cursor_buffer_position, cx)
 5433                    {
 5434                        let mut to_remove = Vec::new();
 5435                        if let Some(completion) = self.active_inline_completion.take() {
 5436                            to_remove.extend(completion.render_inlay_ids.iter());
 5437                        }
 5438
 5439                        let to_add = proposal
 5440                            .inlays
 5441                            .iter()
 5442                            .filter_map(|inlay| {
 5443                                let snapshot = self.buffer.read(cx).snapshot(cx);
 5444                                let id = post_inc(&mut self.next_inlay_id);
 5445                                match inlay {
 5446                                    InlayProposal::Hint(position, hint) => {
 5447                                        let position =
 5448                                            snapshot.anchor_in_excerpt(excerpt_id, *position)?;
 5449                                        Some(Inlay::hint(id, position, hint))
 5450                                    }
 5451                                    InlayProposal::Suggestion(position, text) => {
 5452                                        let position =
 5453                                            snapshot.anchor_in_excerpt(excerpt_id, *position)?;
 5454                                        Some(Inlay::suggestion(id, position, text.clone()))
 5455                                    }
 5456                                }
 5457                            })
 5458                            .collect_vec();
 5459
 5460                        self.active_inline_completion = Some(CompletionState {
 5461                            position: cursor,
 5462                            text: proposal.text,
 5463                            delete_range: proposal.delete_range.and_then(|range| {
 5464                                let snapshot = self.buffer.read(cx).snapshot(cx);
 5465                                let start = snapshot.anchor_in_excerpt(excerpt_id, range.start);
 5466                                let end = snapshot.anchor_in_excerpt(excerpt_id, range.end);
 5467                                Some(start?..end?)
 5468                            }),
 5469                            render_inlay_ids: to_add.iter().map(|i| i.id).collect(),
 5470                        });
 5471
 5472                        self.display_map
 5473                            .update(cx, move |map, cx| map.splice_inlays(to_remove, to_add, cx));
 5474
 5475                        cx.notify();
 5476                        return;
 5477                    }
 5478                }
 5479            }
 5480        }
 5481
 5482        self.discard_inline_completion(false, cx);
 5483    }
 5484
 5485    fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5486        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 5487    }
 5488
 5489    fn render_code_actions_indicator(
 5490        &self,
 5491        _style: &EditorStyle,
 5492        row: DisplayRow,
 5493        is_active: bool,
 5494        cx: &mut ViewContext<Self>,
 5495    ) -> Option<IconButton> {
 5496        if self.available_code_actions.is_some() {
 5497            Some(
 5498                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5499                    .shape(ui::IconButtonShape::Square)
 5500                    .icon_size(IconSize::XSmall)
 5501                    .icon_color(Color::Muted)
 5502                    .selected(is_active)
 5503                    .tooltip({
 5504                        let focus_handle = self.focus_handle.clone();
 5505                        move |cx| {
 5506                            Tooltip::for_action_in(
 5507                                "Toggle Code Actions",
 5508                                &ToggleCodeActions {
 5509                                    deployed_from_indicator: None,
 5510                                },
 5511                                &focus_handle,
 5512                                cx,
 5513                            )
 5514                        }
 5515                    })
 5516                    .on_click(cx.listener(move |editor, _e, cx| {
 5517                        editor.focus(cx);
 5518                        editor.toggle_code_actions(
 5519                            &ToggleCodeActions {
 5520                                deployed_from_indicator: Some(row),
 5521                            },
 5522                            cx,
 5523                        );
 5524                    })),
 5525            )
 5526        } else {
 5527            None
 5528        }
 5529    }
 5530
 5531    fn clear_tasks(&mut self) {
 5532        self.tasks.clear()
 5533    }
 5534
 5535    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5536        if self.tasks.insert(key, value).is_some() {
 5537            // This case should hopefully be rare, but just in case...
 5538            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5539        }
 5540    }
 5541
 5542    fn build_tasks_context(
 5543        project: &Model<Project>,
 5544        buffer: &Model<Buffer>,
 5545        buffer_row: u32,
 5546        tasks: &Arc<RunnableTasks>,
 5547        cx: &mut ViewContext<Self>,
 5548    ) -> Task<Option<task::TaskContext>> {
 5549        let position = Point::new(buffer_row, tasks.column);
 5550        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5551        let location = Location {
 5552            buffer: buffer.clone(),
 5553            range: range_start..range_start,
 5554        };
 5555        // Fill in the environmental variables from the tree-sitter captures
 5556        let mut captured_task_variables = TaskVariables::default();
 5557        for (capture_name, value) in tasks.extra_variables.clone() {
 5558            captured_task_variables.insert(
 5559                task::VariableName::Custom(capture_name.into()),
 5560                value.clone(),
 5561            );
 5562        }
 5563        project.update(cx, |project, cx| {
 5564            project.task_store().update(cx, |task_store, cx| {
 5565                task_store.task_context_for_location(captured_task_variables, location, cx)
 5566            })
 5567        })
 5568    }
 5569
 5570    pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
 5571        let Some((workspace, _)) = self.workspace.clone() else {
 5572            return;
 5573        };
 5574        let Some(project) = self.project.clone() else {
 5575            return;
 5576        };
 5577
 5578        // Try to find a closest, enclosing node using tree-sitter that has a
 5579        // task
 5580        let Some((buffer, buffer_row, tasks)) = self
 5581            .find_enclosing_node_task(cx)
 5582            // Or find the task that's closest in row-distance.
 5583            .or_else(|| self.find_closest_task(cx))
 5584        else {
 5585            return;
 5586        };
 5587
 5588        let reveal_strategy = action.reveal;
 5589        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5590        cx.spawn(|_, mut cx| async move {
 5591            let context = task_context.await?;
 5592            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5593
 5594            let resolved = resolved_task.resolved.as_mut()?;
 5595            resolved.reveal = reveal_strategy;
 5596
 5597            workspace
 5598                .update(&mut cx, |workspace, cx| {
 5599                    workspace::tasks::schedule_resolved_task(
 5600                        workspace,
 5601                        task_source_kind,
 5602                        resolved_task,
 5603                        false,
 5604                        cx,
 5605                    );
 5606                })
 5607                .ok()
 5608        })
 5609        .detach();
 5610    }
 5611
 5612    fn find_closest_task(
 5613        &mut self,
 5614        cx: &mut ViewContext<Self>,
 5615    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5616        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5617
 5618        let ((buffer_id, row), tasks) = self
 5619            .tasks
 5620            .iter()
 5621            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5622
 5623        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5624        let tasks = Arc::new(tasks.to_owned());
 5625        Some((buffer, *row, tasks))
 5626    }
 5627
 5628    fn find_enclosing_node_task(
 5629        &mut self,
 5630        cx: &mut ViewContext<Self>,
 5631    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5632        let snapshot = self.buffer.read(cx).snapshot(cx);
 5633        let offset = self.selections.newest::<usize>(cx).head();
 5634        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5635        let buffer_id = excerpt.buffer().remote_id();
 5636
 5637        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5638        let mut cursor = layer.node().walk();
 5639
 5640        while cursor.goto_first_child_for_byte(offset).is_some() {
 5641            if cursor.node().end_byte() == offset {
 5642                cursor.goto_next_sibling();
 5643            }
 5644        }
 5645
 5646        // Ascend to the smallest ancestor that contains the range and has a task.
 5647        loop {
 5648            let node = cursor.node();
 5649            let node_range = node.byte_range();
 5650            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5651
 5652            // Check if this node contains our offset
 5653            if node_range.start <= offset && node_range.end >= offset {
 5654                // If it contains offset, check for task
 5655                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5656                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5657                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5658                }
 5659            }
 5660
 5661            if !cursor.goto_parent() {
 5662                break;
 5663            }
 5664        }
 5665        None
 5666    }
 5667
 5668    fn render_run_indicator(
 5669        &self,
 5670        _style: &EditorStyle,
 5671        is_active: bool,
 5672        row: DisplayRow,
 5673        cx: &mut ViewContext<Self>,
 5674    ) -> IconButton {
 5675        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5676            .shape(ui::IconButtonShape::Square)
 5677            .icon_size(IconSize::XSmall)
 5678            .icon_color(Color::Muted)
 5679            .selected(is_active)
 5680            .on_click(cx.listener(move |editor, _e, cx| {
 5681                editor.focus(cx);
 5682                editor.toggle_code_actions(
 5683                    &ToggleCodeActions {
 5684                        deployed_from_indicator: Some(row),
 5685                    },
 5686                    cx,
 5687                );
 5688            }))
 5689    }
 5690
 5691    pub fn context_menu_visible(&self) -> bool {
 5692        self.context_menu
 5693            .read()
 5694            .as_ref()
 5695            .map_or(false, |menu| menu.visible())
 5696    }
 5697
 5698    fn render_context_menu(
 5699        &self,
 5700        cursor_position: DisplayPoint,
 5701        style: &EditorStyle,
 5702        max_height: Pixels,
 5703        cx: &mut ViewContext<Editor>,
 5704    ) -> Option<(ContextMenuOrigin, AnyElement)> {
 5705        self.context_menu.read().as_ref().map(|menu| {
 5706            menu.render(
 5707                cursor_position,
 5708                style,
 5709                max_height,
 5710                self.workspace.as_ref().map(|(w, _)| w.clone()),
 5711                cx,
 5712            )
 5713        })
 5714    }
 5715
 5716    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
 5717        cx.notify();
 5718        self.completion_tasks.clear();
 5719        let context_menu = self.context_menu.write().take();
 5720        if context_menu.is_some() {
 5721            self.update_visible_inline_completion(cx);
 5722        }
 5723        context_menu
 5724    }
 5725
 5726    fn show_snippet_choices(
 5727        &mut self,
 5728        choices: &Vec<String>,
 5729        selection: Range<Anchor>,
 5730        cx: &mut ViewContext<Self>,
 5731    ) {
 5732        if selection.start.buffer_id.is_none() {
 5733            return;
 5734        }
 5735        let buffer_id = selection.start.buffer_id.unwrap();
 5736        let buffer = self.buffer().read(cx).buffer(buffer_id);
 5737        let id = post_inc(&mut self.next_completion_id);
 5738
 5739        if let Some(buffer) = buffer {
 5740            *self.context_menu.write() = Some(ContextMenu::Completions(
 5741                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer)
 5742                    .suppress_documentation_resolution(),
 5743            ));
 5744        }
 5745    }
 5746
 5747    pub fn insert_snippet(
 5748        &mut self,
 5749        insertion_ranges: &[Range<usize>],
 5750        snippet: Snippet,
 5751        cx: &mut ViewContext<Self>,
 5752    ) -> Result<()> {
 5753        struct Tabstop<T> {
 5754            is_end_tabstop: bool,
 5755            ranges: Vec<Range<T>>,
 5756            choices: Option<Vec<String>>,
 5757        }
 5758
 5759        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5760            let snippet_text: Arc<str> = snippet.text.clone().into();
 5761            buffer.edit(
 5762                insertion_ranges
 5763                    .iter()
 5764                    .cloned()
 5765                    .map(|range| (range, snippet_text.clone())),
 5766                Some(AutoindentMode::EachLine),
 5767                cx,
 5768            );
 5769
 5770            let snapshot = &*buffer.read(cx);
 5771            let snippet = &snippet;
 5772            snippet
 5773                .tabstops
 5774                .iter()
 5775                .map(|tabstop| {
 5776                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 5777                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5778                    });
 5779                    let mut tabstop_ranges = tabstop
 5780                        .ranges
 5781                        .iter()
 5782                        .flat_map(|tabstop_range| {
 5783                            let mut delta = 0_isize;
 5784                            insertion_ranges.iter().map(move |insertion_range| {
 5785                                let insertion_start = insertion_range.start as isize + delta;
 5786                                delta +=
 5787                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5788
 5789                                let start = ((insertion_start + tabstop_range.start) as usize)
 5790                                    .min(snapshot.len());
 5791                                let end = ((insertion_start + tabstop_range.end) as usize)
 5792                                    .min(snapshot.len());
 5793                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5794                            })
 5795                        })
 5796                        .collect::<Vec<_>>();
 5797                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5798
 5799                    Tabstop {
 5800                        is_end_tabstop,
 5801                        ranges: tabstop_ranges,
 5802                        choices: tabstop.choices.clone(),
 5803                    }
 5804                })
 5805                .collect::<Vec<_>>()
 5806        });
 5807        if let Some(tabstop) = tabstops.first() {
 5808            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5809                s.select_ranges(tabstop.ranges.iter().cloned());
 5810            });
 5811
 5812            if let Some(choices) = &tabstop.choices {
 5813                if let Some(selection) = tabstop.ranges.first() {
 5814                    self.show_snippet_choices(choices, selection.clone(), cx)
 5815                }
 5816            }
 5817
 5818            // If we're already at the last tabstop and it's at the end of the snippet,
 5819            // we're done, we don't need to keep the state around.
 5820            if !tabstop.is_end_tabstop {
 5821                let choices = tabstops
 5822                    .iter()
 5823                    .map(|tabstop| tabstop.choices.clone())
 5824                    .collect();
 5825
 5826                let ranges = tabstops
 5827                    .into_iter()
 5828                    .map(|tabstop| tabstop.ranges)
 5829                    .collect::<Vec<_>>();
 5830
 5831                self.snippet_stack.push(SnippetState {
 5832                    active_index: 0,
 5833                    ranges,
 5834                    choices,
 5835                });
 5836            }
 5837
 5838            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5839            if self.autoclose_regions.is_empty() {
 5840                let snapshot = self.buffer.read(cx).snapshot(cx);
 5841                for selection in &mut self.selections.all::<Point>(cx) {
 5842                    let selection_head = selection.head();
 5843                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5844                        continue;
 5845                    };
 5846
 5847                    let mut bracket_pair = None;
 5848                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5849                    let prev_chars = snapshot
 5850                        .reversed_chars_at(selection_head)
 5851                        .collect::<String>();
 5852                    for (pair, enabled) in scope.brackets() {
 5853                        if enabled
 5854                            && pair.close
 5855                            && prev_chars.starts_with(pair.start.as_str())
 5856                            && next_chars.starts_with(pair.end.as_str())
 5857                        {
 5858                            bracket_pair = Some(pair.clone());
 5859                            break;
 5860                        }
 5861                    }
 5862                    if let Some(pair) = bracket_pair {
 5863                        let start = snapshot.anchor_after(selection_head);
 5864                        let end = snapshot.anchor_after(selection_head);
 5865                        self.autoclose_regions.push(AutocloseRegion {
 5866                            selection_id: selection.id,
 5867                            range: start..end,
 5868                            pair,
 5869                        });
 5870                    }
 5871                }
 5872            }
 5873        }
 5874        Ok(())
 5875    }
 5876
 5877    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5878        self.move_to_snippet_tabstop(Bias::Right, cx)
 5879    }
 5880
 5881    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5882        self.move_to_snippet_tabstop(Bias::Left, cx)
 5883    }
 5884
 5885    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5886        if let Some(mut snippet) = self.snippet_stack.pop() {
 5887            match bias {
 5888                Bias::Left => {
 5889                    if snippet.active_index > 0 {
 5890                        snippet.active_index -= 1;
 5891                    } else {
 5892                        self.snippet_stack.push(snippet);
 5893                        return false;
 5894                    }
 5895                }
 5896                Bias::Right => {
 5897                    if snippet.active_index + 1 < snippet.ranges.len() {
 5898                        snippet.active_index += 1;
 5899                    } else {
 5900                        self.snippet_stack.push(snippet);
 5901                        return false;
 5902                    }
 5903                }
 5904            }
 5905            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5906                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5907                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5908                });
 5909
 5910                if let Some(choices) = &snippet.choices[snippet.active_index] {
 5911                    if let Some(selection) = current_ranges.first() {
 5912                        self.show_snippet_choices(&choices, selection.clone(), cx);
 5913                    }
 5914                }
 5915
 5916                // If snippet state is not at the last tabstop, push it back on the stack
 5917                if snippet.active_index + 1 < snippet.ranges.len() {
 5918                    self.snippet_stack.push(snippet);
 5919                }
 5920                return true;
 5921            }
 5922        }
 5923
 5924        false
 5925    }
 5926
 5927    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 5928        self.transact(cx, |this, cx| {
 5929            this.select_all(&SelectAll, cx);
 5930            this.insert("", cx);
 5931        });
 5932    }
 5933
 5934    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 5935        self.transact(cx, |this, cx| {
 5936            this.select_autoclose_pair(cx);
 5937            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5938            if !this.linked_edit_ranges.is_empty() {
 5939                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5940                let snapshot = this.buffer.read(cx).snapshot(cx);
 5941
 5942                for selection in selections.iter() {
 5943                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5944                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 5945                    if selection_start.buffer_id != selection_end.buffer_id {
 5946                        continue;
 5947                    }
 5948                    if let Some(ranges) =
 5949                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 5950                    {
 5951                        for (buffer, entries) in ranges {
 5952                            linked_ranges.entry(buffer).or_default().extend(entries);
 5953                        }
 5954                    }
 5955                }
 5956            }
 5957
 5958            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 5959            if !this.selections.line_mode {
 5960                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 5961                for selection in &mut selections {
 5962                    if selection.is_empty() {
 5963                        let old_head = selection.head();
 5964                        let mut new_head =
 5965                            movement::left(&display_map, old_head.to_display_point(&display_map))
 5966                                .to_point(&display_map);
 5967                        if let Some((buffer, line_buffer_range)) = display_map
 5968                            .buffer_snapshot
 5969                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 5970                        {
 5971                            let indent_size =
 5972                                buffer.indent_size_for_line(line_buffer_range.start.row);
 5973                            let indent_len = match indent_size.kind {
 5974                                IndentKind::Space => {
 5975                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 5976                                }
 5977                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 5978                            };
 5979                            if old_head.column <= indent_size.len && old_head.column > 0 {
 5980                                let indent_len = indent_len.get();
 5981                                new_head = cmp::min(
 5982                                    new_head,
 5983                                    MultiBufferPoint::new(
 5984                                        old_head.row,
 5985                                        ((old_head.column - 1) / indent_len) * indent_len,
 5986                                    ),
 5987                                );
 5988                            }
 5989                        }
 5990
 5991                        selection.set_head(new_head, SelectionGoal::None);
 5992                    }
 5993                }
 5994            }
 5995
 5996            this.signature_help_state.set_backspace_pressed(true);
 5997            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5998            this.insert("", cx);
 5999            let empty_str: Arc<str> = Arc::from("");
 6000            for (buffer, edits) in linked_ranges {
 6001                let snapshot = buffer.read(cx).snapshot();
 6002                use text::ToPoint as TP;
 6003
 6004                let edits = edits
 6005                    .into_iter()
 6006                    .map(|range| {
 6007                        let end_point = TP::to_point(&range.end, &snapshot);
 6008                        let mut start_point = TP::to_point(&range.start, &snapshot);
 6009
 6010                        if end_point == start_point {
 6011                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 6012                                .saturating_sub(1);
 6013                            start_point = TP::to_point(&offset, &snapshot);
 6014                        };
 6015
 6016                        (start_point..end_point, empty_str.clone())
 6017                    })
 6018                    .sorted_by_key(|(range, _)| range.start)
 6019                    .collect::<Vec<_>>();
 6020                buffer.update(cx, |this, cx| {
 6021                    this.edit(edits, None, cx);
 6022                })
 6023            }
 6024            this.refresh_inline_completion(true, false, cx);
 6025            linked_editing_ranges::refresh_linked_ranges(this, cx);
 6026        });
 6027    }
 6028
 6029    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 6030        self.transact(cx, |this, cx| {
 6031            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6032                let line_mode = s.line_mode;
 6033                s.move_with(|map, selection| {
 6034                    if selection.is_empty() && !line_mode {
 6035                        let cursor = movement::right(map, selection.head());
 6036                        selection.end = cursor;
 6037                        selection.reversed = true;
 6038                        selection.goal = SelectionGoal::None;
 6039                    }
 6040                })
 6041            });
 6042            this.insert("", cx);
 6043            this.refresh_inline_completion(true, false, cx);
 6044        });
 6045    }
 6046
 6047    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 6048        if self.move_to_prev_snippet_tabstop(cx) {
 6049            return;
 6050        }
 6051
 6052        self.outdent(&Outdent, cx);
 6053    }
 6054
 6055    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 6056        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 6057            return;
 6058        }
 6059
 6060        let mut selections = self.selections.all_adjusted(cx);
 6061        let buffer = self.buffer.read(cx);
 6062        let snapshot = buffer.snapshot(cx);
 6063        let rows_iter = selections.iter().map(|s| s.head().row);
 6064        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 6065
 6066        let mut edits = Vec::new();
 6067        let mut prev_edited_row = 0;
 6068        let mut row_delta = 0;
 6069        for selection in &mut selections {
 6070            if selection.start.row != prev_edited_row {
 6071                row_delta = 0;
 6072            }
 6073            prev_edited_row = selection.end.row;
 6074
 6075            // If the selection is non-empty, then increase the indentation of the selected lines.
 6076            if !selection.is_empty() {
 6077                row_delta =
 6078                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6079                continue;
 6080            }
 6081
 6082            // If the selection is empty and the cursor is in the leading whitespace before the
 6083            // suggested indentation, then auto-indent the line.
 6084            let cursor = selection.head();
 6085            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 6086            if let Some(suggested_indent) =
 6087                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 6088            {
 6089                if cursor.column < suggested_indent.len
 6090                    && cursor.column <= current_indent.len
 6091                    && current_indent.len <= suggested_indent.len
 6092                {
 6093                    selection.start = Point::new(cursor.row, suggested_indent.len);
 6094                    selection.end = selection.start;
 6095                    if row_delta == 0 {
 6096                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 6097                            cursor.row,
 6098                            current_indent,
 6099                            suggested_indent,
 6100                        ));
 6101                        row_delta = suggested_indent.len - current_indent.len;
 6102                    }
 6103                    continue;
 6104                }
 6105            }
 6106
 6107            // Otherwise, insert a hard or soft tab.
 6108            let settings = buffer.settings_at(cursor, cx);
 6109            let tab_size = if settings.hard_tabs {
 6110                IndentSize::tab()
 6111            } else {
 6112                let tab_size = settings.tab_size.get();
 6113                let char_column = snapshot
 6114                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 6115                    .flat_map(str::chars)
 6116                    .count()
 6117                    + row_delta as usize;
 6118                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 6119                IndentSize::spaces(chars_to_next_tab_stop)
 6120            };
 6121            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 6122            selection.end = selection.start;
 6123            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 6124            row_delta += tab_size.len;
 6125        }
 6126
 6127        self.transact(cx, |this, cx| {
 6128            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6129            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6130            this.refresh_inline_completion(true, false, cx);
 6131        });
 6132    }
 6133
 6134    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 6135        if self.read_only(cx) {
 6136            return;
 6137        }
 6138        let mut selections = self.selections.all::<Point>(cx);
 6139        let mut prev_edited_row = 0;
 6140        let mut row_delta = 0;
 6141        let mut edits = Vec::new();
 6142        let buffer = self.buffer.read(cx);
 6143        let snapshot = buffer.snapshot(cx);
 6144        for selection in &mut selections {
 6145            if selection.start.row != prev_edited_row {
 6146                row_delta = 0;
 6147            }
 6148            prev_edited_row = selection.end.row;
 6149
 6150            row_delta =
 6151                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6152        }
 6153
 6154        self.transact(cx, |this, cx| {
 6155            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6156            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6157        });
 6158    }
 6159
 6160    fn indent_selection(
 6161        buffer: &MultiBuffer,
 6162        snapshot: &MultiBufferSnapshot,
 6163        selection: &mut Selection<Point>,
 6164        edits: &mut Vec<(Range<Point>, String)>,
 6165        delta_for_start_row: u32,
 6166        cx: &AppContext,
 6167    ) -> u32 {
 6168        let settings = buffer.settings_at(selection.start, cx);
 6169        let tab_size = settings.tab_size.get();
 6170        let indent_kind = if settings.hard_tabs {
 6171            IndentKind::Tab
 6172        } else {
 6173            IndentKind::Space
 6174        };
 6175        let mut start_row = selection.start.row;
 6176        let mut end_row = selection.end.row + 1;
 6177
 6178        // If a selection ends at the beginning of a line, don't indent
 6179        // that last line.
 6180        if selection.end.column == 0 && selection.end.row > selection.start.row {
 6181            end_row -= 1;
 6182        }
 6183
 6184        // Avoid re-indenting a row that has already been indented by a
 6185        // previous selection, but still update this selection's column
 6186        // to reflect that indentation.
 6187        if delta_for_start_row > 0 {
 6188            start_row += 1;
 6189            selection.start.column += delta_for_start_row;
 6190            if selection.end.row == selection.start.row {
 6191                selection.end.column += delta_for_start_row;
 6192            }
 6193        }
 6194
 6195        let mut delta_for_end_row = 0;
 6196        let has_multiple_rows = start_row + 1 != end_row;
 6197        for row in start_row..end_row {
 6198            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 6199            let indent_delta = match (current_indent.kind, indent_kind) {
 6200                (IndentKind::Space, IndentKind::Space) => {
 6201                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 6202                    IndentSize::spaces(columns_to_next_tab_stop)
 6203                }
 6204                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 6205                (_, IndentKind::Tab) => IndentSize::tab(),
 6206            };
 6207
 6208            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 6209                0
 6210            } else {
 6211                selection.start.column
 6212            };
 6213            let row_start = Point::new(row, start);
 6214            edits.push((
 6215                row_start..row_start,
 6216                indent_delta.chars().collect::<String>(),
 6217            ));
 6218
 6219            // Update this selection's endpoints to reflect the indentation.
 6220            if row == selection.start.row {
 6221                selection.start.column += indent_delta.len;
 6222            }
 6223            if row == selection.end.row {
 6224                selection.end.column += indent_delta.len;
 6225                delta_for_end_row = indent_delta.len;
 6226            }
 6227        }
 6228
 6229        if selection.start.row == selection.end.row {
 6230            delta_for_start_row + delta_for_end_row
 6231        } else {
 6232            delta_for_end_row
 6233        }
 6234    }
 6235
 6236    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 6237        if self.read_only(cx) {
 6238            return;
 6239        }
 6240        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6241        let selections = self.selections.all::<Point>(cx);
 6242        let mut deletion_ranges = Vec::new();
 6243        let mut last_outdent = None;
 6244        {
 6245            let buffer = self.buffer.read(cx);
 6246            let snapshot = buffer.snapshot(cx);
 6247            for selection in &selections {
 6248                let settings = buffer.settings_at(selection.start, cx);
 6249                let tab_size = settings.tab_size.get();
 6250                let mut rows = selection.spanned_rows(false, &display_map);
 6251
 6252                // Avoid re-outdenting a row that has already been outdented by a
 6253                // previous selection.
 6254                if let Some(last_row) = last_outdent {
 6255                    if last_row == rows.start {
 6256                        rows.start = rows.start.next_row();
 6257                    }
 6258                }
 6259                let has_multiple_rows = rows.len() > 1;
 6260                for row in rows.iter_rows() {
 6261                    let indent_size = snapshot.indent_size_for_line(row);
 6262                    if indent_size.len > 0 {
 6263                        let deletion_len = match indent_size.kind {
 6264                            IndentKind::Space => {
 6265                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 6266                                if columns_to_prev_tab_stop == 0 {
 6267                                    tab_size
 6268                                } else {
 6269                                    columns_to_prev_tab_stop
 6270                                }
 6271                            }
 6272                            IndentKind::Tab => 1,
 6273                        };
 6274                        let start = if has_multiple_rows
 6275                            || deletion_len > selection.start.column
 6276                            || indent_size.len < selection.start.column
 6277                        {
 6278                            0
 6279                        } else {
 6280                            selection.start.column - deletion_len
 6281                        };
 6282                        deletion_ranges.push(
 6283                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 6284                        );
 6285                        last_outdent = Some(row);
 6286                    }
 6287                }
 6288            }
 6289        }
 6290
 6291        self.transact(cx, |this, cx| {
 6292            this.buffer.update(cx, |buffer, cx| {
 6293                let empty_str: Arc<str> = Arc::default();
 6294                buffer.edit(
 6295                    deletion_ranges
 6296                        .into_iter()
 6297                        .map(|range| (range, empty_str.clone())),
 6298                    None,
 6299                    cx,
 6300                );
 6301            });
 6302            let selections = this.selections.all::<usize>(cx);
 6303            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6304        });
 6305    }
 6306
 6307    pub fn autoindent(&mut self, _: &AutoIndent, cx: &mut ViewContext<Self>) {
 6308        if self.read_only(cx) {
 6309            return;
 6310        }
 6311        let selections = self
 6312            .selections
 6313            .all::<usize>(cx)
 6314            .into_iter()
 6315            .map(|s| s.range());
 6316
 6317        self.transact(cx, |this, cx| {
 6318            this.buffer.update(cx, |buffer, cx| {
 6319                buffer.autoindent_ranges(selections, cx);
 6320            });
 6321            let selections = this.selections.all::<usize>(cx);
 6322            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6323        });
 6324    }
 6325
 6326    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 6327        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6328        let selections = self.selections.all::<Point>(cx);
 6329
 6330        let mut new_cursors = Vec::new();
 6331        let mut edit_ranges = Vec::new();
 6332        let mut selections = selections.iter().peekable();
 6333        while let Some(selection) = selections.next() {
 6334            let mut rows = selection.spanned_rows(false, &display_map);
 6335            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6336
 6337            // Accumulate contiguous regions of rows that we want to delete.
 6338            while let Some(next_selection) = selections.peek() {
 6339                let next_rows = next_selection.spanned_rows(false, &display_map);
 6340                if next_rows.start <= rows.end {
 6341                    rows.end = next_rows.end;
 6342                    selections.next().unwrap();
 6343                } else {
 6344                    break;
 6345                }
 6346            }
 6347
 6348            let buffer = &display_map.buffer_snapshot;
 6349            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6350            let edit_end;
 6351            let cursor_buffer_row;
 6352            if buffer.max_point().row >= rows.end.0 {
 6353                // If there's a line after the range, delete the \n from the end of the row range
 6354                // and position the cursor on the next line.
 6355                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6356                cursor_buffer_row = rows.end;
 6357            } else {
 6358                // If there isn't a line after the range, delete the \n from the line before the
 6359                // start of the row range and position the cursor there.
 6360                edit_start = edit_start.saturating_sub(1);
 6361                edit_end = buffer.len();
 6362                cursor_buffer_row = rows.start.previous_row();
 6363            }
 6364
 6365            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6366            *cursor.column_mut() =
 6367                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6368
 6369            new_cursors.push((
 6370                selection.id,
 6371                buffer.anchor_after(cursor.to_point(&display_map)),
 6372            ));
 6373            edit_ranges.push(edit_start..edit_end);
 6374        }
 6375
 6376        self.transact(cx, |this, cx| {
 6377            let buffer = this.buffer.update(cx, |buffer, cx| {
 6378                let empty_str: Arc<str> = Arc::default();
 6379                buffer.edit(
 6380                    edit_ranges
 6381                        .into_iter()
 6382                        .map(|range| (range, empty_str.clone())),
 6383                    None,
 6384                    cx,
 6385                );
 6386                buffer.snapshot(cx)
 6387            });
 6388            let new_selections = new_cursors
 6389                .into_iter()
 6390                .map(|(id, cursor)| {
 6391                    let cursor = cursor.to_point(&buffer);
 6392                    Selection {
 6393                        id,
 6394                        start: cursor,
 6395                        end: cursor,
 6396                        reversed: false,
 6397                        goal: SelectionGoal::None,
 6398                    }
 6399                })
 6400                .collect();
 6401
 6402            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6403                s.select(new_selections);
 6404            });
 6405        });
 6406    }
 6407
 6408    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 6409        if self.read_only(cx) {
 6410            return;
 6411        }
 6412        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6413        for selection in self.selections.all::<Point>(cx) {
 6414            let start = MultiBufferRow(selection.start.row);
 6415            // Treat single line selections as if they include the next line. Otherwise this action
 6416            // would do nothing for single line selections individual cursors.
 6417            let end = if selection.start.row == selection.end.row {
 6418                MultiBufferRow(selection.start.row + 1)
 6419            } else {
 6420                MultiBufferRow(selection.end.row)
 6421            };
 6422
 6423            if let Some(last_row_range) = row_ranges.last_mut() {
 6424                if start <= last_row_range.end {
 6425                    last_row_range.end = end;
 6426                    continue;
 6427                }
 6428            }
 6429            row_ranges.push(start..end);
 6430        }
 6431
 6432        let snapshot = self.buffer.read(cx).snapshot(cx);
 6433        let mut cursor_positions = Vec::new();
 6434        for row_range in &row_ranges {
 6435            let anchor = snapshot.anchor_before(Point::new(
 6436                row_range.end.previous_row().0,
 6437                snapshot.line_len(row_range.end.previous_row()),
 6438            ));
 6439            cursor_positions.push(anchor..anchor);
 6440        }
 6441
 6442        self.transact(cx, |this, cx| {
 6443            for row_range in row_ranges.into_iter().rev() {
 6444                for row in row_range.iter_rows().rev() {
 6445                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6446                    let next_line_row = row.next_row();
 6447                    let indent = snapshot.indent_size_for_line(next_line_row);
 6448                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 6449
 6450                    let replace = if snapshot.line_len(next_line_row) > indent.len {
 6451                        " "
 6452                    } else {
 6453                        ""
 6454                    };
 6455
 6456                    this.buffer.update(cx, |buffer, cx| {
 6457                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6458                    });
 6459                }
 6460            }
 6461
 6462            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6463                s.select_anchor_ranges(cursor_positions)
 6464            });
 6465        });
 6466    }
 6467
 6468    pub fn sort_lines_case_sensitive(
 6469        &mut self,
 6470        _: &SortLinesCaseSensitive,
 6471        cx: &mut ViewContext<Self>,
 6472    ) {
 6473        self.manipulate_lines(cx, |lines| lines.sort())
 6474    }
 6475
 6476    pub fn sort_lines_case_insensitive(
 6477        &mut self,
 6478        _: &SortLinesCaseInsensitive,
 6479        cx: &mut ViewContext<Self>,
 6480    ) {
 6481        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 6482    }
 6483
 6484    pub fn unique_lines_case_insensitive(
 6485        &mut self,
 6486        _: &UniqueLinesCaseInsensitive,
 6487        cx: &mut ViewContext<Self>,
 6488    ) {
 6489        self.manipulate_lines(cx, |lines| {
 6490            let mut seen = HashSet::default();
 6491            lines.retain(|line| seen.insert(line.to_lowercase()));
 6492        })
 6493    }
 6494
 6495    pub fn unique_lines_case_sensitive(
 6496        &mut self,
 6497        _: &UniqueLinesCaseSensitive,
 6498        cx: &mut ViewContext<Self>,
 6499    ) {
 6500        self.manipulate_lines(cx, |lines| {
 6501            let mut seen = HashSet::default();
 6502            lines.retain(|line| seen.insert(*line));
 6503        })
 6504    }
 6505
 6506    pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
 6507        let mut revert_changes = HashMap::default();
 6508        let snapshot = self.snapshot(cx);
 6509        for hunk in hunks_for_ranges(
 6510            Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter(),
 6511            &snapshot,
 6512        ) {
 6513            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6514        }
 6515        if !revert_changes.is_empty() {
 6516            self.transact(cx, |editor, cx| {
 6517                editor.revert(revert_changes, cx);
 6518            });
 6519        }
 6520    }
 6521
 6522    pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
 6523        let Some(project) = self.project.clone() else {
 6524            return;
 6525        };
 6526        self.reload(project, cx).detach_and_notify_err(cx);
 6527    }
 6528
 6529    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 6530        let revert_changes = self.gather_revert_changes(&self.selections.all(cx), cx);
 6531        if !revert_changes.is_empty() {
 6532            self.transact(cx, |editor, cx| {
 6533                editor.revert(revert_changes, cx);
 6534            });
 6535        }
 6536    }
 6537
 6538    fn revert_hunk(&mut self, hunk: HoveredHunk, cx: &mut ViewContext<Editor>) {
 6539        let snapshot = self.buffer.read(cx).read(cx);
 6540        if let Some(hunk) = crate::hunk_diff::to_diff_hunk(&hunk, &snapshot) {
 6541            drop(snapshot);
 6542            let mut revert_changes = HashMap::default();
 6543            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6544            if !revert_changes.is_empty() {
 6545                self.revert(revert_changes, cx)
 6546            }
 6547        }
 6548    }
 6549
 6550    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 6551        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6552            let project_path = buffer.read(cx).project_path(cx)?;
 6553            let project = self.project.as_ref()?.read(cx);
 6554            let entry = project.entry_for_path(&project_path, cx)?;
 6555            let parent = match &entry.canonical_path {
 6556                Some(canonical_path) => canonical_path.to_path_buf(),
 6557                None => project.absolute_path(&project_path, cx)?,
 6558            }
 6559            .parent()?
 6560            .to_path_buf();
 6561            Some(parent)
 6562        }) {
 6563            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 6564        }
 6565    }
 6566
 6567    fn gather_revert_changes(
 6568        &mut self,
 6569        selections: &[Selection<Point>],
 6570        cx: &mut ViewContext<'_, Editor>,
 6571    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 6572        let mut revert_changes = HashMap::default();
 6573        let snapshot = self.snapshot(cx);
 6574        for hunk in hunks_for_selections(&snapshot, selections) {
 6575            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6576        }
 6577        revert_changes
 6578    }
 6579
 6580    pub fn prepare_revert_change(
 6581        &mut self,
 6582        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6583        hunk: &MultiBufferDiffHunk,
 6584        cx: &AppContext,
 6585    ) -> Option<()> {
 6586        let buffer = self.buffer.read(cx).buffer(hunk.buffer_id)?;
 6587        let buffer = buffer.read(cx);
 6588        let change_set = &self.diff_map.diff_bases.get(&hunk.buffer_id)?.change_set;
 6589        let original_text = change_set
 6590            .read(cx)
 6591            .base_text
 6592            .as_ref()?
 6593            .read(cx)
 6594            .as_rope()
 6595            .slice(hunk.diff_base_byte_range.clone());
 6596        let buffer_snapshot = buffer.snapshot();
 6597        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6598        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6599            probe
 6600                .0
 6601                .start
 6602                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6603                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6604        }) {
 6605            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6606            Some(())
 6607        } else {
 6608            None
 6609        }
 6610    }
 6611
 6612    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 6613        self.manipulate_lines(cx, |lines| lines.reverse())
 6614    }
 6615
 6616    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 6617        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 6618    }
 6619
 6620    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6621    where
 6622        Fn: FnMut(&mut Vec<&str>),
 6623    {
 6624        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6625        let buffer = self.buffer.read(cx).snapshot(cx);
 6626
 6627        let mut edits = Vec::new();
 6628
 6629        let selections = self.selections.all::<Point>(cx);
 6630        let mut selections = selections.iter().peekable();
 6631        let mut contiguous_row_selections = Vec::new();
 6632        let mut new_selections = Vec::new();
 6633        let mut added_lines = 0;
 6634        let mut removed_lines = 0;
 6635
 6636        while let Some(selection) = selections.next() {
 6637            let (start_row, end_row) = consume_contiguous_rows(
 6638                &mut contiguous_row_selections,
 6639                selection,
 6640                &display_map,
 6641                &mut selections,
 6642            );
 6643
 6644            let start_point = Point::new(start_row.0, 0);
 6645            let end_point = Point::new(
 6646                end_row.previous_row().0,
 6647                buffer.line_len(end_row.previous_row()),
 6648            );
 6649            let text = buffer
 6650                .text_for_range(start_point..end_point)
 6651                .collect::<String>();
 6652
 6653            let mut lines = text.split('\n').collect_vec();
 6654
 6655            let lines_before = lines.len();
 6656            callback(&mut lines);
 6657            let lines_after = lines.len();
 6658
 6659            edits.push((start_point..end_point, lines.join("\n")));
 6660
 6661            // Selections must change based on added and removed line count
 6662            let start_row =
 6663                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6664            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6665            new_selections.push(Selection {
 6666                id: selection.id,
 6667                start: start_row,
 6668                end: end_row,
 6669                goal: SelectionGoal::None,
 6670                reversed: selection.reversed,
 6671            });
 6672
 6673            if lines_after > lines_before {
 6674                added_lines += lines_after - lines_before;
 6675            } else if lines_before > lines_after {
 6676                removed_lines += lines_before - lines_after;
 6677            }
 6678        }
 6679
 6680        self.transact(cx, |this, cx| {
 6681            let buffer = this.buffer.update(cx, |buffer, cx| {
 6682                buffer.edit(edits, None, cx);
 6683                buffer.snapshot(cx)
 6684            });
 6685
 6686            // Recalculate offsets on newly edited buffer
 6687            let new_selections = new_selections
 6688                .iter()
 6689                .map(|s| {
 6690                    let start_point = Point::new(s.start.0, 0);
 6691                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6692                    Selection {
 6693                        id: s.id,
 6694                        start: buffer.point_to_offset(start_point),
 6695                        end: buffer.point_to_offset(end_point),
 6696                        goal: s.goal,
 6697                        reversed: s.reversed,
 6698                    }
 6699                })
 6700                .collect();
 6701
 6702            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6703                s.select(new_selections);
 6704            });
 6705
 6706            this.request_autoscroll(Autoscroll::fit(), cx);
 6707        });
 6708    }
 6709
 6710    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 6711        self.manipulate_text(cx, |text| text.to_uppercase())
 6712    }
 6713
 6714    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 6715        self.manipulate_text(cx, |text| text.to_lowercase())
 6716    }
 6717
 6718    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 6719        self.manipulate_text(cx, |text| {
 6720            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6721            // https://github.com/rutrum/convert-case/issues/16
 6722            text.split('\n')
 6723                .map(|line| line.to_case(Case::Title))
 6724                .join("\n")
 6725        })
 6726    }
 6727
 6728    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6729        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6730    }
 6731
 6732    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6733        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6734    }
 6735
 6736    pub fn convert_to_upper_camel_case(
 6737        &mut self,
 6738        _: &ConvertToUpperCamelCase,
 6739        cx: &mut ViewContext<Self>,
 6740    ) {
 6741        self.manipulate_text(cx, |text| {
 6742            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6743            // https://github.com/rutrum/convert-case/issues/16
 6744            text.split('\n')
 6745                .map(|line| line.to_case(Case::UpperCamel))
 6746                .join("\n")
 6747        })
 6748    }
 6749
 6750    pub fn convert_to_lower_camel_case(
 6751        &mut self,
 6752        _: &ConvertToLowerCamelCase,
 6753        cx: &mut ViewContext<Self>,
 6754    ) {
 6755        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6756    }
 6757
 6758    pub fn convert_to_opposite_case(
 6759        &mut self,
 6760        _: &ConvertToOppositeCase,
 6761        cx: &mut ViewContext<Self>,
 6762    ) {
 6763        self.manipulate_text(cx, |text| {
 6764            text.chars()
 6765                .fold(String::with_capacity(text.len()), |mut t, c| {
 6766                    if c.is_uppercase() {
 6767                        t.extend(c.to_lowercase());
 6768                    } else {
 6769                        t.extend(c.to_uppercase());
 6770                    }
 6771                    t
 6772                })
 6773        })
 6774    }
 6775
 6776    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6777    where
 6778        Fn: FnMut(&str) -> String,
 6779    {
 6780        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6781        let buffer = self.buffer.read(cx).snapshot(cx);
 6782
 6783        let mut new_selections = Vec::new();
 6784        let mut edits = Vec::new();
 6785        let mut selection_adjustment = 0i32;
 6786
 6787        for selection in self.selections.all::<usize>(cx) {
 6788            let selection_is_empty = selection.is_empty();
 6789
 6790            let (start, end) = if selection_is_empty {
 6791                let word_range = movement::surrounding_word(
 6792                    &display_map,
 6793                    selection.start.to_display_point(&display_map),
 6794                );
 6795                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6796                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6797                (start, end)
 6798            } else {
 6799                (selection.start, selection.end)
 6800            };
 6801
 6802            let text = buffer.text_for_range(start..end).collect::<String>();
 6803            let old_length = text.len() as i32;
 6804            let text = callback(&text);
 6805
 6806            new_selections.push(Selection {
 6807                start: (start as i32 - selection_adjustment) as usize,
 6808                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6809                goal: SelectionGoal::None,
 6810                ..selection
 6811            });
 6812
 6813            selection_adjustment += old_length - text.len() as i32;
 6814
 6815            edits.push((start..end, text));
 6816        }
 6817
 6818        self.transact(cx, |this, cx| {
 6819            this.buffer.update(cx, |buffer, cx| {
 6820                buffer.edit(edits, None, cx);
 6821            });
 6822
 6823            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6824                s.select(new_selections);
 6825            });
 6826
 6827            this.request_autoscroll(Autoscroll::fit(), cx);
 6828        });
 6829    }
 6830
 6831    pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
 6832        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6833        let buffer = &display_map.buffer_snapshot;
 6834        let selections = self.selections.all::<Point>(cx);
 6835
 6836        let mut edits = Vec::new();
 6837        let mut selections_iter = selections.iter().peekable();
 6838        while let Some(selection) = selections_iter.next() {
 6839            // Avoid duplicating the same lines twice.
 6840            let mut rows = selection.spanned_rows(false, &display_map);
 6841
 6842            while let Some(next_selection) = selections_iter.peek() {
 6843                let next_rows = next_selection.spanned_rows(false, &display_map);
 6844                if next_rows.start < rows.end {
 6845                    rows.end = next_rows.end;
 6846                    selections_iter.next().unwrap();
 6847                } else {
 6848                    break;
 6849                }
 6850            }
 6851
 6852            // Copy the text from the selected row region and splice it either at the start
 6853            // or end of the region.
 6854            let start = Point::new(rows.start.0, 0);
 6855            let end = Point::new(
 6856                rows.end.previous_row().0,
 6857                buffer.line_len(rows.end.previous_row()),
 6858            );
 6859            let text = buffer
 6860                .text_for_range(start..end)
 6861                .chain(Some("\n"))
 6862                .collect::<String>();
 6863            let insert_location = if upwards {
 6864                Point::new(rows.end.0, 0)
 6865            } else {
 6866                start
 6867            };
 6868            edits.push((insert_location..insert_location, text));
 6869        }
 6870
 6871        self.transact(cx, |this, cx| {
 6872            this.buffer.update(cx, |buffer, cx| {
 6873                buffer.edit(edits, None, cx);
 6874            });
 6875
 6876            this.request_autoscroll(Autoscroll::fit(), cx);
 6877        });
 6878    }
 6879
 6880    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6881        self.duplicate_line(true, cx);
 6882    }
 6883
 6884    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6885        self.duplicate_line(false, cx);
 6886    }
 6887
 6888    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6889        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6890        let buffer = self.buffer.read(cx).snapshot(cx);
 6891
 6892        let mut edits = Vec::new();
 6893        let mut unfold_ranges = Vec::new();
 6894        let mut refold_creases = Vec::new();
 6895
 6896        let selections = self.selections.all::<Point>(cx);
 6897        let mut selections = selections.iter().peekable();
 6898        let mut contiguous_row_selections = Vec::new();
 6899        let mut new_selections = Vec::new();
 6900
 6901        while let Some(selection) = selections.next() {
 6902            // Find all the selections that span a contiguous row range
 6903            let (start_row, end_row) = consume_contiguous_rows(
 6904                &mut contiguous_row_selections,
 6905                selection,
 6906                &display_map,
 6907                &mut selections,
 6908            );
 6909
 6910            // Move the text spanned by the row range to be before the line preceding the row range
 6911            if start_row.0 > 0 {
 6912                let range_to_move = Point::new(
 6913                    start_row.previous_row().0,
 6914                    buffer.line_len(start_row.previous_row()),
 6915                )
 6916                    ..Point::new(
 6917                        end_row.previous_row().0,
 6918                        buffer.line_len(end_row.previous_row()),
 6919                    );
 6920                let insertion_point = display_map
 6921                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6922                    .0;
 6923
 6924                // Don't move lines across excerpts
 6925                if buffer
 6926                    .excerpt_boundaries_in_range((
 6927                        Bound::Excluded(insertion_point),
 6928                        Bound::Included(range_to_move.end),
 6929                    ))
 6930                    .next()
 6931                    .is_none()
 6932                {
 6933                    let text = buffer
 6934                        .text_for_range(range_to_move.clone())
 6935                        .flat_map(|s| s.chars())
 6936                        .skip(1)
 6937                        .chain(['\n'])
 6938                        .collect::<String>();
 6939
 6940                    edits.push((
 6941                        buffer.anchor_after(range_to_move.start)
 6942                            ..buffer.anchor_before(range_to_move.end),
 6943                        String::new(),
 6944                    ));
 6945                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6946                    edits.push((insertion_anchor..insertion_anchor, text));
 6947
 6948                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6949
 6950                    // Move selections up
 6951                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6952                        |mut selection| {
 6953                            selection.start.row -= row_delta;
 6954                            selection.end.row -= row_delta;
 6955                            selection
 6956                        },
 6957                    ));
 6958
 6959                    // Move folds up
 6960                    unfold_ranges.push(range_to_move.clone());
 6961                    for fold in display_map.folds_in_range(
 6962                        buffer.anchor_before(range_to_move.start)
 6963                            ..buffer.anchor_after(range_to_move.end),
 6964                    ) {
 6965                        let mut start = fold.range.start.to_point(&buffer);
 6966                        let mut end = fold.range.end.to_point(&buffer);
 6967                        start.row -= row_delta;
 6968                        end.row -= row_delta;
 6969                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6970                    }
 6971                }
 6972            }
 6973
 6974            // If we didn't move line(s), preserve the existing selections
 6975            new_selections.append(&mut contiguous_row_selections);
 6976        }
 6977
 6978        self.transact(cx, |this, cx| {
 6979            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6980            this.buffer.update(cx, |buffer, cx| {
 6981                for (range, text) in edits {
 6982                    buffer.edit([(range, text)], None, cx);
 6983                }
 6984            });
 6985            this.fold_creases(refold_creases, true, cx);
 6986            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6987                s.select(new_selections);
 6988            })
 6989        });
 6990    }
 6991
 6992    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 6993        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6994        let buffer = self.buffer.read(cx).snapshot(cx);
 6995
 6996        let mut edits = Vec::new();
 6997        let mut unfold_ranges = Vec::new();
 6998        let mut refold_creases = Vec::new();
 6999
 7000        let selections = self.selections.all::<Point>(cx);
 7001        let mut selections = selections.iter().peekable();
 7002        let mut contiguous_row_selections = Vec::new();
 7003        let mut new_selections = Vec::new();
 7004
 7005        while let Some(selection) = selections.next() {
 7006            // Find all the selections that span a contiguous row range
 7007            let (start_row, end_row) = consume_contiguous_rows(
 7008                &mut contiguous_row_selections,
 7009                selection,
 7010                &display_map,
 7011                &mut selections,
 7012            );
 7013
 7014            // Move the text spanned by the row range to be after the last line of the row range
 7015            if end_row.0 <= buffer.max_point().row {
 7016                let range_to_move =
 7017                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 7018                let insertion_point = display_map
 7019                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 7020                    .0;
 7021
 7022                // Don't move lines across excerpt boundaries
 7023                if buffer
 7024                    .excerpt_boundaries_in_range((
 7025                        Bound::Excluded(range_to_move.start),
 7026                        Bound::Included(insertion_point),
 7027                    ))
 7028                    .next()
 7029                    .is_none()
 7030                {
 7031                    let mut text = String::from("\n");
 7032                    text.extend(buffer.text_for_range(range_to_move.clone()));
 7033                    text.pop(); // Drop trailing newline
 7034                    edits.push((
 7035                        buffer.anchor_after(range_to_move.start)
 7036                            ..buffer.anchor_before(range_to_move.end),
 7037                        String::new(),
 7038                    ));
 7039                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7040                    edits.push((insertion_anchor..insertion_anchor, text));
 7041
 7042                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 7043
 7044                    // Move selections down
 7045                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7046                        |mut selection| {
 7047                            selection.start.row += row_delta;
 7048                            selection.end.row += row_delta;
 7049                            selection
 7050                        },
 7051                    ));
 7052
 7053                    // Move folds down
 7054                    unfold_ranges.push(range_to_move.clone());
 7055                    for fold in display_map.folds_in_range(
 7056                        buffer.anchor_before(range_to_move.start)
 7057                            ..buffer.anchor_after(range_to_move.end),
 7058                    ) {
 7059                        let mut start = fold.range.start.to_point(&buffer);
 7060                        let mut end = fold.range.end.to_point(&buffer);
 7061                        start.row += row_delta;
 7062                        end.row += row_delta;
 7063                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7064                    }
 7065                }
 7066            }
 7067
 7068            // If we didn't move line(s), preserve the existing selections
 7069            new_selections.append(&mut contiguous_row_selections);
 7070        }
 7071
 7072        self.transact(cx, |this, cx| {
 7073            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7074            this.buffer.update(cx, |buffer, cx| {
 7075                for (range, text) in edits {
 7076                    buffer.edit([(range, text)], None, cx);
 7077                }
 7078            });
 7079            this.fold_creases(refold_creases, true, cx);
 7080            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 7081        });
 7082    }
 7083
 7084    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 7085        let text_layout_details = &self.text_layout_details(cx);
 7086        self.transact(cx, |this, cx| {
 7087            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7088                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 7089                let line_mode = s.line_mode;
 7090                s.move_with(|display_map, selection| {
 7091                    if !selection.is_empty() || line_mode {
 7092                        return;
 7093                    }
 7094
 7095                    let mut head = selection.head();
 7096                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 7097                    if head.column() == display_map.line_len(head.row()) {
 7098                        transpose_offset = display_map
 7099                            .buffer_snapshot
 7100                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7101                    }
 7102
 7103                    if transpose_offset == 0 {
 7104                        return;
 7105                    }
 7106
 7107                    *head.column_mut() += 1;
 7108                    head = display_map.clip_point(head, Bias::Right);
 7109                    let goal = SelectionGoal::HorizontalPosition(
 7110                        display_map
 7111                            .x_for_display_point(head, text_layout_details)
 7112                            .into(),
 7113                    );
 7114                    selection.collapse_to(head, goal);
 7115
 7116                    let transpose_start = display_map
 7117                        .buffer_snapshot
 7118                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7119                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 7120                        let transpose_end = display_map
 7121                            .buffer_snapshot
 7122                            .clip_offset(transpose_offset + 1, Bias::Right);
 7123                        if let Some(ch) =
 7124                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 7125                        {
 7126                            edits.push((transpose_start..transpose_offset, String::new()));
 7127                            edits.push((transpose_end..transpose_end, ch.to_string()));
 7128                        }
 7129                    }
 7130                });
 7131                edits
 7132            });
 7133            this.buffer
 7134                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7135            let selections = this.selections.all::<usize>(cx);
 7136            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7137                s.select(selections);
 7138            });
 7139        });
 7140    }
 7141
 7142    pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
 7143        self.rewrap_impl(IsVimMode::No, cx)
 7144    }
 7145
 7146    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
 7147        let buffer = self.buffer.read(cx).snapshot(cx);
 7148        let selections = self.selections.all::<Point>(cx);
 7149        let mut selections = selections.iter().peekable();
 7150
 7151        let mut edits = Vec::new();
 7152        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 7153
 7154        while let Some(selection) = selections.next() {
 7155            let mut start_row = selection.start.row;
 7156            let mut end_row = selection.end.row;
 7157
 7158            // Skip selections that overlap with a range that has already been rewrapped.
 7159            let selection_range = start_row..end_row;
 7160            if rewrapped_row_ranges
 7161                .iter()
 7162                .any(|range| range.overlaps(&selection_range))
 7163            {
 7164                continue;
 7165            }
 7166
 7167            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 7168
 7169            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 7170                match language_scope.language_name().0.as_ref() {
 7171                    "Markdown" | "Plain Text" => {
 7172                        should_rewrap = true;
 7173                    }
 7174                    _ => {}
 7175                }
 7176            }
 7177
 7178            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 7179
 7180            // Since not all lines in the selection may be at the same indent
 7181            // level, choose the indent size that is the most common between all
 7182            // of the lines.
 7183            //
 7184            // If there is a tie, we use the deepest indent.
 7185            let (indent_size, indent_end) = {
 7186                let mut indent_size_occurrences = HashMap::default();
 7187                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 7188
 7189                for row in start_row..=end_row {
 7190                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 7191                    rows_by_indent_size.entry(indent).or_default().push(row);
 7192                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 7193                }
 7194
 7195                let indent_size = indent_size_occurrences
 7196                    .into_iter()
 7197                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 7198                    .map(|(indent, _)| indent)
 7199                    .unwrap_or_default();
 7200                let row = rows_by_indent_size[&indent_size][0];
 7201                let indent_end = Point::new(row, indent_size.len);
 7202
 7203                (indent_size, indent_end)
 7204            };
 7205
 7206            let mut line_prefix = indent_size.chars().collect::<String>();
 7207
 7208            if let Some(comment_prefix) =
 7209                buffer
 7210                    .language_scope_at(selection.head())
 7211                    .and_then(|language| {
 7212                        language
 7213                            .line_comment_prefixes()
 7214                            .iter()
 7215                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 7216                            .cloned()
 7217                    })
 7218            {
 7219                line_prefix.push_str(&comment_prefix);
 7220                should_rewrap = true;
 7221            }
 7222
 7223            if !should_rewrap {
 7224                continue;
 7225            }
 7226
 7227            if selection.is_empty() {
 7228                'expand_upwards: while start_row > 0 {
 7229                    let prev_row = start_row - 1;
 7230                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 7231                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 7232                    {
 7233                        start_row = prev_row;
 7234                    } else {
 7235                        break 'expand_upwards;
 7236                    }
 7237                }
 7238
 7239                'expand_downwards: while end_row < buffer.max_point().row {
 7240                    let next_row = end_row + 1;
 7241                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 7242                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 7243                    {
 7244                        end_row = next_row;
 7245                    } else {
 7246                        break 'expand_downwards;
 7247                    }
 7248                }
 7249            }
 7250
 7251            let start = Point::new(start_row, 0);
 7252            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 7253            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 7254            let Some(lines_without_prefixes) = selection_text
 7255                .lines()
 7256                .map(|line| {
 7257                    line.strip_prefix(&line_prefix)
 7258                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 7259                        .ok_or_else(|| {
 7260                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 7261                        })
 7262                })
 7263                .collect::<Result<Vec<_>, _>>()
 7264                .log_err()
 7265            else {
 7266                continue;
 7267            };
 7268
 7269            let wrap_column = buffer
 7270                .settings_at(Point::new(start_row, 0), cx)
 7271                .preferred_line_length as usize;
 7272            let wrapped_text = wrap_with_prefix(
 7273                line_prefix,
 7274                lines_without_prefixes.join(" "),
 7275                wrap_column,
 7276                tab_size,
 7277            );
 7278
 7279            // TODO: should always use char-based diff while still supporting cursor behavior that
 7280            // matches vim.
 7281            let diff = match is_vim_mode {
 7282                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 7283                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 7284            };
 7285            let mut offset = start.to_offset(&buffer);
 7286            let mut moved_since_edit = true;
 7287
 7288            for change in diff.iter_all_changes() {
 7289                let value = change.value();
 7290                match change.tag() {
 7291                    ChangeTag::Equal => {
 7292                        offset += value.len();
 7293                        moved_since_edit = true;
 7294                    }
 7295                    ChangeTag::Delete => {
 7296                        let start = buffer.anchor_after(offset);
 7297                        let end = buffer.anchor_before(offset + value.len());
 7298
 7299                        if moved_since_edit {
 7300                            edits.push((start..end, String::new()));
 7301                        } else {
 7302                            edits.last_mut().unwrap().0.end = end;
 7303                        }
 7304
 7305                        offset += value.len();
 7306                        moved_since_edit = false;
 7307                    }
 7308                    ChangeTag::Insert => {
 7309                        if moved_since_edit {
 7310                            let anchor = buffer.anchor_after(offset);
 7311                            edits.push((anchor..anchor, value.to_string()));
 7312                        } else {
 7313                            edits.last_mut().unwrap().1.push_str(value);
 7314                        }
 7315
 7316                        moved_since_edit = false;
 7317                    }
 7318                }
 7319            }
 7320
 7321            rewrapped_row_ranges.push(start_row..=end_row);
 7322        }
 7323
 7324        self.buffer
 7325            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7326    }
 7327
 7328    pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
 7329        let mut text = String::new();
 7330        let buffer = self.buffer.read(cx).snapshot(cx);
 7331        let mut selections = self.selections.all::<Point>(cx);
 7332        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7333        {
 7334            let max_point = buffer.max_point();
 7335            let mut is_first = true;
 7336            for selection in &mut selections {
 7337                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7338                if is_entire_line {
 7339                    selection.start = Point::new(selection.start.row, 0);
 7340                    if !selection.is_empty() && selection.end.column == 0 {
 7341                        selection.end = cmp::min(max_point, selection.end);
 7342                    } else {
 7343                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7344                    }
 7345                    selection.goal = SelectionGoal::None;
 7346                }
 7347                if is_first {
 7348                    is_first = false;
 7349                } else {
 7350                    text += "\n";
 7351                }
 7352                let mut len = 0;
 7353                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7354                    text.push_str(chunk);
 7355                    len += chunk.len();
 7356                }
 7357                clipboard_selections.push(ClipboardSelection {
 7358                    len,
 7359                    is_entire_line,
 7360                    first_line_indent: buffer
 7361                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7362                        .len,
 7363                });
 7364            }
 7365        }
 7366
 7367        self.transact(cx, |this, cx| {
 7368            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7369                s.select(selections);
 7370            });
 7371            this.insert("", cx);
 7372        });
 7373        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 7374    }
 7375
 7376    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 7377        let item = self.cut_common(cx);
 7378        cx.write_to_clipboard(item);
 7379    }
 7380
 7381    pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
 7382        self.change_selections(None, cx, |s| {
 7383            s.move_with(|snapshot, sel| {
 7384                if sel.is_empty() {
 7385                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 7386                }
 7387            });
 7388        });
 7389        let item = self.cut_common(cx);
 7390        cx.set_global(KillRing(item))
 7391    }
 7392
 7393    pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
 7394        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 7395            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 7396                (kill_ring.text().to_string(), kill_ring.metadata_json())
 7397            } else {
 7398                return;
 7399            }
 7400        } else {
 7401            return;
 7402        };
 7403        self.do_paste(&text, metadata, false, cx);
 7404    }
 7405
 7406    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 7407        let selections = self.selections.all::<Point>(cx);
 7408        let buffer = self.buffer.read(cx).read(cx);
 7409        let mut text = String::new();
 7410
 7411        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7412        {
 7413            let max_point = buffer.max_point();
 7414            let mut is_first = true;
 7415            for selection in selections.iter() {
 7416                let mut start = selection.start;
 7417                let mut end = selection.end;
 7418                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7419                if is_entire_line {
 7420                    start = Point::new(start.row, 0);
 7421                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 7422                }
 7423                if is_first {
 7424                    is_first = false;
 7425                } else {
 7426                    text += "\n";
 7427                }
 7428                let mut len = 0;
 7429                for chunk in buffer.text_for_range(start..end) {
 7430                    text.push_str(chunk);
 7431                    len += chunk.len();
 7432                }
 7433                clipboard_selections.push(ClipboardSelection {
 7434                    len,
 7435                    is_entire_line,
 7436                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 7437                });
 7438            }
 7439        }
 7440
 7441        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7442            text,
 7443            clipboard_selections,
 7444        ));
 7445    }
 7446
 7447    pub fn do_paste(
 7448        &mut self,
 7449        text: &String,
 7450        clipboard_selections: Option<Vec<ClipboardSelection>>,
 7451        handle_entire_lines: bool,
 7452        cx: &mut ViewContext<Self>,
 7453    ) {
 7454        if self.read_only(cx) {
 7455            return;
 7456        }
 7457
 7458        let clipboard_text = Cow::Borrowed(text);
 7459
 7460        self.transact(cx, |this, cx| {
 7461            if let Some(mut clipboard_selections) = clipboard_selections {
 7462                let old_selections = this.selections.all::<usize>(cx);
 7463                let all_selections_were_entire_line =
 7464                    clipboard_selections.iter().all(|s| s.is_entire_line);
 7465                let first_selection_indent_column =
 7466                    clipboard_selections.first().map(|s| s.first_line_indent);
 7467                if clipboard_selections.len() != old_selections.len() {
 7468                    clipboard_selections.drain(..);
 7469                }
 7470                let cursor_offset = this.selections.last::<usize>(cx).head();
 7471                let mut auto_indent_on_paste = true;
 7472
 7473                this.buffer.update(cx, |buffer, cx| {
 7474                    let snapshot = buffer.read(cx);
 7475                    auto_indent_on_paste =
 7476                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 7477
 7478                    let mut start_offset = 0;
 7479                    let mut edits = Vec::new();
 7480                    let mut original_indent_columns = Vec::new();
 7481                    for (ix, selection) in old_selections.iter().enumerate() {
 7482                        let to_insert;
 7483                        let entire_line;
 7484                        let original_indent_column;
 7485                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 7486                            let end_offset = start_offset + clipboard_selection.len;
 7487                            to_insert = &clipboard_text[start_offset..end_offset];
 7488                            entire_line = clipboard_selection.is_entire_line;
 7489                            start_offset = end_offset + 1;
 7490                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7491                        } else {
 7492                            to_insert = clipboard_text.as_str();
 7493                            entire_line = all_selections_were_entire_line;
 7494                            original_indent_column = first_selection_indent_column
 7495                        }
 7496
 7497                        // If the corresponding selection was empty when this slice of the
 7498                        // clipboard text was written, then the entire line containing the
 7499                        // selection was copied. If this selection is also currently empty,
 7500                        // then paste the line before the current line of the buffer.
 7501                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7502                            let column = selection.start.to_point(&snapshot).column as usize;
 7503                            let line_start = selection.start - column;
 7504                            line_start..line_start
 7505                        } else {
 7506                            selection.range()
 7507                        };
 7508
 7509                        edits.push((range, to_insert));
 7510                        original_indent_columns.extend(original_indent_column);
 7511                    }
 7512                    drop(snapshot);
 7513
 7514                    buffer.edit(
 7515                        edits,
 7516                        if auto_indent_on_paste {
 7517                            Some(AutoindentMode::Block {
 7518                                original_indent_columns,
 7519                            })
 7520                        } else {
 7521                            None
 7522                        },
 7523                        cx,
 7524                    );
 7525                });
 7526
 7527                let selections = this.selections.all::<usize>(cx);
 7528                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 7529            } else {
 7530                this.insert(&clipboard_text, cx);
 7531            }
 7532        });
 7533    }
 7534
 7535    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 7536        if let Some(item) = cx.read_from_clipboard() {
 7537            let entries = item.entries();
 7538
 7539            match entries.first() {
 7540                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7541                // of all the pasted entries.
 7542                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7543                    .do_paste(
 7544                        clipboard_string.text(),
 7545                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7546                        true,
 7547                        cx,
 7548                    ),
 7549                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
 7550            }
 7551        }
 7552    }
 7553
 7554    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 7555        if self.read_only(cx) {
 7556            return;
 7557        }
 7558
 7559        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7560            if let Some((selections, _)) =
 7561                self.selection_history.transaction(transaction_id).cloned()
 7562            {
 7563                self.change_selections(None, cx, |s| {
 7564                    s.select_anchors(selections.to_vec());
 7565                });
 7566            }
 7567            self.request_autoscroll(Autoscroll::fit(), cx);
 7568            self.unmark_text(cx);
 7569            self.refresh_inline_completion(true, false, cx);
 7570            cx.emit(EditorEvent::Edited { transaction_id });
 7571            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7572        }
 7573    }
 7574
 7575    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 7576        if self.read_only(cx) {
 7577            return;
 7578        }
 7579
 7580        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7581            if let Some((_, Some(selections))) =
 7582                self.selection_history.transaction(transaction_id).cloned()
 7583            {
 7584                self.change_selections(None, cx, |s| {
 7585                    s.select_anchors(selections.to_vec());
 7586                });
 7587            }
 7588            self.request_autoscroll(Autoscroll::fit(), cx);
 7589            self.unmark_text(cx);
 7590            self.refresh_inline_completion(true, false, cx);
 7591            cx.emit(EditorEvent::Edited { transaction_id });
 7592        }
 7593    }
 7594
 7595    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 7596        self.buffer
 7597            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7598    }
 7599
 7600    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 7601        self.buffer
 7602            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7603    }
 7604
 7605    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 7606        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7607            let line_mode = s.line_mode;
 7608            s.move_with(|map, selection| {
 7609                let cursor = if selection.is_empty() && !line_mode {
 7610                    movement::left(map, selection.start)
 7611                } else {
 7612                    selection.start
 7613                };
 7614                selection.collapse_to(cursor, SelectionGoal::None);
 7615            });
 7616        })
 7617    }
 7618
 7619    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 7620        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7621            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7622        })
 7623    }
 7624
 7625    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 7626        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7627            let line_mode = s.line_mode;
 7628            s.move_with(|map, selection| {
 7629                let cursor = if selection.is_empty() && !line_mode {
 7630                    movement::right(map, selection.end)
 7631                } else {
 7632                    selection.end
 7633                };
 7634                selection.collapse_to(cursor, SelectionGoal::None)
 7635            });
 7636        })
 7637    }
 7638
 7639    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 7640        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7641            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7642        })
 7643    }
 7644
 7645    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 7646        if self.take_rename(true, cx).is_some() {
 7647            return;
 7648        }
 7649
 7650        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7651            cx.propagate();
 7652            return;
 7653        }
 7654
 7655        let text_layout_details = &self.text_layout_details(cx);
 7656        let selection_count = self.selections.count();
 7657        let first_selection = self.selections.first_anchor();
 7658
 7659        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7660            let line_mode = s.line_mode;
 7661            s.move_with(|map, selection| {
 7662                if !selection.is_empty() && !line_mode {
 7663                    selection.goal = SelectionGoal::None;
 7664                }
 7665                let (cursor, goal) = movement::up(
 7666                    map,
 7667                    selection.start,
 7668                    selection.goal,
 7669                    false,
 7670                    text_layout_details,
 7671                );
 7672                selection.collapse_to(cursor, goal);
 7673            });
 7674        });
 7675
 7676        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7677        {
 7678            cx.propagate();
 7679        }
 7680    }
 7681
 7682    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 7683        if self.take_rename(true, cx).is_some() {
 7684            return;
 7685        }
 7686
 7687        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7688            cx.propagate();
 7689            return;
 7690        }
 7691
 7692        let text_layout_details = &self.text_layout_details(cx);
 7693
 7694        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7695            let line_mode = s.line_mode;
 7696            s.move_with(|map, selection| {
 7697                if !selection.is_empty() && !line_mode {
 7698                    selection.goal = SelectionGoal::None;
 7699                }
 7700                let (cursor, goal) = movement::up_by_rows(
 7701                    map,
 7702                    selection.start,
 7703                    action.lines,
 7704                    selection.goal,
 7705                    false,
 7706                    text_layout_details,
 7707                );
 7708                selection.collapse_to(cursor, goal);
 7709            });
 7710        })
 7711    }
 7712
 7713    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 7714        if self.take_rename(true, cx).is_some() {
 7715            return;
 7716        }
 7717
 7718        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7719            cx.propagate();
 7720            return;
 7721        }
 7722
 7723        let text_layout_details = &self.text_layout_details(cx);
 7724
 7725        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7726            let line_mode = s.line_mode;
 7727            s.move_with(|map, selection| {
 7728                if !selection.is_empty() && !line_mode {
 7729                    selection.goal = SelectionGoal::None;
 7730                }
 7731                let (cursor, goal) = movement::down_by_rows(
 7732                    map,
 7733                    selection.start,
 7734                    action.lines,
 7735                    selection.goal,
 7736                    false,
 7737                    text_layout_details,
 7738                );
 7739                selection.collapse_to(cursor, goal);
 7740            });
 7741        })
 7742    }
 7743
 7744    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 7745        let text_layout_details = &self.text_layout_details(cx);
 7746        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7747            s.move_heads_with(|map, head, goal| {
 7748                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7749            })
 7750        })
 7751    }
 7752
 7753    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 7754        let text_layout_details = &self.text_layout_details(cx);
 7755        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7756            s.move_heads_with(|map, head, goal| {
 7757                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7758            })
 7759        })
 7760    }
 7761
 7762    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 7763        let Some(row_count) = self.visible_row_count() else {
 7764            return;
 7765        };
 7766
 7767        let text_layout_details = &self.text_layout_details(cx);
 7768
 7769        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7770            s.move_heads_with(|map, head, goal| {
 7771                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7772            })
 7773        })
 7774    }
 7775
 7776    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 7777        if self.take_rename(true, cx).is_some() {
 7778            return;
 7779        }
 7780
 7781        if self
 7782            .context_menu
 7783            .write()
 7784            .as_mut()
 7785            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 7786            .unwrap_or(false)
 7787        {
 7788            return;
 7789        }
 7790
 7791        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7792            cx.propagate();
 7793            return;
 7794        }
 7795
 7796        let Some(row_count) = self.visible_row_count() else {
 7797            return;
 7798        };
 7799
 7800        let autoscroll = if action.center_cursor {
 7801            Autoscroll::center()
 7802        } else {
 7803            Autoscroll::fit()
 7804        };
 7805
 7806        let text_layout_details = &self.text_layout_details(cx);
 7807
 7808        self.change_selections(Some(autoscroll), cx, |s| {
 7809            let line_mode = s.line_mode;
 7810            s.move_with(|map, selection| {
 7811                if !selection.is_empty() && !line_mode {
 7812                    selection.goal = SelectionGoal::None;
 7813                }
 7814                let (cursor, goal) = movement::up_by_rows(
 7815                    map,
 7816                    selection.end,
 7817                    row_count,
 7818                    selection.goal,
 7819                    false,
 7820                    text_layout_details,
 7821                );
 7822                selection.collapse_to(cursor, goal);
 7823            });
 7824        });
 7825    }
 7826
 7827    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 7828        let text_layout_details = &self.text_layout_details(cx);
 7829        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7830            s.move_heads_with(|map, head, goal| {
 7831                movement::up(map, head, goal, false, text_layout_details)
 7832            })
 7833        })
 7834    }
 7835
 7836    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 7837        self.take_rename(true, cx);
 7838
 7839        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7840            cx.propagate();
 7841            return;
 7842        }
 7843
 7844        let text_layout_details = &self.text_layout_details(cx);
 7845        let selection_count = self.selections.count();
 7846        let first_selection = self.selections.first_anchor();
 7847
 7848        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7849            let line_mode = s.line_mode;
 7850            s.move_with(|map, selection| {
 7851                if !selection.is_empty() && !line_mode {
 7852                    selection.goal = SelectionGoal::None;
 7853                }
 7854                let (cursor, goal) = movement::down(
 7855                    map,
 7856                    selection.end,
 7857                    selection.goal,
 7858                    false,
 7859                    text_layout_details,
 7860                );
 7861                selection.collapse_to(cursor, goal);
 7862            });
 7863        });
 7864
 7865        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7866        {
 7867            cx.propagate();
 7868        }
 7869    }
 7870
 7871    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 7872        let Some(row_count) = self.visible_row_count() else {
 7873            return;
 7874        };
 7875
 7876        let text_layout_details = &self.text_layout_details(cx);
 7877
 7878        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7879            s.move_heads_with(|map, head, goal| {
 7880                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 7881            })
 7882        })
 7883    }
 7884
 7885    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 7886        if self.take_rename(true, cx).is_some() {
 7887            return;
 7888        }
 7889
 7890        if self
 7891            .context_menu
 7892            .write()
 7893            .as_mut()
 7894            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 7895            .unwrap_or(false)
 7896        {
 7897            return;
 7898        }
 7899
 7900        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7901            cx.propagate();
 7902            return;
 7903        }
 7904
 7905        let Some(row_count) = self.visible_row_count() else {
 7906            return;
 7907        };
 7908
 7909        let autoscroll = if action.center_cursor {
 7910            Autoscroll::center()
 7911        } else {
 7912            Autoscroll::fit()
 7913        };
 7914
 7915        let text_layout_details = &self.text_layout_details(cx);
 7916        self.change_selections(Some(autoscroll), cx, |s| {
 7917            let line_mode = s.line_mode;
 7918            s.move_with(|map, selection| {
 7919                if !selection.is_empty() && !line_mode {
 7920                    selection.goal = SelectionGoal::None;
 7921                }
 7922                let (cursor, goal) = movement::down_by_rows(
 7923                    map,
 7924                    selection.end,
 7925                    row_count,
 7926                    selection.goal,
 7927                    false,
 7928                    text_layout_details,
 7929                );
 7930                selection.collapse_to(cursor, goal);
 7931            });
 7932        });
 7933    }
 7934
 7935    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 7936        let text_layout_details = &self.text_layout_details(cx);
 7937        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7938            s.move_heads_with(|map, head, goal| {
 7939                movement::down(map, head, goal, false, text_layout_details)
 7940            })
 7941        });
 7942    }
 7943
 7944    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 7945        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7946            context_menu.select_first(self.completion_provider.as_deref(), cx);
 7947        }
 7948    }
 7949
 7950    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 7951        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7952            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 7953        }
 7954    }
 7955
 7956    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7957        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7958            context_menu.select_next(self.completion_provider.as_deref(), cx);
 7959        }
 7960    }
 7961
 7962    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 7963        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7964            context_menu.select_last(self.completion_provider.as_deref(), cx);
 7965        }
 7966    }
 7967
 7968    pub fn move_to_previous_word_start(
 7969        &mut self,
 7970        _: &MoveToPreviousWordStart,
 7971        cx: &mut ViewContext<Self>,
 7972    ) {
 7973        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7974            s.move_cursors_with(|map, head, _| {
 7975                (
 7976                    movement::previous_word_start(map, head),
 7977                    SelectionGoal::None,
 7978                )
 7979            });
 7980        })
 7981    }
 7982
 7983    pub fn move_to_previous_subword_start(
 7984        &mut self,
 7985        _: &MoveToPreviousSubwordStart,
 7986        cx: &mut ViewContext<Self>,
 7987    ) {
 7988        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7989            s.move_cursors_with(|map, head, _| {
 7990                (
 7991                    movement::previous_subword_start(map, head),
 7992                    SelectionGoal::None,
 7993                )
 7994            });
 7995        })
 7996    }
 7997
 7998    pub fn select_to_previous_word_start(
 7999        &mut self,
 8000        _: &SelectToPreviousWordStart,
 8001        cx: &mut ViewContext<Self>,
 8002    ) {
 8003        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8004            s.move_heads_with(|map, head, _| {
 8005                (
 8006                    movement::previous_word_start(map, head),
 8007                    SelectionGoal::None,
 8008                )
 8009            });
 8010        })
 8011    }
 8012
 8013    pub fn select_to_previous_subword_start(
 8014        &mut self,
 8015        _: &SelectToPreviousSubwordStart,
 8016        cx: &mut ViewContext<Self>,
 8017    ) {
 8018        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8019            s.move_heads_with(|map, head, _| {
 8020                (
 8021                    movement::previous_subword_start(map, head),
 8022                    SelectionGoal::None,
 8023                )
 8024            });
 8025        })
 8026    }
 8027
 8028    pub fn delete_to_previous_word_start(
 8029        &mut self,
 8030        action: &DeleteToPreviousWordStart,
 8031        cx: &mut ViewContext<Self>,
 8032    ) {
 8033        self.transact(cx, |this, cx| {
 8034            this.select_autoclose_pair(cx);
 8035            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8036                let line_mode = s.line_mode;
 8037                s.move_with(|map, selection| {
 8038                    if selection.is_empty() && !line_mode {
 8039                        let cursor = if action.ignore_newlines {
 8040                            movement::previous_word_start(map, selection.head())
 8041                        } else {
 8042                            movement::previous_word_start_or_newline(map, selection.head())
 8043                        };
 8044                        selection.set_head(cursor, SelectionGoal::None);
 8045                    }
 8046                });
 8047            });
 8048            this.insert("", cx);
 8049        });
 8050    }
 8051
 8052    pub fn delete_to_previous_subword_start(
 8053        &mut self,
 8054        _: &DeleteToPreviousSubwordStart,
 8055        cx: &mut ViewContext<Self>,
 8056    ) {
 8057        self.transact(cx, |this, cx| {
 8058            this.select_autoclose_pair(cx);
 8059            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8060                let line_mode = s.line_mode;
 8061                s.move_with(|map, selection| {
 8062                    if selection.is_empty() && !line_mode {
 8063                        let cursor = movement::previous_subword_start(map, selection.head());
 8064                        selection.set_head(cursor, SelectionGoal::None);
 8065                    }
 8066                });
 8067            });
 8068            this.insert("", cx);
 8069        });
 8070    }
 8071
 8072    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 8073        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8074            s.move_cursors_with(|map, head, _| {
 8075                (movement::next_word_end(map, head), SelectionGoal::None)
 8076            });
 8077        })
 8078    }
 8079
 8080    pub fn move_to_next_subword_end(
 8081        &mut self,
 8082        _: &MoveToNextSubwordEnd,
 8083        cx: &mut ViewContext<Self>,
 8084    ) {
 8085        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8086            s.move_cursors_with(|map, head, _| {
 8087                (movement::next_subword_end(map, head), SelectionGoal::None)
 8088            });
 8089        })
 8090    }
 8091
 8092    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 8093        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8094            s.move_heads_with(|map, head, _| {
 8095                (movement::next_word_end(map, head), SelectionGoal::None)
 8096            });
 8097        })
 8098    }
 8099
 8100    pub fn select_to_next_subword_end(
 8101        &mut self,
 8102        _: &SelectToNextSubwordEnd,
 8103        cx: &mut ViewContext<Self>,
 8104    ) {
 8105        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8106            s.move_heads_with(|map, head, _| {
 8107                (movement::next_subword_end(map, head), SelectionGoal::None)
 8108            });
 8109        })
 8110    }
 8111
 8112    pub fn delete_to_next_word_end(
 8113        &mut self,
 8114        action: &DeleteToNextWordEnd,
 8115        cx: &mut ViewContext<Self>,
 8116    ) {
 8117        self.transact(cx, |this, cx| {
 8118            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8119                let line_mode = s.line_mode;
 8120                s.move_with(|map, selection| {
 8121                    if selection.is_empty() && !line_mode {
 8122                        let cursor = if action.ignore_newlines {
 8123                            movement::next_word_end(map, selection.head())
 8124                        } else {
 8125                            movement::next_word_end_or_newline(map, selection.head())
 8126                        };
 8127                        selection.set_head(cursor, SelectionGoal::None);
 8128                    }
 8129                });
 8130            });
 8131            this.insert("", cx);
 8132        });
 8133    }
 8134
 8135    pub fn delete_to_next_subword_end(
 8136        &mut self,
 8137        _: &DeleteToNextSubwordEnd,
 8138        cx: &mut ViewContext<Self>,
 8139    ) {
 8140        self.transact(cx, |this, cx| {
 8141            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8142                s.move_with(|map, selection| {
 8143                    if selection.is_empty() {
 8144                        let cursor = movement::next_subword_end(map, selection.head());
 8145                        selection.set_head(cursor, SelectionGoal::None);
 8146                    }
 8147                });
 8148            });
 8149            this.insert("", cx);
 8150        });
 8151    }
 8152
 8153    pub fn move_to_beginning_of_line(
 8154        &mut self,
 8155        action: &MoveToBeginningOfLine,
 8156        cx: &mut ViewContext<Self>,
 8157    ) {
 8158        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8159            s.move_cursors_with(|map, head, _| {
 8160                (
 8161                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8162                    SelectionGoal::None,
 8163                )
 8164            });
 8165        })
 8166    }
 8167
 8168    pub fn select_to_beginning_of_line(
 8169        &mut self,
 8170        action: &SelectToBeginningOfLine,
 8171        cx: &mut ViewContext<Self>,
 8172    ) {
 8173        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8174            s.move_heads_with(|map, head, _| {
 8175                (
 8176                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8177                    SelectionGoal::None,
 8178                )
 8179            });
 8180        });
 8181    }
 8182
 8183    pub fn delete_to_beginning_of_line(
 8184        &mut self,
 8185        _: &DeleteToBeginningOfLine,
 8186        cx: &mut ViewContext<Self>,
 8187    ) {
 8188        self.transact(cx, |this, cx| {
 8189            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8190                s.move_with(|_, selection| {
 8191                    selection.reversed = true;
 8192                });
 8193            });
 8194
 8195            this.select_to_beginning_of_line(
 8196                &SelectToBeginningOfLine {
 8197                    stop_at_soft_wraps: false,
 8198                },
 8199                cx,
 8200            );
 8201            this.backspace(&Backspace, cx);
 8202        });
 8203    }
 8204
 8205    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 8206        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8207            s.move_cursors_with(|map, head, _| {
 8208                (
 8209                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8210                    SelectionGoal::None,
 8211                )
 8212            });
 8213        })
 8214    }
 8215
 8216    pub fn select_to_end_of_line(
 8217        &mut self,
 8218        action: &SelectToEndOfLine,
 8219        cx: &mut ViewContext<Self>,
 8220    ) {
 8221        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8222            s.move_heads_with(|map, head, _| {
 8223                (
 8224                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8225                    SelectionGoal::None,
 8226                )
 8227            });
 8228        })
 8229    }
 8230
 8231    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 8232        self.transact(cx, |this, cx| {
 8233            this.select_to_end_of_line(
 8234                &SelectToEndOfLine {
 8235                    stop_at_soft_wraps: false,
 8236                },
 8237                cx,
 8238            );
 8239            this.delete(&Delete, cx);
 8240        });
 8241    }
 8242
 8243    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 8244        self.transact(cx, |this, cx| {
 8245            this.select_to_end_of_line(
 8246                &SelectToEndOfLine {
 8247                    stop_at_soft_wraps: false,
 8248                },
 8249                cx,
 8250            );
 8251            this.cut(&Cut, cx);
 8252        });
 8253    }
 8254
 8255    pub fn move_to_start_of_paragraph(
 8256        &mut self,
 8257        _: &MoveToStartOfParagraph,
 8258        cx: &mut ViewContext<Self>,
 8259    ) {
 8260        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8261            cx.propagate();
 8262            return;
 8263        }
 8264
 8265        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8266            s.move_with(|map, selection| {
 8267                selection.collapse_to(
 8268                    movement::start_of_paragraph(map, selection.head(), 1),
 8269                    SelectionGoal::None,
 8270                )
 8271            });
 8272        })
 8273    }
 8274
 8275    pub fn move_to_end_of_paragraph(
 8276        &mut self,
 8277        _: &MoveToEndOfParagraph,
 8278        cx: &mut ViewContext<Self>,
 8279    ) {
 8280        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8281            cx.propagate();
 8282            return;
 8283        }
 8284
 8285        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8286            s.move_with(|map, selection| {
 8287                selection.collapse_to(
 8288                    movement::end_of_paragraph(map, selection.head(), 1),
 8289                    SelectionGoal::None,
 8290                )
 8291            });
 8292        })
 8293    }
 8294
 8295    pub fn select_to_start_of_paragraph(
 8296        &mut self,
 8297        _: &SelectToStartOfParagraph,
 8298        cx: &mut ViewContext<Self>,
 8299    ) {
 8300        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8301            cx.propagate();
 8302            return;
 8303        }
 8304
 8305        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8306            s.move_heads_with(|map, head, _| {
 8307                (
 8308                    movement::start_of_paragraph(map, head, 1),
 8309                    SelectionGoal::None,
 8310                )
 8311            });
 8312        })
 8313    }
 8314
 8315    pub fn select_to_end_of_paragraph(
 8316        &mut self,
 8317        _: &SelectToEndOfParagraph,
 8318        cx: &mut ViewContext<Self>,
 8319    ) {
 8320        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8321            cx.propagate();
 8322            return;
 8323        }
 8324
 8325        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8326            s.move_heads_with(|map, head, _| {
 8327                (
 8328                    movement::end_of_paragraph(map, head, 1),
 8329                    SelectionGoal::None,
 8330                )
 8331            });
 8332        })
 8333    }
 8334
 8335    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 8336        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8337            cx.propagate();
 8338            return;
 8339        }
 8340
 8341        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8342            s.select_ranges(vec![0..0]);
 8343        });
 8344    }
 8345
 8346    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 8347        let mut selection = self.selections.last::<Point>(cx);
 8348        selection.set_head(Point::zero(), SelectionGoal::None);
 8349
 8350        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8351            s.select(vec![selection]);
 8352        });
 8353    }
 8354
 8355    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 8356        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8357            cx.propagate();
 8358            return;
 8359        }
 8360
 8361        let cursor = self.buffer.read(cx).read(cx).len();
 8362        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8363            s.select_ranges(vec![cursor..cursor])
 8364        });
 8365    }
 8366
 8367    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 8368        self.nav_history = nav_history;
 8369    }
 8370
 8371    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 8372        self.nav_history.as_ref()
 8373    }
 8374
 8375    fn push_to_nav_history(
 8376        &mut self,
 8377        cursor_anchor: Anchor,
 8378        new_position: Option<Point>,
 8379        cx: &mut ViewContext<Self>,
 8380    ) {
 8381        if let Some(nav_history) = self.nav_history.as_mut() {
 8382            let buffer = self.buffer.read(cx).read(cx);
 8383            let cursor_position = cursor_anchor.to_point(&buffer);
 8384            let scroll_state = self.scroll_manager.anchor();
 8385            let scroll_top_row = scroll_state.top_row(&buffer);
 8386            drop(buffer);
 8387
 8388            if let Some(new_position) = new_position {
 8389                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 8390                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 8391                    return;
 8392                }
 8393            }
 8394
 8395            nav_history.push(
 8396                Some(NavigationData {
 8397                    cursor_anchor,
 8398                    cursor_position,
 8399                    scroll_anchor: scroll_state,
 8400                    scroll_top_row,
 8401                }),
 8402                cx,
 8403            );
 8404        }
 8405    }
 8406
 8407    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 8408        let buffer = self.buffer.read(cx).snapshot(cx);
 8409        let mut selection = self.selections.first::<usize>(cx);
 8410        selection.set_head(buffer.len(), SelectionGoal::None);
 8411        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8412            s.select(vec![selection]);
 8413        });
 8414    }
 8415
 8416    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 8417        let end = self.buffer.read(cx).read(cx).len();
 8418        self.change_selections(None, cx, |s| {
 8419            s.select_ranges(vec![0..end]);
 8420        });
 8421    }
 8422
 8423    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 8424        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8425        let mut selections = self.selections.all::<Point>(cx);
 8426        let max_point = display_map.buffer_snapshot.max_point();
 8427        for selection in &mut selections {
 8428            let rows = selection.spanned_rows(true, &display_map);
 8429            selection.start = Point::new(rows.start.0, 0);
 8430            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 8431            selection.reversed = false;
 8432        }
 8433        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8434            s.select(selections);
 8435        });
 8436    }
 8437
 8438    pub fn split_selection_into_lines(
 8439        &mut self,
 8440        _: &SplitSelectionIntoLines,
 8441        cx: &mut ViewContext<Self>,
 8442    ) {
 8443        let mut to_unfold = Vec::new();
 8444        let mut new_selection_ranges = Vec::new();
 8445        {
 8446            let selections = self.selections.all::<Point>(cx);
 8447            let buffer = self.buffer.read(cx).read(cx);
 8448            for selection in selections {
 8449                for row in selection.start.row..selection.end.row {
 8450                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 8451                    new_selection_ranges.push(cursor..cursor);
 8452                }
 8453                new_selection_ranges.push(selection.end..selection.end);
 8454                to_unfold.push(selection.start..selection.end);
 8455            }
 8456        }
 8457        self.unfold_ranges(&to_unfold, true, true, cx);
 8458        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8459            s.select_ranges(new_selection_ranges);
 8460        });
 8461    }
 8462
 8463    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 8464        self.add_selection(true, cx);
 8465    }
 8466
 8467    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 8468        self.add_selection(false, cx);
 8469    }
 8470
 8471    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 8472        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8473        let mut selections = self.selections.all::<Point>(cx);
 8474        let text_layout_details = self.text_layout_details(cx);
 8475        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 8476            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 8477            let range = oldest_selection.display_range(&display_map).sorted();
 8478
 8479            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 8480            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 8481            let positions = start_x.min(end_x)..start_x.max(end_x);
 8482
 8483            selections.clear();
 8484            let mut stack = Vec::new();
 8485            for row in range.start.row().0..=range.end.row().0 {
 8486                if let Some(selection) = self.selections.build_columnar_selection(
 8487                    &display_map,
 8488                    DisplayRow(row),
 8489                    &positions,
 8490                    oldest_selection.reversed,
 8491                    &text_layout_details,
 8492                ) {
 8493                    stack.push(selection.id);
 8494                    selections.push(selection);
 8495                }
 8496            }
 8497
 8498            if above {
 8499                stack.reverse();
 8500            }
 8501
 8502            AddSelectionsState { above, stack }
 8503        });
 8504
 8505        let last_added_selection = *state.stack.last().unwrap();
 8506        let mut new_selections = Vec::new();
 8507        if above == state.above {
 8508            let end_row = if above {
 8509                DisplayRow(0)
 8510            } else {
 8511                display_map.max_point().row()
 8512            };
 8513
 8514            'outer: for selection in selections {
 8515                if selection.id == last_added_selection {
 8516                    let range = selection.display_range(&display_map).sorted();
 8517                    debug_assert_eq!(range.start.row(), range.end.row());
 8518                    let mut row = range.start.row();
 8519                    let positions =
 8520                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 8521                            px(start)..px(end)
 8522                        } else {
 8523                            let start_x =
 8524                                display_map.x_for_display_point(range.start, &text_layout_details);
 8525                            let end_x =
 8526                                display_map.x_for_display_point(range.end, &text_layout_details);
 8527                            start_x.min(end_x)..start_x.max(end_x)
 8528                        };
 8529
 8530                    while row != end_row {
 8531                        if above {
 8532                            row.0 -= 1;
 8533                        } else {
 8534                            row.0 += 1;
 8535                        }
 8536
 8537                        if let Some(new_selection) = self.selections.build_columnar_selection(
 8538                            &display_map,
 8539                            row,
 8540                            &positions,
 8541                            selection.reversed,
 8542                            &text_layout_details,
 8543                        ) {
 8544                            state.stack.push(new_selection.id);
 8545                            if above {
 8546                                new_selections.push(new_selection);
 8547                                new_selections.push(selection);
 8548                            } else {
 8549                                new_selections.push(selection);
 8550                                new_selections.push(new_selection);
 8551                            }
 8552
 8553                            continue 'outer;
 8554                        }
 8555                    }
 8556                }
 8557
 8558                new_selections.push(selection);
 8559            }
 8560        } else {
 8561            new_selections = selections;
 8562            new_selections.retain(|s| s.id != last_added_selection);
 8563            state.stack.pop();
 8564        }
 8565
 8566        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8567            s.select(new_selections);
 8568        });
 8569        if state.stack.len() > 1 {
 8570            self.add_selections_state = Some(state);
 8571        }
 8572    }
 8573
 8574    pub fn select_next_match_internal(
 8575        &mut self,
 8576        display_map: &DisplaySnapshot,
 8577        replace_newest: bool,
 8578        autoscroll: Option<Autoscroll>,
 8579        cx: &mut ViewContext<Self>,
 8580    ) -> Result<()> {
 8581        fn select_next_match_ranges(
 8582            this: &mut Editor,
 8583            range: Range<usize>,
 8584            replace_newest: bool,
 8585            auto_scroll: Option<Autoscroll>,
 8586            cx: &mut ViewContext<Editor>,
 8587        ) {
 8588            this.unfold_ranges(&[range.clone()], false, true, cx);
 8589            this.change_selections(auto_scroll, cx, |s| {
 8590                if replace_newest {
 8591                    s.delete(s.newest_anchor().id);
 8592                }
 8593                s.insert_range(range.clone());
 8594            });
 8595        }
 8596
 8597        let buffer = &display_map.buffer_snapshot;
 8598        let mut selections = self.selections.all::<usize>(cx);
 8599        if let Some(mut select_next_state) = self.select_next_state.take() {
 8600            let query = &select_next_state.query;
 8601            if !select_next_state.done {
 8602                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8603                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8604                let mut next_selected_range = None;
 8605
 8606                let bytes_after_last_selection =
 8607                    buffer.bytes_in_range(last_selection.end..buffer.len());
 8608                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 8609                let query_matches = query
 8610                    .stream_find_iter(bytes_after_last_selection)
 8611                    .map(|result| (last_selection.end, result))
 8612                    .chain(
 8613                        query
 8614                            .stream_find_iter(bytes_before_first_selection)
 8615                            .map(|result| (0, result)),
 8616                    );
 8617
 8618                for (start_offset, query_match) in query_matches {
 8619                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8620                    let offset_range =
 8621                        start_offset + query_match.start()..start_offset + query_match.end();
 8622                    let display_range = offset_range.start.to_display_point(display_map)
 8623                        ..offset_range.end.to_display_point(display_map);
 8624
 8625                    if !select_next_state.wordwise
 8626                        || (!movement::is_inside_word(display_map, display_range.start)
 8627                            && !movement::is_inside_word(display_map, display_range.end))
 8628                    {
 8629                        // TODO: This is n^2, because we might check all the selections
 8630                        if !selections
 8631                            .iter()
 8632                            .any(|selection| selection.range().overlaps(&offset_range))
 8633                        {
 8634                            next_selected_range = Some(offset_range);
 8635                            break;
 8636                        }
 8637                    }
 8638                }
 8639
 8640                if let Some(next_selected_range) = next_selected_range {
 8641                    select_next_match_ranges(
 8642                        self,
 8643                        next_selected_range,
 8644                        replace_newest,
 8645                        autoscroll,
 8646                        cx,
 8647                    );
 8648                } else {
 8649                    select_next_state.done = true;
 8650                }
 8651            }
 8652
 8653            self.select_next_state = Some(select_next_state);
 8654        } else {
 8655            let mut only_carets = true;
 8656            let mut same_text_selected = true;
 8657            let mut selected_text = None;
 8658
 8659            let mut selections_iter = selections.iter().peekable();
 8660            while let Some(selection) = selections_iter.next() {
 8661                if selection.start != selection.end {
 8662                    only_carets = false;
 8663                }
 8664
 8665                if same_text_selected {
 8666                    if selected_text.is_none() {
 8667                        selected_text =
 8668                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8669                    }
 8670
 8671                    if let Some(next_selection) = selections_iter.peek() {
 8672                        if next_selection.range().len() == selection.range().len() {
 8673                            let next_selected_text = buffer
 8674                                .text_for_range(next_selection.range())
 8675                                .collect::<String>();
 8676                            if Some(next_selected_text) != selected_text {
 8677                                same_text_selected = false;
 8678                                selected_text = None;
 8679                            }
 8680                        } else {
 8681                            same_text_selected = false;
 8682                            selected_text = None;
 8683                        }
 8684                    }
 8685                }
 8686            }
 8687
 8688            if only_carets {
 8689                for selection in &mut selections {
 8690                    let word_range = movement::surrounding_word(
 8691                        display_map,
 8692                        selection.start.to_display_point(display_map),
 8693                    );
 8694                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 8695                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 8696                    selection.goal = SelectionGoal::None;
 8697                    selection.reversed = false;
 8698                    select_next_match_ranges(
 8699                        self,
 8700                        selection.start..selection.end,
 8701                        replace_newest,
 8702                        autoscroll,
 8703                        cx,
 8704                    );
 8705                }
 8706
 8707                if selections.len() == 1 {
 8708                    let selection = selections
 8709                        .last()
 8710                        .expect("ensured that there's only one selection");
 8711                    let query = buffer
 8712                        .text_for_range(selection.start..selection.end)
 8713                        .collect::<String>();
 8714                    let is_empty = query.is_empty();
 8715                    let select_state = SelectNextState {
 8716                        query: AhoCorasick::new(&[query])?,
 8717                        wordwise: true,
 8718                        done: is_empty,
 8719                    };
 8720                    self.select_next_state = Some(select_state);
 8721                } else {
 8722                    self.select_next_state = None;
 8723                }
 8724            } else if let Some(selected_text) = selected_text {
 8725                self.select_next_state = Some(SelectNextState {
 8726                    query: AhoCorasick::new(&[selected_text])?,
 8727                    wordwise: false,
 8728                    done: false,
 8729                });
 8730                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 8731            }
 8732        }
 8733        Ok(())
 8734    }
 8735
 8736    pub fn select_all_matches(
 8737        &mut self,
 8738        _action: &SelectAllMatches,
 8739        cx: &mut ViewContext<Self>,
 8740    ) -> Result<()> {
 8741        self.push_to_selection_history();
 8742        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8743
 8744        self.select_next_match_internal(&display_map, false, None, cx)?;
 8745        let Some(select_next_state) = self.select_next_state.as_mut() else {
 8746            return Ok(());
 8747        };
 8748        if select_next_state.done {
 8749            return Ok(());
 8750        }
 8751
 8752        let mut new_selections = self.selections.all::<usize>(cx);
 8753
 8754        let buffer = &display_map.buffer_snapshot;
 8755        let query_matches = select_next_state
 8756            .query
 8757            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 8758
 8759        for query_match in query_matches {
 8760            let query_match = query_match.unwrap(); // can only fail due to I/O
 8761            let offset_range = query_match.start()..query_match.end();
 8762            let display_range = offset_range.start.to_display_point(&display_map)
 8763                ..offset_range.end.to_display_point(&display_map);
 8764
 8765            if !select_next_state.wordwise
 8766                || (!movement::is_inside_word(&display_map, display_range.start)
 8767                    && !movement::is_inside_word(&display_map, display_range.end))
 8768            {
 8769                self.selections.change_with(cx, |selections| {
 8770                    new_selections.push(Selection {
 8771                        id: selections.new_selection_id(),
 8772                        start: offset_range.start,
 8773                        end: offset_range.end,
 8774                        reversed: false,
 8775                        goal: SelectionGoal::None,
 8776                    });
 8777                });
 8778            }
 8779        }
 8780
 8781        new_selections.sort_by_key(|selection| selection.start);
 8782        let mut ix = 0;
 8783        while ix + 1 < new_selections.len() {
 8784            let current_selection = &new_selections[ix];
 8785            let next_selection = &new_selections[ix + 1];
 8786            if current_selection.range().overlaps(&next_selection.range()) {
 8787                if current_selection.id < next_selection.id {
 8788                    new_selections.remove(ix + 1);
 8789                } else {
 8790                    new_selections.remove(ix);
 8791                }
 8792            } else {
 8793                ix += 1;
 8794            }
 8795        }
 8796
 8797        select_next_state.done = true;
 8798        self.unfold_ranges(
 8799            &new_selections
 8800                .iter()
 8801                .map(|selection| selection.range())
 8802                .collect::<Vec<_>>(),
 8803            false,
 8804            false,
 8805            cx,
 8806        );
 8807        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 8808            selections.select(new_selections)
 8809        });
 8810
 8811        Ok(())
 8812    }
 8813
 8814    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 8815        self.push_to_selection_history();
 8816        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8817        self.select_next_match_internal(
 8818            &display_map,
 8819            action.replace_newest,
 8820            Some(Autoscroll::newest()),
 8821            cx,
 8822        )?;
 8823        Ok(())
 8824    }
 8825
 8826    pub fn select_previous(
 8827        &mut self,
 8828        action: &SelectPrevious,
 8829        cx: &mut ViewContext<Self>,
 8830    ) -> Result<()> {
 8831        self.push_to_selection_history();
 8832        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8833        let buffer = &display_map.buffer_snapshot;
 8834        let mut selections = self.selections.all::<usize>(cx);
 8835        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8836            let query = &select_prev_state.query;
 8837            if !select_prev_state.done {
 8838                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8839                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8840                let mut next_selected_range = None;
 8841                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8842                let bytes_before_last_selection =
 8843                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8844                let bytes_after_first_selection =
 8845                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8846                let query_matches = query
 8847                    .stream_find_iter(bytes_before_last_selection)
 8848                    .map(|result| (last_selection.start, result))
 8849                    .chain(
 8850                        query
 8851                            .stream_find_iter(bytes_after_first_selection)
 8852                            .map(|result| (buffer.len(), result)),
 8853                    );
 8854                for (end_offset, query_match) in query_matches {
 8855                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8856                    let offset_range =
 8857                        end_offset - query_match.end()..end_offset - query_match.start();
 8858                    let display_range = offset_range.start.to_display_point(&display_map)
 8859                        ..offset_range.end.to_display_point(&display_map);
 8860
 8861                    if !select_prev_state.wordwise
 8862                        || (!movement::is_inside_word(&display_map, display_range.start)
 8863                            && !movement::is_inside_word(&display_map, display_range.end))
 8864                    {
 8865                        next_selected_range = Some(offset_range);
 8866                        break;
 8867                    }
 8868                }
 8869
 8870                if let Some(next_selected_range) = next_selected_range {
 8871                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 8872                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8873                        if action.replace_newest {
 8874                            s.delete(s.newest_anchor().id);
 8875                        }
 8876                        s.insert_range(next_selected_range);
 8877                    });
 8878                } else {
 8879                    select_prev_state.done = true;
 8880                }
 8881            }
 8882
 8883            self.select_prev_state = Some(select_prev_state);
 8884        } else {
 8885            let mut only_carets = true;
 8886            let mut same_text_selected = true;
 8887            let mut selected_text = None;
 8888
 8889            let mut selections_iter = selections.iter().peekable();
 8890            while let Some(selection) = selections_iter.next() {
 8891                if selection.start != selection.end {
 8892                    only_carets = false;
 8893                }
 8894
 8895                if same_text_selected {
 8896                    if selected_text.is_none() {
 8897                        selected_text =
 8898                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8899                    }
 8900
 8901                    if let Some(next_selection) = selections_iter.peek() {
 8902                        if next_selection.range().len() == selection.range().len() {
 8903                            let next_selected_text = buffer
 8904                                .text_for_range(next_selection.range())
 8905                                .collect::<String>();
 8906                            if Some(next_selected_text) != selected_text {
 8907                                same_text_selected = false;
 8908                                selected_text = None;
 8909                            }
 8910                        } else {
 8911                            same_text_selected = false;
 8912                            selected_text = None;
 8913                        }
 8914                    }
 8915                }
 8916            }
 8917
 8918            if only_carets {
 8919                for selection in &mut selections {
 8920                    let word_range = movement::surrounding_word(
 8921                        &display_map,
 8922                        selection.start.to_display_point(&display_map),
 8923                    );
 8924                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8925                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8926                    selection.goal = SelectionGoal::None;
 8927                    selection.reversed = false;
 8928                }
 8929                if selections.len() == 1 {
 8930                    let selection = selections
 8931                        .last()
 8932                        .expect("ensured that there's only one selection");
 8933                    let query = buffer
 8934                        .text_for_range(selection.start..selection.end)
 8935                        .collect::<String>();
 8936                    let is_empty = query.is_empty();
 8937                    let select_state = SelectNextState {
 8938                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8939                        wordwise: true,
 8940                        done: is_empty,
 8941                    };
 8942                    self.select_prev_state = Some(select_state);
 8943                } else {
 8944                    self.select_prev_state = None;
 8945                }
 8946
 8947                self.unfold_ranges(
 8948                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8949                    false,
 8950                    true,
 8951                    cx,
 8952                );
 8953                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8954                    s.select(selections);
 8955                });
 8956            } else if let Some(selected_text) = selected_text {
 8957                self.select_prev_state = Some(SelectNextState {
 8958                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8959                    wordwise: false,
 8960                    done: false,
 8961                });
 8962                self.select_previous(action, cx)?;
 8963            }
 8964        }
 8965        Ok(())
 8966    }
 8967
 8968    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 8969        if self.read_only(cx) {
 8970            return;
 8971        }
 8972        let text_layout_details = &self.text_layout_details(cx);
 8973        self.transact(cx, |this, cx| {
 8974            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8975            let mut edits = Vec::new();
 8976            let mut selection_edit_ranges = Vec::new();
 8977            let mut last_toggled_row = None;
 8978            let snapshot = this.buffer.read(cx).read(cx);
 8979            let empty_str: Arc<str> = Arc::default();
 8980            let mut suffixes_inserted = Vec::new();
 8981            let ignore_indent = action.ignore_indent;
 8982
 8983            fn comment_prefix_range(
 8984                snapshot: &MultiBufferSnapshot,
 8985                row: MultiBufferRow,
 8986                comment_prefix: &str,
 8987                comment_prefix_whitespace: &str,
 8988                ignore_indent: bool,
 8989            ) -> Range<Point> {
 8990                let indent_size = if ignore_indent {
 8991                    0
 8992                } else {
 8993                    snapshot.indent_size_for_line(row).len
 8994                };
 8995
 8996                let start = Point::new(row.0, indent_size);
 8997
 8998                let mut line_bytes = snapshot
 8999                    .bytes_in_range(start..snapshot.max_point())
 9000                    .flatten()
 9001                    .copied();
 9002
 9003                // If this line currently begins with the line comment prefix, then record
 9004                // the range containing the prefix.
 9005                if line_bytes
 9006                    .by_ref()
 9007                    .take(comment_prefix.len())
 9008                    .eq(comment_prefix.bytes())
 9009                {
 9010                    // Include any whitespace that matches the comment prefix.
 9011                    let matching_whitespace_len = line_bytes
 9012                        .zip(comment_prefix_whitespace.bytes())
 9013                        .take_while(|(a, b)| a == b)
 9014                        .count() as u32;
 9015                    let end = Point::new(
 9016                        start.row,
 9017                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 9018                    );
 9019                    start..end
 9020                } else {
 9021                    start..start
 9022                }
 9023            }
 9024
 9025            fn comment_suffix_range(
 9026                snapshot: &MultiBufferSnapshot,
 9027                row: MultiBufferRow,
 9028                comment_suffix: &str,
 9029                comment_suffix_has_leading_space: bool,
 9030            ) -> Range<Point> {
 9031                let end = Point::new(row.0, snapshot.line_len(row));
 9032                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 9033
 9034                let mut line_end_bytes = snapshot
 9035                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 9036                    .flatten()
 9037                    .copied();
 9038
 9039                let leading_space_len = if suffix_start_column > 0
 9040                    && line_end_bytes.next() == Some(b' ')
 9041                    && comment_suffix_has_leading_space
 9042                {
 9043                    1
 9044                } else {
 9045                    0
 9046                };
 9047
 9048                // If this line currently begins with the line comment prefix, then record
 9049                // the range containing the prefix.
 9050                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 9051                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 9052                    start..end
 9053                } else {
 9054                    end..end
 9055                }
 9056            }
 9057
 9058            // TODO: Handle selections that cross excerpts
 9059            for selection in &mut selections {
 9060                let start_column = snapshot
 9061                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 9062                    .len;
 9063                let language = if let Some(language) =
 9064                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 9065                {
 9066                    language
 9067                } else {
 9068                    continue;
 9069                };
 9070
 9071                selection_edit_ranges.clear();
 9072
 9073                // If multiple selections contain a given row, avoid processing that
 9074                // row more than once.
 9075                let mut start_row = MultiBufferRow(selection.start.row);
 9076                if last_toggled_row == Some(start_row) {
 9077                    start_row = start_row.next_row();
 9078                }
 9079                let end_row =
 9080                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 9081                        MultiBufferRow(selection.end.row - 1)
 9082                    } else {
 9083                        MultiBufferRow(selection.end.row)
 9084                    };
 9085                last_toggled_row = Some(end_row);
 9086
 9087                if start_row > end_row {
 9088                    continue;
 9089                }
 9090
 9091                // If the language has line comments, toggle those.
 9092                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 9093
 9094                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 9095                if ignore_indent {
 9096                    full_comment_prefixes = full_comment_prefixes
 9097                        .into_iter()
 9098                        .map(|s| Arc::from(s.trim_end()))
 9099                        .collect();
 9100                }
 9101
 9102                if !full_comment_prefixes.is_empty() {
 9103                    let first_prefix = full_comment_prefixes
 9104                        .first()
 9105                        .expect("prefixes is non-empty");
 9106                    let prefix_trimmed_lengths = full_comment_prefixes
 9107                        .iter()
 9108                        .map(|p| p.trim_end_matches(' ').len())
 9109                        .collect::<SmallVec<[usize; 4]>>();
 9110
 9111                    let mut all_selection_lines_are_comments = true;
 9112
 9113                    for row in start_row.0..=end_row.0 {
 9114                        let row = MultiBufferRow(row);
 9115                        if start_row < end_row && snapshot.is_line_blank(row) {
 9116                            continue;
 9117                        }
 9118
 9119                        let prefix_range = full_comment_prefixes
 9120                            .iter()
 9121                            .zip(prefix_trimmed_lengths.iter().copied())
 9122                            .map(|(prefix, trimmed_prefix_len)| {
 9123                                comment_prefix_range(
 9124                                    snapshot.deref(),
 9125                                    row,
 9126                                    &prefix[..trimmed_prefix_len],
 9127                                    &prefix[trimmed_prefix_len..],
 9128                                    ignore_indent,
 9129                                )
 9130                            })
 9131                            .max_by_key(|range| range.end.column - range.start.column)
 9132                            .expect("prefixes is non-empty");
 9133
 9134                        if prefix_range.is_empty() {
 9135                            all_selection_lines_are_comments = false;
 9136                        }
 9137
 9138                        selection_edit_ranges.push(prefix_range);
 9139                    }
 9140
 9141                    if all_selection_lines_are_comments {
 9142                        edits.extend(
 9143                            selection_edit_ranges
 9144                                .iter()
 9145                                .cloned()
 9146                                .map(|range| (range, empty_str.clone())),
 9147                        );
 9148                    } else {
 9149                        let min_column = selection_edit_ranges
 9150                            .iter()
 9151                            .map(|range| range.start.column)
 9152                            .min()
 9153                            .unwrap_or(0);
 9154                        edits.extend(selection_edit_ranges.iter().map(|range| {
 9155                            let position = Point::new(range.start.row, min_column);
 9156                            (position..position, first_prefix.clone())
 9157                        }));
 9158                    }
 9159                } else if let Some((full_comment_prefix, comment_suffix)) =
 9160                    language.block_comment_delimiters()
 9161                {
 9162                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 9163                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 9164                    let prefix_range = comment_prefix_range(
 9165                        snapshot.deref(),
 9166                        start_row,
 9167                        comment_prefix,
 9168                        comment_prefix_whitespace,
 9169                        ignore_indent,
 9170                    );
 9171                    let suffix_range = comment_suffix_range(
 9172                        snapshot.deref(),
 9173                        end_row,
 9174                        comment_suffix.trim_start_matches(' '),
 9175                        comment_suffix.starts_with(' '),
 9176                    );
 9177
 9178                    if prefix_range.is_empty() || suffix_range.is_empty() {
 9179                        edits.push((
 9180                            prefix_range.start..prefix_range.start,
 9181                            full_comment_prefix.clone(),
 9182                        ));
 9183                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 9184                        suffixes_inserted.push((end_row, comment_suffix.len()));
 9185                    } else {
 9186                        edits.push((prefix_range, empty_str.clone()));
 9187                        edits.push((suffix_range, empty_str.clone()));
 9188                    }
 9189                } else {
 9190                    continue;
 9191                }
 9192            }
 9193
 9194            drop(snapshot);
 9195            this.buffer.update(cx, |buffer, cx| {
 9196                buffer.edit(edits, None, cx);
 9197            });
 9198
 9199            // Adjust selections so that they end before any comment suffixes that
 9200            // were inserted.
 9201            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 9202            let mut selections = this.selections.all::<Point>(cx);
 9203            let snapshot = this.buffer.read(cx).read(cx);
 9204            for selection in &mut selections {
 9205                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 9206                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 9207                        Ordering::Less => {
 9208                            suffixes_inserted.next();
 9209                            continue;
 9210                        }
 9211                        Ordering::Greater => break,
 9212                        Ordering::Equal => {
 9213                            if selection.end.column == snapshot.line_len(row) {
 9214                                if selection.is_empty() {
 9215                                    selection.start.column -= suffix_len as u32;
 9216                                }
 9217                                selection.end.column -= suffix_len as u32;
 9218                            }
 9219                            break;
 9220                        }
 9221                    }
 9222                }
 9223            }
 9224
 9225            drop(snapshot);
 9226            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 9227
 9228            let selections = this.selections.all::<Point>(cx);
 9229            let selections_on_single_row = selections.windows(2).all(|selections| {
 9230                selections[0].start.row == selections[1].start.row
 9231                    && selections[0].end.row == selections[1].end.row
 9232                    && selections[0].start.row == selections[0].end.row
 9233            });
 9234            let selections_selecting = selections
 9235                .iter()
 9236                .any(|selection| selection.start != selection.end);
 9237            let advance_downwards = action.advance_downwards
 9238                && selections_on_single_row
 9239                && !selections_selecting
 9240                && !matches!(this.mode, EditorMode::SingleLine { .. });
 9241
 9242            if advance_downwards {
 9243                let snapshot = this.buffer.read(cx).snapshot(cx);
 9244
 9245                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9246                    s.move_cursors_with(|display_snapshot, display_point, _| {
 9247                        let mut point = display_point.to_point(display_snapshot);
 9248                        point.row += 1;
 9249                        point = snapshot.clip_point(point, Bias::Left);
 9250                        let display_point = point.to_display_point(display_snapshot);
 9251                        let goal = SelectionGoal::HorizontalPosition(
 9252                            display_snapshot
 9253                                .x_for_display_point(display_point, text_layout_details)
 9254                                .into(),
 9255                        );
 9256                        (display_point, goal)
 9257                    })
 9258                });
 9259            }
 9260        });
 9261    }
 9262
 9263    pub fn select_enclosing_symbol(
 9264        &mut self,
 9265        _: &SelectEnclosingSymbol,
 9266        cx: &mut ViewContext<Self>,
 9267    ) {
 9268        let buffer = self.buffer.read(cx).snapshot(cx);
 9269        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9270
 9271        fn update_selection(
 9272            selection: &Selection<usize>,
 9273            buffer_snap: &MultiBufferSnapshot,
 9274        ) -> Option<Selection<usize>> {
 9275            let cursor = selection.head();
 9276            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 9277            for symbol in symbols.iter().rev() {
 9278                let start = symbol.range.start.to_offset(buffer_snap);
 9279                let end = symbol.range.end.to_offset(buffer_snap);
 9280                let new_range = start..end;
 9281                if start < selection.start || end > selection.end {
 9282                    return Some(Selection {
 9283                        id: selection.id,
 9284                        start: new_range.start,
 9285                        end: new_range.end,
 9286                        goal: SelectionGoal::None,
 9287                        reversed: selection.reversed,
 9288                    });
 9289                }
 9290            }
 9291            None
 9292        }
 9293
 9294        let mut selected_larger_symbol = false;
 9295        let new_selections = old_selections
 9296            .iter()
 9297            .map(|selection| match update_selection(selection, &buffer) {
 9298                Some(new_selection) => {
 9299                    if new_selection.range() != selection.range() {
 9300                        selected_larger_symbol = true;
 9301                    }
 9302                    new_selection
 9303                }
 9304                None => selection.clone(),
 9305            })
 9306            .collect::<Vec<_>>();
 9307
 9308        if selected_larger_symbol {
 9309            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9310                s.select(new_selections);
 9311            });
 9312        }
 9313    }
 9314
 9315    pub fn select_larger_syntax_node(
 9316        &mut self,
 9317        _: &SelectLargerSyntaxNode,
 9318        cx: &mut ViewContext<Self>,
 9319    ) {
 9320        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9321        let buffer = self.buffer.read(cx).snapshot(cx);
 9322        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9323
 9324        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9325        let mut selected_larger_node = false;
 9326        let new_selections = old_selections
 9327            .iter()
 9328            .map(|selection| {
 9329                let old_range = selection.start..selection.end;
 9330                let mut new_range = old_range.clone();
 9331                while let Some(containing_range) =
 9332                    buffer.range_for_syntax_ancestor(new_range.clone())
 9333                {
 9334                    new_range = containing_range;
 9335                    if !display_map.intersects_fold(new_range.start)
 9336                        && !display_map.intersects_fold(new_range.end)
 9337                    {
 9338                        break;
 9339                    }
 9340                }
 9341
 9342                selected_larger_node |= new_range != old_range;
 9343                Selection {
 9344                    id: selection.id,
 9345                    start: new_range.start,
 9346                    end: new_range.end,
 9347                    goal: SelectionGoal::None,
 9348                    reversed: selection.reversed,
 9349                }
 9350            })
 9351            .collect::<Vec<_>>();
 9352
 9353        if selected_larger_node {
 9354            stack.push(old_selections);
 9355            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9356                s.select(new_selections);
 9357            });
 9358        }
 9359        self.select_larger_syntax_node_stack = stack;
 9360    }
 9361
 9362    pub fn select_smaller_syntax_node(
 9363        &mut self,
 9364        _: &SelectSmallerSyntaxNode,
 9365        cx: &mut ViewContext<Self>,
 9366    ) {
 9367        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9368        if let Some(selections) = stack.pop() {
 9369            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9370                s.select(selections.to_vec());
 9371            });
 9372        }
 9373        self.select_larger_syntax_node_stack = stack;
 9374    }
 9375
 9376    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 9377        if !EditorSettings::get_global(cx).gutter.runnables {
 9378            self.clear_tasks();
 9379            return Task::ready(());
 9380        }
 9381        let project = self.project.as_ref().map(Model::downgrade);
 9382        cx.spawn(|this, mut cx| async move {
 9383            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
 9384            let Some(project) = project.and_then(|p| p.upgrade()) else {
 9385                return;
 9386            };
 9387            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 9388                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 9389            }) else {
 9390                return;
 9391            };
 9392
 9393            let hide_runnables = project
 9394                .update(&mut cx, |project, cx| {
 9395                    // Do not display any test indicators in non-dev server remote projects.
 9396                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 9397                })
 9398                .unwrap_or(true);
 9399            if hide_runnables {
 9400                return;
 9401            }
 9402            let new_rows =
 9403                cx.background_executor()
 9404                    .spawn({
 9405                        let snapshot = display_snapshot.clone();
 9406                        async move {
 9407                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 9408                        }
 9409                    })
 9410                    .await;
 9411            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 9412
 9413            this.update(&mut cx, |this, _| {
 9414                this.clear_tasks();
 9415                for (key, value) in rows {
 9416                    this.insert_tasks(key, value);
 9417                }
 9418            })
 9419            .ok();
 9420        })
 9421    }
 9422    fn fetch_runnable_ranges(
 9423        snapshot: &DisplaySnapshot,
 9424        range: Range<Anchor>,
 9425    ) -> Vec<language::RunnableRange> {
 9426        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 9427    }
 9428
 9429    fn runnable_rows(
 9430        project: Model<Project>,
 9431        snapshot: DisplaySnapshot,
 9432        runnable_ranges: Vec<RunnableRange>,
 9433        mut cx: AsyncWindowContext,
 9434    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 9435        runnable_ranges
 9436            .into_iter()
 9437            .filter_map(|mut runnable| {
 9438                let tasks = cx
 9439                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 9440                    .ok()?;
 9441                if tasks.is_empty() {
 9442                    return None;
 9443                }
 9444
 9445                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 9446
 9447                let row = snapshot
 9448                    .buffer_snapshot
 9449                    .buffer_line_for_row(MultiBufferRow(point.row))?
 9450                    .1
 9451                    .start
 9452                    .row;
 9453
 9454                let context_range =
 9455                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 9456                Some((
 9457                    (runnable.buffer_id, row),
 9458                    RunnableTasks {
 9459                        templates: tasks,
 9460                        offset: MultiBufferOffset(runnable.run_range.start),
 9461                        context_range,
 9462                        column: point.column,
 9463                        extra_variables: runnable.extra_captures,
 9464                    },
 9465                ))
 9466            })
 9467            .collect()
 9468    }
 9469
 9470    fn templates_with_tags(
 9471        project: &Model<Project>,
 9472        runnable: &mut Runnable,
 9473        cx: &WindowContext<'_>,
 9474    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 9475        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 9476            let (worktree_id, file) = project
 9477                .buffer_for_id(runnable.buffer, cx)
 9478                .and_then(|buffer| buffer.read(cx).file())
 9479                .map(|file| (file.worktree_id(cx), file.clone()))
 9480                .unzip();
 9481
 9482            (
 9483                project.task_store().read(cx).task_inventory().cloned(),
 9484                worktree_id,
 9485                file,
 9486            )
 9487        });
 9488
 9489        let tags = mem::take(&mut runnable.tags);
 9490        let mut tags: Vec<_> = tags
 9491            .into_iter()
 9492            .flat_map(|tag| {
 9493                let tag = tag.0.clone();
 9494                inventory
 9495                    .as_ref()
 9496                    .into_iter()
 9497                    .flat_map(|inventory| {
 9498                        inventory.read(cx).list_tasks(
 9499                            file.clone(),
 9500                            Some(runnable.language.clone()),
 9501                            worktree_id,
 9502                            cx,
 9503                        )
 9504                    })
 9505                    .filter(move |(_, template)| {
 9506                        template.tags.iter().any(|source_tag| source_tag == &tag)
 9507                    })
 9508            })
 9509            .sorted_by_key(|(kind, _)| kind.to_owned())
 9510            .collect();
 9511        if let Some((leading_tag_source, _)) = tags.first() {
 9512            // Strongest source wins; if we have worktree tag binding, prefer that to
 9513            // global and language bindings;
 9514            // if we have a global binding, prefer that to language binding.
 9515            let first_mismatch = tags
 9516                .iter()
 9517                .position(|(tag_source, _)| tag_source != leading_tag_source);
 9518            if let Some(index) = first_mismatch {
 9519                tags.truncate(index);
 9520            }
 9521        }
 9522
 9523        tags
 9524    }
 9525
 9526    pub fn move_to_enclosing_bracket(
 9527        &mut self,
 9528        _: &MoveToEnclosingBracket,
 9529        cx: &mut ViewContext<Self>,
 9530    ) {
 9531        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9532            s.move_offsets_with(|snapshot, selection| {
 9533                let Some(enclosing_bracket_ranges) =
 9534                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 9535                else {
 9536                    return;
 9537                };
 9538
 9539                let mut best_length = usize::MAX;
 9540                let mut best_inside = false;
 9541                let mut best_in_bracket_range = false;
 9542                let mut best_destination = None;
 9543                for (open, close) in enclosing_bracket_ranges {
 9544                    let close = close.to_inclusive();
 9545                    let length = close.end() - open.start;
 9546                    let inside = selection.start >= open.end && selection.end <= *close.start();
 9547                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 9548                        || close.contains(&selection.head());
 9549
 9550                    // If best is next to a bracket and current isn't, skip
 9551                    if !in_bracket_range && best_in_bracket_range {
 9552                        continue;
 9553                    }
 9554
 9555                    // Prefer smaller lengths unless best is inside and current isn't
 9556                    if length > best_length && (best_inside || !inside) {
 9557                        continue;
 9558                    }
 9559
 9560                    best_length = length;
 9561                    best_inside = inside;
 9562                    best_in_bracket_range = in_bracket_range;
 9563                    best_destination = Some(
 9564                        if close.contains(&selection.start) && close.contains(&selection.end) {
 9565                            if inside {
 9566                                open.end
 9567                            } else {
 9568                                open.start
 9569                            }
 9570                        } else if inside {
 9571                            *close.start()
 9572                        } else {
 9573                            *close.end()
 9574                        },
 9575                    );
 9576                }
 9577
 9578                if let Some(destination) = best_destination {
 9579                    selection.collapse_to(destination, SelectionGoal::None);
 9580                }
 9581            })
 9582        });
 9583    }
 9584
 9585    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 9586        self.end_selection(cx);
 9587        self.selection_history.mode = SelectionHistoryMode::Undoing;
 9588        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 9589            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9590            self.select_next_state = entry.select_next_state;
 9591            self.select_prev_state = entry.select_prev_state;
 9592            self.add_selections_state = entry.add_selections_state;
 9593            self.request_autoscroll(Autoscroll::newest(), cx);
 9594        }
 9595        self.selection_history.mode = SelectionHistoryMode::Normal;
 9596    }
 9597
 9598    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 9599        self.end_selection(cx);
 9600        self.selection_history.mode = SelectionHistoryMode::Redoing;
 9601        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 9602            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9603            self.select_next_state = entry.select_next_state;
 9604            self.select_prev_state = entry.select_prev_state;
 9605            self.add_selections_state = entry.add_selections_state;
 9606            self.request_autoscroll(Autoscroll::newest(), cx);
 9607        }
 9608        self.selection_history.mode = SelectionHistoryMode::Normal;
 9609    }
 9610
 9611    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 9612        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 9613    }
 9614
 9615    pub fn expand_excerpts_down(
 9616        &mut self,
 9617        action: &ExpandExcerptsDown,
 9618        cx: &mut ViewContext<Self>,
 9619    ) {
 9620        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 9621    }
 9622
 9623    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 9624        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 9625    }
 9626
 9627    pub fn expand_excerpts_for_direction(
 9628        &mut self,
 9629        lines: u32,
 9630        direction: ExpandExcerptDirection,
 9631        cx: &mut ViewContext<Self>,
 9632    ) {
 9633        let selections = self.selections.disjoint_anchors();
 9634
 9635        let lines = if lines == 0 {
 9636            EditorSettings::get_global(cx).expand_excerpt_lines
 9637        } else {
 9638            lines
 9639        };
 9640
 9641        self.buffer.update(cx, |buffer, cx| {
 9642            buffer.expand_excerpts(
 9643                selections
 9644                    .iter()
 9645                    .map(|selection| selection.head().excerpt_id)
 9646                    .dedup(),
 9647                lines,
 9648                direction,
 9649                cx,
 9650            )
 9651        })
 9652    }
 9653
 9654    pub fn expand_excerpt(
 9655        &mut self,
 9656        excerpt: ExcerptId,
 9657        direction: ExpandExcerptDirection,
 9658        cx: &mut ViewContext<Self>,
 9659    ) {
 9660        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 9661        self.buffer.update(cx, |buffer, cx| {
 9662            buffer.expand_excerpts([excerpt], lines, direction, cx)
 9663        })
 9664    }
 9665
 9666    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 9667        self.go_to_diagnostic_impl(Direction::Next, cx)
 9668    }
 9669
 9670    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 9671        self.go_to_diagnostic_impl(Direction::Prev, cx)
 9672    }
 9673
 9674    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 9675        let buffer = self.buffer.read(cx).snapshot(cx);
 9676        let selection = self.selections.newest::<usize>(cx);
 9677
 9678        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 9679        if direction == Direction::Next {
 9680            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 9681                let (group_id, jump_to) = popover.activation_info();
 9682                if self.activate_diagnostics(group_id, cx) {
 9683                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9684                        let mut new_selection = s.newest_anchor().clone();
 9685                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 9686                        s.select_anchors(vec![new_selection.clone()]);
 9687                    });
 9688                }
 9689                return;
 9690            }
 9691        }
 9692
 9693        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 9694            active_diagnostics
 9695                .primary_range
 9696                .to_offset(&buffer)
 9697                .to_inclusive()
 9698        });
 9699        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 9700            if active_primary_range.contains(&selection.head()) {
 9701                *active_primary_range.start()
 9702            } else {
 9703                selection.head()
 9704            }
 9705        } else {
 9706            selection.head()
 9707        };
 9708        let snapshot = self.snapshot(cx);
 9709        loop {
 9710            let diagnostics = if direction == Direction::Prev {
 9711                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 9712            } else {
 9713                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 9714            }
 9715            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 9716            let group = diagnostics
 9717                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 9718                // be sorted in a stable way
 9719                // skip until we are at current active diagnostic, if it exists
 9720                .skip_while(|entry| {
 9721                    (match direction {
 9722                        Direction::Prev => entry.range.start >= search_start,
 9723                        Direction::Next => entry.range.start <= search_start,
 9724                    }) && self
 9725                        .active_diagnostics
 9726                        .as_ref()
 9727                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 9728                })
 9729                .find_map(|entry| {
 9730                    if entry.diagnostic.is_primary
 9731                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 9732                        && !entry.range.is_empty()
 9733                        // if we match with the active diagnostic, skip it
 9734                        && Some(entry.diagnostic.group_id)
 9735                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 9736                    {
 9737                        Some((entry.range, entry.diagnostic.group_id))
 9738                    } else {
 9739                        None
 9740                    }
 9741                });
 9742
 9743            if let Some((primary_range, group_id)) = group {
 9744                if self.activate_diagnostics(group_id, cx) {
 9745                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9746                        s.select(vec![Selection {
 9747                            id: selection.id,
 9748                            start: primary_range.start,
 9749                            end: primary_range.start,
 9750                            reversed: false,
 9751                            goal: SelectionGoal::None,
 9752                        }]);
 9753                    });
 9754                }
 9755                break;
 9756            } else {
 9757                // Cycle around to the start of the buffer, potentially moving back to the start of
 9758                // the currently active diagnostic.
 9759                active_primary_range.take();
 9760                if direction == Direction::Prev {
 9761                    if search_start == buffer.len() {
 9762                        break;
 9763                    } else {
 9764                        search_start = buffer.len();
 9765                    }
 9766                } else if search_start == 0 {
 9767                    break;
 9768                } else {
 9769                    search_start = 0;
 9770                }
 9771            }
 9772        }
 9773    }
 9774
 9775    fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 9776        let snapshot = self.snapshot(cx);
 9777        let selection = self.selections.newest::<Point>(cx);
 9778        self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
 9779    }
 9780
 9781    fn go_to_hunk_after_position(
 9782        &mut self,
 9783        snapshot: &EditorSnapshot,
 9784        position: Point,
 9785        cx: &mut ViewContext<'_, Editor>,
 9786    ) -> Option<MultiBufferDiffHunk> {
 9787        for (ix, position) in [position, Point::zero()].into_iter().enumerate() {
 9788            if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9789                snapshot,
 9790                position,
 9791                ix > 0,
 9792                snapshot.diff_map.diff_hunks_in_range(
 9793                    position + Point::new(1, 0)..snapshot.buffer_snapshot.max_point(),
 9794                    &snapshot.buffer_snapshot,
 9795                ),
 9796                cx,
 9797            ) {
 9798                return Some(hunk);
 9799            }
 9800        }
 9801        None
 9802    }
 9803
 9804    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 9805        let snapshot = self.snapshot(cx);
 9806        let selection = self.selections.newest::<Point>(cx);
 9807        self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
 9808    }
 9809
 9810    fn go_to_hunk_before_position(
 9811        &mut self,
 9812        snapshot: &EditorSnapshot,
 9813        position: Point,
 9814        cx: &mut ViewContext<'_, Editor>,
 9815    ) -> Option<MultiBufferDiffHunk> {
 9816        for (ix, position) in [position, snapshot.buffer_snapshot.max_point()]
 9817            .into_iter()
 9818            .enumerate()
 9819        {
 9820            if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9821                snapshot,
 9822                position,
 9823                ix > 0,
 9824                snapshot
 9825                    .diff_map
 9826                    .diff_hunks_in_range_rev(Point::zero()..position, &snapshot.buffer_snapshot),
 9827                cx,
 9828            ) {
 9829                return Some(hunk);
 9830            }
 9831        }
 9832        None
 9833    }
 9834
 9835    fn go_to_next_hunk_in_direction(
 9836        &mut self,
 9837        snapshot: &DisplaySnapshot,
 9838        initial_point: Point,
 9839        is_wrapped: bool,
 9840        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
 9841        cx: &mut ViewContext<Editor>,
 9842    ) -> Option<MultiBufferDiffHunk> {
 9843        let display_point = initial_point.to_display_point(snapshot);
 9844        let mut hunks = hunks
 9845            .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
 9846            .filter(|(display_hunk, _)| {
 9847                is_wrapped || !display_hunk.contains_display_row(display_point.row())
 9848            })
 9849            .dedup();
 9850
 9851        if let Some((display_hunk, hunk)) = hunks.next() {
 9852            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9853                let row = display_hunk.start_display_row();
 9854                let point = DisplayPoint::new(row, 0);
 9855                s.select_display_ranges([point..point]);
 9856            });
 9857
 9858            Some(hunk)
 9859        } else {
 9860            None
 9861        }
 9862    }
 9863
 9864    pub fn go_to_definition(
 9865        &mut self,
 9866        _: &GoToDefinition,
 9867        cx: &mut ViewContext<Self>,
 9868    ) -> Task<Result<Navigated>> {
 9869        let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
 9870        cx.spawn(|editor, mut cx| async move {
 9871            if definition.await? == Navigated::Yes {
 9872                return Ok(Navigated::Yes);
 9873            }
 9874            match editor.update(&mut cx, |editor, cx| {
 9875                editor.find_all_references(&FindAllReferences, cx)
 9876            })? {
 9877                Some(references) => references.await,
 9878                None => Ok(Navigated::No),
 9879            }
 9880        })
 9881    }
 9882
 9883    pub fn go_to_declaration(
 9884        &mut self,
 9885        _: &GoToDeclaration,
 9886        cx: &mut ViewContext<Self>,
 9887    ) -> Task<Result<Navigated>> {
 9888        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
 9889    }
 9890
 9891    pub fn go_to_declaration_split(
 9892        &mut self,
 9893        _: &GoToDeclaration,
 9894        cx: &mut ViewContext<Self>,
 9895    ) -> Task<Result<Navigated>> {
 9896        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
 9897    }
 9898
 9899    pub fn go_to_implementation(
 9900        &mut self,
 9901        _: &GoToImplementation,
 9902        cx: &mut ViewContext<Self>,
 9903    ) -> Task<Result<Navigated>> {
 9904        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 9905    }
 9906
 9907    pub fn go_to_implementation_split(
 9908        &mut self,
 9909        _: &GoToImplementationSplit,
 9910        cx: &mut ViewContext<Self>,
 9911    ) -> Task<Result<Navigated>> {
 9912        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 9913    }
 9914
 9915    pub fn go_to_type_definition(
 9916        &mut self,
 9917        _: &GoToTypeDefinition,
 9918        cx: &mut ViewContext<Self>,
 9919    ) -> Task<Result<Navigated>> {
 9920        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 9921    }
 9922
 9923    pub fn go_to_definition_split(
 9924        &mut self,
 9925        _: &GoToDefinitionSplit,
 9926        cx: &mut ViewContext<Self>,
 9927    ) -> Task<Result<Navigated>> {
 9928        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 9929    }
 9930
 9931    pub fn go_to_type_definition_split(
 9932        &mut self,
 9933        _: &GoToTypeDefinitionSplit,
 9934        cx: &mut ViewContext<Self>,
 9935    ) -> Task<Result<Navigated>> {
 9936        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 9937    }
 9938
 9939    fn go_to_definition_of_kind(
 9940        &mut self,
 9941        kind: GotoDefinitionKind,
 9942        split: bool,
 9943        cx: &mut ViewContext<Self>,
 9944    ) -> Task<Result<Navigated>> {
 9945        let Some(provider) = self.semantics_provider.clone() else {
 9946            return Task::ready(Ok(Navigated::No));
 9947        };
 9948        let head = self.selections.newest::<usize>(cx).head();
 9949        let buffer = self.buffer.read(cx);
 9950        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 9951            text_anchor
 9952        } else {
 9953            return Task::ready(Ok(Navigated::No));
 9954        };
 9955
 9956        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
 9957            return Task::ready(Ok(Navigated::No));
 9958        };
 9959
 9960        cx.spawn(|editor, mut cx| async move {
 9961            let definitions = definitions.await?;
 9962            let navigated = editor
 9963                .update(&mut cx, |editor, cx| {
 9964                    editor.navigate_to_hover_links(
 9965                        Some(kind),
 9966                        definitions
 9967                            .into_iter()
 9968                            .filter(|location| {
 9969                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 9970                            })
 9971                            .map(HoverLink::Text)
 9972                            .collect::<Vec<_>>(),
 9973                        split,
 9974                        cx,
 9975                    )
 9976                })?
 9977                .await?;
 9978            anyhow::Ok(navigated)
 9979        })
 9980    }
 9981
 9982    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 9983        let position = self.selections.newest_anchor().head();
 9984        let Some((buffer, buffer_position)) =
 9985            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9986        else {
 9987            return;
 9988        };
 9989
 9990        cx.spawn(|editor, mut cx| async move {
 9991            if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
 9992                editor.update(&mut cx, |_, cx| {
 9993                    cx.open_url(&url);
 9994                })
 9995            } else {
 9996                Ok(())
 9997            }
 9998        })
 9999        .detach();
10000    }
10001
10002    pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
10003        let Some(workspace) = self.workspace() else {
10004            return;
10005        };
10006
10007        let position = self.selections.newest_anchor().head();
10008
10009        let Some((buffer, buffer_position)) =
10010            self.buffer.read(cx).text_anchor_for_position(position, cx)
10011        else {
10012            return;
10013        };
10014
10015        let project = self.project.clone();
10016
10017        cx.spawn(|_, mut cx| async move {
10018            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10019
10020            if let Some((_, path)) = result {
10021                workspace
10022                    .update(&mut cx, |workspace, cx| {
10023                        workspace.open_resolved_path(path, cx)
10024                    })?
10025                    .await?;
10026            }
10027            anyhow::Ok(())
10028        })
10029        .detach();
10030    }
10031
10032    pub(crate) fn navigate_to_hover_links(
10033        &mut self,
10034        kind: Option<GotoDefinitionKind>,
10035        mut definitions: Vec<HoverLink>,
10036        split: bool,
10037        cx: &mut ViewContext<Editor>,
10038    ) -> Task<Result<Navigated>> {
10039        // If there is one definition, just open it directly
10040        if definitions.len() == 1 {
10041            let definition = definitions.pop().unwrap();
10042
10043            enum TargetTaskResult {
10044                Location(Option<Location>),
10045                AlreadyNavigated,
10046            }
10047
10048            let target_task = match definition {
10049                HoverLink::Text(link) => {
10050                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10051                }
10052                HoverLink::InlayHint(lsp_location, server_id) => {
10053                    let computation = self.compute_target_location(lsp_location, server_id, cx);
10054                    cx.background_executor().spawn(async move {
10055                        let location = computation.await?;
10056                        Ok(TargetTaskResult::Location(location))
10057                    })
10058                }
10059                HoverLink::Url(url) => {
10060                    cx.open_url(&url);
10061                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10062                }
10063                HoverLink::File(path) => {
10064                    if let Some(workspace) = self.workspace() {
10065                        cx.spawn(|_, mut cx| async move {
10066                            workspace
10067                                .update(&mut cx, |workspace, cx| {
10068                                    workspace.open_resolved_path(path, cx)
10069                                })?
10070                                .await
10071                                .map(|_| TargetTaskResult::AlreadyNavigated)
10072                        })
10073                    } else {
10074                        Task::ready(Ok(TargetTaskResult::Location(None)))
10075                    }
10076                }
10077            };
10078            cx.spawn(|editor, mut cx| async move {
10079                let target = match target_task.await.context("target resolution task")? {
10080                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10081                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
10082                    TargetTaskResult::Location(Some(target)) => target,
10083                };
10084
10085                editor.update(&mut cx, |editor, cx| {
10086                    let Some(workspace) = editor.workspace() else {
10087                        return Navigated::No;
10088                    };
10089                    let pane = workspace.read(cx).active_pane().clone();
10090
10091                    let range = target.range.to_offset(target.buffer.read(cx));
10092                    let range = editor.range_for_match(&range);
10093
10094                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10095                        let buffer = target.buffer.read(cx);
10096                        let range = check_multiline_range(buffer, range);
10097                        editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10098                            s.select_ranges([range]);
10099                        });
10100                    } else {
10101                        cx.window_context().defer(move |cx| {
10102                            let target_editor: View<Self> =
10103                                workspace.update(cx, |workspace, cx| {
10104                                    let pane = if split {
10105                                        workspace.adjacent_pane(cx)
10106                                    } else {
10107                                        workspace.active_pane().clone()
10108                                    };
10109
10110                                    workspace.open_project_item(
10111                                        pane,
10112                                        target.buffer.clone(),
10113                                        true,
10114                                        true,
10115                                        cx,
10116                                    )
10117                                });
10118                            target_editor.update(cx, |target_editor, cx| {
10119                                // When selecting a definition in a different buffer, disable the nav history
10120                                // to avoid creating a history entry at the previous cursor location.
10121                                pane.update(cx, |pane, _| pane.disable_history());
10122                                let buffer = target.buffer.read(cx);
10123                                let range = check_multiline_range(buffer, range);
10124                                target_editor.change_selections(
10125                                    Some(Autoscroll::focused()),
10126                                    cx,
10127                                    |s| {
10128                                        s.select_ranges([range]);
10129                                    },
10130                                );
10131                                pane.update(cx, |pane, _| pane.enable_history());
10132                            });
10133                        });
10134                    }
10135                    Navigated::Yes
10136                })
10137            })
10138        } else if !definitions.is_empty() {
10139            cx.spawn(|editor, mut cx| async move {
10140                let (title, location_tasks, workspace) = editor
10141                    .update(&mut cx, |editor, cx| {
10142                        let tab_kind = match kind {
10143                            Some(GotoDefinitionKind::Implementation) => "Implementations",
10144                            _ => "Definitions",
10145                        };
10146                        let title = definitions
10147                            .iter()
10148                            .find_map(|definition| match definition {
10149                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10150                                    let buffer = origin.buffer.read(cx);
10151                                    format!(
10152                                        "{} for {}",
10153                                        tab_kind,
10154                                        buffer
10155                                            .text_for_range(origin.range.clone())
10156                                            .collect::<String>()
10157                                    )
10158                                }),
10159                                HoverLink::InlayHint(_, _) => None,
10160                                HoverLink::Url(_) => None,
10161                                HoverLink::File(_) => None,
10162                            })
10163                            .unwrap_or(tab_kind.to_string());
10164                        let location_tasks = definitions
10165                            .into_iter()
10166                            .map(|definition| match definition {
10167                                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
10168                                HoverLink::InlayHint(lsp_location, server_id) => {
10169                                    editor.compute_target_location(lsp_location, server_id, cx)
10170                                }
10171                                HoverLink::Url(_) => Task::ready(Ok(None)),
10172                                HoverLink::File(_) => Task::ready(Ok(None)),
10173                            })
10174                            .collect::<Vec<_>>();
10175                        (title, location_tasks, editor.workspace().clone())
10176                    })
10177                    .context("location tasks preparation")?;
10178
10179                let locations = future::join_all(location_tasks)
10180                    .await
10181                    .into_iter()
10182                    .filter_map(|location| location.transpose())
10183                    .collect::<Result<_>>()
10184                    .context("location tasks")?;
10185
10186                let Some(workspace) = workspace else {
10187                    return Ok(Navigated::No);
10188                };
10189                let opened = workspace
10190                    .update(&mut cx, |workspace, cx| {
10191                        Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
10192                    })
10193                    .ok();
10194
10195                anyhow::Ok(Navigated::from_bool(opened.is_some()))
10196            })
10197        } else {
10198            Task::ready(Ok(Navigated::No))
10199        }
10200    }
10201
10202    fn compute_target_location(
10203        &self,
10204        lsp_location: lsp::Location,
10205        server_id: LanguageServerId,
10206        cx: &mut ViewContext<Self>,
10207    ) -> Task<anyhow::Result<Option<Location>>> {
10208        let Some(project) = self.project.clone() else {
10209            return Task::Ready(Some(Ok(None)));
10210        };
10211
10212        cx.spawn(move |editor, mut cx| async move {
10213            let location_task = editor.update(&mut cx, |_, cx| {
10214                project.update(cx, |project, cx| {
10215                    let language_server_name = project
10216                        .language_server_statuses(cx)
10217                        .find(|(id, _)| server_id == *id)
10218                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10219                    language_server_name.map(|language_server_name| {
10220                        project.open_local_buffer_via_lsp(
10221                            lsp_location.uri.clone(),
10222                            server_id,
10223                            language_server_name,
10224                            cx,
10225                        )
10226                    })
10227                })
10228            })?;
10229            let location = match location_task {
10230                Some(task) => Some({
10231                    let target_buffer_handle = task.await.context("open local buffer")?;
10232                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10233                        let target_start = target_buffer
10234                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10235                        let target_end = target_buffer
10236                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10237                        target_buffer.anchor_after(target_start)
10238                            ..target_buffer.anchor_before(target_end)
10239                    })?;
10240                    Location {
10241                        buffer: target_buffer_handle,
10242                        range,
10243                    }
10244                }),
10245                None => None,
10246            };
10247            Ok(location)
10248        })
10249    }
10250
10251    pub fn find_all_references(
10252        &mut self,
10253        _: &FindAllReferences,
10254        cx: &mut ViewContext<Self>,
10255    ) -> Option<Task<Result<Navigated>>> {
10256        let selection = self.selections.newest::<usize>(cx);
10257        let multi_buffer = self.buffer.read(cx);
10258        let head = selection.head();
10259
10260        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10261        let head_anchor = multi_buffer_snapshot.anchor_at(
10262            head,
10263            if head < selection.tail() {
10264                Bias::Right
10265            } else {
10266                Bias::Left
10267            },
10268        );
10269
10270        match self
10271            .find_all_references_task_sources
10272            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10273        {
10274            Ok(_) => {
10275                log::info!(
10276                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
10277                );
10278                return None;
10279            }
10280            Err(i) => {
10281                self.find_all_references_task_sources.insert(i, head_anchor);
10282            }
10283        }
10284
10285        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10286        let workspace = self.workspace()?;
10287        let project = workspace.read(cx).project().clone();
10288        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10289        Some(cx.spawn(|editor, mut cx| async move {
10290            let _cleanup = defer({
10291                let mut cx = cx.clone();
10292                move || {
10293                    let _ = editor.update(&mut cx, |editor, _| {
10294                        if let Ok(i) =
10295                            editor
10296                                .find_all_references_task_sources
10297                                .binary_search_by(|anchor| {
10298                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10299                                })
10300                        {
10301                            editor.find_all_references_task_sources.remove(i);
10302                        }
10303                    });
10304                }
10305            });
10306
10307            let locations = references.await?;
10308            if locations.is_empty() {
10309                return anyhow::Ok(Navigated::No);
10310            }
10311
10312            workspace.update(&mut cx, |workspace, cx| {
10313                let title = locations
10314                    .first()
10315                    .as_ref()
10316                    .map(|location| {
10317                        let buffer = location.buffer.read(cx);
10318                        format!(
10319                            "References to `{}`",
10320                            buffer
10321                                .text_for_range(location.range.clone())
10322                                .collect::<String>()
10323                        )
10324                    })
10325                    .unwrap();
10326                Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
10327                Navigated::Yes
10328            })
10329        }))
10330    }
10331
10332    /// Opens a multibuffer with the given project locations in it
10333    pub fn open_locations_in_multibuffer(
10334        workspace: &mut Workspace,
10335        mut locations: Vec<Location>,
10336        title: String,
10337        split: bool,
10338        cx: &mut ViewContext<Workspace>,
10339    ) {
10340        // If there are multiple definitions, open them in a multibuffer
10341        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10342        let mut locations = locations.into_iter().peekable();
10343        let mut ranges_to_highlight = Vec::new();
10344        let capability = workspace.project().read(cx).capability();
10345
10346        let excerpt_buffer = cx.new_model(|cx| {
10347            let mut multibuffer = MultiBuffer::new(capability);
10348            while let Some(location) = locations.next() {
10349                let buffer = location.buffer.read(cx);
10350                let mut ranges_for_buffer = Vec::new();
10351                let range = location.range.to_offset(buffer);
10352                ranges_for_buffer.push(range.clone());
10353
10354                while let Some(next_location) = locations.peek() {
10355                    if next_location.buffer == location.buffer {
10356                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
10357                        locations.next();
10358                    } else {
10359                        break;
10360                    }
10361                }
10362
10363                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10364                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
10365                    location.buffer.clone(),
10366                    ranges_for_buffer,
10367                    DEFAULT_MULTIBUFFER_CONTEXT,
10368                    cx,
10369                ))
10370            }
10371
10372            multibuffer.with_title(title)
10373        });
10374
10375        let editor = cx.new_view(|cx| {
10376            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
10377        });
10378        editor.update(cx, |editor, cx| {
10379            if let Some(first_range) = ranges_to_highlight.first() {
10380                editor.change_selections(None, cx, |selections| {
10381                    selections.clear_disjoint();
10382                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10383                });
10384            }
10385            editor.highlight_background::<Self>(
10386                &ranges_to_highlight,
10387                |theme| theme.editor_highlighted_line_background,
10388                cx,
10389            );
10390        });
10391
10392        let item = Box::new(editor);
10393        let item_id = item.item_id();
10394
10395        if split {
10396            workspace.split_item(SplitDirection::Right, item.clone(), cx);
10397        } else {
10398            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10399                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10400                    pane.close_current_preview_item(cx)
10401                } else {
10402                    None
10403                }
10404            });
10405            workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
10406        }
10407        workspace.active_pane().update(cx, |pane, cx| {
10408            pane.set_preview_item_id(Some(item_id), cx);
10409        });
10410    }
10411
10412    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10413        use language::ToOffset as _;
10414
10415        let provider = self.semantics_provider.clone()?;
10416        let selection = self.selections.newest_anchor().clone();
10417        let (cursor_buffer, cursor_buffer_position) = self
10418            .buffer
10419            .read(cx)
10420            .text_anchor_for_position(selection.head(), cx)?;
10421        let (tail_buffer, cursor_buffer_position_end) = self
10422            .buffer
10423            .read(cx)
10424            .text_anchor_for_position(selection.tail(), cx)?;
10425        if tail_buffer != cursor_buffer {
10426            return None;
10427        }
10428
10429        let snapshot = cursor_buffer.read(cx).snapshot();
10430        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10431        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10432        let prepare_rename = provider
10433            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10434            .unwrap_or_else(|| Task::ready(Ok(None)));
10435        drop(snapshot);
10436
10437        Some(cx.spawn(|this, mut cx| async move {
10438            let rename_range = if let Some(range) = prepare_rename.await? {
10439                Some(range)
10440            } else {
10441                this.update(&mut cx, |this, cx| {
10442                    let buffer = this.buffer.read(cx).snapshot(cx);
10443                    let mut buffer_highlights = this
10444                        .document_highlights_for_position(selection.head(), &buffer)
10445                        .filter(|highlight| {
10446                            highlight.start.excerpt_id == selection.head().excerpt_id
10447                                && highlight.end.excerpt_id == selection.head().excerpt_id
10448                        });
10449                    buffer_highlights
10450                        .next()
10451                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10452                })?
10453            };
10454            if let Some(rename_range) = rename_range {
10455                this.update(&mut cx, |this, cx| {
10456                    let snapshot = cursor_buffer.read(cx).snapshot();
10457                    let rename_buffer_range = rename_range.to_offset(&snapshot);
10458                    let cursor_offset_in_rename_range =
10459                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10460                    let cursor_offset_in_rename_range_end =
10461                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10462
10463                    this.take_rename(false, cx);
10464                    let buffer = this.buffer.read(cx).read(cx);
10465                    let cursor_offset = selection.head().to_offset(&buffer);
10466                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10467                    let rename_end = rename_start + rename_buffer_range.len();
10468                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10469                    let mut old_highlight_id = None;
10470                    let old_name: Arc<str> = buffer
10471                        .chunks(rename_start..rename_end, true)
10472                        .map(|chunk| {
10473                            if old_highlight_id.is_none() {
10474                                old_highlight_id = chunk.syntax_highlight_id;
10475                            }
10476                            chunk.text
10477                        })
10478                        .collect::<String>()
10479                        .into();
10480
10481                    drop(buffer);
10482
10483                    // Position the selection in the rename editor so that it matches the current selection.
10484                    this.show_local_selections = false;
10485                    let rename_editor = cx.new_view(|cx| {
10486                        let mut editor = Editor::single_line(cx);
10487                        editor.buffer.update(cx, |buffer, cx| {
10488                            buffer.edit([(0..0, old_name.clone())], None, cx)
10489                        });
10490                        let rename_selection_range = match cursor_offset_in_rename_range
10491                            .cmp(&cursor_offset_in_rename_range_end)
10492                        {
10493                            Ordering::Equal => {
10494                                editor.select_all(&SelectAll, cx);
10495                                return editor;
10496                            }
10497                            Ordering::Less => {
10498                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10499                            }
10500                            Ordering::Greater => {
10501                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10502                            }
10503                        };
10504                        if rename_selection_range.end > old_name.len() {
10505                            editor.select_all(&SelectAll, cx);
10506                        } else {
10507                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10508                                s.select_ranges([rename_selection_range]);
10509                            });
10510                        }
10511                        editor
10512                    });
10513                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10514                        if e == &EditorEvent::Focused {
10515                            cx.emit(EditorEvent::FocusedIn)
10516                        }
10517                    })
10518                    .detach();
10519
10520                    let write_highlights =
10521                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10522                    let read_highlights =
10523                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
10524                    let ranges = write_highlights
10525                        .iter()
10526                        .flat_map(|(_, ranges)| ranges.iter())
10527                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10528                        .cloned()
10529                        .collect();
10530
10531                    this.highlight_text::<Rename>(
10532                        ranges,
10533                        HighlightStyle {
10534                            fade_out: Some(0.6),
10535                            ..Default::default()
10536                        },
10537                        cx,
10538                    );
10539                    let rename_focus_handle = rename_editor.focus_handle(cx);
10540                    cx.focus(&rename_focus_handle);
10541                    let block_id = this.insert_blocks(
10542                        [BlockProperties {
10543                            style: BlockStyle::Flex,
10544                            placement: BlockPlacement::Below(range.start),
10545                            height: 1,
10546                            render: Arc::new({
10547                                let rename_editor = rename_editor.clone();
10548                                move |cx: &mut BlockContext| {
10549                                    let mut text_style = cx.editor_style.text.clone();
10550                                    if let Some(highlight_style) = old_highlight_id
10551                                        .and_then(|h| h.style(&cx.editor_style.syntax))
10552                                    {
10553                                        text_style = text_style.highlight(highlight_style);
10554                                    }
10555                                    div()
10556                                        .block_mouse_down()
10557                                        .pl(cx.anchor_x)
10558                                        .child(EditorElement::new(
10559                                            &rename_editor,
10560                                            EditorStyle {
10561                                                background: cx.theme().system().transparent,
10562                                                local_player: cx.editor_style.local_player,
10563                                                text: text_style,
10564                                                scrollbar_width: cx.editor_style.scrollbar_width,
10565                                                syntax: cx.editor_style.syntax.clone(),
10566                                                status: cx.editor_style.status.clone(),
10567                                                inlay_hints_style: HighlightStyle {
10568                                                    font_weight: Some(FontWeight::BOLD),
10569                                                    ..make_inlay_hints_style(cx)
10570                                                },
10571                                                suggestions_style: HighlightStyle {
10572                                                    color: Some(cx.theme().status().predictive),
10573                                                    ..HighlightStyle::default()
10574                                                },
10575                                                ..EditorStyle::default()
10576                                            },
10577                                        ))
10578                                        .into_any_element()
10579                                }
10580                            }),
10581                            priority: 0,
10582                        }],
10583                        Some(Autoscroll::fit()),
10584                        cx,
10585                    )[0];
10586                    this.pending_rename = Some(RenameState {
10587                        range,
10588                        old_name,
10589                        editor: rename_editor,
10590                        block_id,
10591                    });
10592                })?;
10593            }
10594
10595            Ok(())
10596        }))
10597    }
10598
10599    pub fn confirm_rename(
10600        &mut self,
10601        _: &ConfirmRename,
10602        cx: &mut ViewContext<Self>,
10603    ) -> Option<Task<Result<()>>> {
10604        let rename = self.take_rename(false, cx)?;
10605        let workspace = self.workspace()?.downgrade();
10606        let (buffer, start) = self
10607            .buffer
10608            .read(cx)
10609            .text_anchor_for_position(rename.range.start, cx)?;
10610        let (end_buffer, _) = self
10611            .buffer
10612            .read(cx)
10613            .text_anchor_for_position(rename.range.end, cx)?;
10614        if buffer != end_buffer {
10615            return None;
10616        }
10617
10618        let old_name = rename.old_name;
10619        let new_name = rename.editor.read(cx).text(cx);
10620
10621        let rename = self.semantics_provider.as_ref()?.perform_rename(
10622            &buffer,
10623            start,
10624            new_name.clone(),
10625            cx,
10626        )?;
10627
10628        Some(cx.spawn(|editor, mut cx| async move {
10629            let project_transaction = rename.await?;
10630            Self::open_project_transaction(
10631                &editor,
10632                workspace,
10633                project_transaction,
10634                format!("Rename: {}{}", old_name, new_name),
10635                cx.clone(),
10636            )
10637            .await?;
10638
10639            editor.update(&mut cx, |editor, cx| {
10640                editor.refresh_document_highlights(cx);
10641            })?;
10642            Ok(())
10643        }))
10644    }
10645
10646    fn take_rename(
10647        &mut self,
10648        moving_cursor: bool,
10649        cx: &mut ViewContext<Self>,
10650    ) -> Option<RenameState> {
10651        let rename = self.pending_rename.take()?;
10652        if rename.editor.focus_handle(cx).is_focused(cx) {
10653            cx.focus(&self.focus_handle);
10654        }
10655
10656        self.remove_blocks(
10657            [rename.block_id].into_iter().collect(),
10658            Some(Autoscroll::fit()),
10659            cx,
10660        );
10661        self.clear_highlights::<Rename>(cx);
10662        self.show_local_selections = true;
10663
10664        if moving_cursor {
10665            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10666                editor.selections.newest::<usize>(cx).head()
10667            });
10668
10669            // Update the selection to match the position of the selection inside
10670            // the rename editor.
10671            let snapshot = self.buffer.read(cx).read(cx);
10672            let rename_range = rename.range.to_offset(&snapshot);
10673            let cursor_in_editor = snapshot
10674                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10675                .min(rename_range.end);
10676            drop(snapshot);
10677
10678            self.change_selections(None, cx, |s| {
10679                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10680            });
10681        } else {
10682            self.refresh_document_highlights(cx);
10683        }
10684
10685        Some(rename)
10686    }
10687
10688    pub fn pending_rename(&self) -> Option<&RenameState> {
10689        self.pending_rename.as_ref()
10690    }
10691
10692    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10693        let project = match &self.project {
10694            Some(project) => project.clone(),
10695            None => return None,
10696        };
10697
10698        Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10699    }
10700
10701    fn format_selections(
10702        &mut self,
10703        _: &FormatSelections,
10704        cx: &mut ViewContext<Self>,
10705    ) -> Option<Task<Result<()>>> {
10706        let project = match &self.project {
10707            Some(project) => project.clone(),
10708            None => return None,
10709        };
10710
10711        let selections = self
10712            .selections
10713            .all_adjusted(cx)
10714            .into_iter()
10715            .filter(|s| !s.is_empty())
10716            .collect_vec();
10717
10718        Some(self.perform_format(
10719            project,
10720            FormatTrigger::Manual,
10721            FormatTarget::Ranges(selections),
10722            cx,
10723        ))
10724    }
10725
10726    fn perform_format(
10727        &mut self,
10728        project: Model<Project>,
10729        trigger: FormatTrigger,
10730        target: FormatTarget,
10731        cx: &mut ViewContext<Self>,
10732    ) -> Task<Result<()>> {
10733        let buffer = self.buffer().clone();
10734        let mut buffers = buffer.read(cx).all_buffers();
10735        if trigger == FormatTrigger::Save {
10736            buffers.retain(|buffer| buffer.read(cx).is_dirty());
10737        }
10738
10739        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10740        let format = project.update(cx, |project, cx| {
10741            project.format(buffers, true, trigger, target, cx)
10742        });
10743
10744        cx.spawn(|_, mut cx| async move {
10745            let transaction = futures::select_biased! {
10746                () = timeout => {
10747                    log::warn!("timed out waiting for formatting");
10748                    None
10749                }
10750                transaction = format.log_err().fuse() => transaction,
10751            };
10752
10753            buffer
10754                .update(&mut cx, |buffer, cx| {
10755                    if let Some(transaction) = transaction {
10756                        if !buffer.is_singleton() {
10757                            buffer.push_transaction(&transaction.0, cx);
10758                        }
10759                    }
10760
10761                    cx.notify();
10762                })
10763                .ok();
10764
10765            Ok(())
10766        })
10767    }
10768
10769    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10770        if let Some(project) = self.project.clone() {
10771            self.buffer.update(cx, |multi_buffer, cx| {
10772                project.update(cx, |project, cx| {
10773                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10774                });
10775            })
10776        }
10777    }
10778
10779    fn cancel_language_server_work(
10780        &mut self,
10781        _: &actions::CancelLanguageServerWork,
10782        cx: &mut ViewContext<Self>,
10783    ) {
10784        if let Some(project) = self.project.clone() {
10785            self.buffer.update(cx, |multi_buffer, cx| {
10786                project.update(cx, |project, cx| {
10787                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10788                });
10789            })
10790        }
10791    }
10792
10793    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10794        cx.show_character_palette();
10795    }
10796
10797    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10798        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10799            let buffer = self.buffer.read(cx).snapshot(cx);
10800            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10801            let is_valid = buffer
10802                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10803                .any(|entry| {
10804                    entry.diagnostic.is_primary
10805                        && !entry.range.is_empty()
10806                        && entry.range.start == primary_range_start
10807                        && entry.diagnostic.message == active_diagnostics.primary_message
10808                });
10809
10810            if is_valid != active_diagnostics.is_valid {
10811                active_diagnostics.is_valid = is_valid;
10812                let mut new_styles = HashMap::default();
10813                for (block_id, diagnostic) in &active_diagnostics.blocks {
10814                    new_styles.insert(
10815                        *block_id,
10816                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10817                    );
10818                }
10819                self.display_map.update(cx, |display_map, _cx| {
10820                    display_map.replace_blocks(new_styles)
10821                });
10822            }
10823        }
10824    }
10825
10826    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10827        self.dismiss_diagnostics(cx);
10828        let snapshot = self.snapshot(cx);
10829        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10830            let buffer = self.buffer.read(cx).snapshot(cx);
10831
10832            let mut primary_range = None;
10833            let mut primary_message = None;
10834            let mut group_end = Point::zero();
10835            let diagnostic_group = buffer
10836                .diagnostic_group::<MultiBufferPoint>(group_id)
10837                .filter_map(|entry| {
10838                    if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10839                        && (entry.range.start.row == entry.range.end.row
10840                            || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10841                    {
10842                        return None;
10843                    }
10844                    if entry.range.end > group_end {
10845                        group_end = entry.range.end;
10846                    }
10847                    if entry.diagnostic.is_primary {
10848                        primary_range = Some(entry.range.clone());
10849                        primary_message = Some(entry.diagnostic.message.clone());
10850                    }
10851                    Some(entry)
10852                })
10853                .collect::<Vec<_>>();
10854            let primary_range = primary_range?;
10855            let primary_message = primary_message?;
10856            let primary_range =
10857                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10858
10859            let blocks = display_map
10860                .insert_blocks(
10861                    diagnostic_group.iter().map(|entry| {
10862                        let diagnostic = entry.diagnostic.clone();
10863                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10864                        BlockProperties {
10865                            style: BlockStyle::Fixed,
10866                            placement: BlockPlacement::Below(
10867                                buffer.anchor_after(entry.range.start),
10868                            ),
10869                            height: message_height,
10870                            render: diagnostic_block_renderer(diagnostic, None, true, true),
10871                            priority: 0,
10872                        }
10873                    }),
10874                    cx,
10875                )
10876                .into_iter()
10877                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10878                .collect();
10879
10880            Some(ActiveDiagnosticGroup {
10881                primary_range,
10882                primary_message,
10883                group_id,
10884                blocks,
10885                is_valid: true,
10886            })
10887        });
10888        self.active_diagnostics.is_some()
10889    }
10890
10891    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10892        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10893            self.display_map.update(cx, |display_map, cx| {
10894                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10895            });
10896            cx.notify();
10897        }
10898    }
10899
10900    pub fn set_selections_from_remote(
10901        &mut self,
10902        selections: Vec<Selection<Anchor>>,
10903        pending_selection: Option<Selection<Anchor>>,
10904        cx: &mut ViewContext<Self>,
10905    ) {
10906        let old_cursor_position = self.selections.newest_anchor().head();
10907        self.selections.change_with(cx, |s| {
10908            s.select_anchors(selections);
10909            if let Some(pending_selection) = pending_selection {
10910                s.set_pending(pending_selection, SelectMode::Character);
10911            } else {
10912                s.clear_pending();
10913            }
10914        });
10915        self.selections_did_change(false, &old_cursor_position, true, cx);
10916    }
10917
10918    fn push_to_selection_history(&mut self) {
10919        self.selection_history.push(SelectionHistoryEntry {
10920            selections: self.selections.disjoint_anchors(),
10921            select_next_state: self.select_next_state.clone(),
10922            select_prev_state: self.select_prev_state.clone(),
10923            add_selections_state: self.add_selections_state.clone(),
10924        });
10925    }
10926
10927    pub fn transact(
10928        &mut self,
10929        cx: &mut ViewContext<Self>,
10930        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10931    ) -> Option<TransactionId> {
10932        self.start_transaction_at(Instant::now(), cx);
10933        update(self, cx);
10934        self.end_transaction_at(Instant::now(), cx)
10935    }
10936
10937    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10938        self.end_selection(cx);
10939        if let Some(tx_id) = self
10940            .buffer
10941            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10942        {
10943            self.selection_history
10944                .insert_transaction(tx_id, self.selections.disjoint_anchors());
10945            cx.emit(EditorEvent::TransactionBegun {
10946                transaction_id: tx_id,
10947            })
10948        }
10949    }
10950
10951    fn end_transaction_at(
10952        &mut self,
10953        now: Instant,
10954        cx: &mut ViewContext<Self>,
10955    ) -> Option<TransactionId> {
10956        if let Some(transaction_id) = self
10957            .buffer
10958            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10959        {
10960            if let Some((_, end_selections)) =
10961                self.selection_history.transaction_mut(transaction_id)
10962            {
10963                *end_selections = Some(self.selections.disjoint_anchors());
10964            } else {
10965                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10966            }
10967
10968            cx.emit(EditorEvent::Edited { transaction_id });
10969            Some(transaction_id)
10970        } else {
10971            None
10972        }
10973    }
10974
10975    pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10976        let selection = self.selections.newest::<Point>(cx);
10977
10978        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10979        let range = if selection.is_empty() {
10980            let point = selection.head().to_display_point(&display_map);
10981            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10982            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10983                .to_point(&display_map);
10984            start..end
10985        } else {
10986            selection.range()
10987        };
10988        if display_map.folds_in_range(range).next().is_some() {
10989            self.unfold_lines(&Default::default(), cx)
10990        } else {
10991            self.fold(&Default::default(), cx)
10992        }
10993    }
10994
10995    pub fn toggle_fold_recursive(
10996        &mut self,
10997        _: &actions::ToggleFoldRecursive,
10998        cx: &mut ViewContext<Self>,
10999    ) {
11000        let selection = self.selections.newest::<Point>(cx);
11001
11002        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11003        let range = if selection.is_empty() {
11004            let point = selection.head().to_display_point(&display_map);
11005            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11006            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11007                .to_point(&display_map);
11008            start..end
11009        } else {
11010            selection.range()
11011        };
11012        if display_map.folds_in_range(range).next().is_some() {
11013            self.unfold_recursive(&Default::default(), cx)
11014        } else {
11015            self.fold_recursive(&Default::default(), cx)
11016        }
11017    }
11018
11019    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
11020        let mut to_fold = Vec::new();
11021        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11022        let selections = self.selections.all_adjusted(cx);
11023
11024        for selection in selections {
11025            let range = selection.range().sorted();
11026            let buffer_start_row = range.start.row;
11027
11028            if range.start.row != range.end.row {
11029                let mut found = false;
11030                let mut row = range.start.row;
11031                while row <= range.end.row {
11032                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11033                        found = true;
11034                        row = crease.range().end.row + 1;
11035                        to_fold.push(crease);
11036                    } else {
11037                        row += 1
11038                    }
11039                }
11040                if found {
11041                    continue;
11042                }
11043            }
11044
11045            for row in (0..=range.start.row).rev() {
11046                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11047                    if crease.range().end.row >= buffer_start_row {
11048                        to_fold.push(crease);
11049                        if row <= range.start.row {
11050                            break;
11051                        }
11052                    }
11053                }
11054            }
11055        }
11056
11057        self.fold_creases(to_fold, true, cx);
11058    }
11059
11060    fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
11061        if !self.buffer.read(cx).is_singleton() {
11062            return;
11063        }
11064
11065        let fold_at_level = fold_at.level;
11066        let snapshot = self.buffer.read(cx).snapshot(cx);
11067        let mut to_fold = Vec::new();
11068        let mut stack = vec![(0, snapshot.max_row().0, 1)];
11069
11070        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
11071            while start_row < end_row {
11072                match self
11073                    .snapshot(cx)
11074                    .crease_for_buffer_row(MultiBufferRow(start_row))
11075                {
11076                    Some(crease) => {
11077                        let nested_start_row = crease.range().start.row + 1;
11078                        let nested_end_row = crease.range().end.row;
11079
11080                        if current_level < fold_at_level {
11081                            stack.push((nested_start_row, nested_end_row, current_level + 1));
11082                        } else if current_level == fold_at_level {
11083                            to_fold.push(crease);
11084                        }
11085
11086                        start_row = nested_end_row + 1;
11087                    }
11088                    None => start_row += 1,
11089                }
11090            }
11091        }
11092
11093        self.fold_creases(to_fold, true, cx);
11094    }
11095
11096    pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
11097        if !self.buffer.read(cx).is_singleton() {
11098            return;
11099        }
11100
11101        let mut fold_ranges = Vec::new();
11102        let snapshot = self.buffer.read(cx).snapshot(cx);
11103
11104        for row in 0..snapshot.max_row().0 {
11105            if let Some(foldable_range) =
11106                self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
11107            {
11108                fold_ranges.push(foldable_range);
11109            }
11110        }
11111
11112        self.fold_creases(fold_ranges, true, cx);
11113    }
11114
11115    pub fn fold_function_bodies(
11116        &mut self,
11117        _: &actions::FoldFunctionBodies,
11118        cx: &mut ViewContext<Self>,
11119    ) {
11120        let snapshot = self.buffer.read(cx).snapshot(cx);
11121        let Some((_, _, buffer)) = snapshot.as_singleton() else {
11122            return;
11123        };
11124        let creases = buffer
11125            .function_body_fold_ranges(0..buffer.len())
11126            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
11127            .collect();
11128
11129        self.fold_creases(creases, true, cx);
11130    }
11131
11132    pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
11133        let mut to_fold = Vec::new();
11134        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11135        let selections = self.selections.all_adjusted(cx);
11136
11137        for selection in selections {
11138            let range = selection.range().sorted();
11139            let buffer_start_row = range.start.row;
11140
11141            if range.start.row != range.end.row {
11142                let mut found = false;
11143                for row in range.start.row..=range.end.row {
11144                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11145                        found = true;
11146                        to_fold.push(crease);
11147                    }
11148                }
11149                if found {
11150                    continue;
11151                }
11152            }
11153
11154            for row in (0..=range.start.row).rev() {
11155                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11156                    if crease.range().end.row >= buffer_start_row {
11157                        to_fold.push(crease);
11158                    } else {
11159                        break;
11160                    }
11161                }
11162            }
11163        }
11164
11165        self.fold_creases(to_fold, true, cx);
11166    }
11167
11168    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
11169        let buffer_row = fold_at.buffer_row;
11170        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11171
11172        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
11173            let autoscroll = self
11174                .selections
11175                .all::<Point>(cx)
11176                .iter()
11177                .any(|selection| crease.range().overlaps(&selection.range()));
11178
11179            self.fold_creases(vec![crease], autoscroll, cx);
11180        }
11181    }
11182
11183    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
11184        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11185        let buffer = &display_map.buffer_snapshot;
11186        let selections = self.selections.all::<Point>(cx);
11187        let ranges = selections
11188            .iter()
11189            .map(|s| {
11190                let range = s.display_range(&display_map).sorted();
11191                let mut start = range.start.to_point(&display_map);
11192                let mut end = range.end.to_point(&display_map);
11193                start.column = 0;
11194                end.column = buffer.line_len(MultiBufferRow(end.row));
11195                start..end
11196            })
11197            .collect::<Vec<_>>();
11198
11199        self.unfold_ranges(&ranges, true, true, cx);
11200    }
11201
11202    pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
11203        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11204        let selections = self.selections.all::<Point>(cx);
11205        let ranges = selections
11206            .iter()
11207            .map(|s| {
11208                let mut range = s.display_range(&display_map).sorted();
11209                *range.start.column_mut() = 0;
11210                *range.end.column_mut() = display_map.line_len(range.end.row());
11211                let start = range.start.to_point(&display_map);
11212                let end = range.end.to_point(&display_map);
11213                start..end
11214            })
11215            .collect::<Vec<_>>();
11216
11217        self.unfold_ranges(&ranges, true, true, cx);
11218    }
11219
11220    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
11221        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11222
11223        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
11224            ..Point::new(
11225                unfold_at.buffer_row.0,
11226                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
11227            );
11228
11229        let autoscroll = self
11230            .selections
11231            .all::<Point>(cx)
11232            .iter()
11233            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
11234
11235        self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
11236    }
11237
11238    pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
11239        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11240        self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
11241    }
11242
11243    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
11244        let selections = self.selections.all::<Point>(cx);
11245        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11246        let line_mode = self.selections.line_mode;
11247        let ranges = selections
11248            .into_iter()
11249            .map(|s| {
11250                if line_mode {
11251                    let start = Point::new(s.start.row, 0);
11252                    let end = Point::new(
11253                        s.end.row,
11254                        display_map
11255                            .buffer_snapshot
11256                            .line_len(MultiBufferRow(s.end.row)),
11257                    );
11258                    Crease::simple(start..end, display_map.fold_placeholder.clone())
11259                } else {
11260                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
11261                }
11262            })
11263            .collect::<Vec<_>>();
11264        self.fold_creases(ranges, true, cx);
11265    }
11266
11267    pub fn fold_creases<T: ToOffset + Clone>(
11268        &mut self,
11269        creases: Vec<Crease<T>>,
11270        auto_scroll: bool,
11271        cx: &mut ViewContext<Self>,
11272    ) {
11273        if creases.is_empty() {
11274            return;
11275        }
11276
11277        let mut buffers_affected = HashSet::default();
11278        let multi_buffer = self.buffer().read(cx);
11279        for crease in &creases {
11280            if let Some((_, buffer, _)) =
11281                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
11282            {
11283                buffers_affected.insert(buffer.read(cx).remote_id());
11284            };
11285        }
11286
11287        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
11288
11289        if auto_scroll {
11290            self.request_autoscroll(Autoscroll::fit(), cx);
11291        }
11292
11293        for buffer_id in buffers_affected {
11294            Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
11295        }
11296
11297        cx.notify();
11298
11299        if let Some(active_diagnostics) = self.active_diagnostics.take() {
11300            // Clear diagnostics block when folding a range that contains it.
11301            let snapshot = self.snapshot(cx);
11302            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
11303                drop(snapshot);
11304                self.active_diagnostics = Some(active_diagnostics);
11305                self.dismiss_diagnostics(cx);
11306            } else {
11307                self.active_diagnostics = Some(active_diagnostics);
11308            }
11309        }
11310
11311        self.scrollbar_marker_state.dirty = true;
11312    }
11313
11314    /// Removes any folds whose ranges intersect any of the given ranges.
11315    pub fn unfold_ranges<T: ToOffset + Clone>(
11316        &mut self,
11317        ranges: &[Range<T>],
11318        inclusive: bool,
11319        auto_scroll: bool,
11320        cx: &mut ViewContext<Self>,
11321    ) {
11322        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11323            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
11324        });
11325    }
11326
11327    /// Removes any folds with the given ranges.
11328    pub fn remove_folds_with_type<T: ToOffset + Clone>(
11329        &mut self,
11330        ranges: &[Range<T>],
11331        type_id: TypeId,
11332        auto_scroll: bool,
11333        cx: &mut ViewContext<Self>,
11334    ) {
11335        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11336            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
11337        });
11338    }
11339
11340    fn remove_folds_with<T: ToOffset + Clone>(
11341        &mut self,
11342        ranges: &[Range<T>],
11343        auto_scroll: bool,
11344        cx: &mut ViewContext<Self>,
11345        update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
11346    ) {
11347        if ranges.is_empty() {
11348            return;
11349        }
11350
11351        let mut buffers_affected = HashSet::default();
11352        let multi_buffer = self.buffer().read(cx);
11353        for range in ranges {
11354            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11355                buffers_affected.insert(buffer.read(cx).remote_id());
11356            };
11357        }
11358
11359        self.display_map.update(cx, update);
11360
11361        if auto_scroll {
11362            self.request_autoscroll(Autoscroll::fit(), cx);
11363        }
11364
11365        for buffer_id in buffers_affected {
11366            Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
11367        }
11368
11369        cx.notify();
11370        self.scrollbar_marker_state.dirty = true;
11371        self.active_indent_guides_state.dirty = true;
11372    }
11373
11374    pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
11375        self.display_map.read(cx).fold_placeholder.clone()
11376    }
11377
11378    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11379        if hovered != self.gutter_hovered {
11380            self.gutter_hovered = hovered;
11381            cx.notify();
11382        }
11383    }
11384
11385    pub fn insert_blocks(
11386        &mut self,
11387        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11388        autoscroll: Option<Autoscroll>,
11389        cx: &mut ViewContext<Self>,
11390    ) -> Vec<CustomBlockId> {
11391        let blocks = self
11392            .display_map
11393            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11394        if let Some(autoscroll) = autoscroll {
11395            self.request_autoscroll(autoscroll, cx);
11396        }
11397        cx.notify();
11398        blocks
11399    }
11400
11401    pub fn resize_blocks(
11402        &mut self,
11403        heights: HashMap<CustomBlockId, u32>,
11404        autoscroll: Option<Autoscroll>,
11405        cx: &mut ViewContext<Self>,
11406    ) {
11407        self.display_map
11408            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11409        if let Some(autoscroll) = autoscroll {
11410            self.request_autoscroll(autoscroll, cx);
11411        }
11412        cx.notify();
11413    }
11414
11415    pub fn replace_blocks(
11416        &mut self,
11417        renderers: HashMap<CustomBlockId, RenderBlock>,
11418        autoscroll: Option<Autoscroll>,
11419        cx: &mut ViewContext<Self>,
11420    ) {
11421        self.display_map
11422            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11423        if let Some(autoscroll) = autoscroll {
11424            self.request_autoscroll(autoscroll, cx);
11425        }
11426        cx.notify();
11427    }
11428
11429    pub fn remove_blocks(
11430        &mut self,
11431        block_ids: HashSet<CustomBlockId>,
11432        autoscroll: Option<Autoscroll>,
11433        cx: &mut ViewContext<Self>,
11434    ) {
11435        self.display_map.update(cx, |display_map, cx| {
11436            display_map.remove_blocks(block_ids, cx)
11437        });
11438        if let Some(autoscroll) = autoscroll {
11439            self.request_autoscroll(autoscroll, cx);
11440        }
11441        cx.notify();
11442    }
11443
11444    pub fn row_for_block(
11445        &self,
11446        block_id: CustomBlockId,
11447        cx: &mut ViewContext<Self>,
11448    ) -> Option<DisplayRow> {
11449        self.display_map
11450            .update(cx, |map, cx| map.row_for_block(block_id, cx))
11451    }
11452
11453    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11454        self.focused_block = Some(focused_block);
11455    }
11456
11457    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11458        self.focused_block.take()
11459    }
11460
11461    pub fn insert_creases(
11462        &mut self,
11463        creases: impl IntoIterator<Item = Crease<Anchor>>,
11464        cx: &mut ViewContext<Self>,
11465    ) -> Vec<CreaseId> {
11466        self.display_map
11467            .update(cx, |map, cx| map.insert_creases(creases, cx))
11468    }
11469
11470    pub fn remove_creases(
11471        &mut self,
11472        ids: impl IntoIterator<Item = CreaseId>,
11473        cx: &mut ViewContext<Self>,
11474    ) {
11475        self.display_map
11476            .update(cx, |map, cx| map.remove_creases(ids, cx));
11477    }
11478
11479    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11480        self.display_map
11481            .update(cx, |map, cx| map.snapshot(cx))
11482            .longest_row()
11483    }
11484
11485    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11486        self.display_map
11487            .update(cx, |map, cx| map.snapshot(cx))
11488            .max_point()
11489    }
11490
11491    pub fn text(&self, cx: &AppContext) -> String {
11492        self.buffer.read(cx).read(cx).text()
11493    }
11494
11495    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11496        let text = self.text(cx);
11497        let text = text.trim();
11498
11499        if text.is_empty() {
11500            return None;
11501        }
11502
11503        Some(text.to_string())
11504    }
11505
11506    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11507        self.transact(cx, |this, cx| {
11508            this.buffer
11509                .read(cx)
11510                .as_singleton()
11511                .expect("you can only call set_text on editors for singleton buffers")
11512                .update(cx, |buffer, cx| buffer.set_text(text, cx));
11513        });
11514    }
11515
11516    pub fn display_text(&self, cx: &mut AppContext) -> String {
11517        self.display_map
11518            .update(cx, |map, cx| map.snapshot(cx))
11519            .text()
11520    }
11521
11522    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11523        let mut wrap_guides = smallvec::smallvec![];
11524
11525        if self.show_wrap_guides == Some(false) {
11526            return wrap_guides;
11527        }
11528
11529        let settings = self.buffer.read(cx).settings_at(0, cx);
11530        if settings.show_wrap_guides {
11531            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11532                wrap_guides.push((soft_wrap as usize, true));
11533            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11534                wrap_guides.push((soft_wrap as usize, true));
11535            }
11536            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11537        }
11538
11539        wrap_guides
11540    }
11541
11542    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11543        let settings = self.buffer.read(cx).settings_at(0, cx);
11544        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11545        match mode {
11546            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11547                SoftWrap::None
11548            }
11549            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11550            language_settings::SoftWrap::PreferredLineLength => {
11551                SoftWrap::Column(settings.preferred_line_length)
11552            }
11553            language_settings::SoftWrap::Bounded => {
11554                SoftWrap::Bounded(settings.preferred_line_length)
11555            }
11556        }
11557    }
11558
11559    pub fn set_soft_wrap_mode(
11560        &mut self,
11561        mode: language_settings::SoftWrap,
11562        cx: &mut ViewContext<Self>,
11563    ) {
11564        self.soft_wrap_mode_override = Some(mode);
11565        cx.notify();
11566    }
11567
11568    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11569        self.text_style_refinement = Some(style);
11570    }
11571
11572    /// called by the Element so we know what style we were most recently rendered with.
11573    pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11574        let rem_size = cx.rem_size();
11575        self.display_map.update(cx, |map, cx| {
11576            map.set_font(
11577                style.text.font(),
11578                style.text.font_size.to_pixels(rem_size),
11579                cx,
11580            )
11581        });
11582        self.style = Some(style);
11583    }
11584
11585    pub fn style(&self) -> Option<&EditorStyle> {
11586        self.style.as_ref()
11587    }
11588
11589    // Called by the element. This method is not designed to be called outside of the editor
11590    // element's layout code because it does not notify when rewrapping is computed synchronously.
11591    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11592        self.display_map
11593            .update(cx, |map, cx| map.set_wrap_width(width, cx))
11594    }
11595
11596    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11597        if self.soft_wrap_mode_override.is_some() {
11598            self.soft_wrap_mode_override.take();
11599        } else {
11600            let soft_wrap = match self.soft_wrap_mode(cx) {
11601                SoftWrap::GitDiff => return,
11602                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11603                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11604                    language_settings::SoftWrap::None
11605                }
11606            };
11607            self.soft_wrap_mode_override = Some(soft_wrap);
11608        }
11609        cx.notify();
11610    }
11611
11612    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11613        let Some(workspace) = self.workspace() else {
11614            return;
11615        };
11616        let fs = workspace.read(cx).app_state().fs.clone();
11617        let current_show = TabBarSettings::get_global(cx).show;
11618        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11619            setting.show = Some(!current_show);
11620        });
11621    }
11622
11623    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11624        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11625            self.buffer
11626                .read(cx)
11627                .settings_at(0, cx)
11628                .indent_guides
11629                .enabled
11630        });
11631        self.show_indent_guides = Some(!currently_enabled);
11632        cx.notify();
11633    }
11634
11635    fn should_show_indent_guides(&self) -> Option<bool> {
11636        self.show_indent_guides
11637    }
11638
11639    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11640        let mut editor_settings = EditorSettings::get_global(cx).clone();
11641        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11642        EditorSettings::override_global(editor_settings, cx);
11643    }
11644
11645    pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11646        self.use_relative_line_numbers
11647            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11648    }
11649
11650    pub fn toggle_relative_line_numbers(
11651        &mut self,
11652        _: &ToggleRelativeLineNumbers,
11653        cx: &mut ViewContext<Self>,
11654    ) {
11655        let is_relative = self.should_use_relative_line_numbers(cx);
11656        self.set_relative_line_number(Some(!is_relative), cx)
11657    }
11658
11659    pub fn set_relative_line_number(
11660        &mut self,
11661        is_relative: Option<bool>,
11662        cx: &mut ViewContext<Self>,
11663    ) {
11664        self.use_relative_line_numbers = is_relative;
11665        cx.notify();
11666    }
11667
11668    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11669        self.show_gutter = show_gutter;
11670        cx.notify();
11671    }
11672
11673    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11674        self.show_line_numbers = Some(show_line_numbers);
11675        cx.notify();
11676    }
11677
11678    pub fn set_show_git_diff_gutter(
11679        &mut self,
11680        show_git_diff_gutter: bool,
11681        cx: &mut ViewContext<Self>,
11682    ) {
11683        self.show_git_diff_gutter = Some(show_git_diff_gutter);
11684        cx.notify();
11685    }
11686
11687    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11688        self.show_code_actions = Some(show_code_actions);
11689        cx.notify();
11690    }
11691
11692    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11693        self.show_runnables = Some(show_runnables);
11694        cx.notify();
11695    }
11696
11697    pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11698        if self.display_map.read(cx).masked != masked {
11699            self.display_map.update(cx, |map, _| map.masked = masked);
11700        }
11701        cx.notify()
11702    }
11703
11704    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11705        self.show_wrap_guides = Some(show_wrap_guides);
11706        cx.notify();
11707    }
11708
11709    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11710        self.show_indent_guides = Some(show_indent_guides);
11711        cx.notify();
11712    }
11713
11714    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11715        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11716            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11717                if let Some(dir) = file.abs_path(cx).parent() {
11718                    return Some(dir.to_owned());
11719                }
11720            }
11721
11722            if let Some(project_path) = buffer.read(cx).project_path(cx) {
11723                return Some(project_path.path.to_path_buf());
11724            }
11725        }
11726
11727        None
11728    }
11729
11730    fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11731        self.active_excerpt(cx)?
11732            .1
11733            .read(cx)
11734            .file()
11735            .and_then(|f| f.as_local())
11736    }
11737
11738    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11739        if let Some(target) = self.target_file(cx) {
11740            cx.reveal_path(&target.abs_path(cx));
11741        }
11742    }
11743
11744    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11745        if let Some(file) = self.target_file(cx) {
11746            if let Some(path) = file.abs_path(cx).to_str() {
11747                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11748            }
11749        }
11750    }
11751
11752    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11753        if let Some(file) = self.target_file(cx) {
11754            if let Some(path) = file.path().to_str() {
11755                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11756            }
11757        }
11758    }
11759
11760    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11761        self.show_git_blame_gutter = !self.show_git_blame_gutter;
11762
11763        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11764            self.start_git_blame(true, cx);
11765        }
11766
11767        cx.notify();
11768    }
11769
11770    pub fn toggle_git_blame_inline(
11771        &mut self,
11772        _: &ToggleGitBlameInline,
11773        cx: &mut ViewContext<Self>,
11774    ) {
11775        self.toggle_git_blame_inline_internal(true, cx);
11776        cx.notify();
11777    }
11778
11779    pub fn git_blame_inline_enabled(&self) -> bool {
11780        self.git_blame_inline_enabled
11781    }
11782
11783    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11784        self.show_selection_menu = self
11785            .show_selection_menu
11786            .map(|show_selections_menu| !show_selections_menu)
11787            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11788
11789        cx.notify();
11790    }
11791
11792    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11793        self.show_selection_menu
11794            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11795    }
11796
11797    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11798        if let Some(project) = self.project.as_ref() {
11799            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11800                return;
11801            };
11802
11803            if buffer.read(cx).file().is_none() {
11804                return;
11805            }
11806
11807            let focused = self.focus_handle(cx).contains_focused(cx);
11808
11809            let project = project.clone();
11810            let blame =
11811                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11812            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11813            self.blame = Some(blame);
11814        }
11815    }
11816
11817    fn toggle_git_blame_inline_internal(
11818        &mut self,
11819        user_triggered: bool,
11820        cx: &mut ViewContext<Self>,
11821    ) {
11822        if self.git_blame_inline_enabled {
11823            self.git_blame_inline_enabled = false;
11824            self.show_git_blame_inline = false;
11825            self.show_git_blame_inline_delay_task.take();
11826        } else {
11827            self.git_blame_inline_enabled = true;
11828            self.start_git_blame_inline(user_triggered, cx);
11829        }
11830
11831        cx.notify();
11832    }
11833
11834    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11835        self.start_git_blame(user_triggered, cx);
11836
11837        if ProjectSettings::get_global(cx)
11838            .git
11839            .inline_blame_delay()
11840            .is_some()
11841        {
11842            self.start_inline_blame_timer(cx);
11843        } else {
11844            self.show_git_blame_inline = true
11845        }
11846    }
11847
11848    pub fn blame(&self) -> Option<&Model<GitBlame>> {
11849        self.blame.as_ref()
11850    }
11851
11852    pub fn show_git_blame_gutter(&self) -> bool {
11853        self.show_git_blame_gutter
11854    }
11855
11856    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11857        self.show_git_blame_gutter && self.has_blame_entries(cx)
11858    }
11859
11860    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11861        self.show_git_blame_inline
11862            && self.focus_handle.is_focused(cx)
11863            && !self.newest_selection_head_on_empty_line(cx)
11864            && self.has_blame_entries(cx)
11865    }
11866
11867    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11868        self.blame()
11869            .map_or(false, |blame| blame.read(cx).has_generated_entries())
11870    }
11871
11872    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11873        let cursor_anchor = self.selections.newest_anchor().head();
11874
11875        let snapshot = self.buffer.read(cx).snapshot(cx);
11876        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11877
11878        snapshot.line_len(buffer_row) == 0
11879    }
11880
11881    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11882        let buffer_and_selection = maybe!({
11883            let selection = self.selections.newest::<Point>(cx);
11884            let selection_range = selection.range();
11885
11886            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11887                (buffer, selection_range.start.row..selection_range.end.row)
11888            } else {
11889                let buffer_ranges = self
11890                    .buffer()
11891                    .read(cx)
11892                    .range_to_buffer_ranges(selection_range, cx);
11893
11894                let (buffer, range, _) = if selection.reversed {
11895                    buffer_ranges.first()
11896                } else {
11897                    buffer_ranges.last()
11898                }?;
11899
11900                let snapshot = buffer.read(cx).snapshot();
11901                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11902                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
11903                (buffer.clone(), selection)
11904            };
11905
11906            Some((buffer, selection))
11907        });
11908
11909        let Some((buffer, selection)) = buffer_and_selection else {
11910            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11911        };
11912
11913        let Some(project) = self.project.as_ref() else {
11914            return Task::ready(Err(anyhow!("editor does not have project")));
11915        };
11916
11917        project.update(cx, |project, cx| {
11918            project.get_permalink_to_line(&buffer, selection, cx)
11919        })
11920    }
11921
11922    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11923        let permalink_task = self.get_permalink_to_line(cx);
11924        let workspace = self.workspace();
11925
11926        cx.spawn(|_, mut cx| async move {
11927            match permalink_task.await {
11928                Ok(permalink) => {
11929                    cx.update(|cx| {
11930                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11931                    })
11932                    .ok();
11933                }
11934                Err(err) => {
11935                    let message = format!("Failed to copy permalink: {err}");
11936
11937                    Err::<(), anyhow::Error>(err).log_err();
11938
11939                    if let Some(workspace) = workspace {
11940                        workspace
11941                            .update(&mut cx, |workspace, cx| {
11942                                struct CopyPermalinkToLine;
11943
11944                                workspace.show_toast(
11945                                    Toast::new(
11946                                        NotificationId::unique::<CopyPermalinkToLine>(),
11947                                        message,
11948                                    ),
11949                                    cx,
11950                                )
11951                            })
11952                            .ok();
11953                    }
11954                }
11955            }
11956        })
11957        .detach();
11958    }
11959
11960    pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11961        let selection = self.selections.newest::<Point>(cx).start.row + 1;
11962        if let Some(file) = self.target_file(cx) {
11963            if let Some(path) = file.path().to_str() {
11964                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11965            }
11966        }
11967    }
11968
11969    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11970        let permalink_task = self.get_permalink_to_line(cx);
11971        let workspace = self.workspace();
11972
11973        cx.spawn(|_, mut cx| async move {
11974            match permalink_task.await {
11975                Ok(permalink) => {
11976                    cx.update(|cx| {
11977                        cx.open_url(permalink.as_ref());
11978                    })
11979                    .ok();
11980                }
11981                Err(err) => {
11982                    let message = format!("Failed to open permalink: {err}");
11983
11984                    Err::<(), anyhow::Error>(err).log_err();
11985
11986                    if let Some(workspace) = workspace {
11987                        workspace
11988                            .update(&mut cx, |workspace, cx| {
11989                                struct OpenPermalinkToLine;
11990
11991                                workspace.show_toast(
11992                                    Toast::new(
11993                                        NotificationId::unique::<OpenPermalinkToLine>(),
11994                                        message,
11995                                    ),
11996                                    cx,
11997                                )
11998                            })
11999                            .ok();
12000                    }
12001                }
12002            }
12003        })
12004        .detach();
12005    }
12006
12007    /// Adds a row highlight for the given range. If a row has multiple highlights, the
12008    /// last highlight added will be used.
12009    ///
12010    /// If the range ends at the beginning of a line, then that line will not be highlighted.
12011    pub fn highlight_rows<T: 'static>(
12012        &mut self,
12013        range: Range<Anchor>,
12014        color: Hsla,
12015        should_autoscroll: bool,
12016        cx: &mut ViewContext<Self>,
12017    ) {
12018        let snapshot = self.buffer().read(cx).snapshot(cx);
12019        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
12020        let ix = row_highlights.binary_search_by(|highlight| {
12021            Ordering::Equal
12022                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
12023                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
12024        });
12025
12026        if let Err(mut ix) = ix {
12027            let index = post_inc(&mut self.highlight_order);
12028
12029            // If this range intersects with the preceding highlight, then merge it with
12030            // the preceding highlight. Otherwise insert a new highlight.
12031            let mut merged = false;
12032            if ix > 0 {
12033                let prev_highlight = &mut row_highlights[ix - 1];
12034                if prev_highlight
12035                    .range
12036                    .end
12037                    .cmp(&range.start, &snapshot)
12038                    .is_ge()
12039                {
12040                    ix -= 1;
12041                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
12042                        prev_highlight.range.end = range.end;
12043                    }
12044                    merged = true;
12045                    prev_highlight.index = index;
12046                    prev_highlight.color = color;
12047                    prev_highlight.should_autoscroll = should_autoscroll;
12048                }
12049            }
12050
12051            if !merged {
12052                row_highlights.insert(
12053                    ix,
12054                    RowHighlight {
12055                        range: range.clone(),
12056                        index,
12057                        color,
12058                        should_autoscroll,
12059                    },
12060                );
12061            }
12062
12063            // If any of the following highlights intersect with this one, merge them.
12064            while let Some(next_highlight) = row_highlights.get(ix + 1) {
12065                let highlight = &row_highlights[ix];
12066                if next_highlight
12067                    .range
12068                    .start
12069                    .cmp(&highlight.range.end, &snapshot)
12070                    .is_le()
12071                {
12072                    if next_highlight
12073                        .range
12074                        .end
12075                        .cmp(&highlight.range.end, &snapshot)
12076                        .is_gt()
12077                    {
12078                        row_highlights[ix].range.end = next_highlight.range.end;
12079                    }
12080                    row_highlights.remove(ix + 1);
12081                } else {
12082                    break;
12083                }
12084            }
12085        }
12086    }
12087
12088    /// Remove any highlighted row ranges of the given type that intersect the
12089    /// given ranges.
12090    pub fn remove_highlighted_rows<T: 'static>(
12091        &mut self,
12092        ranges_to_remove: Vec<Range<Anchor>>,
12093        cx: &mut ViewContext<Self>,
12094    ) {
12095        let snapshot = self.buffer().read(cx).snapshot(cx);
12096        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
12097        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
12098        row_highlights.retain(|highlight| {
12099            while let Some(range_to_remove) = ranges_to_remove.peek() {
12100                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
12101                    Ordering::Less | Ordering::Equal => {
12102                        ranges_to_remove.next();
12103                    }
12104                    Ordering::Greater => {
12105                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
12106                            Ordering::Less | Ordering::Equal => {
12107                                return false;
12108                            }
12109                            Ordering::Greater => break,
12110                        }
12111                    }
12112                }
12113            }
12114
12115            true
12116        })
12117    }
12118
12119    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
12120    pub fn clear_row_highlights<T: 'static>(&mut self) {
12121        self.highlighted_rows.remove(&TypeId::of::<T>());
12122    }
12123
12124    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
12125    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
12126        self.highlighted_rows
12127            .get(&TypeId::of::<T>())
12128            .map_or(&[] as &[_], |vec| vec.as_slice())
12129            .iter()
12130            .map(|highlight| (highlight.range.clone(), highlight.color))
12131    }
12132
12133    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
12134    /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
12135    /// Allows to ignore certain kinds of highlights.
12136    pub fn highlighted_display_rows(
12137        &mut self,
12138        cx: &mut WindowContext,
12139    ) -> BTreeMap<DisplayRow, Hsla> {
12140        let snapshot = self.snapshot(cx);
12141        let mut used_highlight_orders = HashMap::default();
12142        self.highlighted_rows
12143            .iter()
12144            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
12145            .fold(
12146                BTreeMap::<DisplayRow, Hsla>::new(),
12147                |mut unique_rows, highlight| {
12148                    let start = highlight.range.start.to_display_point(&snapshot);
12149                    let end = highlight.range.end.to_display_point(&snapshot);
12150                    let start_row = start.row().0;
12151                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
12152                        && end.column() == 0
12153                    {
12154                        end.row().0.saturating_sub(1)
12155                    } else {
12156                        end.row().0
12157                    };
12158                    for row in start_row..=end_row {
12159                        let used_index =
12160                            used_highlight_orders.entry(row).or_insert(highlight.index);
12161                        if highlight.index >= *used_index {
12162                            *used_index = highlight.index;
12163                            unique_rows.insert(DisplayRow(row), highlight.color);
12164                        }
12165                    }
12166                    unique_rows
12167                },
12168            )
12169    }
12170
12171    pub fn highlighted_display_row_for_autoscroll(
12172        &self,
12173        snapshot: &DisplaySnapshot,
12174    ) -> Option<DisplayRow> {
12175        self.highlighted_rows
12176            .values()
12177            .flat_map(|highlighted_rows| highlighted_rows.iter())
12178            .filter_map(|highlight| {
12179                if highlight.should_autoscroll {
12180                    Some(highlight.range.start.to_display_point(snapshot).row())
12181                } else {
12182                    None
12183                }
12184            })
12185            .min()
12186    }
12187
12188    pub fn set_search_within_ranges(
12189        &mut self,
12190        ranges: &[Range<Anchor>],
12191        cx: &mut ViewContext<Self>,
12192    ) {
12193        self.highlight_background::<SearchWithinRange>(
12194            ranges,
12195            |colors| colors.editor_document_highlight_read_background,
12196            cx,
12197        )
12198    }
12199
12200    pub fn set_breadcrumb_header(&mut self, new_header: String) {
12201        self.breadcrumb_header = Some(new_header);
12202    }
12203
12204    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
12205        self.clear_background_highlights::<SearchWithinRange>(cx);
12206    }
12207
12208    pub fn highlight_background<T: 'static>(
12209        &mut self,
12210        ranges: &[Range<Anchor>],
12211        color_fetcher: fn(&ThemeColors) -> Hsla,
12212        cx: &mut ViewContext<Self>,
12213    ) {
12214        self.background_highlights
12215            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12216        self.scrollbar_marker_state.dirty = true;
12217        cx.notify();
12218    }
12219
12220    pub fn clear_background_highlights<T: 'static>(
12221        &mut self,
12222        cx: &mut ViewContext<Self>,
12223    ) -> Option<BackgroundHighlight> {
12224        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
12225        if !text_highlights.1.is_empty() {
12226            self.scrollbar_marker_state.dirty = true;
12227            cx.notify();
12228        }
12229        Some(text_highlights)
12230    }
12231
12232    pub fn highlight_gutter<T: 'static>(
12233        &mut self,
12234        ranges: &[Range<Anchor>],
12235        color_fetcher: fn(&AppContext) -> Hsla,
12236        cx: &mut ViewContext<Self>,
12237    ) {
12238        self.gutter_highlights
12239            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12240        cx.notify();
12241    }
12242
12243    pub fn clear_gutter_highlights<T: 'static>(
12244        &mut self,
12245        cx: &mut ViewContext<Self>,
12246    ) -> Option<GutterHighlight> {
12247        cx.notify();
12248        self.gutter_highlights.remove(&TypeId::of::<T>())
12249    }
12250
12251    #[cfg(feature = "test-support")]
12252    pub fn all_text_background_highlights(
12253        &mut self,
12254        cx: &mut ViewContext<Self>,
12255    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12256        let snapshot = self.snapshot(cx);
12257        let buffer = &snapshot.buffer_snapshot;
12258        let start = buffer.anchor_before(0);
12259        let end = buffer.anchor_after(buffer.len());
12260        let theme = cx.theme().colors();
12261        self.background_highlights_in_range(start..end, &snapshot, theme)
12262    }
12263
12264    #[cfg(feature = "test-support")]
12265    pub fn search_background_highlights(
12266        &mut self,
12267        cx: &mut ViewContext<Self>,
12268    ) -> Vec<Range<Point>> {
12269        let snapshot = self.buffer().read(cx).snapshot(cx);
12270
12271        let highlights = self
12272            .background_highlights
12273            .get(&TypeId::of::<items::BufferSearchHighlights>());
12274
12275        if let Some((_color, ranges)) = highlights {
12276            ranges
12277                .iter()
12278                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
12279                .collect_vec()
12280        } else {
12281            vec![]
12282        }
12283    }
12284
12285    fn document_highlights_for_position<'a>(
12286        &'a self,
12287        position: Anchor,
12288        buffer: &'a MultiBufferSnapshot,
12289    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
12290        let read_highlights = self
12291            .background_highlights
12292            .get(&TypeId::of::<DocumentHighlightRead>())
12293            .map(|h| &h.1);
12294        let write_highlights = self
12295            .background_highlights
12296            .get(&TypeId::of::<DocumentHighlightWrite>())
12297            .map(|h| &h.1);
12298        let left_position = position.bias_left(buffer);
12299        let right_position = position.bias_right(buffer);
12300        read_highlights
12301            .into_iter()
12302            .chain(write_highlights)
12303            .flat_map(move |ranges| {
12304                let start_ix = match ranges.binary_search_by(|probe| {
12305                    let cmp = probe.end.cmp(&left_position, buffer);
12306                    if cmp.is_ge() {
12307                        Ordering::Greater
12308                    } else {
12309                        Ordering::Less
12310                    }
12311                }) {
12312                    Ok(i) | Err(i) => i,
12313                };
12314
12315                ranges[start_ix..]
12316                    .iter()
12317                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
12318            })
12319    }
12320
12321    pub fn has_background_highlights<T: 'static>(&self) -> bool {
12322        self.background_highlights
12323            .get(&TypeId::of::<T>())
12324            .map_or(false, |(_, highlights)| !highlights.is_empty())
12325    }
12326
12327    pub fn background_highlights_in_range(
12328        &self,
12329        search_range: Range<Anchor>,
12330        display_snapshot: &DisplaySnapshot,
12331        theme: &ThemeColors,
12332    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12333        let mut results = Vec::new();
12334        for (color_fetcher, ranges) in self.background_highlights.values() {
12335            let color = color_fetcher(theme);
12336            let start_ix = match ranges.binary_search_by(|probe| {
12337                let cmp = probe
12338                    .end
12339                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12340                if cmp.is_gt() {
12341                    Ordering::Greater
12342                } else {
12343                    Ordering::Less
12344                }
12345            }) {
12346                Ok(i) | Err(i) => i,
12347            };
12348            for range in &ranges[start_ix..] {
12349                if range
12350                    .start
12351                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12352                    .is_ge()
12353                {
12354                    break;
12355                }
12356
12357                let start = range.start.to_display_point(display_snapshot);
12358                let end = range.end.to_display_point(display_snapshot);
12359                results.push((start..end, color))
12360            }
12361        }
12362        results
12363    }
12364
12365    pub fn background_highlight_row_ranges<T: 'static>(
12366        &self,
12367        search_range: Range<Anchor>,
12368        display_snapshot: &DisplaySnapshot,
12369        count: usize,
12370    ) -> Vec<RangeInclusive<DisplayPoint>> {
12371        let mut results = Vec::new();
12372        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12373            return vec![];
12374        };
12375
12376        let start_ix = match ranges.binary_search_by(|probe| {
12377            let cmp = probe
12378                .end
12379                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12380            if cmp.is_gt() {
12381                Ordering::Greater
12382            } else {
12383                Ordering::Less
12384            }
12385        }) {
12386            Ok(i) | Err(i) => i,
12387        };
12388        let mut push_region = |start: Option<Point>, end: Option<Point>| {
12389            if let (Some(start_display), Some(end_display)) = (start, end) {
12390                results.push(
12391                    start_display.to_display_point(display_snapshot)
12392                        ..=end_display.to_display_point(display_snapshot),
12393                );
12394            }
12395        };
12396        let mut start_row: Option<Point> = None;
12397        let mut end_row: Option<Point> = None;
12398        if ranges.len() > count {
12399            return Vec::new();
12400        }
12401        for range in &ranges[start_ix..] {
12402            if range
12403                .start
12404                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12405                .is_ge()
12406            {
12407                break;
12408            }
12409            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12410            if let Some(current_row) = &end_row {
12411                if end.row == current_row.row {
12412                    continue;
12413                }
12414            }
12415            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12416            if start_row.is_none() {
12417                assert_eq!(end_row, None);
12418                start_row = Some(start);
12419                end_row = Some(end);
12420                continue;
12421            }
12422            if let Some(current_end) = end_row.as_mut() {
12423                if start.row > current_end.row + 1 {
12424                    push_region(start_row, end_row);
12425                    start_row = Some(start);
12426                    end_row = Some(end);
12427                } else {
12428                    // Merge two hunks.
12429                    *current_end = end;
12430                }
12431            } else {
12432                unreachable!();
12433            }
12434        }
12435        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12436        push_region(start_row, end_row);
12437        results
12438    }
12439
12440    pub fn gutter_highlights_in_range(
12441        &self,
12442        search_range: Range<Anchor>,
12443        display_snapshot: &DisplaySnapshot,
12444        cx: &AppContext,
12445    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12446        let mut results = Vec::new();
12447        for (color_fetcher, ranges) in self.gutter_highlights.values() {
12448            let color = color_fetcher(cx);
12449            let start_ix = match ranges.binary_search_by(|probe| {
12450                let cmp = probe
12451                    .end
12452                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12453                if cmp.is_gt() {
12454                    Ordering::Greater
12455                } else {
12456                    Ordering::Less
12457                }
12458            }) {
12459                Ok(i) | Err(i) => i,
12460            };
12461            for range in &ranges[start_ix..] {
12462                if range
12463                    .start
12464                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12465                    .is_ge()
12466                {
12467                    break;
12468                }
12469
12470                let start = range.start.to_display_point(display_snapshot);
12471                let end = range.end.to_display_point(display_snapshot);
12472                results.push((start..end, color))
12473            }
12474        }
12475        results
12476    }
12477
12478    /// Get the text ranges corresponding to the redaction query
12479    pub fn redacted_ranges(
12480        &self,
12481        search_range: Range<Anchor>,
12482        display_snapshot: &DisplaySnapshot,
12483        cx: &WindowContext,
12484    ) -> Vec<Range<DisplayPoint>> {
12485        display_snapshot
12486            .buffer_snapshot
12487            .redacted_ranges(search_range, |file| {
12488                if let Some(file) = file {
12489                    file.is_private()
12490                        && EditorSettings::get(
12491                            Some(SettingsLocation {
12492                                worktree_id: file.worktree_id(cx),
12493                                path: file.path().as_ref(),
12494                            }),
12495                            cx,
12496                        )
12497                        .redact_private_values
12498                } else {
12499                    false
12500                }
12501            })
12502            .map(|range| {
12503                range.start.to_display_point(display_snapshot)
12504                    ..range.end.to_display_point(display_snapshot)
12505            })
12506            .collect()
12507    }
12508
12509    pub fn highlight_text<T: 'static>(
12510        &mut self,
12511        ranges: Vec<Range<Anchor>>,
12512        style: HighlightStyle,
12513        cx: &mut ViewContext<Self>,
12514    ) {
12515        self.display_map.update(cx, |map, _| {
12516            map.highlight_text(TypeId::of::<T>(), ranges, style)
12517        });
12518        cx.notify();
12519    }
12520
12521    pub(crate) fn highlight_inlays<T: 'static>(
12522        &mut self,
12523        highlights: Vec<InlayHighlight>,
12524        style: HighlightStyle,
12525        cx: &mut ViewContext<Self>,
12526    ) {
12527        self.display_map.update(cx, |map, _| {
12528            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12529        });
12530        cx.notify();
12531    }
12532
12533    pub fn text_highlights<'a, T: 'static>(
12534        &'a self,
12535        cx: &'a AppContext,
12536    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12537        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12538    }
12539
12540    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12541        let cleared = self
12542            .display_map
12543            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12544        if cleared {
12545            cx.notify();
12546        }
12547    }
12548
12549    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12550        (self.read_only(cx) || self.blink_manager.read(cx).visible())
12551            && self.focus_handle.is_focused(cx)
12552    }
12553
12554    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12555        self.show_cursor_when_unfocused = is_enabled;
12556        cx.notify();
12557    }
12558
12559    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12560        cx.notify();
12561    }
12562
12563    fn on_buffer_event(
12564        &mut self,
12565        multibuffer: Model<MultiBuffer>,
12566        event: &multi_buffer::Event,
12567        cx: &mut ViewContext<Self>,
12568    ) {
12569        match event {
12570            multi_buffer::Event::Edited {
12571                singleton_buffer_edited,
12572            } => {
12573                self.scrollbar_marker_state.dirty = true;
12574                self.active_indent_guides_state.dirty = true;
12575                self.refresh_active_diagnostics(cx);
12576                self.refresh_code_actions(cx);
12577                if self.has_active_inline_completion(cx) {
12578                    self.update_visible_inline_completion(cx);
12579                }
12580                cx.emit(EditorEvent::BufferEdited);
12581                cx.emit(SearchEvent::MatchesInvalidated);
12582                if *singleton_buffer_edited {
12583                    if let Some(project) = &self.project {
12584                        let project = project.read(cx);
12585                        #[allow(clippy::mutable_key_type)]
12586                        let languages_affected = multibuffer
12587                            .read(cx)
12588                            .all_buffers()
12589                            .into_iter()
12590                            .filter_map(|buffer| {
12591                                let buffer = buffer.read(cx);
12592                                let language = buffer.language()?;
12593                                if project.is_local()
12594                                    && project.language_servers_for_buffer(buffer, cx).count() == 0
12595                                {
12596                                    None
12597                                } else {
12598                                    Some(language)
12599                                }
12600                            })
12601                            .cloned()
12602                            .collect::<HashSet<_>>();
12603                        if !languages_affected.is_empty() {
12604                            self.refresh_inlay_hints(
12605                                InlayHintRefreshReason::BufferEdited(languages_affected),
12606                                cx,
12607                            );
12608                        }
12609                    }
12610                }
12611
12612                let Some(project) = &self.project else { return };
12613                let (telemetry, is_via_ssh) = {
12614                    let project = project.read(cx);
12615                    let telemetry = project.client().telemetry().clone();
12616                    let is_via_ssh = project.is_via_ssh();
12617                    (telemetry, is_via_ssh)
12618                };
12619                refresh_linked_ranges(self, cx);
12620                telemetry.log_edit_event("editor", is_via_ssh);
12621            }
12622            multi_buffer::Event::ExcerptsAdded {
12623                buffer,
12624                predecessor,
12625                excerpts,
12626            } => {
12627                self.tasks_update_task = Some(self.refresh_runnables(cx));
12628                let buffer_id = buffer.read(cx).remote_id();
12629                if !self.diff_map.diff_bases.contains_key(&buffer_id) {
12630                    if let Some(project) = &self.project {
12631                        get_unstaged_changes_for_buffers(project, [buffer.clone()], cx);
12632                    }
12633                }
12634                cx.emit(EditorEvent::ExcerptsAdded {
12635                    buffer: buffer.clone(),
12636                    predecessor: *predecessor,
12637                    excerpts: excerpts.clone(),
12638                });
12639                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12640            }
12641            multi_buffer::Event::ExcerptsRemoved { ids } => {
12642                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12643                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12644            }
12645            multi_buffer::Event::ExcerptsEdited { ids } => {
12646                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12647            }
12648            multi_buffer::Event::ExcerptsExpanded { ids } => {
12649                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12650            }
12651            multi_buffer::Event::Reparsed(buffer_id) => {
12652                self.tasks_update_task = Some(self.refresh_runnables(cx));
12653
12654                cx.emit(EditorEvent::Reparsed(*buffer_id));
12655            }
12656            multi_buffer::Event::LanguageChanged(buffer_id) => {
12657                linked_editing_ranges::refresh_linked_ranges(self, cx);
12658                cx.emit(EditorEvent::Reparsed(*buffer_id));
12659                cx.notify();
12660            }
12661            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12662            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12663            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12664                cx.emit(EditorEvent::TitleChanged)
12665            }
12666            // multi_buffer::Event::DiffBaseChanged => {
12667            //     self.scrollbar_marker_state.dirty = true;
12668            //     cx.emit(EditorEvent::DiffBaseChanged);
12669            //     cx.notify();
12670            // }
12671            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12672            multi_buffer::Event::DiagnosticsUpdated => {
12673                self.refresh_active_diagnostics(cx);
12674                self.scrollbar_marker_state.dirty = true;
12675                cx.notify();
12676            }
12677            _ => {}
12678        };
12679    }
12680
12681    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12682        cx.notify();
12683    }
12684
12685    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12686        self.tasks_update_task = Some(self.refresh_runnables(cx));
12687        self.refresh_inline_completion(true, false, cx);
12688        self.refresh_inlay_hints(
12689            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12690                self.selections.newest_anchor().head(),
12691                &self.buffer.read(cx).snapshot(cx),
12692                cx,
12693            )),
12694            cx,
12695        );
12696
12697        let old_cursor_shape = self.cursor_shape;
12698
12699        {
12700            let editor_settings = EditorSettings::get_global(cx);
12701            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12702            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12703            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12704        }
12705
12706        if old_cursor_shape != self.cursor_shape {
12707            cx.emit(EditorEvent::CursorShapeChanged);
12708        }
12709
12710        let project_settings = ProjectSettings::get_global(cx);
12711        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12712
12713        if self.mode == EditorMode::Full {
12714            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12715            if self.git_blame_inline_enabled != inline_blame_enabled {
12716                self.toggle_git_blame_inline_internal(false, cx);
12717            }
12718        }
12719
12720        cx.notify();
12721    }
12722
12723    pub fn set_searchable(&mut self, searchable: bool) {
12724        self.searchable = searchable;
12725    }
12726
12727    pub fn searchable(&self) -> bool {
12728        self.searchable
12729    }
12730
12731    fn open_proposed_changes_editor(
12732        &mut self,
12733        _: &OpenProposedChangesEditor,
12734        cx: &mut ViewContext<Self>,
12735    ) {
12736        let Some(workspace) = self.workspace() else {
12737            cx.propagate();
12738            return;
12739        };
12740
12741        let selections = self.selections.all::<usize>(cx);
12742        let buffer = self.buffer.read(cx);
12743        let mut new_selections_by_buffer = HashMap::default();
12744        for selection in selections {
12745            for (buffer, range, _) in
12746                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12747            {
12748                let mut range = range.to_point(buffer.read(cx));
12749                range.start.column = 0;
12750                range.end.column = buffer.read(cx).line_len(range.end.row);
12751                new_selections_by_buffer
12752                    .entry(buffer)
12753                    .or_insert(Vec::new())
12754                    .push(range)
12755            }
12756        }
12757
12758        let proposed_changes_buffers = new_selections_by_buffer
12759            .into_iter()
12760            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12761            .collect::<Vec<_>>();
12762        let proposed_changes_editor = cx.new_view(|cx| {
12763            ProposedChangesEditor::new(
12764                "Proposed changes",
12765                proposed_changes_buffers,
12766                self.project.clone(),
12767                cx,
12768            )
12769        });
12770
12771        cx.window_context().defer(move |cx| {
12772            workspace.update(cx, |workspace, cx| {
12773                workspace.active_pane().update(cx, |pane, cx| {
12774                    pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12775                });
12776            });
12777        });
12778    }
12779
12780    pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12781        self.open_excerpts_common(None, true, cx)
12782    }
12783
12784    pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12785        self.open_excerpts_common(None, false, cx)
12786    }
12787
12788    fn open_excerpts_common(
12789        &mut self,
12790        jump_data: Option<JumpData>,
12791        split: bool,
12792        cx: &mut ViewContext<Self>,
12793    ) {
12794        let Some(workspace) = self.workspace() else {
12795            cx.propagate();
12796            return;
12797        };
12798
12799        if self.buffer.read(cx).is_singleton() {
12800            cx.propagate();
12801            return;
12802        }
12803
12804        let mut new_selections_by_buffer = HashMap::default();
12805        match &jump_data {
12806            Some(jump_data) => {
12807                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12808                if let Some(buffer) = multi_buffer_snapshot
12809                    .buffer_id_for_excerpt(jump_data.excerpt_id)
12810                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12811                {
12812                    let buffer_snapshot = buffer.read(cx).snapshot();
12813                    let jump_to_point = if buffer_snapshot.can_resolve(&jump_data.anchor) {
12814                        language::ToPoint::to_point(&jump_data.anchor, &buffer_snapshot)
12815                    } else {
12816                        buffer_snapshot.clip_point(jump_data.position, Bias::Left)
12817                    };
12818                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12819                    new_selections_by_buffer.insert(
12820                        buffer,
12821                        (
12822                            vec![jump_to_offset..jump_to_offset],
12823                            Some(jump_data.line_offset_from_top),
12824                        ),
12825                    );
12826                }
12827            }
12828            None => {
12829                let selections = self.selections.all::<usize>(cx);
12830                let buffer = self.buffer.read(cx);
12831                for selection in selections {
12832                    for (mut buffer_handle, mut range, _) in
12833                        buffer.range_to_buffer_ranges(selection.range(), cx)
12834                    {
12835                        // When editing branch buffers, jump to the corresponding location
12836                        // in their base buffer.
12837                        let buffer = buffer_handle.read(cx);
12838                        if let Some(base_buffer) = buffer.base_buffer() {
12839                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12840                            buffer_handle = base_buffer;
12841                        }
12842
12843                        if selection.reversed {
12844                            mem::swap(&mut range.start, &mut range.end);
12845                        }
12846                        new_selections_by_buffer
12847                            .entry(buffer_handle)
12848                            .or_insert((Vec::new(), None))
12849                            .0
12850                            .push(range)
12851                    }
12852                }
12853            }
12854        }
12855
12856        if new_selections_by_buffer.is_empty() {
12857            return;
12858        }
12859
12860        // We defer the pane interaction because we ourselves are a workspace item
12861        // and activating a new item causes the pane to call a method on us reentrantly,
12862        // which panics if we're on the stack.
12863        cx.window_context().defer(move |cx| {
12864            workspace.update(cx, |workspace, cx| {
12865                let pane = if split {
12866                    workspace.adjacent_pane(cx)
12867                } else {
12868                    workspace.active_pane().clone()
12869                };
12870
12871                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12872                    let editor = buffer
12873                        .read(cx)
12874                        .file()
12875                        .is_none()
12876                        .then(|| {
12877                            // Handle file-less buffers separately: those are not really the project items, so won't have a paroject path or entity id,
12878                            // so `workspace.open_project_item` will never find them, always opening a new editor.
12879                            // Instead, we try to activate the existing editor in the pane first.
12880                            let (editor, pane_item_index) =
12881                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
12882                                    let editor = item.downcast::<Editor>()?;
12883                                    let singleton_buffer =
12884                                        editor.read(cx).buffer().read(cx).as_singleton()?;
12885                                    if singleton_buffer == buffer {
12886                                        Some((editor, i))
12887                                    } else {
12888                                        None
12889                                    }
12890                                })?;
12891                            pane.update(cx, |pane, cx| {
12892                                pane.activate_item(pane_item_index, true, true, cx)
12893                            });
12894                            Some(editor)
12895                        })
12896                        .flatten()
12897                        .unwrap_or_else(|| {
12898                            workspace.open_project_item::<Self>(
12899                                pane.clone(),
12900                                buffer,
12901                                true,
12902                                true,
12903                                cx,
12904                            )
12905                        });
12906
12907                    editor.update(cx, |editor, cx| {
12908                        let autoscroll = match scroll_offset {
12909                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12910                            None => Autoscroll::newest(),
12911                        };
12912                        let nav_history = editor.nav_history.take();
12913                        editor.change_selections(Some(autoscroll), cx, |s| {
12914                            s.select_ranges(ranges);
12915                        });
12916                        editor.nav_history = nav_history;
12917                    });
12918                }
12919            })
12920        });
12921    }
12922
12923    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12924        let snapshot = self.buffer.read(cx).read(cx);
12925        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12926        Some(
12927            ranges
12928                .iter()
12929                .map(move |range| {
12930                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12931                })
12932                .collect(),
12933        )
12934    }
12935
12936    fn selection_replacement_ranges(
12937        &self,
12938        range: Range<OffsetUtf16>,
12939        cx: &mut AppContext,
12940    ) -> Vec<Range<OffsetUtf16>> {
12941        let selections = self.selections.all::<OffsetUtf16>(cx);
12942        let newest_selection = selections
12943            .iter()
12944            .max_by_key(|selection| selection.id)
12945            .unwrap();
12946        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12947        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12948        let snapshot = self.buffer.read(cx).read(cx);
12949        selections
12950            .into_iter()
12951            .map(|mut selection| {
12952                selection.start.0 =
12953                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
12954                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12955                snapshot.clip_offset_utf16(selection.start, Bias::Left)
12956                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12957            })
12958            .collect()
12959    }
12960
12961    fn report_editor_event(
12962        &self,
12963        operation: &'static str,
12964        file_extension: Option<String>,
12965        cx: &AppContext,
12966    ) {
12967        if cfg!(any(test, feature = "test-support")) {
12968            return;
12969        }
12970
12971        let Some(project) = &self.project else { return };
12972
12973        // If None, we are in a file without an extension
12974        let file = self
12975            .buffer
12976            .read(cx)
12977            .as_singleton()
12978            .and_then(|b| b.read(cx).file());
12979        let file_extension = file_extension.or(file
12980            .as_ref()
12981            .and_then(|file| Path::new(file.file_name(cx)).extension())
12982            .and_then(|e| e.to_str())
12983            .map(|a| a.to_string()));
12984
12985        let vim_mode = cx
12986            .global::<SettingsStore>()
12987            .raw_user_settings()
12988            .get("vim_mode")
12989            == Some(&serde_json::Value::Bool(true));
12990
12991        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12992            == language::language_settings::InlineCompletionProvider::Copilot;
12993        let copilot_enabled_for_language = self
12994            .buffer
12995            .read(cx)
12996            .settings_at(0, cx)
12997            .show_inline_completions;
12998
12999        let project = project.read(cx);
13000        let telemetry = project.client().telemetry().clone();
13001        telemetry.report_editor_event(
13002            file_extension,
13003            vim_mode,
13004            operation,
13005            copilot_enabled,
13006            copilot_enabled_for_language,
13007            project.is_via_ssh(),
13008        )
13009    }
13010
13011    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
13012    /// with each line being an array of {text, highlight} objects.
13013    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
13014        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
13015            return;
13016        };
13017
13018        #[derive(Serialize)]
13019        struct Chunk<'a> {
13020            text: String,
13021            highlight: Option<&'a str>,
13022        }
13023
13024        let snapshot = buffer.read(cx).snapshot();
13025        let range = self
13026            .selected_text_range(false, cx)
13027            .and_then(|selection| {
13028                if selection.range.is_empty() {
13029                    None
13030                } else {
13031                    Some(selection.range)
13032                }
13033            })
13034            .unwrap_or_else(|| 0..snapshot.len());
13035
13036        let chunks = snapshot.chunks(range, true);
13037        let mut lines = Vec::new();
13038        let mut line: VecDeque<Chunk> = VecDeque::new();
13039
13040        let Some(style) = self.style.as_ref() else {
13041            return;
13042        };
13043
13044        for chunk in chunks {
13045            let highlight = chunk
13046                .syntax_highlight_id
13047                .and_then(|id| id.name(&style.syntax));
13048            let mut chunk_lines = chunk.text.split('\n').peekable();
13049            while let Some(text) = chunk_lines.next() {
13050                let mut merged_with_last_token = false;
13051                if let Some(last_token) = line.back_mut() {
13052                    if last_token.highlight == highlight {
13053                        last_token.text.push_str(text);
13054                        merged_with_last_token = true;
13055                    }
13056                }
13057
13058                if !merged_with_last_token {
13059                    line.push_back(Chunk {
13060                        text: text.into(),
13061                        highlight,
13062                    });
13063                }
13064
13065                if chunk_lines.peek().is_some() {
13066                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
13067                        line.pop_front();
13068                    }
13069                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
13070                        line.pop_back();
13071                    }
13072
13073                    lines.push(mem::take(&mut line));
13074                }
13075            }
13076        }
13077
13078        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
13079            return;
13080        };
13081        cx.write_to_clipboard(ClipboardItem::new_string(lines));
13082    }
13083
13084    pub fn open_context_menu(&mut self, _: &OpenContextMenu, cx: &mut ViewContext<Self>) {
13085        self.request_autoscroll(Autoscroll::newest(), cx);
13086        let position = self.selections.newest_display(cx).start;
13087        mouse_context_menu::deploy_context_menu(self, None, position, cx);
13088    }
13089
13090    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
13091        &self.inlay_hint_cache
13092    }
13093
13094    pub fn replay_insert_event(
13095        &mut self,
13096        text: &str,
13097        relative_utf16_range: Option<Range<isize>>,
13098        cx: &mut ViewContext<Self>,
13099    ) {
13100        if !self.input_enabled {
13101            cx.emit(EditorEvent::InputIgnored { text: text.into() });
13102            return;
13103        }
13104        if let Some(relative_utf16_range) = relative_utf16_range {
13105            let selections = self.selections.all::<OffsetUtf16>(cx);
13106            self.change_selections(None, cx, |s| {
13107                let new_ranges = selections.into_iter().map(|range| {
13108                    let start = OffsetUtf16(
13109                        range
13110                            .head()
13111                            .0
13112                            .saturating_add_signed(relative_utf16_range.start),
13113                    );
13114                    let end = OffsetUtf16(
13115                        range
13116                            .head()
13117                            .0
13118                            .saturating_add_signed(relative_utf16_range.end),
13119                    );
13120                    start..end
13121                });
13122                s.select_ranges(new_ranges);
13123            });
13124        }
13125
13126        self.handle_input(text, cx);
13127    }
13128
13129    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
13130        let Some(provider) = self.semantics_provider.as_ref() else {
13131            return false;
13132        };
13133
13134        let mut supports = false;
13135        self.buffer().read(cx).for_each_buffer(|buffer| {
13136            supports |= provider.supports_inlay_hints(buffer, cx);
13137        });
13138        supports
13139    }
13140
13141    pub fn focus(&self, cx: &mut WindowContext) {
13142        cx.focus(&self.focus_handle)
13143    }
13144
13145    pub fn is_focused(&self, cx: &WindowContext) -> bool {
13146        self.focus_handle.is_focused(cx)
13147    }
13148
13149    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
13150        cx.emit(EditorEvent::Focused);
13151
13152        if let Some(descendant) = self
13153            .last_focused_descendant
13154            .take()
13155            .and_then(|descendant| descendant.upgrade())
13156        {
13157            cx.focus(&descendant);
13158        } else {
13159            if let Some(blame) = self.blame.as_ref() {
13160                blame.update(cx, GitBlame::focus)
13161            }
13162
13163            self.blink_manager.update(cx, BlinkManager::enable);
13164            self.show_cursor_names(cx);
13165            self.buffer.update(cx, |buffer, cx| {
13166                buffer.finalize_last_transaction(cx);
13167                if self.leader_peer_id.is_none() {
13168                    buffer.set_active_selections(
13169                        &self.selections.disjoint_anchors(),
13170                        self.selections.line_mode,
13171                        self.cursor_shape,
13172                        cx,
13173                    );
13174                }
13175            });
13176        }
13177    }
13178
13179    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
13180        cx.emit(EditorEvent::FocusedIn)
13181    }
13182
13183    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
13184        if event.blurred != self.focus_handle {
13185            self.last_focused_descendant = Some(event.blurred);
13186        }
13187    }
13188
13189    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
13190        self.blink_manager.update(cx, BlinkManager::disable);
13191        self.buffer
13192            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
13193
13194        if let Some(blame) = self.blame.as_ref() {
13195            blame.update(cx, GitBlame::blur)
13196        }
13197        if !self.hover_state.focused(cx) {
13198            hide_hover(self, cx);
13199        }
13200
13201        self.hide_context_menu(cx);
13202        cx.emit(EditorEvent::Blurred);
13203        cx.notify();
13204    }
13205
13206    pub fn register_action<A: Action>(
13207        &mut self,
13208        listener: impl Fn(&A, &mut WindowContext) + 'static,
13209    ) -> Subscription {
13210        let id = self.next_editor_action_id.post_inc();
13211        let listener = Arc::new(listener);
13212        self.editor_actions.borrow_mut().insert(
13213            id,
13214            Box::new(move |cx| {
13215                let cx = cx.window_context();
13216                let listener = listener.clone();
13217                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
13218                    let action = action.downcast_ref().unwrap();
13219                    if phase == DispatchPhase::Bubble {
13220                        listener(action, cx)
13221                    }
13222                })
13223            }),
13224        );
13225
13226        let editor_actions = self.editor_actions.clone();
13227        Subscription::new(move || {
13228            editor_actions.borrow_mut().remove(&id);
13229        })
13230    }
13231
13232    pub fn file_header_size(&self) -> u32 {
13233        FILE_HEADER_HEIGHT
13234    }
13235
13236    pub fn revert(
13237        &mut self,
13238        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
13239        cx: &mut ViewContext<Self>,
13240    ) {
13241        self.buffer().update(cx, |multi_buffer, cx| {
13242            for (buffer_id, changes) in revert_changes {
13243                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13244                    buffer.update(cx, |buffer, cx| {
13245                        buffer.edit(
13246                            changes.into_iter().map(|(range, text)| {
13247                                (range, text.to_string().map(Arc::<str>::from))
13248                            }),
13249                            None,
13250                            cx,
13251                        );
13252                    });
13253                }
13254            }
13255        });
13256        self.change_selections(None, cx, |selections| selections.refresh());
13257    }
13258
13259    pub fn to_pixel_point(
13260        &mut self,
13261        source: multi_buffer::Anchor,
13262        editor_snapshot: &EditorSnapshot,
13263        cx: &mut ViewContext<Self>,
13264    ) -> Option<gpui::Point<Pixels>> {
13265        let source_point = source.to_display_point(editor_snapshot);
13266        self.display_to_pixel_point(source_point, editor_snapshot, cx)
13267    }
13268
13269    pub fn display_to_pixel_point(
13270        &mut self,
13271        source: DisplayPoint,
13272        editor_snapshot: &EditorSnapshot,
13273        cx: &mut ViewContext<Self>,
13274    ) -> Option<gpui::Point<Pixels>> {
13275        let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
13276        let text_layout_details = self.text_layout_details(cx);
13277        let scroll_top = text_layout_details
13278            .scroll_anchor
13279            .scroll_position(editor_snapshot)
13280            .y;
13281
13282        if source.row().as_f32() < scroll_top.floor() {
13283            return None;
13284        }
13285        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
13286        let source_y = line_height * (source.row().as_f32() - scroll_top);
13287        Some(gpui::Point::new(source_x, source_y))
13288    }
13289
13290    pub fn has_active_completions_menu(&self) -> bool {
13291        self.context_menu.read().as_ref().map_or(false, |menu| {
13292            menu.visible() && matches!(menu, ContextMenu::Completions(_))
13293        })
13294    }
13295
13296    pub fn register_addon<T: Addon>(&mut self, instance: T) {
13297        self.addons
13298            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
13299    }
13300
13301    pub fn unregister_addon<T: Addon>(&mut self) {
13302        self.addons.remove(&std::any::TypeId::of::<T>());
13303    }
13304
13305    pub fn addon<T: Addon>(&self) -> Option<&T> {
13306        let type_id = std::any::TypeId::of::<T>();
13307        self.addons
13308            .get(&type_id)
13309            .and_then(|item| item.to_any().downcast_ref::<T>())
13310    }
13311
13312    fn character_size(&self, cx: &mut ViewContext<Self>) -> gpui::Point<Pixels> {
13313        let text_layout_details = self.text_layout_details(cx);
13314        let style = &text_layout_details.editor_style;
13315        let font_id = cx.text_system().resolve_font(&style.text.font());
13316        let font_size = style.text.font_size.to_pixels(cx.rem_size());
13317        let line_height = style.text.line_height_in_pixels(cx.rem_size());
13318
13319        let em_width = cx
13320            .text_system()
13321            .typographic_bounds(font_id, font_size, 'm')
13322            .unwrap()
13323            .size
13324            .width;
13325
13326        gpui::Point::new(em_width, line_height)
13327    }
13328}
13329
13330fn get_unstaged_changes_for_buffers(
13331    project: &Model<Project>,
13332    buffers: impl IntoIterator<Item = Model<Buffer>>,
13333    cx: &mut ViewContext<Editor>,
13334) {
13335    let mut tasks = Vec::new();
13336    project.update(cx, |project, cx| {
13337        for buffer in buffers {
13338            tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
13339        }
13340    });
13341    cx.spawn(|this, mut cx| async move {
13342        let change_sets = futures::future::join_all(tasks).await;
13343        this.update(&mut cx, |this, cx| {
13344            for change_set in change_sets {
13345                if let Some(change_set) = change_set.log_err() {
13346                    this.diff_map.add_change_set(change_set, cx);
13347                }
13348            }
13349        })
13350        .ok();
13351    })
13352    .detach();
13353}
13354
13355fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13356    let tab_size = tab_size.get() as usize;
13357    let mut width = offset;
13358
13359    for ch in text.chars() {
13360        width += if ch == '\t' {
13361            tab_size - (width % tab_size)
13362        } else {
13363            1
13364        };
13365    }
13366
13367    width - offset
13368}
13369
13370#[cfg(test)]
13371mod tests {
13372    use super::*;
13373
13374    #[test]
13375    fn test_string_size_with_expanded_tabs() {
13376        let nz = |val| NonZeroU32::new(val).unwrap();
13377        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13378        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13379        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13380        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13381        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13382        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13383        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13384        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13385    }
13386}
13387
13388/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13389struct WordBreakingTokenizer<'a> {
13390    input: &'a str,
13391}
13392
13393impl<'a> WordBreakingTokenizer<'a> {
13394    fn new(input: &'a str) -> Self {
13395        Self { input }
13396    }
13397}
13398
13399fn is_char_ideographic(ch: char) -> bool {
13400    use unicode_script::Script::*;
13401    use unicode_script::UnicodeScript;
13402    matches!(ch.script(), Han | Tangut | Yi)
13403}
13404
13405fn is_grapheme_ideographic(text: &str) -> bool {
13406    text.chars().any(is_char_ideographic)
13407}
13408
13409fn is_grapheme_whitespace(text: &str) -> bool {
13410    text.chars().any(|x| x.is_whitespace())
13411}
13412
13413fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13414    text.chars().next().map_or(false, |ch| {
13415        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13416    })
13417}
13418
13419#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13420struct WordBreakToken<'a> {
13421    token: &'a str,
13422    grapheme_len: usize,
13423    is_whitespace: bool,
13424}
13425
13426impl<'a> Iterator for WordBreakingTokenizer<'a> {
13427    /// Yields a span, the count of graphemes in the token, and whether it was
13428    /// whitespace. Note that it also breaks at word boundaries.
13429    type Item = WordBreakToken<'a>;
13430
13431    fn next(&mut self) -> Option<Self::Item> {
13432        use unicode_segmentation::UnicodeSegmentation;
13433        if self.input.is_empty() {
13434            return None;
13435        }
13436
13437        let mut iter = self.input.graphemes(true).peekable();
13438        let mut offset = 0;
13439        let mut graphemes = 0;
13440        if let Some(first_grapheme) = iter.next() {
13441            let is_whitespace = is_grapheme_whitespace(first_grapheme);
13442            offset += first_grapheme.len();
13443            graphemes += 1;
13444            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13445                if let Some(grapheme) = iter.peek().copied() {
13446                    if should_stay_with_preceding_ideograph(grapheme) {
13447                        offset += grapheme.len();
13448                        graphemes += 1;
13449                    }
13450                }
13451            } else {
13452                let mut words = self.input[offset..].split_word_bound_indices().peekable();
13453                let mut next_word_bound = words.peek().copied();
13454                if next_word_bound.map_or(false, |(i, _)| i == 0) {
13455                    next_word_bound = words.next();
13456                }
13457                while let Some(grapheme) = iter.peek().copied() {
13458                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
13459                        break;
13460                    };
13461                    if is_grapheme_whitespace(grapheme) != is_whitespace {
13462                        break;
13463                    };
13464                    offset += grapheme.len();
13465                    graphemes += 1;
13466                    iter.next();
13467                }
13468            }
13469            let token = &self.input[..offset];
13470            self.input = &self.input[offset..];
13471            if is_whitespace {
13472                Some(WordBreakToken {
13473                    token: " ",
13474                    grapheme_len: 1,
13475                    is_whitespace: true,
13476                })
13477            } else {
13478                Some(WordBreakToken {
13479                    token,
13480                    grapheme_len: graphemes,
13481                    is_whitespace: false,
13482                })
13483            }
13484        } else {
13485            None
13486        }
13487    }
13488}
13489
13490#[test]
13491fn test_word_breaking_tokenizer() {
13492    let tests: &[(&str, &[(&str, usize, bool)])] = &[
13493        ("", &[]),
13494        ("  ", &[(" ", 1, true)]),
13495        ("Ʒ", &[("Ʒ", 1, false)]),
13496        ("Ǽ", &[("Ǽ", 1, false)]),
13497        ("", &[("", 1, false)]),
13498        ("⋑⋑", &[("⋑⋑", 2, false)]),
13499        (
13500            "原理,进而",
13501            &[
13502                ("", 1, false),
13503                ("理,", 2, false),
13504                ("", 1, false),
13505                ("", 1, false),
13506            ],
13507        ),
13508        (
13509            "hello world",
13510            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13511        ),
13512        (
13513            "hello, world",
13514            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13515        ),
13516        (
13517            "  hello world",
13518            &[
13519                (" ", 1, true),
13520                ("hello", 5, false),
13521                (" ", 1, true),
13522                ("world", 5, false),
13523            ],
13524        ),
13525        (
13526            "这是什么 \n 钢笔",
13527            &[
13528                ("", 1, false),
13529                ("", 1, false),
13530                ("", 1, false),
13531                ("", 1, false),
13532                (" ", 1, true),
13533                ("", 1, false),
13534                ("", 1, false),
13535            ],
13536        ),
13537        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13538    ];
13539
13540    for (input, result) in tests {
13541        assert_eq!(
13542            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13543            result
13544                .iter()
13545                .copied()
13546                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13547                    token,
13548                    grapheme_len,
13549                    is_whitespace,
13550                })
13551                .collect::<Vec<_>>()
13552        );
13553    }
13554}
13555
13556fn wrap_with_prefix(
13557    line_prefix: String,
13558    unwrapped_text: String,
13559    wrap_column: usize,
13560    tab_size: NonZeroU32,
13561) -> String {
13562    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13563    let mut wrapped_text = String::new();
13564    let mut current_line = line_prefix.clone();
13565
13566    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13567    let mut current_line_len = line_prefix_len;
13568    for WordBreakToken {
13569        token,
13570        grapheme_len,
13571        is_whitespace,
13572    } in tokenizer
13573    {
13574        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13575            wrapped_text.push_str(current_line.trim_end());
13576            wrapped_text.push('\n');
13577            current_line.truncate(line_prefix.len());
13578            current_line_len = line_prefix_len;
13579            if !is_whitespace {
13580                current_line.push_str(token);
13581                current_line_len += grapheme_len;
13582            }
13583        } else if !is_whitespace {
13584            current_line.push_str(token);
13585            current_line_len += grapheme_len;
13586        } else if current_line_len != line_prefix_len {
13587            current_line.push(' ');
13588            current_line_len += 1;
13589        }
13590    }
13591
13592    if !current_line.is_empty() {
13593        wrapped_text.push_str(&current_line);
13594    }
13595    wrapped_text
13596}
13597
13598#[test]
13599fn test_wrap_with_prefix() {
13600    assert_eq!(
13601        wrap_with_prefix(
13602            "# ".to_string(),
13603            "abcdefg".to_string(),
13604            4,
13605            NonZeroU32::new(4).unwrap()
13606        ),
13607        "# abcdefg"
13608    );
13609    assert_eq!(
13610        wrap_with_prefix(
13611            "".to_string(),
13612            "\thello world".to_string(),
13613            8,
13614            NonZeroU32::new(4).unwrap()
13615        ),
13616        "hello\nworld"
13617    );
13618    assert_eq!(
13619        wrap_with_prefix(
13620            "// ".to_string(),
13621            "xx \nyy zz aa bb cc".to_string(),
13622            12,
13623            NonZeroU32::new(4).unwrap()
13624        ),
13625        "// xx yy zz\n// aa bb cc"
13626    );
13627    assert_eq!(
13628        wrap_with_prefix(
13629            String::new(),
13630            "这是什么 \n 钢笔".to_string(),
13631            3,
13632            NonZeroU32::new(4).unwrap()
13633        ),
13634        "这是什\n么 钢\n"
13635    );
13636}
13637
13638fn hunks_for_selections(
13639    snapshot: &EditorSnapshot,
13640    selections: &[Selection<Point>],
13641) -> Vec<MultiBufferDiffHunk> {
13642    hunks_for_ranges(
13643        selections.iter().map(|selection| selection.range()),
13644        snapshot,
13645    )
13646}
13647
13648pub fn hunks_for_ranges(
13649    ranges: impl Iterator<Item = Range<Point>>,
13650    snapshot: &EditorSnapshot,
13651) -> Vec<MultiBufferDiffHunk> {
13652    let mut hunks = Vec::new();
13653    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13654        HashMap::default();
13655    for query_range in ranges {
13656        let query_rows =
13657            MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
13658        for hunk in snapshot.diff_map.diff_hunks_in_range(
13659            Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
13660            &snapshot.buffer_snapshot,
13661        ) {
13662            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13663            // when the caret is just above or just below the deleted hunk.
13664            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13665            let related_to_selection = if allow_adjacent {
13666                hunk.row_range.overlaps(&query_rows)
13667                    || hunk.row_range.start == query_rows.end
13668                    || hunk.row_range.end == query_rows.start
13669            } else {
13670                hunk.row_range.overlaps(&query_rows)
13671            };
13672            if related_to_selection {
13673                if !processed_buffer_rows
13674                    .entry(hunk.buffer_id)
13675                    .or_default()
13676                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13677                {
13678                    continue;
13679                }
13680                hunks.push(hunk);
13681            }
13682        }
13683    }
13684
13685    hunks
13686}
13687
13688pub trait CollaborationHub {
13689    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13690    fn user_participant_indices<'a>(
13691        &self,
13692        cx: &'a AppContext,
13693    ) -> &'a HashMap<u64, ParticipantIndex>;
13694    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13695}
13696
13697impl CollaborationHub for Model<Project> {
13698    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13699        self.read(cx).collaborators()
13700    }
13701
13702    fn user_participant_indices<'a>(
13703        &self,
13704        cx: &'a AppContext,
13705    ) -> &'a HashMap<u64, ParticipantIndex> {
13706        self.read(cx).user_store().read(cx).participant_indices()
13707    }
13708
13709    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13710        let this = self.read(cx);
13711        let user_ids = this.collaborators().values().map(|c| c.user_id);
13712        this.user_store().read_with(cx, |user_store, cx| {
13713            user_store.participant_names(user_ids, cx)
13714        })
13715    }
13716}
13717
13718pub trait SemanticsProvider {
13719    fn hover(
13720        &self,
13721        buffer: &Model<Buffer>,
13722        position: text::Anchor,
13723        cx: &mut AppContext,
13724    ) -> Option<Task<Vec<project::Hover>>>;
13725
13726    fn inlay_hints(
13727        &self,
13728        buffer_handle: Model<Buffer>,
13729        range: Range<text::Anchor>,
13730        cx: &mut AppContext,
13731    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13732
13733    fn resolve_inlay_hint(
13734        &self,
13735        hint: InlayHint,
13736        buffer_handle: Model<Buffer>,
13737        server_id: LanguageServerId,
13738        cx: &mut AppContext,
13739    ) -> Option<Task<anyhow::Result<InlayHint>>>;
13740
13741    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13742
13743    fn document_highlights(
13744        &self,
13745        buffer: &Model<Buffer>,
13746        position: text::Anchor,
13747        cx: &mut AppContext,
13748    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13749
13750    fn definitions(
13751        &self,
13752        buffer: &Model<Buffer>,
13753        position: text::Anchor,
13754        kind: GotoDefinitionKind,
13755        cx: &mut AppContext,
13756    ) -> Option<Task<Result<Vec<LocationLink>>>>;
13757
13758    fn range_for_rename(
13759        &self,
13760        buffer: &Model<Buffer>,
13761        position: text::Anchor,
13762        cx: &mut AppContext,
13763    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13764
13765    fn perform_rename(
13766        &self,
13767        buffer: &Model<Buffer>,
13768        position: text::Anchor,
13769        new_name: String,
13770        cx: &mut AppContext,
13771    ) -> Option<Task<Result<ProjectTransaction>>>;
13772}
13773
13774pub trait CompletionProvider {
13775    fn completions(
13776        &self,
13777        buffer: &Model<Buffer>,
13778        buffer_position: text::Anchor,
13779        trigger: CompletionContext,
13780        cx: &mut ViewContext<Editor>,
13781    ) -> Task<Result<Vec<Completion>>>;
13782
13783    fn resolve_completions(
13784        &self,
13785        buffer: Model<Buffer>,
13786        completion_indices: Vec<usize>,
13787        completions: Arc<RwLock<Box<[Completion]>>>,
13788        cx: &mut ViewContext<Editor>,
13789    ) -> Task<Result<bool>>;
13790
13791    fn apply_additional_edits_for_completion(
13792        &self,
13793        buffer: Model<Buffer>,
13794        completion: Completion,
13795        push_to_history: bool,
13796        cx: &mut ViewContext<Editor>,
13797    ) -> Task<Result<Option<language::Transaction>>>;
13798
13799    fn is_completion_trigger(
13800        &self,
13801        buffer: &Model<Buffer>,
13802        position: language::Anchor,
13803        text: &str,
13804        trigger_in_words: bool,
13805        cx: &mut ViewContext<Editor>,
13806    ) -> bool;
13807
13808    fn sort_completions(&self) -> bool {
13809        true
13810    }
13811}
13812
13813pub trait CodeActionProvider {
13814    fn code_actions(
13815        &self,
13816        buffer: &Model<Buffer>,
13817        range: Range<text::Anchor>,
13818        cx: &mut WindowContext,
13819    ) -> Task<Result<Vec<CodeAction>>>;
13820
13821    fn apply_code_action(
13822        &self,
13823        buffer_handle: Model<Buffer>,
13824        action: CodeAction,
13825        excerpt_id: ExcerptId,
13826        push_to_history: bool,
13827        cx: &mut WindowContext,
13828    ) -> Task<Result<ProjectTransaction>>;
13829}
13830
13831impl CodeActionProvider for Model<Project> {
13832    fn code_actions(
13833        &self,
13834        buffer: &Model<Buffer>,
13835        range: Range<text::Anchor>,
13836        cx: &mut WindowContext,
13837    ) -> Task<Result<Vec<CodeAction>>> {
13838        self.update(cx, |project, cx| {
13839            project.code_actions(buffer, range, None, cx)
13840        })
13841    }
13842
13843    fn apply_code_action(
13844        &self,
13845        buffer_handle: Model<Buffer>,
13846        action: CodeAction,
13847        _excerpt_id: ExcerptId,
13848        push_to_history: bool,
13849        cx: &mut WindowContext,
13850    ) -> Task<Result<ProjectTransaction>> {
13851        self.update(cx, |project, cx| {
13852            project.apply_code_action(buffer_handle, action, push_to_history, cx)
13853        })
13854    }
13855}
13856
13857fn snippet_completions(
13858    project: &Project,
13859    buffer: &Model<Buffer>,
13860    buffer_position: text::Anchor,
13861    cx: &mut AppContext,
13862) -> Task<Result<Vec<Completion>>> {
13863    let language = buffer.read(cx).language_at(buffer_position);
13864    let language_name = language.as_ref().map(|language| language.lsp_id());
13865    let snippet_store = project.snippets().read(cx);
13866    let snippets = snippet_store.snippets_for(language_name, cx);
13867
13868    if snippets.is_empty() {
13869        return Task::ready(Ok(vec![]));
13870    }
13871    let snapshot = buffer.read(cx).text_snapshot();
13872    let chars: String = snapshot
13873        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
13874        .collect();
13875
13876    let scope = language.map(|language| language.default_scope());
13877    let executor = cx.background_executor().clone();
13878
13879    cx.background_executor().spawn(async move {
13880        let classifier = CharClassifier::new(scope).for_completion(true);
13881        let mut last_word = chars
13882            .chars()
13883            .take_while(|c| classifier.is_word(*c))
13884            .collect::<String>();
13885        last_word = last_word.chars().rev().collect();
13886
13887        if last_word.is_empty() {
13888            return Ok(vec![]);
13889        }
13890
13891        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13892        let to_lsp = |point: &text::Anchor| {
13893            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13894            point_to_lsp(end)
13895        };
13896        let lsp_end = to_lsp(&buffer_position);
13897
13898        let candidates = snippets
13899            .iter()
13900            .enumerate()
13901            .flat_map(|(ix, snippet)| {
13902                snippet
13903                    .prefix
13904                    .iter()
13905                    .map(move |prefix| StringMatchCandidate::new(ix, prefix.clone()))
13906            })
13907            .collect::<Vec<StringMatchCandidate>>();
13908
13909        let mut matches = fuzzy::match_strings(
13910            &candidates,
13911            &last_word,
13912            last_word.chars().any(|c| c.is_uppercase()),
13913            100,
13914            &Default::default(),
13915            executor,
13916        )
13917        .await;
13918
13919        // Remove all candidates where the query's start does not match the start of any word in the candidate
13920        if let Some(query_start) = last_word.chars().next() {
13921            matches.retain(|string_match| {
13922                split_words(&string_match.string).any(|word| {
13923                    // Check that the first codepoint of the word as lowercase matches the first
13924                    // codepoint of the query as lowercase
13925                    word.chars()
13926                        .flat_map(|codepoint| codepoint.to_lowercase())
13927                        .zip(query_start.to_lowercase())
13928                        .all(|(word_cp, query_cp)| word_cp == query_cp)
13929                })
13930            });
13931        }
13932
13933        let matched_strings = matches
13934            .into_iter()
13935            .map(|m| m.string)
13936            .collect::<HashSet<_>>();
13937
13938        let result: Vec<Completion> = snippets
13939            .into_iter()
13940            .filter_map(|snippet| {
13941                let matching_prefix = snippet
13942                    .prefix
13943                    .iter()
13944                    .find(|prefix| matched_strings.contains(*prefix))?;
13945                let start = as_offset - last_word.len();
13946                let start = snapshot.anchor_before(start);
13947                let range = start..buffer_position;
13948                let lsp_start = to_lsp(&start);
13949                let lsp_range = lsp::Range {
13950                    start: lsp_start,
13951                    end: lsp_end,
13952                };
13953                Some(Completion {
13954                    old_range: range,
13955                    new_text: snippet.body.clone(),
13956                    label: CodeLabel {
13957                        text: matching_prefix.clone(),
13958                        runs: vec![],
13959                        filter_range: 0..matching_prefix.len(),
13960                    },
13961                    server_id: LanguageServerId(usize::MAX),
13962                    documentation: snippet.description.clone().map(Documentation::SingleLine),
13963                    lsp_completion: lsp::CompletionItem {
13964                        label: snippet.prefix.first().unwrap().clone(),
13965                        kind: Some(CompletionItemKind::SNIPPET),
13966                        label_details: snippet.description.as_ref().map(|description| {
13967                            lsp::CompletionItemLabelDetails {
13968                                detail: Some(description.clone()),
13969                                description: None,
13970                            }
13971                        }),
13972                        insert_text_format: Some(InsertTextFormat::SNIPPET),
13973                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13974                            lsp::InsertReplaceEdit {
13975                                new_text: snippet.body.clone(),
13976                                insert: lsp_range,
13977                                replace: lsp_range,
13978                            },
13979                        )),
13980                        filter_text: Some(snippet.body.clone()),
13981                        sort_text: Some(char::MAX.to_string()),
13982                        ..Default::default()
13983                    },
13984                    confirm: None,
13985                })
13986            })
13987            .collect();
13988
13989        Ok(result)
13990    })
13991}
13992
13993impl CompletionProvider for Model<Project> {
13994    fn completions(
13995        &self,
13996        buffer: &Model<Buffer>,
13997        buffer_position: text::Anchor,
13998        options: CompletionContext,
13999        cx: &mut ViewContext<Editor>,
14000    ) -> Task<Result<Vec<Completion>>> {
14001        self.update(cx, |project, cx| {
14002            let snippets = snippet_completions(project, buffer, buffer_position, cx);
14003            let project_completions = project.completions(buffer, buffer_position, options, cx);
14004            cx.background_executor().spawn(async move {
14005                let mut completions = project_completions.await?;
14006                let snippets_completions = snippets.await?;
14007                completions.extend(snippets_completions);
14008                Ok(completions)
14009            })
14010        })
14011    }
14012
14013    fn resolve_completions(
14014        &self,
14015        buffer: Model<Buffer>,
14016        completion_indices: Vec<usize>,
14017        completions: Arc<RwLock<Box<[Completion]>>>,
14018        cx: &mut ViewContext<Editor>,
14019    ) -> Task<Result<bool>> {
14020        self.update(cx, |project, cx| {
14021            project.resolve_completions(buffer, completion_indices, completions, cx)
14022        })
14023    }
14024
14025    fn apply_additional_edits_for_completion(
14026        &self,
14027        buffer: Model<Buffer>,
14028        completion: Completion,
14029        push_to_history: bool,
14030        cx: &mut ViewContext<Editor>,
14031    ) -> Task<Result<Option<language::Transaction>>> {
14032        self.update(cx, |project, cx| {
14033            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
14034        })
14035    }
14036
14037    fn is_completion_trigger(
14038        &self,
14039        buffer: &Model<Buffer>,
14040        position: language::Anchor,
14041        text: &str,
14042        trigger_in_words: bool,
14043        cx: &mut ViewContext<Editor>,
14044    ) -> bool {
14045        if !EditorSettings::get_global(cx).show_completions_on_input {
14046            return false;
14047        }
14048
14049        let mut chars = text.chars();
14050        let char = if let Some(char) = chars.next() {
14051            char
14052        } else {
14053            return false;
14054        };
14055        if chars.next().is_some() {
14056            return false;
14057        }
14058
14059        let buffer = buffer.read(cx);
14060        let classifier = buffer
14061            .snapshot()
14062            .char_classifier_at(position)
14063            .for_completion(true);
14064        if trigger_in_words && classifier.is_word(char) {
14065            return true;
14066        }
14067
14068        buffer.completion_triggers().contains(text)
14069    }
14070}
14071
14072impl SemanticsProvider for Model<Project> {
14073    fn hover(
14074        &self,
14075        buffer: &Model<Buffer>,
14076        position: text::Anchor,
14077        cx: &mut AppContext,
14078    ) -> Option<Task<Vec<project::Hover>>> {
14079        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
14080    }
14081
14082    fn document_highlights(
14083        &self,
14084        buffer: &Model<Buffer>,
14085        position: text::Anchor,
14086        cx: &mut AppContext,
14087    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
14088        Some(self.update(cx, |project, cx| {
14089            project.document_highlights(buffer, position, cx)
14090        }))
14091    }
14092
14093    fn definitions(
14094        &self,
14095        buffer: &Model<Buffer>,
14096        position: text::Anchor,
14097        kind: GotoDefinitionKind,
14098        cx: &mut AppContext,
14099    ) -> Option<Task<Result<Vec<LocationLink>>>> {
14100        Some(self.update(cx, |project, cx| match kind {
14101            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
14102            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
14103            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
14104            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
14105        }))
14106    }
14107
14108    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
14109        // TODO: make this work for remote projects
14110        self.read(cx)
14111            .language_servers_for_buffer(buffer.read(cx), cx)
14112            .any(
14113                |(_, server)| match server.capabilities().inlay_hint_provider {
14114                    Some(lsp::OneOf::Left(enabled)) => enabled,
14115                    Some(lsp::OneOf::Right(_)) => true,
14116                    None => false,
14117                },
14118            )
14119    }
14120
14121    fn inlay_hints(
14122        &self,
14123        buffer_handle: Model<Buffer>,
14124        range: Range<text::Anchor>,
14125        cx: &mut AppContext,
14126    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
14127        Some(self.update(cx, |project, cx| {
14128            project.inlay_hints(buffer_handle, range, cx)
14129        }))
14130    }
14131
14132    fn resolve_inlay_hint(
14133        &self,
14134        hint: InlayHint,
14135        buffer_handle: Model<Buffer>,
14136        server_id: LanguageServerId,
14137        cx: &mut AppContext,
14138    ) -> Option<Task<anyhow::Result<InlayHint>>> {
14139        Some(self.update(cx, |project, cx| {
14140            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
14141        }))
14142    }
14143
14144    fn range_for_rename(
14145        &self,
14146        buffer: &Model<Buffer>,
14147        position: text::Anchor,
14148        cx: &mut AppContext,
14149    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
14150        Some(self.update(cx, |project, cx| {
14151            project.prepare_rename(buffer.clone(), position, cx)
14152        }))
14153    }
14154
14155    fn perform_rename(
14156        &self,
14157        buffer: &Model<Buffer>,
14158        position: text::Anchor,
14159        new_name: String,
14160        cx: &mut AppContext,
14161    ) -> Option<Task<Result<ProjectTransaction>>> {
14162        Some(self.update(cx, |project, cx| {
14163            project.perform_rename(buffer.clone(), position, new_name, cx)
14164        }))
14165    }
14166}
14167
14168fn inlay_hint_settings(
14169    location: Anchor,
14170    snapshot: &MultiBufferSnapshot,
14171    cx: &mut ViewContext<'_, Editor>,
14172) -> InlayHintSettings {
14173    let file = snapshot.file_at(location);
14174    let language = snapshot.language_at(location).map(|l| l.name());
14175    language_settings(language, file, cx).inlay_hints
14176}
14177
14178fn consume_contiguous_rows(
14179    contiguous_row_selections: &mut Vec<Selection<Point>>,
14180    selection: &Selection<Point>,
14181    display_map: &DisplaySnapshot,
14182    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
14183) -> (MultiBufferRow, MultiBufferRow) {
14184    contiguous_row_selections.push(selection.clone());
14185    let start_row = MultiBufferRow(selection.start.row);
14186    let mut end_row = ending_row(selection, display_map);
14187
14188    while let Some(next_selection) = selections.peek() {
14189        if next_selection.start.row <= end_row.0 {
14190            end_row = ending_row(next_selection, display_map);
14191            contiguous_row_selections.push(selections.next().unwrap().clone());
14192        } else {
14193            break;
14194        }
14195    }
14196    (start_row, end_row)
14197}
14198
14199fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
14200    if next_selection.end.column > 0 || next_selection.is_empty() {
14201        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
14202    } else {
14203        MultiBufferRow(next_selection.end.row)
14204    }
14205}
14206
14207impl EditorSnapshot {
14208    pub fn remote_selections_in_range<'a>(
14209        &'a self,
14210        range: &'a Range<Anchor>,
14211        collaboration_hub: &dyn CollaborationHub,
14212        cx: &'a AppContext,
14213    ) -> impl 'a + Iterator<Item = RemoteSelection> {
14214        let participant_names = collaboration_hub.user_names(cx);
14215        let participant_indices = collaboration_hub.user_participant_indices(cx);
14216        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
14217        let collaborators_by_replica_id = collaborators_by_peer_id
14218            .iter()
14219            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
14220            .collect::<HashMap<_, _>>();
14221        self.buffer_snapshot
14222            .selections_in_range(range, false)
14223            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
14224                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
14225                let participant_index = participant_indices.get(&collaborator.user_id).copied();
14226                let user_name = participant_names.get(&collaborator.user_id).cloned();
14227                Some(RemoteSelection {
14228                    replica_id,
14229                    selection,
14230                    cursor_shape,
14231                    line_mode,
14232                    participant_index,
14233                    peer_id: collaborator.peer_id,
14234                    user_name,
14235                })
14236            })
14237    }
14238
14239    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
14240        self.display_snapshot.buffer_snapshot.language_at(position)
14241    }
14242
14243    pub fn is_focused(&self) -> bool {
14244        self.is_focused
14245    }
14246
14247    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
14248        self.placeholder_text.as_ref()
14249    }
14250
14251    pub fn scroll_position(&self) -> gpui::Point<f32> {
14252        self.scroll_anchor.scroll_position(&self.display_snapshot)
14253    }
14254
14255    fn gutter_dimensions(
14256        &self,
14257        font_id: FontId,
14258        font_size: Pixels,
14259        em_width: Pixels,
14260        em_advance: Pixels,
14261        max_line_number_width: Pixels,
14262        cx: &AppContext,
14263    ) -> GutterDimensions {
14264        if !self.show_gutter {
14265            return GutterDimensions::default();
14266        }
14267        let descent = cx.text_system().descent(font_id, font_size);
14268
14269        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
14270            matches!(
14271                ProjectSettings::get_global(cx).git.git_gutter,
14272                Some(GitGutterSetting::TrackedFiles)
14273            )
14274        });
14275        let gutter_settings = EditorSettings::get_global(cx).gutter;
14276        let show_line_numbers = self
14277            .show_line_numbers
14278            .unwrap_or(gutter_settings.line_numbers);
14279        let line_gutter_width = if show_line_numbers {
14280            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
14281            let min_width_for_number_on_gutter = em_advance * 4.0;
14282            max_line_number_width.max(min_width_for_number_on_gutter)
14283        } else {
14284            0.0.into()
14285        };
14286
14287        let show_code_actions = self
14288            .show_code_actions
14289            .unwrap_or(gutter_settings.code_actions);
14290
14291        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
14292
14293        let git_blame_entries_width =
14294            self.git_blame_gutter_max_author_length
14295                .map(|max_author_length| {
14296                    // Length of the author name, but also space for the commit hash,
14297                    // the spacing and the timestamp.
14298                    let max_char_count = max_author_length
14299                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
14300                        + 7 // length of commit sha
14301                        + 14 // length of max relative timestamp ("60 minutes ago")
14302                        + 4; // gaps and margins
14303
14304                    em_advance * max_char_count
14305                });
14306
14307        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
14308        left_padding += if show_code_actions || show_runnables {
14309            em_width * 3.0
14310        } else if show_git_gutter && show_line_numbers {
14311            em_width * 2.0
14312        } else if show_git_gutter || show_line_numbers {
14313            em_width
14314        } else {
14315            px(0.)
14316        };
14317
14318        let right_padding = if gutter_settings.folds && show_line_numbers {
14319            em_width * 4.0
14320        } else if gutter_settings.folds {
14321            em_width * 3.0
14322        } else if show_line_numbers {
14323            em_width
14324        } else {
14325            px(0.)
14326        };
14327
14328        GutterDimensions {
14329            left_padding,
14330            right_padding,
14331            width: line_gutter_width + left_padding + right_padding,
14332            margin: -descent,
14333            git_blame_entries_width,
14334        }
14335    }
14336
14337    pub fn render_crease_toggle(
14338        &self,
14339        buffer_row: MultiBufferRow,
14340        row_contains_cursor: bool,
14341        editor: View<Editor>,
14342        cx: &mut WindowContext,
14343    ) -> Option<AnyElement> {
14344        let folded = self.is_line_folded(buffer_row);
14345        let mut is_foldable = false;
14346
14347        if let Some(crease) = self
14348            .crease_snapshot
14349            .query_row(buffer_row, &self.buffer_snapshot)
14350        {
14351            is_foldable = true;
14352            match crease {
14353                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
14354                    if let Some(render_toggle) = render_toggle {
14355                        let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14356                            if folded {
14357                                editor.update(cx, |editor, cx| {
14358                                    editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14359                                });
14360                            } else {
14361                                editor.update(cx, |editor, cx| {
14362                                    editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14363                                });
14364                            }
14365                        });
14366                        return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
14367                    }
14368                }
14369            }
14370        }
14371
14372        is_foldable |= self.starts_indent(buffer_row);
14373
14374        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
14375            Some(
14376                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
14377                    .selected(folded)
14378                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14379                        if folded {
14380                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
14381                        } else {
14382                            this.fold_at(&FoldAt { buffer_row }, cx);
14383                        }
14384                    }))
14385                    .into_any_element(),
14386            )
14387        } else {
14388            None
14389        }
14390    }
14391
14392    pub fn render_crease_trailer(
14393        &self,
14394        buffer_row: MultiBufferRow,
14395        cx: &mut WindowContext,
14396    ) -> Option<AnyElement> {
14397        let folded = self.is_line_folded(buffer_row);
14398        if let Crease::Inline { render_trailer, .. } = self
14399            .crease_snapshot
14400            .query_row(buffer_row, &self.buffer_snapshot)?
14401        {
14402            let render_trailer = render_trailer.as_ref()?;
14403            Some(render_trailer(buffer_row, folded, cx))
14404        } else {
14405            None
14406        }
14407    }
14408}
14409
14410impl Deref for EditorSnapshot {
14411    type Target = DisplaySnapshot;
14412
14413    fn deref(&self) -> &Self::Target {
14414        &self.display_snapshot
14415    }
14416}
14417
14418#[derive(Clone, Debug, PartialEq, Eq)]
14419pub enum EditorEvent {
14420    InputIgnored {
14421        text: Arc<str>,
14422    },
14423    InputHandled {
14424        utf16_range_to_replace: Option<Range<isize>>,
14425        text: Arc<str>,
14426    },
14427    ExcerptsAdded {
14428        buffer: Model<Buffer>,
14429        predecessor: ExcerptId,
14430        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14431    },
14432    ExcerptsRemoved {
14433        ids: Vec<ExcerptId>,
14434    },
14435    ExcerptsEdited {
14436        ids: Vec<ExcerptId>,
14437    },
14438    ExcerptsExpanded {
14439        ids: Vec<ExcerptId>,
14440    },
14441    BufferEdited,
14442    Edited {
14443        transaction_id: clock::Lamport,
14444    },
14445    Reparsed(BufferId),
14446    Focused,
14447    FocusedIn,
14448    Blurred,
14449    DirtyChanged,
14450    Saved,
14451    TitleChanged,
14452    DiffBaseChanged,
14453    SelectionsChanged {
14454        local: bool,
14455    },
14456    ScrollPositionChanged {
14457        local: bool,
14458        autoscroll: bool,
14459    },
14460    Closed,
14461    TransactionUndone {
14462        transaction_id: clock::Lamport,
14463    },
14464    TransactionBegun {
14465        transaction_id: clock::Lamport,
14466    },
14467    Reloaded,
14468    CursorShapeChanged,
14469}
14470
14471impl EventEmitter<EditorEvent> for Editor {}
14472
14473impl FocusableView for Editor {
14474    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14475        self.focus_handle.clone()
14476    }
14477}
14478
14479impl Render for Editor {
14480    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14481        let settings = ThemeSettings::get_global(cx);
14482
14483        let mut text_style = match self.mode {
14484            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14485                color: cx.theme().colors().editor_foreground,
14486                font_family: settings.ui_font.family.clone(),
14487                font_features: settings.ui_font.features.clone(),
14488                font_fallbacks: settings.ui_font.fallbacks.clone(),
14489                font_size: rems(0.875).into(),
14490                font_weight: settings.ui_font.weight,
14491                line_height: relative(settings.buffer_line_height.value()),
14492                ..Default::default()
14493            },
14494            EditorMode::Full => TextStyle {
14495                color: cx.theme().colors().editor_foreground,
14496                font_family: settings.buffer_font.family.clone(),
14497                font_features: settings.buffer_font.features.clone(),
14498                font_fallbacks: settings.buffer_font.fallbacks.clone(),
14499                font_size: settings.buffer_font_size(cx).into(),
14500                font_weight: settings.buffer_font.weight,
14501                line_height: relative(settings.buffer_line_height.value()),
14502                ..Default::default()
14503            },
14504        };
14505        if let Some(text_style_refinement) = &self.text_style_refinement {
14506            text_style.refine(text_style_refinement)
14507        }
14508
14509        let background = match self.mode {
14510            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14511            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14512            EditorMode::Full => cx.theme().colors().editor_background,
14513        };
14514
14515        EditorElement::new(
14516            cx.view(),
14517            EditorStyle {
14518                background,
14519                local_player: cx.theme().players().local(),
14520                text: text_style,
14521                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14522                syntax: cx.theme().syntax().clone(),
14523                status: cx.theme().status().clone(),
14524                inlay_hints_style: make_inlay_hints_style(cx),
14525                suggestions_style: HighlightStyle {
14526                    color: Some(cx.theme().status().predictive),
14527                    ..HighlightStyle::default()
14528                },
14529                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14530            },
14531        )
14532    }
14533}
14534
14535impl ViewInputHandler for Editor {
14536    fn text_for_range(
14537        &mut self,
14538        range_utf16: Range<usize>,
14539        adjusted_range: &mut Option<Range<usize>>,
14540        cx: &mut ViewContext<Self>,
14541    ) -> Option<String> {
14542        let snapshot = self.buffer.read(cx).read(cx);
14543        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
14544        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
14545        if (start.0..end.0) != range_utf16 {
14546            adjusted_range.replace(start.0..end.0);
14547        }
14548        Some(snapshot.text_for_range(start..end).collect())
14549    }
14550
14551    fn selected_text_range(
14552        &mut self,
14553        ignore_disabled_input: bool,
14554        cx: &mut ViewContext<Self>,
14555    ) -> Option<UTF16Selection> {
14556        // Prevent the IME menu from appearing when holding down an alphabetic key
14557        // while input is disabled.
14558        if !ignore_disabled_input && !self.input_enabled {
14559            return None;
14560        }
14561
14562        let selection = self.selections.newest::<OffsetUtf16>(cx);
14563        let range = selection.range();
14564
14565        Some(UTF16Selection {
14566            range: range.start.0..range.end.0,
14567            reversed: selection.reversed,
14568        })
14569    }
14570
14571    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14572        let snapshot = self.buffer.read(cx).read(cx);
14573        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14574        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14575    }
14576
14577    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14578        self.clear_highlights::<InputComposition>(cx);
14579        self.ime_transaction.take();
14580    }
14581
14582    fn replace_text_in_range(
14583        &mut self,
14584        range_utf16: Option<Range<usize>>,
14585        text: &str,
14586        cx: &mut ViewContext<Self>,
14587    ) {
14588        if !self.input_enabled {
14589            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14590            return;
14591        }
14592
14593        self.transact(cx, |this, cx| {
14594            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14595                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14596                Some(this.selection_replacement_ranges(range_utf16, cx))
14597            } else {
14598                this.marked_text_ranges(cx)
14599            };
14600
14601            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14602                let newest_selection_id = this.selections.newest_anchor().id;
14603                this.selections
14604                    .all::<OffsetUtf16>(cx)
14605                    .iter()
14606                    .zip(ranges_to_replace.iter())
14607                    .find_map(|(selection, range)| {
14608                        if selection.id == newest_selection_id {
14609                            Some(
14610                                (range.start.0 as isize - selection.head().0 as isize)
14611                                    ..(range.end.0 as isize - selection.head().0 as isize),
14612                            )
14613                        } else {
14614                            None
14615                        }
14616                    })
14617            });
14618
14619            cx.emit(EditorEvent::InputHandled {
14620                utf16_range_to_replace: range_to_replace,
14621                text: text.into(),
14622            });
14623
14624            if let Some(new_selected_ranges) = new_selected_ranges {
14625                this.change_selections(None, cx, |selections| {
14626                    selections.select_ranges(new_selected_ranges)
14627                });
14628                this.backspace(&Default::default(), cx);
14629            }
14630
14631            this.handle_input(text, cx);
14632        });
14633
14634        if let Some(transaction) = self.ime_transaction {
14635            self.buffer.update(cx, |buffer, cx| {
14636                buffer.group_until_transaction(transaction, cx);
14637            });
14638        }
14639
14640        self.unmark_text(cx);
14641    }
14642
14643    fn replace_and_mark_text_in_range(
14644        &mut self,
14645        range_utf16: Option<Range<usize>>,
14646        text: &str,
14647        new_selected_range_utf16: Option<Range<usize>>,
14648        cx: &mut ViewContext<Self>,
14649    ) {
14650        if !self.input_enabled {
14651            return;
14652        }
14653
14654        let transaction = self.transact(cx, |this, cx| {
14655            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14656                let snapshot = this.buffer.read(cx).read(cx);
14657                if let Some(relative_range_utf16) = range_utf16.as_ref() {
14658                    for marked_range in &mut marked_ranges {
14659                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14660                        marked_range.start.0 += relative_range_utf16.start;
14661                        marked_range.start =
14662                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14663                        marked_range.end =
14664                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14665                    }
14666                }
14667                Some(marked_ranges)
14668            } else if let Some(range_utf16) = range_utf16 {
14669                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14670                Some(this.selection_replacement_ranges(range_utf16, cx))
14671            } else {
14672                None
14673            };
14674
14675            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14676                let newest_selection_id = this.selections.newest_anchor().id;
14677                this.selections
14678                    .all::<OffsetUtf16>(cx)
14679                    .iter()
14680                    .zip(ranges_to_replace.iter())
14681                    .find_map(|(selection, range)| {
14682                        if selection.id == newest_selection_id {
14683                            Some(
14684                                (range.start.0 as isize - selection.head().0 as isize)
14685                                    ..(range.end.0 as isize - selection.head().0 as isize),
14686                            )
14687                        } else {
14688                            None
14689                        }
14690                    })
14691            });
14692
14693            cx.emit(EditorEvent::InputHandled {
14694                utf16_range_to_replace: range_to_replace,
14695                text: text.into(),
14696            });
14697
14698            if let Some(ranges) = ranges_to_replace {
14699                this.change_selections(None, cx, |s| s.select_ranges(ranges));
14700            }
14701
14702            let marked_ranges = {
14703                let snapshot = this.buffer.read(cx).read(cx);
14704                this.selections
14705                    .disjoint_anchors()
14706                    .iter()
14707                    .map(|selection| {
14708                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14709                    })
14710                    .collect::<Vec<_>>()
14711            };
14712
14713            if text.is_empty() {
14714                this.unmark_text(cx);
14715            } else {
14716                this.highlight_text::<InputComposition>(
14717                    marked_ranges.clone(),
14718                    HighlightStyle {
14719                        underline: Some(UnderlineStyle {
14720                            thickness: px(1.),
14721                            color: None,
14722                            wavy: false,
14723                        }),
14724                        ..Default::default()
14725                    },
14726                    cx,
14727                );
14728            }
14729
14730            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14731            let use_autoclose = this.use_autoclose;
14732            let use_auto_surround = this.use_auto_surround;
14733            this.set_use_autoclose(false);
14734            this.set_use_auto_surround(false);
14735            this.handle_input(text, cx);
14736            this.set_use_autoclose(use_autoclose);
14737            this.set_use_auto_surround(use_auto_surround);
14738
14739            if let Some(new_selected_range) = new_selected_range_utf16 {
14740                let snapshot = this.buffer.read(cx).read(cx);
14741                let new_selected_ranges = marked_ranges
14742                    .into_iter()
14743                    .map(|marked_range| {
14744                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14745                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14746                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14747                        snapshot.clip_offset_utf16(new_start, Bias::Left)
14748                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14749                    })
14750                    .collect::<Vec<_>>();
14751
14752                drop(snapshot);
14753                this.change_selections(None, cx, |selections| {
14754                    selections.select_ranges(new_selected_ranges)
14755                });
14756            }
14757        });
14758
14759        self.ime_transaction = self.ime_transaction.or(transaction);
14760        if let Some(transaction) = self.ime_transaction {
14761            self.buffer.update(cx, |buffer, cx| {
14762                buffer.group_until_transaction(transaction, cx);
14763            });
14764        }
14765
14766        if self.text_highlights::<InputComposition>(cx).is_none() {
14767            self.ime_transaction.take();
14768        }
14769    }
14770
14771    fn bounds_for_range(
14772        &mut self,
14773        range_utf16: Range<usize>,
14774        element_bounds: gpui::Bounds<Pixels>,
14775        cx: &mut ViewContext<Self>,
14776    ) -> Option<gpui::Bounds<Pixels>> {
14777        let text_layout_details = self.text_layout_details(cx);
14778        let gpui::Point {
14779            x: em_width,
14780            y: line_height,
14781        } = self.character_size(cx);
14782
14783        let snapshot = self.snapshot(cx);
14784        let scroll_position = snapshot.scroll_position();
14785        let scroll_left = scroll_position.x * em_width;
14786
14787        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14788        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14789            + self.gutter_dimensions.width
14790            + self.gutter_dimensions.margin;
14791        let y = line_height * (start.row().as_f32() - scroll_position.y);
14792
14793        Some(Bounds {
14794            origin: element_bounds.origin + point(x, y),
14795            size: size(em_width, line_height),
14796        })
14797    }
14798}
14799
14800trait SelectionExt {
14801    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14802    fn spanned_rows(
14803        &self,
14804        include_end_if_at_line_start: bool,
14805        map: &DisplaySnapshot,
14806    ) -> Range<MultiBufferRow>;
14807}
14808
14809impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14810    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14811        let start = self
14812            .start
14813            .to_point(&map.buffer_snapshot)
14814            .to_display_point(map);
14815        let end = self
14816            .end
14817            .to_point(&map.buffer_snapshot)
14818            .to_display_point(map);
14819        if self.reversed {
14820            end..start
14821        } else {
14822            start..end
14823        }
14824    }
14825
14826    fn spanned_rows(
14827        &self,
14828        include_end_if_at_line_start: bool,
14829        map: &DisplaySnapshot,
14830    ) -> Range<MultiBufferRow> {
14831        let start = self.start.to_point(&map.buffer_snapshot);
14832        let mut end = self.end.to_point(&map.buffer_snapshot);
14833        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14834            end.row -= 1;
14835        }
14836
14837        let buffer_start = map.prev_line_boundary(start).0;
14838        let buffer_end = map.next_line_boundary(end).0;
14839        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14840    }
14841}
14842
14843impl<T: InvalidationRegion> InvalidationStack<T> {
14844    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14845    where
14846        S: Clone + ToOffset,
14847    {
14848        while let Some(region) = self.last() {
14849            let all_selections_inside_invalidation_ranges =
14850                if selections.len() == region.ranges().len() {
14851                    selections
14852                        .iter()
14853                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14854                        .all(|(selection, invalidation_range)| {
14855                            let head = selection.head().to_offset(buffer);
14856                            invalidation_range.start <= head && invalidation_range.end >= head
14857                        })
14858                } else {
14859                    false
14860                };
14861
14862            if all_selections_inside_invalidation_ranges {
14863                break;
14864            } else {
14865                self.pop();
14866            }
14867        }
14868    }
14869}
14870
14871impl<T> Default for InvalidationStack<T> {
14872    fn default() -> Self {
14873        Self(Default::default())
14874    }
14875}
14876
14877impl<T> Deref for InvalidationStack<T> {
14878    type Target = Vec<T>;
14879
14880    fn deref(&self) -> &Self::Target {
14881        &self.0
14882    }
14883}
14884
14885impl<T> DerefMut for InvalidationStack<T> {
14886    fn deref_mut(&mut self) -> &mut Self::Target {
14887        &mut self.0
14888    }
14889}
14890
14891impl InvalidationRegion for SnippetState {
14892    fn ranges(&self) -> &[Range<Anchor>] {
14893        &self.ranges[self.active_index]
14894    }
14895}
14896
14897pub fn diagnostic_block_renderer(
14898    diagnostic: Diagnostic,
14899    max_message_rows: Option<u8>,
14900    allow_closing: bool,
14901    _is_valid: bool,
14902) -> RenderBlock {
14903    let (text_without_backticks, code_ranges) =
14904        highlight_diagnostic_message(&diagnostic, max_message_rows);
14905
14906    Arc::new(move |cx: &mut BlockContext| {
14907        let group_id: SharedString = cx.block_id.to_string().into();
14908
14909        let mut text_style = cx.text_style().clone();
14910        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14911        let theme_settings = ThemeSettings::get_global(cx);
14912        text_style.font_family = theme_settings.buffer_font.family.clone();
14913        text_style.font_style = theme_settings.buffer_font.style;
14914        text_style.font_features = theme_settings.buffer_font.features.clone();
14915        text_style.font_weight = theme_settings.buffer_font.weight;
14916
14917        let multi_line_diagnostic = diagnostic.message.contains('\n');
14918
14919        let buttons = |diagnostic: &Diagnostic| {
14920            if multi_line_diagnostic {
14921                v_flex()
14922            } else {
14923                h_flex()
14924            }
14925            .when(allow_closing, |div| {
14926                div.children(diagnostic.is_primary.then(|| {
14927                    IconButton::new("close-block", IconName::XCircle)
14928                        .icon_color(Color::Muted)
14929                        .size(ButtonSize::Compact)
14930                        .style(ButtonStyle::Transparent)
14931                        .visible_on_hover(group_id.clone())
14932                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14933                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14934                }))
14935            })
14936            .child(
14937                IconButton::new("copy-block", IconName::Copy)
14938                    .icon_color(Color::Muted)
14939                    .size(ButtonSize::Compact)
14940                    .style(ButtonStyle::Transparent)
14941                    .visible_on_hover(group_id.clone())
14942                    .on_click({
14943                        let message = diagnostic.message.clone();
14944                        move |_click, cx| {
14945                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14946                        }
14947                    })
14948                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14949            )
14950        };
14951
14952        let icon_size = buttons(&diagnostic)
14953            .into_any_element()
14954            .layout_as_root(AvailableSpace::min_size(), cx);
14955
14956        h_flex()
14957            .id(cx.block_id)
14958            .group(group_id.clone())
14959            .relative()
14960            .size_full()
14961            .block_mouse_down()
14962            .pl(cx.gutter_dimensions.width)
14963            .w(cx.max_width - cx.gutter_dimensions.full_width())
14964            .child(
14965                div()
14966                    .flex()
14967                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14968                    .flex_shrink(),
14969            )
14970            .child(buttons(&diagnostic))
14971            .child(div().flex().flex_shrink_0().child(
14972                StyledText::new(text_without_backticks.clone()).with_highlights(
14973                    &text_style,
14974                    code_ranges.iter().map(|range| {
14975                        (
14976                            range.clone(),
14977                            HighlightStyle {
14978                                font_weight: Some(FontWeight::BOLD),
14979                                ..Default::default()
14980                            },
14981                        )
14982                    }),
14983                ),
14984            ))
14985            .into_any_element()
14986    })
14987}
14988
14989pub fn highlight_diagnostic_message(
14990    diagnostic: &Diagnostic,
14991    mut max_message_rows: Option<u8>,
14992) -> (SharedString, Vec<Range<usize>>) {
14993    let mut text_without_backticks = String::new();
14994    let mut code_ranges = Vec::new();
14995
14996    if let Some(source) = &diagnostic.source {
14997        text_without_backticks.push_str(source);
14998        code_ranges.push(0..source.len());
14999        text_without_backticks.push_str(": ");
15000    }
15001
15002    let mut prev_offset = 0;
15003    let mut in_code_block = false;
15004    let has_row_limit = max_message_rows.is_some();
15005    let mut newline_indices = diagnostic
15006        .message
15007        .match_indices('\n')
15008        .filter(|_| has_row_limit)
15009        .map(|(ix, _)| ix)
15010        .fuse()
15011        .peekable();
15012
15013    for (quote_ix, _) in diagnostic
15014        .message
15015        .match_indices('`')
15016        .chain([(diagnostic.message.len(), "")])
15017    {
15018        let mut first_newline_ix = None;
15019        let mut last_newline_ix = None;
15020        while let Some(newline_ix) = newline_indices.peek() {
15021            if *newline_ix < quote_ix {
15022                if first_newline_ix.is_none() {
15023                    first_newline_ix = Some(*newline_ix);
15024                }
15025                last_newline_ix = Some(*newline_ix);
15026
15027                if let Some(rows_left) = &mut max_message_rows {
15028                    if *rows_left == 0 {
15029                        break;
15030                    } else {
15031                        *rows_left -= 1;
15032                    }
15033                }
15034                let _ = newline_indices.next();
15035            } else {
15036                break;
15037            }
15038        }
15039        let prev_len = text_without_backticks.len();
15040        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
15041        text_without_backticks.push_str(new_text);
15042        if in_code_block {
15043            code_ranges.push(prev_len..text_without_backticks.len());
15044        }
15045        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
15046        in_code_block = !in_code_block;
15047        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
15048            text_without_backticks.push_str("...");
15049            break;
15050        }
15051    }
15052
15053    (text_without_backticks.into(), code_ranges)
15054}
15055
15056fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
15057    match severity {
15058        DiagnosticSeverity::ERROR => colors.error,
15059        DiagnosticSeverity::WARNING => colors.warning,
15060        DiagnosticSeverity::INFORMATION => colors.info,
15061        DiagnosticSeverity::HINT => colors.info,
15062        _ => colors.ignored,
15063    }
15064}
15065
15066pub fn styled_runs_for_code_label<'a>(
15067    label: &'a CodeLabel,
15068    syntax_theme: &'a theme::SyntaxTheme,
15069) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
15070    let fade_out = HighlightStyle {
15071        fade_out: Some(0.35),
15072        ..Default::default()
15073    };
15074
15075    let mut prev_end = label.filter_range.end;
15076    label
15077        .runs
15078        .iter()
15079        .enumerate()
15080        .flat_map(move |(ix, (range, highlight_id))| {
15081            let style = if let Some(style) = highlight_id.style(syntax_theme) {
15082                style
15083            } else {
15084                return Default::default();
15085            };
15086            let mut muted_style = style;
15087            muted_style.highlight(fade_out);
15088
15089            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
15090            if range.start >= label.filter_range.end {
15091                if range.start > prev_end {
15092                    runs.push((prev_end..range.start, fade_out));
15093                }
15094                runs.push((range.clone(), muted_style));
15095            } else if range.end <= label.filter_range.end {
15096                runs.push((range.clone(), style));
15097            } else {
15098                runs.push((range.start..label.filter_range.end, style));
15099                runs.push((label.filter_range.end..range.end, muted_style));
15100            }
15101            prev_end = cmp::max(prev_end, range.end);
15102
15103            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
15104                runs.push((prev_end..label.text.len(), fade_out));
15105            }
15106
15107            runs
15108        })
15109}
15110
15111pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
15112    let mut prev_index = 0;
15113    let mut prev_codepoint: Option<char> = None;
15114    text.char_indices()
15115        .chain([(text.len(), '\0')])
15116        .filter_map(move |(index, codepoint)| {
15117            let prev_codepoint = prev_codepoint.replace(codepoint)?;
15118            let is_boundary = index == text.len()
15119                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
15120                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
15121            if is_boundary {
15122                let chunk = &text[prev_index..index];
15123                prev_index = index;
15124                Some(chunk)
15125            } else {
15126                None
15127            }
15128        })
15129}
15130
15131pub trait RangeToAnchorExt: Sized {
15132    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
15133
15134    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
15135        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
15136        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
15137    }
15138}
15139
15140impl<T: ToOffset> RangeToAnchorExt for Range<T> {
15141    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
15142        let start_offset = self.start.to_offset(snapshot);
15143        let end_offset = self.end.to_offset(snapshot);
15144        if start_offset == end_offset {
15145            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
15146        } else {
15147            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
15148        }
15149    }
15150}
15151
15152pub trait RowExt {
15153    fn as_f32(&self) -> f32;
15154
15155    fn next_row(&self) -> Self;
15156
15157    fn previous_row(&self) -> Self;
15158
15159    fn minus(&self, other: Self) -> u32;
15160}
15161
15162impl RowExt for DisplayRow {
15163    fn as_f32(&self) -> f32 {
15164        self.0 as f32
15165    }
15166
15167    fn next_row(&self) -> Self {
15168        Self(self.0 + 1)
15169    }
15170
15171    fn previous_row(&self) -> Self {
15172        Self(self.0.saturating_sub(1))
15173    }
15174
15175    fn minus(&self, other: Self) -> u32 {
15176        self.0 - other.0
15177    }
15178}
15179
15180impl RowExt for MultiBufferRow {
15181    fn as_f32(&self) -> f32 {
15182        self.0 as f32
15183    }
15184
15185    fn next_row(&self) -> Self {
15186        Self(self.0 + 1)
15187    }
15188
15189    fn previous_row(&self) -> Self {
15190        Self(self.0.saturating_sub(1))
15191    }
15192
15193    fn minus(&self, other: Self) -> u32 {
15194        self.0 - other.0
15195    }
15196}
15197
15198trait RowRangeExt {
15199    type Row;
15200
15201    fn len(&self) -> usize;
15202
15203    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
15204}
15205
15206impl RowRangeExt for Range<MultiBufferRow> {
15207    type Row = MultiBufferRow;
15208
15209    fn len(&self) -> usize {
15210        (self.end.0 - self.start.0) as usize
15211    }
15212
15213    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
15214        (self.start.0..self.end.0).map(MultiBufferRow)
15215    }
15216}
15217
15218impl RowRangeExt for Range<DisplayRow> {
15219    type Row = DisplayRow;
15220
15221    fn len(&self) -> usize {
15222        (self.end.0 - self.start.0) as usize
15223    }
15224
15225    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
15226        (self.start.0..self.end.0).map(DisplayRow)
15227    }
15228}
15229
15230fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
15231    if hunk.diff_base_byte_range.is_empty() {
15232        DiffHunkStatus::Added
15233    } else if hunk.row_range.is_empty() {
15234        DiffHunkStatus::Removed
15235    } else {
15236        DiffHunkStatus::Modified
15237    }
15238}
15239
15240/// If select range has more than one line, we
15241/// just point the cursor to range.start.
15242fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
15243    if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
15244        range
15245    } else {
15246        range.start..range.start
15247    }
15248}
15249
15250pub struct KillRing(ClipboardItem);
15251impl Global for KillRing {}
15252
15253const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);