editor.rs

    1#![allow(rustdoc::private_intra_doc_links)]
    2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
    3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
    4//! It comes in different flavors: single line, multiline and a fixed height one.
    5//!
    6//! Editor contains of multiple large submodules:
    7//! * [`element`] — the place where all rendering happens
    8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
    9//!   Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
   10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
   11//!
   12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
   13//!
   14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
   15pub mod actions;
   16mod blame_entry_tooltip;
   17mod blink_manager;
   18mod clangd_ext;
   19mod debounced_delay;
   20pub mod display_map;
   21mod editor_settings;
   22mod editor_settings_controls;
   23mod element;
   24mod git;
   25mod highlight_matching_bracket;
   26mod hover_links;
   27mod hover_popover;
   28mod hunk_diff;
   29mod indent_guides;
   30mod inlay_hint_cache;
   31pub mod items;
   32mod linked_editing_ranges;
   33mod lsp_ext;
   34mod mouse_context_menu;
   35pub mod movement;
   36mod persistence;
   37mod proposed_changes_editor;
   38mod rust_analyzer_ext;
   39pub mod scroll;
   40mod selections_collection;
   41pub mod tasks;
   42
   43#[cfg(test)]
   44mod editor_tests;
   45mod signature_help;
   46#[cfg(any(test, feature = "test-support"))]
   47pub mod test;
   48
   49use ::git::diff::DiffHunkStatus;
   50pub(crate) use actions::*;
   51pub use actions::{OpenExcerpts, OpenExcerptsSplit};
   52use aho_corasick::AhoCorasick;
   53use anyhow::{anyhow, Context as _, Result};
   54use blink_manager::BlinkManager;
   55use client::{Collaborator, ParticipantIndex};
   56use clock::ReplicaId;
   57use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
   58use convert_case::{Case, Casing};
   59use debounced_delay::DebouncedDelay;
   60use display_map::*;
   61pub use display_map::{DisplayPoint, FoldPlaceholder};
   62pub use editor_settings::{
   63    CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
   64};
   65pub use editor_settings_controls::*;
   66use element::LineWithInvisibles;
   67pub use element::{
   68    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   69};
   70use futures::{future, FutureExt};
   71use fuzzy::{StringMatch, StringMatchCandidate};
   72use git::blame::GitBlame;
   73use gpui::{
   74    div, impl_actions, point, prelude::*, px, relative, size, uniform_list, Action, AnyElement,
   75    AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds, ClipboardEntry,
   76    ClipboardItem, Context, DispatchPhase, ElementId, EventEmitter, FocusHandle, FocusOutEvent,
   77    FocusableView, FontId, FontWeight, Global, HighlightStyle, Hsla, InteractiveText, KeyContext,
   78    ListSizingBehavior, Model, ModelContext, MouseButton, PaintQuad, ParentElement, Pixels, Render,
   79    ScrollStrategy, SharedString, Size, StrikethroughStyle, Styled, StyledText, Subscription, Task,
   80    TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle, View,
   81    ViewContext, ViewInputHandler, VisualContext, WeakFocusHandle, WeakView, WindowContext,
   82};
   83use highlight_matching_bracket::refresh_matching_bracket_highlights;
   84use hover_popover::{hide_hover, HoverState};
   85pub(crate) use hunk_diff::HoveredHunk;
   86use hunk_diff::{diff_hunk_to_display, ExpandedHunks};
   87use indent_guides::ActiveIndentGuidesState;
   88use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   89pub use inline_completion::Direction;
   90use inline_completion::{InlayProposal, InlineCompletionProvider, InlineCompletionProviderHandle};
   91pub use items::MAX_TAB_TITLE_LEN;
   92use itertools::Itertools;
   93use language::{
   94    language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
   95    markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
   96    CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
   97    Point, Selection, SelectionGoal, TransactionId,
   98};
   99use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
  100use linked_editing_ranges::refresh_linked_ranges;
  101pub use proposed_changes_editor::{
  102    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  103};
  104use similar::{ChangeTag, TextDiff};
  105use std::iter::Peekable;
  106use task::{ResolvedTask, TaskTemplate, TaskVariables};
  107
  108use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  109pub use lsp::CompletionContext;
  110use lsp::{
  111    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  112    LanguageServerId, LanguageServerName,
  113};
  114use mouse_context_menu::MouseContextMenu;
  115use movement::TextLayoutDetails;
  116pub use multi_buffer::{
  117    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
  118    ToPoint,
  119};
  120use multi_buffer::{
  121    ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
  122};
  123use ordered_float::OrderedFloat;
  124use parking_lot::{Mutex, RwLock};
  125use project::{
  126    lsp_store::{FormatTarget, FormatTrigger},
  127    project_settings::{GitGutterSetting, ProjectSettings},
  128    CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Item, Location,
  129    LocationLink, Project, ProjectTransaction, TaskSourceKind,
  130};
  131use rand::prelude::*;
  132use rpc::{proto::*, ErrorExt};
  133use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  134use selections_collection::{
  135    resolve_selections, MutableSelectionsCollection, SelectionsCollection,
  136};
  137use serde::{Deserialize, Serialize};
  138use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  139use smallvec::SmallVec;
  140use snippet::Snippet;
  141use std::{
  142    any::TypeId,
  143    borrow::Cow,
  144    cell::RefCell,
  145    cmp::{self, Ordering, Reverse},
  146    mem,
  147    num::NonZeroU32,
  148    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  149    path::{Path, PathBuf},
  150    rc::Rc,
  151    sync::Arc,
  152    time::{Duration, Instant},
  153};
  154pub use sum_tree::Bias;
  155use sum_tree::TreeMap;
  156use text::{BufferId, OffsetUtf16, Rope};
  157use theme::{
  158    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  159    ThemeColors, ThemeSettings,
  160};
  161use ui::{
  162    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
  163    ListItem, Popover, PopoverMenuHandle, Tooltip,
  164};
  165use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  166use workspace::item::{ItemHandle, PreviewTabsSettings};
  167use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
  168use workspace::{
  169    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  170};
  171use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  172
  173use crate::hover_links::find_url;
  174use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  175
  176pub const FILE_HEADER_HEIGHT: u32 = 2;
  177pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  178pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  179pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  180const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  181const MAX_LINE_LEN: usize = 1024;
  182const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  183const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  184pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  185#[doc(hidden)]
  186pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  187#[doc(hidden)]
  188pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
  189
  190pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  191pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  192
  193pub fn render_parsed_markdown(
  194    element_id: impl Into<ElementId>,
  195    parsed: &language::ParsedMarkdown,
  196    editor_style: &EditorStyle,
  197    workspace: Option<WeakView<Workspace>>,
  198    cx: &mut WindowContext,
  199) -> InteractiveText {
  200    let code_span_background_color = cx
  201        .theme()
  202        .colors()
  203        .editor_document_highlight_read_background;
  204
  205    let highlights = gpui::combine_highlights(
  206        parsed.highlights.iter().filter_map(|(range, highlight)| {
  207            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  208            Some((range.clone(), highlight))
  209        }),
  210        parsed
  211            .regions
  212            .iter()
  213            .zip(&parsed.region_ranges)
  214            .filter_map(|(region, range)| {
  215                if region.code {
  216                    Some((
  217                        range.clone(),
  218                        HighlightStyle {
  219                            background_color: Some(code_span_background_color),
  220                            ..Default::default()
  221                        },
  222                    ))
  223                } else {
  224                    None
  225                }
  226            }),
  227    );
  228
  229    let mut links = Vec::new();
  230    let mut link_ranges = Vec::new();
  231    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  232        if let Some(link) = region.link.clone() {
  233            links.push(link);
  234            link_ranges.push(range.clone());
  235        }
  236    }
  237
  238    InteractiveText::new(
  239        element_id,
  240        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  241    )
  242    .on_click(link_ranges, move |clicked_range_ix, cx| {
  243        match &links[clicked_range_ix] {
  244            markdown::Link::Web { url } => cx.open_url(url),
  245            markdown::Link::Path { path } => {
  246                if let Some(workspace) = &workspace {
  247                    _ = workspace.update(cx, |workspace, cx| {
  248                        workspace.open_abs_path(path.clone(), false, cx).detach();
  249                    });
  250                }
  251            }
  252        }
  253    })
  254}
  255
  256#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  257pub(crate) enum InlayId {
  258    Suggestion(usize),
  259    Hint(usize),
  260}
  261
  262impl InlayId {
  263    fn id(&self) -> usize {
  264        match self {
  265            Self::Suggestion(id) => *id,
  266            Self::Hint(id) => *id,
  267        }
  268    }
  269}
  270
  271enum DiffRowHighlight {}
  272enum DocumentHighlightRead {}
  273enum DocumentHighlightWrite {}
  274enum InputComposition {}
  275
  276#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  277pub enum Navigated {
  278    Yes,
  279    No,
  280}
  281
  282impl Navigated {
  283    pub fn from_bool(yes: bool) -> Navigated {
  284        if yes {
  285            Navigated::Yes
  286        } else {
  287            Navigated::No
  288        }
  289    }
  290}
  291
  292pub fn init_settings(cx: &mut AppContext) {
  293    EditorSettings::register(cx);
  294}
  295
  296pub fn init(cx: &mut AppContext) {
  297    init_settings(cx);
  298
  299    workspace::register_project_item::<Editor>(cx);
  300    workspace::FollowableViewRegistry::register::<Editor>(cx);
  301    workspace::register_serializable_item::<Editor>(cx);
  302
  303    cx.observe_new_views(
  304        |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
  305            workspace.register_action(Editor::new_file);
  306            workspace.register_action(Editor::new_file_vertical);
  307            workspace.register_action(Editor::new_file_horizontal);
  308        },
  309    )
  310    .detach();
  311
  312    cx.on_action(move |_: &workspace::NewFile, cx| {
  313        let app_state = workspace::AppState::global(cx);
  314        if let Some(app_state) = app_state.upgrade() {
  315            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  316                Editor::new_file(workspace, &Default::default(), cx)
  317            })
  318            .detach();
  319        }
  320    });
  321    cx.on_action(move |_: &workspace::NewWindow, cx| {
  322        let app_state = workspace::AppState::global(cx);
  323        if let Some(app_state) = app_state.upgrade() {
  324            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  325                Editor::new_file(workspace, &Default::default(), cx)
  326            })
  327            .detach();
  328        }
  329    });
  330}
  331
  332pub struct SearchWithinRange;
  333
  334trait InvalidationRegion {
  335    fn ranges(&self) -> &[Range<Anchor>];
  336}
  337
  338#[derive(Clone, Debug, PartialEq)]
  339pub enum SelectPhase {
  340    Begin {
  341        position: DisplayPoint,
  342        add: bool,
  343        click_count: usize,
  344    },
  345    BeginColumnar {
  346        position: DisplayPoint,
  347        reset: bool,
  348        goal_column: u32,
  349    },
  350    Extend {
  351        position: DisplayPoint,
  352        click_count: usize,
  353    },
  354    Update {
  355        position: DisplayPoint,
  356        goal_column: u32,
  357        scroll_delta: gpui::Point<f32>,
  358    },
  359    End,
  360}
  361
  362#[derive(Clone, Debug)]
  363pub enum SelectMode {
  364    Character,
  365    Word(Range<Anchor>),
  366    Line(Range<Anchor>),
  367    All,
  368}
  369
  370#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  371pub enum EditorMode {
  372    SingleLine { auto_width: bool },
  373    AutoHeight { max_lines: usize },
  374    Full,
  375}
  376
  377#[derive(Copy, Clone, Debug)]
  378pub enum SoftWrap {
  379    /// Prefer not to wrap at all.
  380    ///
  381    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  382    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  383    GitDiff,
  384    /// Prefer a single line generally, unless an overly long line is encountered.
  385    None,
  386    /// Soft wrap lines that exceed the editor width.
  387    EditorWidth,
  388    /// Soft wrap lines at the preferred line length.
  389    Column(u32),
  390    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  391    Bounded(u32),
  392}
  393
  394#[derive(Clone)]
  395pub struct EditorStyle {
  396    pub background: Hsla,
  397    pub local_player: PlayerColor,
  398    pub text: TextStyle,
  399    pub scrollbar_width: Pixels,
  400    pub syntax: Arc<SyntaxTheme>,
  401    pub status: StatusColors,
  402    pub inlay_hints_style: HighlightStyle,
  403    pub suggestions_style: HighlightStyle,
  404    pub unnecessary_code_fade: f32,
  405}
  406
  407impl Default for EditorStyle {
  408    fn default() -> Self {
  409        Self {
  410            background: Hsla::default(),
  411            local_player: PlayerColor::default(),
  412            text: TextStyle::default(),
  413            scrollbar_width: Pixels::default(),
  414            syntax: Default::default(),
  415            // HACK: Status colors don't have a real default.
  416            // We should look into removing the status colors from the editor
  417            // style and retrieve them directly from the theme.
  418            status: StatusColors::dark(),
  419            inlay_hints_style: HighlightStyle::default(),
  420            suggestions_style: HighlightStyle::default(),
  421            unnecessary_code_fade: Default::default(),
  422        }
  423    }
  424}
  425
  426pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
  427    let show_background = language_settings::language_settings(None, None, cx)
  428        .inlay_hints
  429        .show_background;
  430
  431    HighlightStyle {
  432        color: Some(cx.theme().status().hint),
  433        background_color: show_background.then(|| cx.theme().status().hint_background),
  434        ..HighlightStyle::default()
  435    }
  436}
  437
  438type CompletionId = usize;
  439
  440#[derive(Clone, Debug)]
  441struct CompletionState {
  442    // render_inlay_ids represents the inlay hints that are inserted
  443    // for rendering the inline completions. They may be discontinuous
  444    // in the event that the completion provider returns some intersection
  445    // with the existing content.
  446    render_inlay_ids: Vec<InlayId>,
  447    // text is the resulting rope that is inserted when the user accepts a completion.
  448    text: Rope,
  449    // position is the position of the cursor when the completion was triggered.
  450    position: multi_buffer::Anchor,
  451    // delete_range is the range of text that this completion state covers.
  452    // if the completion is accepted, this range should be deleted.
  453    delete_range: Option<Range<multi_buffer::Anchor>>,
  454}
  455
  456#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  457struct EditorActionId(usize);
  458
  459impl EditorActionId {
  460    pub fn post_inc(&mut self) -> Self {
  461        let answer = self.0;
  462
  463        *self = Self(answer + 1);
  464
  465        Self(answer)
  466    }
  467}
  468
  469// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  470// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  471
  472type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  473type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
  474
  475#[derive(Default)]
  476struct ScrollbarMarkerState {
  477    scrollbar_size: Size<Pixels>,
  478    dirty: bool,
  479    markers: Arc<[PaintQuad]>,
  480    pending_refresh: Option<Task<Result<()>>>,
  481}
  482
  483impl ScrollbarMarkerState {
  484    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  485        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  486    }
  487}
  488
  489#[derive(Clone, Debug)]
  490struct RunnableTasks {
  491    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  492    offset: MultiBufferOffset,
  493    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  494    column: u32,
  495    // Values of all named captures, including those starting with '_'
  496    extra_variables: HashMap<String, String>,
  497    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  498    context_range: Range<BufferOffset>,
  499}
  500
  501impl RunnableTasks {
  502    fn resolve<'a>(
  503        &'a self,
  504        cx: &'a task::TaskContext,
  505    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  506        self.templates.iter().filter_map(|(kind, template)| {
  507            template
  508                .resolve_task(&kind.to_id_base(), cx)
  509                .map(|task| (kind.clone(), task))
  510        })
  511    }
  512}
  513
  514#[derive(Clone)]
  515struct ResolvedTasks {
  516    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  517    position: Anchor,
  518}
  519#[derive(Copy, Clone, Debug)]
  520struct MultiBufferOffset(usize);
  521#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  522struct BufferOffset(usize);
  523
  524// Addons allow storing per-editor state in other crates (e.g. Vim)
  525pub trait Addon: 'static {
  526    fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
  527
  528    fn to_any(&self) -> &dyn std::any::Any;
  529}
  530
  531#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  532pub enum IsVimMode {
  533    Yes,
  534    No,
  535}
  536
  537/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
  538///
  539/// See the [module level documentation](self) for more information.
  540pub struct Editor {
  541    focus_handle: FocusHandle,
  542    last_focused_descendant: Option<WeakFocusHandle>,
  543    /// The text buffer being edited
  544    buffer: Model<MultiBuffer>,
  545    /// Map of how text in the buffer should be displayed.
  546    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  547    pub display_map: Model<DisplayMap>,
  548    pub selections: SelectionsCollection,
  549    pub scroll_manager: ScrollManager,
  550    /// When inline assist editors are linked, they all render cursors because
  551    /// typing enters text into each of them, even the ones that aren't focused.
  552    pub(crate) show_cursor_when_unfocused: bool,
  553    columnar_selection_tail: Option<Anchor>,
  554    add_selections_state: Option<AddSelectionsState>,
  555    select_next_state: Option<SelectNextState>,
  556    select_prev_state: Option<SelectNextState>,
  557    selection_history: SelectionHistory,
  558    autoclose_regions: Vec<AutocloseRegion>,
  559    snippet_stack: InvalidationStack<SnippetState>,
  560    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  561    ime_transaction: Option<TransactionId>,
  562    active_diagnostics: Option<ActiveDiagnosticGroup>,
  563    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  564
  565    project: Option<Model<Project>>,
  566    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  567    completion_provider: Option<Box<dyn CompletionProvider>>,
  568    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  569    blink_manager: Model<BlinkManager>,
  570    show_cursor_names: bool,
  571    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  572    pub show_local_selections: bool,
  573    mode: EditorMode,
  574    show_breadcrumbs: bool,
  575    show_gutter: bool,
  576    show_line_numbers: Option<bool>,
  577    use_relative_line_numbers: Option<bool>,
  578    show_git_diff_gutter: Option<bool>,
  579    show_code_actions: Option<bool>,
  580    show_runnables: Option<bool>,
  581    show_wrap_guides: Option<bool>,
  582    show_indent_guides: Option<bool>,
  583    placeholder_text: Option<Arc<str>>,
  584    highlight_order: usize,
  585    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  586    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  587    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  588    scrollbar_marker_state: ScrollbarMarkerState,
  589    active_indent_guides_state: ActiveIndentGuidesState,
  590    nav_history: Option<ItemNavHistory>,
  591    context_menu: RwLock<Option<ContextMenu>>,
  592    mouse_context_menu: Option<MouseContextMenu>,
  593    hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
  594    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  595    signature_help_state: SignatureHelpState,
  596    auto_signature_help: Option<bool>,
  597    find_all_references_task_sources: Vec<Anchor>,
  598    next_completion_id: CompletionId,
  599    completion_documentation_pre_resolve_debounce: DebouncedDelay,
  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    expanded_hunks: ExpandedHunks,
  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    is_focused: bool,
  696    scroll_anchor: ScrollAnchor,
  697    ongoing_scroll: OngoingScroll,
  698    current_line_highlight: CurrentLineHighlight,
  699    gutter_hovered: bool,
  700}
  701
  702const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  703
  704#[derive(Default, Debug, Clone, Copy)]
  705pub struct GutterDimensions {
  706    pub left_padding: Pixels,
  707    pub right_padding: Pixels,
  708    pub width: Pixels,
  709    pub margin: Pixels,
  710    pub git_blame_entries_width: Option<Pixels>,
  711}
  712
  713impl GutterDimensions {
  714    /// The full width of the space taken up by the gutter.
  715    pub fn full_width(&self) -> Pixels {
  716        self.margin + self.width
  717    }
  718
  719    /// The width of the space reserved for the fold indicators,
  720    /// use alongside 'justify_end' and `gutter_width` to
  721    /// right align content with the line numbers
  722    pub fn fold_area_width(&self) -> Pixels {
  723        self.margin + self.right_padding
  724    }
  725}
  726
  727#[derive(Debug)]
  728pub struct RemoteSelection {
  729    pub replica_id: ReplicaId,
  730    pub selection: Selection<Anchor>,
  731    pub cursor_shape: CursorShape,
  732    pub peer_id: PeerId,
  733    pub line_mode: bool,
  734    pub participant_index: Option<ParticipantIndex>,
  735    pub user_name: Option<SharedString>,
  736}
  737
  738#[derive(Clone, Debug)]
  739struct SelectionHistoryEntry {
  740    selections: Arc<[Selection<Anchor>]>,
  741    select_next_state: Option<SelectNextState>,
  742    select_prev_state: Option<SelectNextState>,
  743    add_selections_state: Option<AddSelectionsState>,
  744}
  745
  746enum SelectionHistoryMode {
  747    Normal,
  748    Undoing,
  749    Redoing,
  750}
  751
  752#[derive(Clone, PartialEq, Eq, Hash)]
  753struct HoveredCursor {
  754    replica_id: u16,
  755    selection_id: usize,
  756}
  757
  758impl Default for SelectionHistoryMode {
  759    fn default() -> Self {
  760        Self::Normal
  761    }
  762}
  763
  764#[derive(Default)]
  765struct SelectionHistory {
  766    #[allow(clippy::type_complexity)]
  767    selections_by_transaction:
  768        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  769    mode: SelectionHistoryMode,
  770    undo_stack: VecDeque<SelectionHistoryEntry>,
  771    redo_stack: VecDeque<SelectionHistoryEntry>,
  772}
  773
  774impl SelectionHistory {
  775    fn insert_transaction(
  776        &mut self,
  777        transaction_id: TransactionId,
  778        selections: Arc<[Selection<Anchor>]>,
  779    ) {
  780        self.selections_by_transaction
  781            .insert(transaction_id, (selections, None));
  782    }
  783
  784    #[allow(clippy::type_complexity)]
  785    fn transaction(
  786        &self,
  787        transaction_id: TransactionId,
  788    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  789        self.selections_by_transaction.get(&transaction_id)
  790    }
  791
  792    #[allow(clippy::type_complexity)]
  793    fn transaction_mut(
  794        &mut self,
  795        transaction_id: TransactionId,
  796    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  797        self.selections_by_transaction.get_mut(&transaction_id)
  798    }
  799
  800    fn push(&mut self, entry: SelectionHistoryEntry) {
  801        if !entry.selections.is_empty() {
  802            match self.mode {
  803                SelectionHistoryMode::Normal => {
  804                    self.push_undo(entry);
  805                    self.redo_stack.clear();
  806                }
  807                SelectionHistoryMode::Undoing => self.push_redo(entry),
  808                SelectionHistoryMode::Redoing => self.push_undo(entry),
  809            }
  810        }
  811    }
  812
  813    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  814        if self
  815            .undo_stack
  816            .back()
  817            .map_or(true, |e| e.selections != entry.selections)
  818        {
  819            self.undo_stack.push_back(entry);
  820            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  821                self.undo_stack.pop_front();
  822            }
  823        }
  824    }
  825
  826    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  827        if self
  828            .redo_stack
  829            .back()
  830            .map_or(true, |e| e.selections != entry.selections)
  831        {
  832            self.redo_stack.push_back(entry);
  833            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  834                self.redo_stack.pop_front();
  835            }
  836        }
  837    }
  838}
  839
  840struct RowHighlight {
  841    index: usize,
  842    range: Range<Anchor>,
  843    color: Hsla,
  844    should_autoscroll: bool,
  845}
  846
  847#[derive(Clone, Debug)]
  848struct AddSelectionsState {
  849    above: bool,
  850    stack: Vec<usize>,
  851}
  852
  853#[derive(Clone)]
  854struct SelectNextState {
  855    query: AhoCorasick,
  856    wordwise: bool,
  857    done: bool,
  858}
  859
  860impl std::fmt::Debug for SelectNextState {
  861    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  862        f.debug_struct(std::any::type_name::<Self>())
  863            .field("wordwise", &self.wordwise)
  864            .field("done", &self.done)
  865            .finish()
  866    }
  867}
  868
  869#[derive(Debug)]
  870struct AutocloseRegion {
  871    selection_id: usize,
  872    range: Range<Anchor>,
  873    pair: BracketPair,
  874}
  875
  876#[derive(Debug)]
  877struct SnippetState {
  878    ranges: Vec<Vec<Range<Anchor>>>,
  879    active_index: usize,
  880    choices: Vec<Option<Vec<String>>>,
  881}
  882
  883#[doc(hidden)]
  884pub struct RenameState {
  885    pub range: Range<Anchor>,
  886    pub old_name: Arc<str>,
  887    pub editor: View<Editor>,
  888    block_id: CustomBlockId,
  889}
  890
  891struct InvalidationStack<T>(Vec<T>);
  892
  893struct RegisteredInlineCompletionProvider {
  894    provider: Arc<dyn InlineCompletionProviderHandle>,
  895    _subscription: Subscription,
  896}
  897
  898enum ContextMenu {
  899    Completions(CompletionsMenu),
  900    CodeActions(CodeActionsMenu),
  901}
  902
  903impl ContextMenu {
  904    fn select_first(
  905        &mut self,
  906        provider: Option<&dyn CompletionProvider>,
  907        cx: &mut ViewContext<Editor>,
  908    ) -> bool {
  909        if self.visible() {
  910            match self {
  911                ContextMenu::Completions(menu) => menu.select_first(provider, cx),
  912                ContextMenu::CodeActions(menu) => menu.select_first(cx),
  913            }
  914            true
  915        } else {
  916            false
  917        }
  918    }
  919
  920    fn select_prev(
  921        &mut self,
  922        provider: Option<&dyn CompletionProvider>,
  923        cx: &mut ViewContext<Editor>,
  924    ) -> bool {
  925        if self.visible() {
  926            match self {
  927                ContextMenu::Completions(menu) => menu.select_prev(provider, cx),
  928                ContextMenu::CodeActions(menu) => menu.select_prev(cx),
  929            }
  930            true
  931        } else {
  932            false
  933        }
  934    }
  935
  936    fn select_next(
  937        &mut self,
  938        provider: Option<&dyn CompletionProvider>,
  939        cx: &mut ViewContext<Editor>,
  940    ) -> bool {
  941        if self.visible() {
  942            match self {
  943                ContextMenu::Completions(menu) => menu.select_next(provider, cx),
  944                ContextMenu::CodeActions(menu) => menu.select_next(cx),
  945            }
  946            true
  947        } else {
  948            false
  949        }
  950    }
  951
  952    fn select_last(
  953        &mut self,
  954        provider: Option<&dyn CompletionProvider>,
  955        cx: &mut ViewContext<Editor>,
  956    ) -> bool {
  957        if self.visible() {
  958            match self {
  959                ContextMenu::Completions(menu) => menu.select_last(provider, cx),
  960                ContextMenu::CodeActions(menu) => menu.select_last(cx),
  961            }
  962            true
  963        } else {
  964            false
  965        }
  966    }
  967
  968    fn visible(&self) -> bool {
  969        match self {
  970            ContextMenu::Completions(menu) => menu.visible(),
  971            ContextMenu::CodeActions(menu) => menu.visible(),
  972        }
  973    }
  974
  975    fn render(
  976        &self,
  977        cursor_position: DisplayPoint,
  978        style: &EditorStyle,
  979        max_height: Pixels,
  980        workspace: Option<WeakView<Workspace>>,
  981        cx: &mut ViewContext<Editor>,
  982    ) -> (ContextMenuOrigin, AnyElement) {
  983        match self {
  984            ContextMenu::Completions(menu) => (
  985                ContextMenuOrigin::EditorPoint(cursor_position),
  986                menu.render(style, max_height, workspace, cx),
  987            ),
  988            ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
  989        }
  990    }
  991}
  992
  993enum ContextMenuOrigin {
  994    EditorPoint(DisplayPoint),
  995    GutterIndicator(DisplayRow),
  996}
  997
  998#[derive(Clone, Debug)]
  999struct CompletionsMenu {
 1000    id: CompletionId,
 1001    sort_completions: bool,
 1002    initial_position: Anchor,
 1003    buffer: Model<Buffer>,
 1004    completions: Arc<RwLock<Box<[Completion]>>>,
 1005    match_candidates: Arc<[StringMatchCandidate]>,
 1006    matches: Arc<[StringMatch]>,
 1007    selected_item: usize,
 1008    scroll_handle: UniformListScrollHandle,
 1009    selected_completion_documentation_resolve_debounce: Option<Arc<Mutex<DebouncedDelay>>>,
 1010}
 1011
 1012impl CompletionsMenu {
 1013    fn new(
 1014        id: CompletionId,
 1015        sort_completions: bool,
 1016        initial_position: Anchor,
 1017        buffer: Model<Buffer>,
 1018        completions: Box<[Completion]>,
 1019    ) -> Self {
 1020        let match_candidates = completions
 1021            .iter()
 1022            .enumerate()
 1023            .map(|(id, completion)| {
 1024                StringMatchCandidate::new(
 1025                    id,
 1026                    completion.label.text[completion.label.filter_range.clone()].into(),
 1027                )
 1028            })
 1029            .collect();
 1030
 1031        Self {
 1032            id,
 1033            sort_completions,
 1034            initial_position,
 1035            buffer,
 1036            completions: Arc::new(RwLock::new(completions)),
 1037            match_candidates,
 1038            matches: Vec::new().into(),
 1039            selected_item: 0,
 1040            scroll_handle: UniformListScrollHandle::new(),
 1041            selected_completion_documentation_resolve_debounce: Some(Arc::new(Mutex::new(
 1042                DebouncedDelay::new(),
 1043            ))),
 1044        }
 1045    }
 1046
 1047    fn new_snippet_choices(
 1048        id: CompletionId,
 1049        sort_completions: bool,
 1050        choices: &Vec<String>,
 1051        selection: Range<Anchor>,
 1052        buffer: Model<Buffer>,
 1053    ) -> Self {
 1054        let completions = choices
 1055            .iter()
 1056            .map(|choice| Completion {
 1057                old_range: selection.start.text_anchor..selection.end.text_anchor,
 1058                new_text: choice.to_string(),
 1059                label: CodeLabel {
 1060                    text: choice.to_string(),
 1061                    runs: Default::default(),
 1062                    filter_range: Default::default(),
 1063                },
 1064                server_id: LanguageServerId(usize::MAX),
 1065                documentation: None,
 1066                lsp_completion: Default::default(),
 1067                confirm: None,
 1068            })
 1069            .collect();
 1070
 1071        let match_candidates = choices
 1072            .iter()
 1073            .enumerate()
 1074            .map(|(id, completion)| StringMatchCandidate::new(id, completion.to_string()))
 1075            .collect();
 1076        let matches = choices
 1077            .iter()
 1078            .enumerate()
 1079            .map(|(id, completion)| StringMatch {
 1080                candidate_id: id,
 1081                score: 1.,
 1082                positions: vec![],
 1083                string: completion.clone(),
 1084            })
 1085            .collect();
 1086        Self {
 1087            id,
 1088            sort_completions,
 1089            initial_position: selection.start,
 1090            buffer,
 1091            completions: Arc::new(RwLock::new(completions)),
 1092            match_candidates,
 1093            matches,
 1094            selected_item: 0,
 1095            scroll_handle: UniformListScrollHandle::new(),
 1096            selected_completion_documentation_resolve_debounce: Some(Arc::new(Mutex::new(
 1097                DebouncedDelay::new(),
 1098            ))),
 1099        }
 1100    }
 1101
 1102    fn suppress_documentation_resolution(mut self) -> Self {
 1103        self.selected_completion_documentation_resolve_debounce
 1104            .take();
 1105        self
 1106    }
 1107
 1108    fn select_first(
 1109        &mut self,
 1110        provider: Option<&dyn CompletionProvider>,
 1111        cx: &mut ViewContext<Editor>,
 1112    ) {
 1113        self.selected_item = 0;
 1114        self.scroll_handle
 1115            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1116        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1117        cx.notify();
 1118    }
 1119
 1120    fn select_prev(
 1121        &mut self,
 1122        provider: Option<&dyn CompletionProvider>,
 1123        cx: &mut ViewContext<Editor>,
 1124    ) {
 1125        if self.selected_item > 0 {
 1126            self.selected_item -= 1;
 1127        } else {
 1128            self.selected_item = self.matches.len() - 1;
 1129        }
 1130        self.scroll_handle
 1131            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1132        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1133        cx.notify();
 1134    }
 1135
 1136    fn select_next(
 1137        &mut self,
 1138        provider: Option<&dyn CompletionProvider>,
 1139        cx: &mut ViewContext<Editor>,
 1140    ) {
 1141        if self.selected_item + 1 < self.matches.len() {
 1142            self.selected_item += 1;
 1143        } else {
 1144            self.selected_item = 0;
 1145        }
 1146        self.scroll_handle
 1147            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1148        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1149        cx.notify();
 1150    }
 1151
 1152    fn select_last(
 1153        &mut self,
 1154        provider: Option<&dyn CompletionProvider>,
 1155        cx: &mut ViewContext<Editor>,
 1156    ) {
 1157        self.selected_item = self.matches.len() - 1;
 1158        self.scroll_handle
 1159            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1160        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1161        cx.notify();
 1162    }
 1163
 1164    fn pre_resolve_completion_documentation(
 1165        buffer: Model<Buffer>,
 1166        completions: Arc<RwLock<Box<[Completion]>>>,
 1167        matches: Arc<[StringMatch]>,
 1168        editor: &Editor,
 1169        cx: &mut ViewContext<Editor>,
 1170    ) -> Task<()> {
 1171        let settings = EditorSettings::get_global(cx);
 1172        if !settings.show_completion_documentation {
 1173            return Task::ready(());
 1174        }
 1175
 1176        let Some(provider) = editor.completion_provider.as_ref() else {
 1177            return Task::ready(());
 1178        };
 1179
 1180        let resolve_task = provider.resolve_completions(
 1181            buffer,
 1182            matches.iter().map(|m| m.candidate_id).collect(),
 1183            completions.clone(),
 1184            cx,
 1185        );
 1186
 1187        cx.spawn(move |this, mut cx| async move {
 1188            if let Some(true) = resolve_task.await.log_err() {
 1189                this.update(&mut cx, |_, cx| cx.notify()).ok();
 1190            }
 1191        })
 1192    }
 1193
 1194    fn attempt_resolve_selected_completion_documentation(
 1195        &mut self,
 1196        provider: Option<&dyn CompletionProvider>,
 1197        cx: &mut ViewContext<Editor>,
 1198    ) {
 1199        let settings = EditorSettings::get_global(cx);
 1200        if !settings.show_completion_documentation {
 1201            return;
 1202        }
 1203
 1204        let completion_index = self.matches[self.selected_item].candidate_id;
 1205        let Some(provider) = provider else {
 1206            return;
 1207        };
 1208        let Some(documentation_resolve) = self
 1209            .selected_completion_documentation_resolve_debounce
 1210            .as_ref()
 1211        else {
 1212            return;
 1213        };
 1214
 1215        let resolve_task = provider.resolve_completions(
 1216            self.buffer.clone(),
 1217            vec![completion_index],
 1218            self.completions.clone(),
 1219            cx,
 1220        );
 1221
 1222        let delay_ms =
 1223            EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
 1224        let delay = Duration::from_millis(delay_ms);
 1225
 1226        documentation_resolve.lock().fire_new(delay, cx, |_, cx| {
 1227            cx.spawn(move |this, mut cx| async move {
 1228                if let Some(true) = resolve_task.await.log_err() {
 1229                    this.update(&mut cx, |_, cx| cx.notify()).ok();
 1230                }
 1231            })
 1232        });
 1233    }
 1234
 1235    fn visible(&self) -> bool {
 1236        !self.matches.is_empty()
 1237    }
 1238
 1239    fn render(
 1240        &self,
 1241        style: &EditorStyle,
 1242        max_height: Pixels,
 1243        workspace: Option<WeakView<Workspace>>,
 1244        cx: &mut ViewContext<Editor>,
 1245    ) -> AnyElement {
 1246        let settings = EditorSettings::get_global(cx);
 1247        let show_completion_documentation = settings.show_completion_documentation;
 1248
 1249        let widest_completion_ix = self
 1250            .matches
 1251            .iter()
 1252            .enumerate()
 1253            .max_by_key(|(_, mat)| {
 1254                let completions = self.completions.read();
 1255                let completion = &completions[mat.candidate_id];
 1256                let documentation = &completion.documentation;
 1257
 1258                let mut len = completion.label.text.chars().count();
 1259                if let Some(Documentation::SingleLine(text)) = documentation {
 1260                    if show_completion_documentation {
 1261                        len += text.chars().count();
 1262                    }
 1263                }
 1264
 1265                len
 1266            })
 1267            .map(|(ix, _)| ix);
 1268
 1269        let completions = self.completions.clone();
 1270        let matches = self.matches.clone();
 1271        let selected_item = self.selected_item;
 1272        let style = style.clone();
 1273
 1274        let multiline_docs = if show_completion_documentation {
 1275            let mat = &self.matches[selected_item];
 1276            let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
 1277                Some(Documentation::MultiLinePlainText(text)) => {
 1278                    Some(div().child(SharedString::from(text.clone())))
 1279                }
 1280                Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
 1281                    Some(div().child(render_parsed_markdown(
 1282                        "completions_markdown",
 1283                        parsed,
 1284                        &style,
 1285                        workspace,
 1286                        cx,
 1287                    )))
 1288                }
 1289                _ => None,
 1290            };
 1291            multiline_docs.map(|div| {
 1292                div.id("multiline_docs")
 1293                    .max_h(max_height)
 1294                    .flex_1()
 1295                    .px_1p5()
 1296                    .py_1()
 1297                    .min_w(px(260.))
 1298                    .max_w(px(640.))
 1299                    .w(px(500.))
 1300                    .overflow_y_scroll()
 1301                    .occlude()
 1302            })
 1303        } else {
 1304            None
 1305        };
 1306
 1307        let list = uniform_list(
 1308            cx.view().clone(),
 1309            "completions",
 1310            matches.len(),
 1311            move |_editor, range, cx| {
 1312                let start_ix = range.start;
 1313                let completions_guard = completions.read();
 1314
 1315                matches[range]
 1316                    .iter()
 1317                    .enumerate()
 1318                    .map(|(ix, mat)| {
 1319                        let item_ix = start_ix + ix;
 1320                        let candidate_id = mat.candidate_id;
 1321                        let completion = &completions_guard[candidate_id];
 1322
 1323                        let documentation = if show_completion_documentation {
 1324                            &completion.documentation
 1325                        } else {
 1326                            &None
 1327                        };
 1328
 1329                        let highlights = gpui::combine_highlights(
 1330                            mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
 1331                            styled_runs_for_code_label(&completion.label, &style.syntax).map(
 1332                                |(range, mut highlight)| {
 1333                                    // Ignore font weight for syntax highlighting, as we'll use it
 1334                                    // for fuzzy matches.
 1335                                    highlight.font_weight = None;
 1336
 1337                                    if completion.lsp_completion.deprecated.unwrap_or(false) {
 1338                                        highlight.strikethrough = Some(StrikethroughStyle {
 1339                                            thickness: 1.0.into(),
 1340                                            ..Default::default()
 1341                                        });
 1342                                        highlight.color = Some(cx.theme().colors().text_muted);
 1343                                    }
 1344
 1345                                    (range, highlight)
 1346                                },
 1347                            ),
 1348                        );
 1349                        let completion_label = StyledText::new(completion.label.text.clone())
 1350                            .with_highlights(&style.text, highlights);
 1351                        let documentation_label =
 1352                            if let Some(Documentation::SingleLine(text)) = documentation {
 1353                                if text.trim().is_empty() {
 1354                                    None
 1355                                } else {
 1356                                    Some(
 1357                                        Label::new(text.clone())
 1358                                            .ml_4()
 1359                                            .size(LabelSize::Small)
 1360                                            .color(Color::Muted),
 1361                                    )
 1362                                }
 1363                            } else {
 1364                                None
 1365                            };
 1366
 1367                        let color_swatch = completion
 1368                            .color()
 1369                            .map(|color| div().size_4().bg(color).rounded_sm());
 1370
 1371                        div().min_w(px(220.)).max_w(px(540.)).child(
 1372                            ListItem::new(mat.candidate_id)
 1373                                .inset(true)
 1374                                .selected(item_ix == selected_item)
 1375                                .on_click(cx.listener(move |editor, _event, cx| {
 1376                                    cx.stop_propagation();
 1377                                    if let Some(task) = editor.confirm_completion(
 1378                                        &ConfirmCompletion {
 1379                                            item_ix: Some(item_ix),
 1380                                        },
 1381                                        cx,
 1382                                    ) {
 1383                                        task.detach_and_log_err(cx)
 1384                                    }
 1385                                }))
 1386                                .start_slot::<Div>(color_swatch)
 1387                                .child(h_flex().overflow_hidden().child(completion_label))
 1388                                .end_slot::<Label>(documentation_label),
 1389                        )
 1390                    })
 1391                    .collect()
 1392            },
 1393        )
 1394        .occlude()
 1395        .max_h(max_height)
 1396        .track_scroll(self.scroll_handle.clone())
 1397        .with_width_from_item(widest_completion_ix)
 1398        .with_sizing_behavior(ListSizingBehavior::Infer);
 1399
 1400        Popover::new()
 1401            .child(list)
 1402            .when_some(multiline_docs, |popover, multiline_docs| {
 1403                popover.aside(multiline_docs)
 1404            })
 1405            .into_any_element()
 1406    }
 1407
 1408    pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
 1409        let mut matches = if let Some(query) = query {
 1410            fuzzy::match_strings(
 1411                &self.match_candidates,
 1412                query,
 1413                query.chars().any(|c| c.is_uppercase()),
 1414                100,
 1415                &Default::default(),
 1416                executor,
 1417            )
 1418            .await
 1419        } else {
 1420            self.match_candidates
 1421                .iter()
 1422                .enumerate()
 1423                .map(|(candidate_id, candidate)| StringMatch {
 1424                    candidate_id,
 1425                    score: Default::default(),
 1426                    positions: Default::default(),
 1427                    string: candidate.string.clone(),
 1428                })
 1429                .collect()
 1430        };
 1431
 1432        // Remove all candidates where the query's start does not match the start of any word in the candidate
 1433        if let Some(query) = query {
 1434            if let Some(query_start) = query.chars().next() {
 1435                matches.retain(|string_match| {
 1436                    split_words(&string_match.string).any(|word| {
 1437                        // Check that the first codepoint of the word as lowercase matches the first
 1438                        // codepoint of the query as lowercase
 1439                        word.chars()
 1440                            .flat_map(|codepoint| codepoint.to_lowercase())
 1441                            .zip(query_start.to_lowercase())
 1442                            .all(|(word_cp, query_cp)| word_cp == query_cp)
 1443                    })
 1444                });
 1445            }
 1446        }
 1447
 1448        let completions = self.completions.read();
 1449        if self.sort_completions {
 1450            matches.sort_unstable_by_key(|mat| {
 1451                // We do want to strike a balance here between what the language server tells us
 1452                // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
 1453                // `Creat` and there is a local variable called `CreateComponent`).
 1454                // So what we do is: we bucket all matches into two buckets
 1455                // - Strong matches
 1456                // - Weak matches
 1457                // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
 1458                // and the Weak matches are the rest.
 1459                //
 1460                // For the strong matches, we sort by our fuzzy-finder score first and for the weak
 1461                // matches, we prefer language-server sort_text first.
 1462                //
 1463                // The thinking behind that: we want to show strong matches first in order of relevance(fuzzy score).
 1464                // Rest of the matches(weak) can be sorted as language-server expects.
 1465
 1466                #[derive(PartialEq, Eq, PartialOrd, Ord)]
 1467                enum MatchScore<'a> {
 1468                    Strong {
 1469                        score: Reverse<OrderedFloat<f64>>,
 1470                        sort_text: Option<&'a str>,
 1471                        sort_key: (usize, &'a str),
 1472                    },
 1473                    Weak {
 1474                        sort_text: Option<&'a str>,
 1475                        score: Reverse<OrderedFloat<f64>>,
 1476                        sort_key: (usize, &'a str),
 1477                    },
 1478                }
 1479
 1480                let completion = &completions[mat.candidate_id];
 1481                let sort_key = completion.sort_key();
 1482                let sort_text = completion.lsp_completion.sort_text.as_deref();
 1483                let score = Reverse(OrderedFloat(mat.score));
 1484
 1485                if mat.score >= 0.2 {
 1486                    MatchScore::Strong {
 1487                        score,
 1488                        sort_text,
 1489                        sort_key,
 1490                    }
 1491                } else {
 1492                    MatchScore::Weak {
 1493                        sort_text,
 1494                        score,
 1495                        sort_key,
 1496                    }
 1497                }
 1498            });
 1499        }
 1500
 1501        for mat in &mut matches {
 1502            let completion = &completions[mat.candidate_id];
 1503            mat.string.clone_from(&completion.label.text);
 1504            for position in &mut mat.positions {
 1505                *position += completion.label.filter_range.start;
 1506            }
 1507        }
 1508        drop(completions);
 1509
 1510        self.matches = matches.into();
 1511        self.selected_item = 0;
 1512    }
 1513}
 1514
 1515#[derive(Clone)]
 1516struct AvailableCodeAction {
 1517    excerpt_id: ExcerptId,
 1518    action: CodeAction,
 1519    provider: Arc<dyn CodeActionProvider>,
 1520}
 1521
 1522#[derive(Clone)]
 1523struct CodeActionContents {
 1524    tasks: Option<Arc<ResolvedTasks>>,
 1525    actions: Option<Arc<[AvailableCodeAction]>>,
 1526}
 1527
 1528impl CodeActionContents {
 1529    fn len(&self) -> usize {
 1530        match (&self.tasks, &self.actions) {
 1531            (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
 1532            (Some(tasks), None) => tasks.templates.len(),
 1533            (None, Some(actions)) => actions.len(),
 1534            (None, None) => 0,
 1535        }
 1536    }
 1537
 1538    fn is_empty(&self) -> bool {
 1539        match (&self.tasks, &self.actions) {
 1540            (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
 1541            (Some(tasks), None) => tasks.templates.is_empty(),
 1542            (None, Some(actions)) => actions.is_empty(),
 1543            (None, None) => true,
 1544        }
 1545    }
 1546
 1547    fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
 1548        self.tasks
 1549            .iter()
 1550            .flat_map(|tasks| {
 1551                tasks
 1552                    .templates
 1553                    .iter()
 1554                    .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
 1555            })
 1556            .chain(self.actions.iter().flat_map(|actions| {
 1557                actions.iter().map(|available| CodeActionsItem::CodeAction {
 1558                    excerpt_id: available.excerpt_id,
 1559                    action: available.action.clone(),
 1560                    provider: available.provider.clone(),
 1561                })
 1562            }))
 1563    }
 1564    fn get(&self, index: usize) -> Option<CodeActionsItem> {
 1565        match (&self.tasks, &self.actions) {
 1566            (Some(tasks), Some(actions)) => {
 1567                if index < tasks.templates.len() {
 1568                    tasks
 1569                        .templates
 1570                        .get(index)
 1571                        .cloned()
 1572                        .map(|(kind, task)| CodeActionsItem::Task(kind, task))
 1573                } else {
 1574                    actions.get(index - tasks.templates.len()).map(|available| {
 1575                        CodeActionsItem::CodeAction {
 1576                            excerpt_id: available.excerpt_id,
 1577                            action: available.action.clone(),
 1578                            provider: available.provider.clone(),
 1579                        }
 1580                    })
 1581                }
 1582            }
 1583            (Some(tasks), None) => tasks
 1584                .templates
 1585                .get(index)
 1586                .cloned()
 1587                .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
 1588            (None, Some(actions)) => {
 1589                actions
 1590                    .get(index)
 1591                    .map(|available| CodeActionsItem::CodeAction {
 1592                        excerpt_id: available.excerpt_id,
 1593                        action: available.action.clone(),
 1594                        provider: available.provider.clone(),
 1595                    })
 1596            }
 1597            (None, None) => None,
 1598        }
 1599    }
 1600}
 1601
 1602#[allow(clippy::large_enum_variant)]
 1603#[derive(Clone)]
 1604enum CodeActionsItem {
 1605    Task(TaskSourceKind, ResolvedTask),
 1606    CodeAction {
 1607        excerpt_id: ExcerptId,
 1608        action: CodeAction,
 1609        provider: Arc<dyn CodeActionProvider>,
 1610    },
 1611}
 1612
 1613impl CodeActionsItem {
 1614    fn as_task(&self) -> Option<&ResolvedTask> {
 1615        let Self::Task(_, task) = self else {
 1616            return None;
 1617        };
 1618        Some(task)
 1619    }
 1620    fn as_code_action(&self) -> Option<&CodeAction> {
 1621        let Self::CodeAction { action, .. } = self else {
 1622            return None;
 1623        };
 1624        Some(action)
 1625    }
 1626    fn label(&self) -> String {
 1627        match self {
 1628            Self::CodeAction { action, .. } => action.lsp_action.title.clone(),
 1629            Self::Task(_, task) => task.resolved_label.clone(),
 1630        }
 1631    }
 1632}
 1633
 1634struct CodeActionsMenu {
 1635    actions: CodeActionContents,
 1636    buffer: Model<Buffer>,
 1637    selected_item: usize,
 1638    scroll_handle: UniformListScrollHandle,
 1639    deployed_from_indicator: Option<DisplayRow>,
 1640}
 1641
 1642impl CodeActionsMenu {
 1643    fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
 1644        self.selected_item = 0;
 1645        self.scroll_handle
 1646            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1647        cx.notify()
 1648    }
 1649
 1650    fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
 1651        if self.selected_item > 0 {
 1652            self.selected_item -= 1;
 1653        } else {
 1654            self.selected_item = self.actions.len() - 1;
 1655        }
 1656        self.scroll_handle
 1657            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1658        cx.notify();
 1659    }
 1660
 1661    fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
 1662        if self.selected_item + 1 < self.actions.len() {
 1663            self.selected_item += 1;
 1664        } else {
 1665            self.selected_item = 0;
 1666        }
 1667        self.scroll_handle
 1668            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1669        cx.notify();
 1670    }
 1671
 1672    fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
 1673        self.selected_item = self.actions.len() - 1;
 1674        self.scroll_handle
 1675            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1676        cx.notify()
 1677    }
 1678
 1679    fn visible(&self) -> bool {
 1680        !self.actions.is_empty()
 1681    }
 1682
 1683    fn render(
 1684        &self,
 1685        cursor_position: DisplayPoint,
 1686        _style: &EditorStyle,
 1687        max_height: Pixels,
 1688        cx: &mut ViewContext<Editor>,
 1689    ) -> (ContextMenuOrigin, AnyElement) {
 1690        let actions = self.actions.clone();
 1691        let selected_item = self.selected_item;
 1692        let element = uniform_list(
 1693            cx.view().clone(),
 1694            "code_actions_menu",
 1695            self.actions.len(),
 1696            move |_this, range, cx| {
 1697                actions
 1698                    .iter()
 1699                    .skip(range.start)
 1700                    .take(range.end - range.start)
 1701                    .enumerate()
 1702                    .map(|(ix, action)| {
 1703                        let item_ix = range.start + ix;
 1704                        let selected = selected_item == item_ix;
 1705                        let colors = cx.theme().colors();
 1706                        div()
 1707                            .px_1()
 1708                            .rounded_md()
 1709                            .text_color(colors.text)
 1710                            .when(selected, |style| {
 1711                                style
 1712                                    .bg(colors.element_active)
 1713                                    .text_color(colors.text_accent)
 1714                            })
 1715                            .hover(|style| {
 1716                                style
 1717                                    .bg(colors.element_hover)
 1718                                    .text_color(colors.text_accent)
 1719                            })
 1720                            .whitespace_nowrap()
 1721                            .when_some(action.as_code_action(), |this, action| {
 1722                                this.on_mouse_down(
 1723                                    MouseButton::Left,
 1724                                    cx.listener(move |editor, _, cx| {
 1725                                        cx.stop_propagation();
 1726                                        if let Some(task) = editor.confirm_code_action(
 1727                                            &ConfirmCodeAction {
 1728                                                item_ix: Some(item_ix),
 1729                                            },
 1730                                            cx,
 1731                                        ) {
 1732                                            task.detach_and_log_err(cx)
 1733                                        }
 1734                                    }),
 1735                                )
 1736                                // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
 1737                                .child(SharedString::from(action.lsp_action.title.clone()))
 1738                            })
 1739                            .when_some(action.as_task(), |this, task| {
 1740                                this.on_mouse_down(
 1741                                    MouseButton::Left,
 1742                                    cx.listener(move |editor, _, cx| {
 1743                                        cx.stop_propagation();
 1744                                        if let Some(task) = editor.confirm_code_action(
 1745                                            &ConfirmCodeAction {
 1746                                                item_ix: Some(item_ix),
 1747                                            },
 1748                                            cx,
 1749                                        ) {
 1750                                            task.detach_and_log_err(cx)
 1751                                        }
 1752                                    }),
 1753                                )
 1754                                .child(SharedString::from(task.resolved_label.clone()))
 1755                            })
 1756                    })
 1757                    .collect()
 1758            },
 1759        )
 1760        .elevation_1(cx)
 1761        .p_1()
 1762        .max_h(max_height)
 1763        .occlude()
 1764        .track_scroll(self.scroll_handle.clone())
 1765        .with_width_from_item(
 1766            self.actions
 1767                .iter()
 1768                .enumerate()
 1769                .max_by_key(|(_, action)| match action {
 1770                    CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
 1771                    CodeActionsItem::CodeAction { action, .. } => {
 1772                        action.lsp_action.title.chars().count()
 1773                    }
 1774                })
 1775                .map(|(ix, _)| ix),
 1776        )
 1777        .with_sizing_behavior(ListSizingBehavior::Infer)
 1778        .into_any_element();
 1779
 1780        let cursor_position = if let Some(row) = self.deployed_from_indicator {
 1781            ContextMenuOrigin::GutterIndicator(row)
 1782        } else {
 1783            ContextMenuOrigin::EditorPoint(cursor_position)
 1784        };
 1785
 1786        (cursor_position, element)
 1787    }
 1788}
 1789
 1790#[derive(Debug)]
 1791struct ActiveDiagnosticGroup {
 1792    primary_range: Range<Anchor>,
 1793    primary_message: String,
 1794    group_id: usize,
 1795    blocks: HashMap<CustomBlockId, Diagnostic>,
 1796    is_valid: bool,
 1797}
 1798
 1799#[derive(Serialize, Deserialize, Clone, Debug)]
 1800pub struct ClipboardSelection {
 1801    pub len: usize,
 1802    pub is_entire_line: bool,
 1803    pub first_line_indent: u32,
 1804}
 1805
 1806#[derive(Debug)]
 1807pub(crate) struct NavigationData {
 1808    cursor_anchor: Anchor,
 1809    cursor_position: Point,
 1810    scroll_anchor: ScrollAnchor,
 1811    scroll_top_row: u32,
 1812}
 1813
 1814#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1815pub enum GotoDefinitionKind {
 1816    Symbol,
 1817    Declaration,
 1818    Type,
 1819    Implementation,
 1820}
 1821
 1822#[derive(Debug, Clone)]
 1823enum InlayHintRefreshReason {
 1824    Toggle(bool),
 1825    SettingsChange(InlayHintSettings),
 1826    NewLinesShown,
 1827    BufferEdited(HashSet<Arc<Language>>),
 1828    RefreshRequested,
 1829    ExcerptsRemoved(Vec<ExcerptId>),
 1830}
 1831
 1832impl InlayHintRefreshReason {
 1833    fn description(&self) -> &'static str {
 1834        match self {
 1835            Self::Toggle(_) => "toggle",
 1836            Self::SettingsChange(_) => "settings change",
 1837            Self::NewLinesShown => "new lines shown",
 1838            Self::BufferEdited(_) => "buffer edited",
 1839            Self::RefreshRequested => "refresh requested",
 1840            Self::ExcerptsRemoved(_) => "excerpts removed",
 1841        }
 1842    }
 1843}
 1844
 1845pub(crate) struct FocusedBlock {
 1846    id: BlockId,
 1847    focus_handle: WeakFocusHandle,
 1848}
 1849
 1850#[derive(Clone)]
 1851struct JumpData {
 1852    excerpt_id: ExcerptId,
 1853    position: Point,
 1854    anchor: text::Anchor,
 1855    path: Option<project::ProjectPath>,
 1856    line_offset_from_top: u32,
 1857}
 1858
 1859impl Editor {
 1860    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
 1861        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1862        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1863        Self::new(
 1864            EditorMode::SingleLine { auto_width: false },
 1865            buffer,
 1866            None,
 1867            false,
 1868            cx,
 1869        )
 1870    }
 1871
 1872    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
 1873        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1874        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1875        Self::new(EditorMode::Full, buffer, None, false, cx)
 1876    }
 1877
 1878    pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
 1879        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1880        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1881        Self::new(
 1882            EditorMode::SingleLine { auto_width: true },
 1883            buffer,
 1884            None,
 1885            false,
 1886            cx,
 1887        )
 1888    }
 1889
 1890    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
 1891        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1892        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1893        Self::new(
 1894            EditorMode::AutoHeight { max_lines },
 1895            buffer,
 1896            None,
 1897            false,
 1898            cx,
 1899        )
 1900    }
 1901
 1902    pub fn for_buffer(
 1903        buffer: Model<Buffer>,
 1904        project: Option<Model<Project>>,
 1905        cx: &mut ViewContext<Self>,
 1906    ) -> Self {
 1907        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1908        Self::new(EditorMode::Full, buffer, project, false, cx)
 1909    }
 1910
 1911    pub fn for_multibuffer(
 1912        buffer: Model<MultiBuffer>,
 1913        project: Option<Model<Project>>,
 1914        show_excerpt_controls: bool,
 1915        cx: &mut ViewContext<Self>,
 1916    ) -> Self {
 1917        Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
 1918    }
 1919
 1920    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 1921        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1922        let mut clone = Self::new(
 1923            self.mode,
 1924            self.buffer.clone(),
 1925            self.project.clone(),
 1926            show_excerpt_controls,
 1927            cx,
 1928        );
 1929        self.display_map.update(cx, |display_map, cx| {
 1930            let snapshot = display_map.snapshot(cx);
 1931            clone.display_map.update(cx, |display_map, cx| {
 1932                display_map.set_state(&snapshot, cx);
 1933            });
 1934        });
 1935        clone.selections.clone_state(&self.selections);
 1936        clone.scroll_manager.clone_state(&self.scroll_manager);
 1937        clone.searchable = self.searchable;
 1938        clone
 1939    }
 1940
 1941    pub fn new(
 1942        mode: EditorMode,
 1943        buffer: Model<MultiBuffer>,
 1944        project: Option<Model<Project>>,
 1945        show_excerpt_controls: bool,
 1946        cx: &mut ViewContext<Self>,
 1947    ) -> Self {
 1948        let style = cx.text_style();
 1949        let font_size = style.font_size.to_pixels(cx.rem_size());
 1950        let editor = cx.view().downgrade();
 1951        let fold_placeholder = FoldPlaceholder {
 1952            constrain_width: true,
 1953            render: Arc::new(move |fold_id, fold_range, cx| {
 1954                let editor = editor.clone();
 1955                div()
 1956                    .id(fold_id)
 1957                    .bg(cx.theme().colors().ghost_element_background)
 1958                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1959                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1960                    .rounded_sm()
 1961                    .size_full()
 1962                    .cursor_pointer()
 1963                    .child("")
 1964                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 1965                    .on_click(move |_, cx| {
 1966                        editor
 1967                            .update(cx, |editor, cx| {
 1968                                editor.unfold_ranges(
 1969                                    &[fold_range.start..fold_range.end],
 1970                                    true,
 1971                                    false,
 1972                                    cx,
 1973                                );
 1974                                cx.stop_propagation();
 1975                            })
 1976                            .ok();
 1977                    })
 1978                    .into_any()
 1979            }),
 1980            merge_adjacent: true,
 1981            ..Default::default()
 1982        };
 1983        let display_map = cx.new_model(|cx| {
 1984            DisplayMap::new(
 1985                buffer.clone(),
 1986                style.font(),
 1987                font_size,
 1988                None,
 1989                show_excerpt_controls,
 1990                FILE_HEADER_HEIGHT,
 1991                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1992                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1993                fold_placeholder,
 1994                cx,
 1995            )
 1996        });
 1997
 1998        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1999
 2000        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 2001
 2002        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 2003            .then(|| language_settings::SoftWrap::None);
 2004
 2005        let mut project_subscriptions = Vec::new();
 2006        if mode == EditorMode::Full {
 2007            if let Some(project) = project.as_ref() {
 2008                if buffer.read(cx).is_singleton() {
 2009                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
 2010                        cx.emit(EditorEvent::TitleChanged);
 2011                    }));
 2012                }
 2013                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
 2014                    if let project::Event::RefreshInlayHints = event {
 2015                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 2016                    } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 2017                        if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 2018                            let focus_handle = editor.focus_handle(cx);
 2019                            if focus_handle.is_focused(cx) {
 2020                                let snapshot = buffer.read(cx).snapshot();
 2021                                for (range, snippet) in snippet_edits {
 2022                                    let editor_range =
 2023                                        language::range_from_lsp(*range).to_offset(&snapshot);
 2024                                    editor
 2025                                        .insert_snippet(&[editor_range], snippet.clone(), cx)
 2026                                        .ok();
 2027                                }
 2028                            }
 2029                        }
 2030                    }
 2031                }));
 2032                if let Some(task_inventory) = project
 2033                    .read(cx)
 2034                    .task_store()
 2035                    .read(cx)
 2036                    .task_inventory()
 2037                    .cloned()
 2038                {
 2039                    project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
 2040                        editor.tasks_update_task = Some(editor.refresh_runnables(cx));
 2041                    }));
 2042                }
 2043            }
 2044        }
 2045
 2046        let inlay_hint_settings = inlay_hint_settings(
 2047            selections.newest_anchor().head(),
 2048            &buffer.read(cx).snapshot(cx),
 2049            cx,
 2050        );
 2051        let focus_handle = cx.focus_handle();
 2052        cx.on_focus(&focus_handle, Self::handle_focus).detach();
 2053        cx.on_focus_in(&focus_handle, Self::handle_focus_in)
 2054            .detach();
 2055        cx.on_focus_out(&focus_handle, Self::handle_focus_out)
 2056            .detach();
 2057        cx.on_blur(&focus_handle, Self::handle_blur).detach();
 2058
 2059        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 2060            Some(false)
 2061        } else {
 2062            None
 2063        };
 2064
 2065        let mut code_action_providers = Vec::new();
 2066        if let Some(project) = project.clone() {
 2067            code_action_providers.push(Arc::new(project) as Arc<_>);
 2068        }
 2069
 2070        let mut this = Self {
 2071            focus_handle,
 2072            show_cursor_when_unfocused: false,
 2073            last_focused_descendant: None,
 2074            buffer: buffer.clone(),
 2075            display_map: display_map.clone(),
 2076            selections,
 2077            scroll_manager: ScrollManager::new(cx),
 2078            columnar_selection_tail: None,
 2079            add_selections_state: None,
 2080            select_next_state: None,
 2081            select_prev_state: None,
 2082            selection_history: Default::default(),
 2083            autoclose_regions: Default::default(),
 2084            snippet_stack: Default::default(),
 2085            select_larger_syntax_node_stack: Vec::new(),
 2086            ime_transaction: Default::default(),
 2087            active_diagnostics: None,
 2088            soft_wrap_mode_override,
 2089            completion_provider: project.clone().map(|project| Box::new(project) as _),
 2090            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 2091            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 2092            project,
 2093            blink_manager: blink_manager.clone(),
 2094            show_local_selections: true,
 2095            mode,
 2096            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 2097            show_gutter: mode == EditorMode::Full,
 2098            show_line_numbers: None,
 2099            use_relative_line_numbers: None,
 2100            show_git_diff_gutter: None,
 2101            show_code_actions: None,
 2102            show_runnables: None,
 2103            show_wrap_guides: None,
 2104            show_indent_guides,
 2105            placeholder_text: None,
 2106            highlight_order: 0,
 2107            highlighted_rows: HashMap::default(),
 2108            background_highlights: Default::default(),
 2109            gutter_highlights: TreeMap::default(),
 2110            scrollbar_marker_state: ScrollbarMarkerState::default(),
 2111            active_indent_guides_state: ActiveIndentGuidesState::default(),
 2112            nav_history: None,
 2113            context_menu: RwLock::new(None),
 2114            mouse_context_menu: None,
 2115            hunk_controls_menu_handle: PopoverMenuHandle::default(),
 2116            completion_tasks: Default::default(),
 2117            signature_help_state: SignatureHelpState::default(),
 2118            auto_signature_help: None,
 2119            find_all_references_task_sources: Vec::new(),
 2120            next_completion_id: 0,
 2121            completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
 2122            next_inlay_id: 0,
 2123            code_action_providers,
 2124            available_code_actions: Default::default(),
 2125            code_actions_task: Default::default(),
 2126            document_highlights_task: Default::default(),
 2127            linked_editing_range_task: Default::default(),
 2128            pending_rename: Default::default(),
 2129            searchable: true,
 2130            cursor_shape: EditorSettings::get_global(cx)
 2131                .cursor_shape
 2132                .unwrap_or_default(),
 2133            current_line_highlight: None,
 2134            autoindent_mode: Some(AutoindentMode::EachLine),
 2135            collapse_matches: false,
 2136            workspace: None,
 2137            input_enabled: true,
 2138            use_modal_editing: mode == EditorMode::Full,
 2139            read_only: false,
 2140            use_autoclose: true,
 2141            use_auto_surround: true,
 2142            auto_replace_emoji_shortcode: false,
 2143            leader_peer_id: None,
 2144            remote_id: None,
 2145            hover_state: Default::default(),
 2146            hovered_link_state: Default::default(),
 2147            inline_completion_provider: None,
 2148            active_inline_completion: None,
 2149            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 2150            expanded_hunks: ExpandedHunks::default(),
 2151            gutter_hovered: false,
 2152            pixel_position_of_newest_cursor: None,
 2153            last_bounds: None,
 2154            expect_bounds_change: None,
 2155            gutter_dimensions: GutterDimensions::default(),
 2156            style: None,
 2157            show_cursor_names: false,
 2158            hovered_cursors: Default::default(),
 2159            next_editor_action_id: EditorActionId::default(),
 2160            editor_actions: Rc::default(),
 2161            show_inline_completions_override: None,
 2162            enable_inline_completions: true,
 2163            custom_context_menu: None,
 2164            show_git_blame_gutter: false,
 2165            show_git_blame_inline: false,
 2166            show_selection_menu: None,
 2167            show_git_blame_inline_delay_task: None,
 2168            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 2169            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 2170                .session
 2171                .restore_unsaved_buffers,
 2172            blame: None,
 2173            blame_subscription: None,
 2174            tasks: Default::default(),
 2175            _subscriptions: vec![
 2176                cx.observe(&buffer, Self::on_buffer_changed),
 2177                cx.subscribe(&buffer, Self::on_buffer_event),
 2178                cx.observe(&display_map, Self::on_display_map_changed),
 2179                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 2180                cx.observe_global::<SettingsStore>(Self::settings_changed),
 2181                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 2182                cx.observe_window_activation(|editor, cx| {
 2183                    let active = cx.is_window_active();
 2184                    editor.blink_manager.update(cx, |blink_manager, cx| {
 2185                        if active {
 2186                            blink_manager.enable(cx);
 2187                        } else {
 2188                            blink_manager.disable(cx);
 2189                        }
 2190                    });
 2191                }),
 2192            ],
 2193            tasks_update_task: None,
 2194            linked_edit_ranges: Default::default(),
 2195            previous_search_ranges: None,
 2196            breadcrumb_header: None,
 2197            focused_block: None,
 2198            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 2199            addons: HashMap::default(),
 2200            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 2201            text_style_refinement: None,
 2202        };
 2203        this.tasks_update_task = Some(this.refresh_runnables(cx));
 2204        this._subscriptions.extend(project_subscriptions);
 2205
 2206        this.end_selection(cx);
 2207        this.scroll_manager.show_scrollbar(cx);
 2208
 2209        if mode == EditorMode::Full {
 2210            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 2211            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 2212
 2213            if this.git_blame_inline_enabled {
 2214                this.git_blame_inline_enabled = true;
 2215                this.start_git_blame_inline(false, cx);
 2216            }
 2217        }
 2218
 2219        this.report_editor_event("open", None, cx);
 2220        this
 2221    }
 2222
 2223    pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
 2224        self.mouse_context_menu
 2225            .as_ref()
 2226            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
 2227    }
 2228
 2229    fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
 2230        let mut key_context = KeyContext::new_with_defaults();
 2231        key_context.add("Editor");
 2232        let mode = match self.mode {
 2233            EditorMode::SingleLine { .. } => "single_line",
 2234            EditorMode::AutoHeight { .. } => "auto_height",
 2235            EditorMode::Full => "full",
 2236        };
 2237
 2238        if EditorSettings::jupyter_enabled(cx) {
 2239            key_context.add("jupyter");
 2240        }
 2241
 2242        key_context.set("mode", mode);
 2243        if self.pending_rename.is_some() {
 2244            key_context.add("renaming");
 2245        }
 2246        if self.context_menu_visible() {
 2247            match self.context_menu.read().as_ref() {
 2248                Some(ContextMenu::Completions(_)) => {
 2249                    key_context.add("menu");
 2250                    key_context.add("showing_completions")
 2251                }
 2252                Some(ContextMenu::CodeActions(_)) => {
 2253                    key_context.add("menu");
 2254                    key_context.add("showing_code_actions")
 2255                }
 2256                None => {}
 2257            }
 2258        }
 2259
 2260        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 2261        if !self.focus_handle(cx).contains_focused(cx)
 2262            || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
 2263        {
 2264            for addon in self.addons.values() {
 2265                addon.extend_key_context(&mut key_context, cx)
 2266            }
 2267        }
 2268
 2269        if let Some(extension) = self
 2270            .buffer
 2271            .read(cx)
 2272            .as_singleton()
 2273            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 2274        {
 2275            key_context.set("extension", extension.to_string());
 2276        }
 2277
 2278        if self.has_active_inline_completion(cx) {
 2279            key_context.add("copilot_suggestion");
 2280            key_context.add("inline_completion");
 2281        }
 2282
 2283        key_context
 2284    }
 2285
 2286    pub fn new_file(
 2287        workspace: &mut Workspace,
 2288        _: &workspace::NewFile,
 2289        cx: &mut ViewContext<Workspace>,
 2290    ) {
 2291        Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
 2292            "Failed to create buffer",
 2293            cx,
 2294            |e, _| match e.error_code() {
 2295                ErrorCode::RemoteUpgradeRequired => Some(format!(
 2296                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2297                e.error_tag("required").unwrap_or("the latest version")
 2298            )),
 2299                _ => None,
 2300            },
 2301        );
 2302    }
 2303
 2304    pub fn new_in_workspace(
 2305        workspace: &mut Workspace,
 2306        cx: &mut ViewContext<Workspace>,
 2307    ) -> Task<Result<View<Editor>>> {
 2308        let project = workspace.project().clone();
 2309        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2310
 2311        cx.spawn(|workspace, mut cx| async move {
 2312            let buffer = create.await?;
 2313            workspace.update(&mut cx, |workspace, cx| {
 2314                let editor =
 2315                    cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
 2316                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 2317                editor
 2318            })
 2319        })
 2320    }
 2321
 2322    fn new_file_vertical(
 2323        workspace: &mut Workspace,
 2324        _: &workspace::NewFileSplitVertical,
 2325        cx: &mut ViewContext<Workspace>,
 2326    ) {
 2327        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
 2328    }
 2329
 2330    fn new_file_horizontal(
 2331        workspace: &mut Workspace,
 2332        _: &workspace::NewFileSplitHorizontal,
 2333        cx: &mut ViewContext<Workspace>,
 2334    ) {
 2335        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
 2336    }
 2337
 2338    fn new_file_in_direction(
 2339        workspace: &mut Workspace,
 2340        direction: SplitDirection,
 2341        cx: &mut ViewContext<Workspace>,
 2342    ) {
 2343        let project = workspace.project().clone();
 2344        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2345
 2346        cx.spawn(|workspace, mut cx| async move {
 2347            let buffer = create.await?;
 2348            workspace.update(&mut cx, move |workspace, cx| {
 2349                workspace.split_item(
 2350                    direction,
 2351                    Box::new(
 2352                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 2353                    ),
 2354                    cx,
 2355                )
 2356            })?;
 2357            anyhow::Ok(())
 2358        })
 2359        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 2360            ErrorCode::RemoteUpgradeRequired => Some(format!(
 2361                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2362                e.error_tag("required").unwrap_or("the latest version")
 2363            )),
 2364            _ => None,
 2365        });
 2366    }
 2367
 2368    pub fn leader_peer_id(&self) -> Option<PeerId> {
 2369        self.leader_peer_id
 2370    }
 2371
 2372    pub fn buffer(&self) -> &Model<MultiBuffer> {
 2373        &self.buffer
 2374    }
 2375
 2376    pub fn workspace(&self) -> Option<View<Workspace>> {
 2377        self.workspace.as_ref()?.0.upgrade()
 2378    }
 2379
 2380    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
 2381        self.buffer().read(cx).title(cx)
 2382    }
 2383
 2384    pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
 2385        let git_blame_gutter_max_author_length = self
 2386            .render_git_blame_gutter(cx)
 2387            .then(|| {
 2388                if let Some(blame) = self.blame.as_ref() {
 2389                    let max_author_length =
 2390                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 2391                    Some(max_author_length)
 2392                } else {
 2393                    None
 2394                }
 2395            })
 2396            .flatten();
 2397
 2398        EditorSnapshot {
 2399            mode: self.mode,
 2400            show_gutter: self.show_gutter,
 2401            show_line_numbers: self.show_line_numbers,
 2402            show_git_diff_gutter: self.show_git_diff_gutter,
 2403            show_code_actions: self.show_code_actions,
 2404            show_runnables: self.show_runnables,
 2405            git_blame_gutter_max_author_length,
 2406            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 2407            scroll_anchor: self.scroll_manager.anchor(),
 2408            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 2409            placeholder_text: self.placeholder_text.clone(),
 2410            is_focused: self.focus_handle.is_focused(cx),
 2411            current_line_highlight: self
 2412                .current_line_highlight
 2413                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 2414            gutter_hovered: self.gutter_hovered,
 2415        }
 2416    }
 2417
 2418    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
 2419        self.buffer.read(cx).language_at(point, cx)
 2420    }
 2421
 2422    pub fn file_at<T: ToOffset>(
 2423        &self,
 2424        point: T,
 2425        cx: &AppContext,
 2426    ) -> Option<Arc<dyn language::File>> {
 2427        self.buffer.read(cx).read(cx).file_at(point).cloned()
 2428    }
 2429
 2430    pub fn active_excerpt(
 2431        &self,
 2432        cx: &AppContext,
 2433    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
 2434        self.buffer
 2435            .read(cx)
 2436            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 2437    }
 2438
 2439    pub fn mode(&self) -> EditorMode {
 2440        self.mode
 2441    }
 2442
 2443    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 2444        self.collaboration_hub.as_deref()
 2445    }
 2446
 2447    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 2448        self.collaboration_hub = Some(hub);
 2449    }
 2450
 2451    pub fn set_custom_context_menu(
 2452        &mut self,
 2453        f: impl 'static
 2454            + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
 2455    ) {
 2456        self.custom_context_menu = Some(Box::new(f))
 2457    }
 2458
 2459    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 2460        self.completion_provider = provider;
 2461    }
 2462
 2463    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 2464        self.semantics_provider.clone()
 2465    }
 2466
 2467    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 2468        self.semantics_provider = provider;
 2469    }
 2470
 2471    pub fn set_inline_completion_provider<T>(
 2472        &mut self,
 2473        provider: Option<Model<T>>,
 2474        cx: &mut ViewContext<Self>,
 2475    ) where
 2476        T: InlineCompletionProvider,
 2477    {
 2478        self.inline_completion_provider =
 2479            provider.map(|provider| RegisteredInlineCompletionProvider {
 2480                _subscription: cx.observe(&provider, |this, _, cx| {
 2481                    if this.focus_handle.is_focused(cx) {
 2482                        this.update_visible_inline_completion(cx);
 2483                    }
 2484                }),
 2485                provider: Arc::new(provider),
 2486            });
 2487        self.refresh_inline_completion(false, false, cx);
 2488    }
 2489
 2490    pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
 2491        self.placeholder_text.as_deref()
 2492    }
 2493
 2494    pub fn set_placeholder_text(
 2495        &mut self,
 2496        placeholder_text: impl Into<Arc<str>>,
 2497        cx: &mut ViewContext<Self>,
 2498    ) {
 2499        let placeholder_text = Some(placeholder_text.into());
 2500        if self.placeholder_text != placeholder_text {
 2501            self.placeholder_text = placeholder_text;
 2502            cx.notify();
 2503        }
 2504    }
 2505
 2506    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
 2507        self.cursor_shape = cursor_shape;
 2508
 2509        // Disrupt blink for immediate user feedback that the cursor shape has changed
 2510        self.blink_manager.update(cx, BlinkManager::show_cursor);
 2511
 2512        cx.notify();
 2513    }
 2514
 2515    pub fn set_current_line_highlight(
 2516        &mut self,
 2517        current_line_highlight: Option<CurrentLineHighlight>,
 2518    ) {
 2519        self.current_line_highlight = current_line_highlight;
 2520    }
 2521
 2522    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 2523        self.collapse_matches = collapse_matches;
 2524    }
 2525
 2526    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 2527        if self.collapse_matches {
 2528            return range.start..range.start;
 2529        }
 2530        range.clone()
 2531    }
 2532
 2533    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
 2534        if self.display_map.read(cx).clip_at_line_ends != clip {
 2535            self.display_map
 2536                .update(cx, |map, _| map.clip_at_line_ends = clip);
 2537        }
 2538    }
 2539
 2540    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 2541        self.input_enabled = input_enabled;
 2542    }
 2543
 2544    pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
 2545        self.enable_inline_completions = enabled;
 2546    }
 2547
 2548    pub fn set_autoindent(&mut self, autoindent: bool) {
 2549        if autoindent {
 2550            self.autoindent_mode = Some(AutoindentMode::EachLine);
 2551        } else {
 2552            self.autoindent_mode = None;
 2553        }
 2554    }
 2555
 2556    pub fn read_only(&self, cx: &AppContext) -> bool {
 2557        self.read_only || self.buffer.read(cx).read_only()
 2558    }
 2559
 2560    pub fn set_read_only(&mut self, read_only: bool) {
 2561        self.read_only = read_only;
 2562    }
 2563
 2564    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 2565        self.use_autoclose = autoclose;
 2566    }
 2567
 2568    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 2569        self.use_auto_surround = auto_surround;
 2570    }
 2571
 2572    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 2573        self.auto_replace_emoji_shortcode = auto_replace;
 2574    }
 2575
 2576    pub fn toggle_inline_completions(
 2577        &mut self,
 2578        _: &ToggleInlineCompletions,
 2579        cx: &mut ViewContext<Self>,
 2580    ) {
 2581        if self.show_inline_completions_override.is_some() {
 2582            self.set_show_inline_completions(None, cx);
 2583        } else {
 2584            let cursor = self.selections.newest_anchor().head();
 2585            if let Some((buffer, cursor_buffer_position)) =
 2586                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 2587            {
 2588                let show_inline_completions =
 2589                    !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
 2590                self.set_show_inline_completions(Some(show_inline_completions), cx);
 2591            }
 2592        }
 2593    }
 2594
 2595    pub fn set_show_inline_completions(
 2596        &mut self,
 2597        show_inline_completions: Option<bool>,
 2598        cx: &mut ViewContext<Self>,
 2599    ) {
 2600        self.show_inline_completions_override = show_inline_completions;
 2601        self.refresh_inline_completion(false, true, cx);
 2602    }
 2603
 2604    fn should_show_inline_completions(
 2605        &self,
 2606        buffer: &Model<Buffer>,
 2607        buffer_position: language::Anchor,
 2608        cx: &AppContext,
 2609    ) -> bool {
 2610        if !self.snippet_stack.is_empty() {
 2611            return false;
 2612        }
 2613
 2614        if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
 2615            return false;
 2616        }
 2617
 2618        if let Some(provider) = self.inline_completion_provider() {
 2619            if let Some(show_inline_completions) = self.show_inline_completions_override {
 2620                show_inline_completions
 2621            } else {
 2622                self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
 2623            }
 2624        } else {
 2625            false
 2626        }
 2627    }
 2628
 2629    fn inline_completions_disabled_in_scope(
 2630        &self,
 2631        buffer: &Model<Buffer>,
 2632        buffer_position: language::Anchor,
 2633        cx: &AppContext,
 2634    ) -> bool {
 2635        let snapshot = buffer.read(cx).snapshot();
 2636        let settings = snapshot.settings_at(buffer_position, cx);
 2637
 2638        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 2639            return false;
 2640        };
 2641
 2642        scope.override_name().map_or(false, |scope_name| {
 2643            settings
 2644                .inline_completions_disabled_in
 2645                .iter()
 2646                .any(|s| s == scope_name)
 2647        })
 2648    }
 2649
 2650    pub fn set_use_modal_editing(&mut self, to: bool) {
 2651        self.use_modal_editing = to;
 2652    }
 2653
 2654    pub fn use_modal_editing(&self) -> bool {
 2655        self.use_modal_editing
 2656    }
 2657
 2658    fn selections_did_change(
 2659        &mut self,
 2660        local: bool,
 2661        old_cursor_position: &Anchor,
 2662        show_completions: bool,
 2663        cx: &mut ViewContext<Self>,
 2664    ) {
 2665        cx.invalidate_character_coordinates();
 2666
 2667        // Copy selections to primary selection buffer
 2668        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 2669        if local {
 2670            let selections = self.selections.all::<usize>(cx);
 2671            let buffer_handle = self.buffer.read(cx).read(cx);
 2672
 2673            let mut text = String::new();
 2674            for (index, selection) in selections.iter().enumerate() {
 2675                let text_for_selection = buffer_handle
 2676                    .text_for_range(selection.start..selection.end)
 2677                    .collect::<String>();
 2678
 2679                text.push_str(&text_for_selection);
 2680                if index != selections.len() - 1 {
 2681                    text.push('\n');
 2682                }
 2683            }
 2684
 2685            if !text.is_empty() {
 2686                cx.write_to_primary(ClipboardItem::new_string(text));
 2687            }
 2688        }
 2689
 2690        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
 2691            self.buffer.update(cx, |buffer, cx| {
 2692                buffer.set_active_selections(
 2693                    &self.selections.disjoint_anchors(),
 2694                    self.selections.line_mode,
 2695                    self.cursor_shape,
 2696                    cx,
 2697                )
 2698            });
 2699        }
 2700        let display_map = self
 2701            .display_map
 2702            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2703        let buffer = &display_map.buffer_snapshot;
 2704        self.add_selections_state = None;
 2705        self.select_next_state = None;
 2706        self.select_prev_state = None;
 2707        self.select_larger_syntax_node_stack.clear();
 2708        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2709        self.snippet_stack
 2710            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2711        self.take_rename(false, cx);
 2712
 2713        let new_cursor_position = self.selections.newest_anchor().head();
 2714
 2715        self.push_to_nav_history(
 2716            *old_cursor_position,
 2717            Some(new_cursor_position.to_point(buffer)),
 2718            cx,
 2719        );
 2720
 2721        if local {
 2722            let new_cursor_position = self.selections.newest_anchor().head();
 2723            let mut context_menu = self.context_menu.write();
 2724            let completion_menu = match context_menu.as_ref() {
 2725                Some(ContextMenu::Completions(menu)) => Some(menu),
 2726
 2727                _ => {
 2728                    *context_menu = None;
 2729                    None
 2730                }
 2731            };
 2732
 2733            if let Some(completion_menu) = completion_menu {
 2734                let cursor_position = new_cursor_position.to_offset(buffer);
 2735                let (word_range, kind) =
 2736                    buffer.surrounding_word(completion_menu.initial_position, true);
 2737                if kind == Some(CharKind::Word)
 2738                    && word_range.to_inclusive().contains(&cursor_position)
 2739                {
 2740                    let mut completion_menu = completion_menu.clone();
 2741                    drop(context_menu);
 2742
 2743                    let query = Self::completion_query(buffer, cursor_position);
 2744                    cx.spawn(move |this, mut cx| async move {
 2745                        completion_menu
 2746                            .filter(query.as_deref(), cx.background_executor().clone())
 2747                            .await;
 2748
 2749                        this.update(&mut cx, |this, cx| {
 2750                            let mut context_menu = this.context_menu.write();
 2751                            let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
 2752                                return;
 2753                            };
 2754
 2755                            if menu.id > completion_menu.id {
 2756                                return;
 2757                            }
 2758
 2759                            *context_menu = Some(ContextMenu::Completions(completion_menu));
 2760                            drop(context_menu);
 2761                            cx.notify();
 2762                        })
 2763                    })
 2764                    .detach();
 2765
 2766                    if show_completions {
 2767                        self.show_completions(&ShowCompletions { trigger: None }, cx);
 2768                    }
 2769                } else {
 2770                    drop(context_menu);
 2771                    self.hide_context_menu(cx);
 2772                }
 2773            } else {
 2774                drop(context_menu);
 2775            }
 2776
 2777            hide_hover(self, cx);
 2778
 2779            if old_cursor_position.to_display_point(&display_map).row()
 2780                != new_cursor_position.to_display_point(&display_map).row()
 2781            {
 2782                self.available_code_actions.take();
 2783            }
 2784            self.refresh_code_actions(cx);
 2785            self.refresh_document_highlights(cx);
 2786            refresh_matching_bracket_highlights(self, cx);
 2787            self.discard_inline_completion(false, cx);
 2788            linked_editing_ranges::refresh_linked_ranges(self, cx);
 2789            if self.git_blame_inline_enabled {
 2790                self.start_inline_blame_timer(cx);
 2791            }
 2792        }
 2793
 2794        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2795        cx.emit(EditorEvent::SelectionsChanged { local });
 2796
 2797        if self.selections.disjoint_anchors().len() == 1 {
 2798            cx.emit(SearchEvent::ActiveMatchChanged)
 2799        }
 2800        cx.notify();
 2801    }
 2802
 2803    pub fn change_selections<R>(
 2804        &mut self,
 2805        autoscroll: Option<Autoscroll>,
 2806        cx: &mut ViewContext<Self>,
 2807        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2808    ) -> R {
 2809        self.change_selections_inner(autoscroll, true, cx, change)
 2810    }
 2811
 2812    pub fn change_selections_inner<R>(
 2813        &mut self,
 2814        autoscroll: Option<Autoscroll>,
 2815        request_completions: bool,
 2816        cx: &mut ViewContext<Self>,
 2817        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2818    ) -> R {
 2819        let old_cursor_position = self.selections.newest_anchor().head();
 2820        self.push_to_selection_history();
 2821
 2822        let (changed, result) = self.selections.change_with(cx, change);
 2823
 2824        if changed {
 2825            if let Some(autoscroll) = autoscroll {
 2826                self.request_autoscroll(autoscroll, cx);
 2827            }
 2828            self.selections_did_change(true, &old_cursor_position, request_completions, cx);
 2829
 2830            if self.should_open_signature_help_automatically(
 2831                &old_cursor_position,
 2832                self.signature_help_state.backspace_pressed(),
 2833                cx,
 2834            ) {
 2835                self.show_signature_help(&ShowSignatureHelp, cx);
 2836            }
 2837            self.signature_help_state.set_backspace_pressed(false);
 2838        }
 2839
 2840        result
 2841    }
 2842
 2843    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2844    where
 2845        I: IntoIterator<Item = (Range<S>, T)>,
 2846        S: ToOffset,
 2847        T: Into<Arc<str>>,
 2848    {
 2849        if self.read_only(cx) {
 2850            return;
 2851        }
 2852
 2853        self.buffer
 2854            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2855    }
 2856
 2857    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2858    where
 2859        I: IntoIterator<Item = (Range<S>, T)>,
 2860        S: ToOffset,
 2861        T: Into<Arc<str>>,
 2862    {
 2863        if self.read_only(cx) {
 2864            return;
 2865        }
 2866
 2867        self.buffer.update(cx, |buffer, cx| {
 2868            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2869        });
 2870    }
 2871
 2872    pub fn edit_with_block_indent<I, S, T>(
 2873        &mut self,
 2874        edits: I,
 2875        original_indent_columns: Vec<u32>,
 2876        cx: &mut ViewContext<Self>,
 2877    ) where
 2878        I: IntoIterator<Item = (Range<S>, T)>,
 2879        S: ToOffset,
 2880        T: Into<Arc<str>>,
 2881    {
 2882        if self.read_only(cx) {
 2883            return;
 2884        }
 2885
 2886        self.buffer.update(cx, |buffer, cx| {
 2887            buffer.edit(
 2888                edits,
 2889                Some(AutoindentMode::Block {
 2890                    original_indent_columns,
 2891                }),
 2892                cx,
 2893            )
 2894        });
 2895    }
 2896
 2897    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
 2898        self.hide_context_menu(cx);
 2899
 2900        match phase {
 2901            SelectPhase::Begin {
 2902                position,
 2903                add,
 2904                click_count,
 2905            } => self.begin_selection(position, add, click_count, cx),
 2906            SelectPhase::BeginColumnar {
 2907                position,
 2908                goal_column,
 2909                reset,
 2910            } => self.begin_columnar_selection(position, goal_column, reset, cx),
 2911            SelectPhase::Extend {
 2912                position,
 2913                click_count,
 2914            } => self.extend_selection(position, click_count, cx),
 2915            SelectPhase::Update {
 2916                position,
 2917                goal_column,
 2918                scroll_delta,
 2919            } => self.update_selection(position, goal_column, scroll_delta, cx),
 2920            SelectPhase::End => self.end_selection(cx),
 2921        }
 2922    }
 2923
 2924    fn extend_selection(
 2925        &mut self,
 2926        position: DisplayPoint,
 2927        click_count: usize,
 2928        cx: &mut ViewContext<Self>,
 2929    ) {
 2930        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2931        let tail = self.selections.newest::<usize>(cx).tail();
 2932        self.begin_selection(position, false, click_count, cx);
 2933
 2934        let position = position.to_offset(&display_map, Bias::Left);
 2935        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2936
 2937        let mut pending_selection = self
 2938            .selections
 2939            .pending_anchor()
 2940            .expect("extend_selection not called with pending selection");
 2941        if position >= tail {
 2942            pending_selection.start = tail_anchor;
 2943        } else {
 2944            pending_selection.end = tail_anchor;
 2945            pending_selection.reversed = true;
 2946        }
 2947
 2948        let mut pending_mode = self.selections.pending_mode().unwrap();
 2949        match &mut pending_mode {
 2950            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2951            _ => {}
 2952        }
 2953
 2954        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 2955            s.set_pending(pending_selection, pending_mode)
 2956        });
 2957    }
 2958
 2959    fn begin_selection(
 2960        &mut self,
 2961        position: DisplayPoint,
 2962        add: bool,
 2963        click_count: usize,
 2964        cx: &mut ViewContext<Self>,
 2965    ) {
 2966        if !self.focus_handle.is_focused(cx) {
 2967            self.last_focused_descendant = None;
 2968            cx.focus(&self.focus_handle);
 2969        }
 2970
 2971        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2972        let buffer = &display_map.buffer_snapshot;
 2973        let newest_selection = self.selections.newest_anchor().clone();
 2974        let position = display_map.clip_point(position, Bias::Left);
 2975
 2976        let start;
 2977        let end;
 2978        let mode;
 2979        let auto_scroll;
 2980        match click_count {
 2981            1 => {
 2982                start = buffer.anchor_before(position.to_point(&display_map));
 2983                end = start;
 2984                mode = SelectMode::Character;
 2985                auto_scroll = true;
 2986            }
 2987            2 => {
 2988                let range = movement::surrounding_word(&display_map, position);
 2989                start = buffer.anchor_before(range.start.to_point(&display_map));
 2990                end = buffer.anchor_before(range.end.to_point(&display_map));
 2991                mode = SelectMode::Word(start..end);
 2992                auto_scroll = true;
 2993            }
 2994            3 => {
 2995                let position = display_map
 2996                    .clip_point(position, Bias::Left)
 2997                    .to_point(&display_map);
 2998                let line_start = display_map.prev_line_boundary(position).0;
 2999                let next_line_start = buffer.clip_point(
 3000                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 3001                    Bias::Left,
 3002                );
 3003                start = buffer.anchor_before(line_start);
 3004                end = buffer.anchor_before(next_line_start);
 3005                mode = SelectMode::Line(start..end);
 3006                auto_scroll = true;
 3007            }
 3008            _ => {
 3009                start = buffer.anchor_before(0);
 3010                end = buffer.anchor_before(buffer.len());
 3011                mode = SelectMode::All;
 3012                auto_scroll = false;
 3013            }
 3014        }
 3015
 3016        let point_to_delete: Option<usize> = {
 3017            let selected_points: Vec<Selection<Point>> =
 3018                self.selections.disjoint_in_range(start..end, cx);
 3019
 3020            if !add || click_count > 1 {
 3021                None
 3022            } else if !selected_points.is_empty() {
 3023                Some(selected_points[0].id)
 3024            } else {
 3025                let clicked_point_already_selected =
 3026                    self.selections.disjoint.iter().find(|selection| {
 3027                        selection.start.to_point(buffer) == start.to_point(buffer)
 3028                            || selection.end.to_point(buffer) == end.to_point(buffer)
 3029                    });
 3030
 3031                clicked_point_already_selected.map(|selection| selection.id)
 3032            }
 3033        };
 3034
 3035        let selections_count = self.selections.count();
 3036
 3037        self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
 3038            if let Some(point_to_delete) = point_to_delete {
 3039                s.delete(point_to_delete);
 3040
 3041                if selections_count == 1 {
 3042                    s.set_pending_anchor_range(start..end, mode);
 3043                }
 3044            } else {
 3045                if !add {
 3046                    s.clear_disjoint();
 3047                } else if click_count > 1 {
 3048                    s.delete(newest_selection.id)
 3049                }
 3050
 3051                s.set_pending_anchor_range(start..end, mode);
 3052            }
 3053        });
 3054    }
 3055
 3056    fn begin_columnar_selection(
 3057        &mut self,
 3058        position: DisplayPoint,
 3059        goal_column: u32,
 3060        reset: bool,
 3061        cx: &mut ViewContext<Self>,
 3062    ) {
 3063        if !self.focus_handle.is_focused(cx) {
 3064            self.last_focused_descendant = None;
 3065            cx.focus(&self.focus_handle);
 3066        }
 3067
 3068        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 3069
 3070        if reset {
 3071            let pointer_position = display_map
 3072                .buffer_snapshot
 3073                .anchor_before(position.to_point(&display_map));
 3074
 3075            self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 3076                s.clear_disjoint();
 3077                s.set_pending_anchor_range(
 3078                    pointer_position..pointer_position,
 3079                    SelectMode::Character,
 3080                );
 3081            });
 3082        }
 3083
 3084        let tail = self.selections.newest::<Point>(cx).tail();
 3085        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 3086
 3087        if !reset {
 3088            self.select_columns(
 3089                tail.to_display_point(&display_map),
 3090                position,
 3091                goal_column,
 3092                &display_map,
 3093                cx,
 3094            );
 3095        }
 3096    }
 3097
 3098    fn update_selection(
 3099        &mut self,
 3100        position: DisplayPoint,
 3101        goal_column: u32,
 3102        scroll_delta: gpui::Point<f32>,
 3103        cx: &mut ViewContext<Self>,
 3104    ) {
 3105        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 3106
 3107        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 3108            let tail = tail.to_display_point(&display_map);
 3109            self.select_columns(tail, position, goal_column, &display_map, cx);
 3110        } else if let Some(mut pending) = self.selections.pending_anchor() {
 3111            let buffer = self.buffer.read(cx).snapshot(cx);
 3112            let head;
 3113            let tail;
 3114            let mode = self.selections.pending_mode().unwrap();
 3115            match &mode {
 3116                SelectMode::Character => {
 3117                    head = position.to_point(&display_map);
 3118                    tail = pending.tail().to_point(&buffer);
 3119                }
 3120                SelectMode::Word(original_range) => {
 3121                    let original_display_range = original_range.start.to_display_point(&display_map)
 3122                        ..original_range.end.to_display_point(&display_map);
 3123                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 3124                        ..original_display_range.end.to_point(&display_map);
 3125                    if movement::is_inside_word(&display_map, position)
 3126                        || original_display_range.contains(&position)
 3127                    {
 3128                        let word_range = movement::surrounding_word(&display_map, position);
 3129                        if word_range.start < original_display_range.start {
 3130                            head = word_range.start.to_point(&display_map);
 3131                        } else {
 3132                            head = word_range.end.to_point(&display_map);
 3133                        }
 3134                    } else {
 3135                        head = position.to_point(&display_map);
 3136                    }
 3137
 3138                    if head <= original_buffer_range.start {
 3139                        tail = original_buffer_range.end;
 3140                    } else {
 3141                        tail = original_buffer_range.start;
 3142                    }
 3143                }
 3144                SelectMode::Line(original_range) => {
 3145                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 3146
 3147                    let position = display_map
 3148                        .clip_point(position, Bias::Left)
 3149                        .to_point(&display_map);
 3150                    let line_start = display_map.prev_line_boundary(position).0;
 3151                    let next_line_start = buffer.clip_point(
 3152                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 3153                        Bias::Left,
 3154                    );
 3155
 3156                    if line_start < original_range.start {
 3157                        head = line_start
 3158                    } else {
 3159                        head = next_line_start
 3160                    }
 3161
 3162                    if head <= original_range.start {
 3163                        tail = original_range.end;
 3164                    } else {
 3165                        tail = original_range.start;
 3166                    }
 3167                }
 3168                SelectMode::All => {
 3169                    return;
 3170                }
 3171            };
 3172
 3173            if head < tail {
 3174                pending.start = buffer.anchor_before(head);
 3175                pending.end = buffer.anchor_before(tail);
 3176                pending.reversed = true;
 3177            } else {
 3178                pending.start = buffer.anchor_before(tail);
 3179                pending.end = buffer.anchor_before(head);
 3180                pending.reversed = false;
 3181            }
 3182
 3183            self.change_selections(None, cx, |s| {
 3184                s.set_pending(pending, mode);
 3185            });
 3186        } else {
 3187            log::error!("update_selection dispatched with no pending selection");
 3188            return;
 3189        }
 3190
 3191        self.apply_scroll_delta(scroll_delta, cx);
 3192        cx.notify();
 3193    }
 3194
 3195    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 3196        self.columnar_selection_tail.take();
 3197        if self.selections.pending_anchor().is_some() {
 3198            let selections = self.selections.all::<usize>(cx);
 3199            self.change_selections(None, cx, |s| {
 3200                s.select(selections);
 3201                s.clear_pending();
 3202            });
 3203        }
 3204    }
 3205
 3206    fn select_columns(
 3207        &mut self,
 3208        tail: DisplayPoint,
 3209        head: DisplayPoint,
 3210        goal_column: u32,
 3211        display_map: &DisplaySnapshot,
 3212        cx: &mut ViewContext<Self>,
 3213    ) {
 3214        let start_row = cmp::min(tail.row(), head.row());
 3215        let end_row = cmp::max(tail.row(), head.row());
 3216        let start_column = cmp::min(tail.column(), goal_column);
 3217        let end_column = cmp::max(tail.column(), goal_column);
 3218        let reversed = start_column < tail.column();
 3219
 3220        let selection_ranges = (start_row.0..=end_row.0)
 3221            .map(DisplayRow)
 3222            .filter_map(|row| {
 3223                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 3224                    let start = display_map
 3225                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 3226                        .to_point(display_map);
 3227                    let end = display_map
 3228                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 3229                        .to_point(display_map);
 3230                    if reversed {
 3231                        Some(end..start)
 3232                    } else {
 3233                        Some(start..end)
 3234                    }
 3235                } else {
 3236                    None
 3237                }
 3238            })
 3239            .collect::<Vec<_>>();
 3240
 3241        self.change_selections(None, cx, |s| {
 3242            s.select_ranges(selection_ranges);
 3243        });
 3244        cx.notify();
 3245    }
 3246
 3247    pub fn has_pending_nonempty_selection(&self) -> bool {
 3248        let pending_nonempty_selection = match self.selections.pending_anchor() {
 3249            Some(Selection { start, end, .. }) => start != end,
 3250            None => false,
 3251        };
 3252
 3253        pending_nonempty_selection
 3254            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 3255    }
 3256
 3257    pub fn has_pending_selection(&self) -> bool {
 3258        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 3259    }
 3260
 3261    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 3262        if self.clear_expanded_diff_hunks(cx) {
 3263            cx.notify();
 3264            return;
 3265        }
 3266        if self.dismiss_menus_and_popups(true, cx) {
 3267            return;
 3268        }
 3269
 3270        if self.mode == EditorMode::Full
 3271            && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
 3272        {
 3273            return;
 3274        }
 3275
 3276        cx.propagate();
 3277    }
 3278
 3279    pub fn dismiss_menus_and_popups(
 3280        &mut self,
 3281        should_report_inline_completion_event: bool,
 3282        cx: &mut ViewContext<Self>,
 3283    ) -> bool {
 3284        if self.take_rename(false, cx).is_some() {
 3285            return true;
 3286        }
 3287
 3288        if hide_hover(self, cx) {
 3289            return true;
 3290        }
 3291
 3292        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 3293            return true;
 3294        }
 3295
 3296        if self.hide_context_menu(cx).is_some() {
 3297            return true;
 3298        }
 3299
 3300        if self.mouse_context_menu.take().is_some() {
 3301            return true;
 3302        }
 3303
 3304        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 3305            return true;
 3306        }
 3307
 3308        if self.snippet_stack.pop().is_some() {
 3309            return true;
 3310        }
 3311
 3312        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 3313            self.dismiss_diagnostics(cx);
 3314            return true;
 3315        }
 3316
 3317        false
 3318    }
 3319
 3320    fn linked_editing_ranges_for(
 3321        &self,
 3322        selection: Range<text::Anchor>,
 3323        cx: &AppContext,
 3324    ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
 3325        if self.linked_edit_ranges.is_empty() {
 3326            return None;
 3327        }
 3328        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 3329            selection.end.buffer_id.and_then(|end_buffer_id| {
 3330                if selection.start.buffer_id != Some(end_buffer_id) {
 3331                    return None;
 3332                }
 3333                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 3334                let snapshot = buffer.read(cx).snapshot();
 3335                self.linked_edit_ranges
 3336                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 3337                    .map(|ranges| (ranges, snapshot, buffer))
 3338            })?;
 3339        use text::ToOffset as TO;
 3340        // find offset from the start of current range to current cursor position
 3341        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 3342
 3343        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 3344        let start_difference = start_offset - start_byte_offset;
 3345        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 3346        let end_difference = end_offset - start_byte_offset;
 3347        // Current range has associated linked ranges.
 3348        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3349        for range in linked_ranges.iter() {
 3350            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 3351            let end_offset = start_offset + end_difference;
 3352            let start_offset = start_offset + start_difference;
 3353            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 3354                continue;
 3355            }
 3356            if self.selections.disjoint_anchor_ranges().iter().any(|s| {
 3357                if s.start.buffer_id != selection.start.buffer_id
 3358                    || s.end.buffer_id != selection.end.buffer_id
 3359                {
 3360                    return false;
 3361                }
 3362                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 3363                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 3364            }) {
 3365                continue;
 3366            }
 3367            let start = buffer_snapshot.anchor_after(start_offset);
 3368            let end = buffer_snapshot.anchor_after(end_offset);
 3369            linked_edits
 3370                .entry(buffer.clone())
 3371                .or_default()
 3372                .push(start..end);
 3373        }
 3374        Some(linked_edits)
 3375    }
 3376
 3377    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3378        let text: Arc<str> = text.into();
 3379
 3380        if self.read_only(cx) {
 3381            return;
 3382        }
 3383
 3384        let selections = self.selections.all_adjusted(cx);
 3385        let mut bracket_inserted = false;
 3386        let mut edits = Vec::new();
 3387        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3388        let mut new_selections = Vec::with_capacity(selections.len());
 3389        let mut new_autoclose_regions = Vec::new();
 3390        let snapshot = self.buffer.read(cx).read(cx);
 3391
 3392        for (selection, autoclose_region) in
 3393            self.selections_with_autoclose_regions(selections, &snapshot)
 3394        {
 3395            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 3396                // Determine if the inserted text matches the opening or closing
 3397                // bracket of any of this language's bracket pairs.
 3398                let mut bracket_pair = None;
 3399                let mut is_bracket_pair_start = false;
 3400                let mut is_bracket_pair_end = false;
 3401                if !text.is_empty() {
 3402                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 3403                    //  and they are removing the character that triggered IME popup.
 3404                    for (pair, enabled) in scope.brackets() {
 3405                        if !pair.close && !pair.surround {
 3406                            continue;
 3407                        }
 3408
 3409                        if enabled && pair.start.ends_with(text.as_ref()) {
 3410                            let prefix_len = pair.start.len() - text.len();
 3411                            let preceding_text_matches_prefix = prefix_len == 0
 3412                                || (selection.start.column >= (prefix_len as u32)
 3413                                    && snapshot.contains_str_at(
 3414                                        Point::new(
 3415                                            selection.start.row,
 3416                                            selection.start.column - (prefix_len as u32),
 3417                                        ),
 3418                                        &pair.start[..prefix_len],
 3419                                    ));
 3420                            if preceding_text_matches_prefix {
 3421                                bracket_pair = Some(pair.clone());
 3422                                is_bracket_pair_start = true;
 3423                                break;
 3424                            }
 3425                        }
 3426                        if pair.end.as_str() == text.as_ref() {
 3427                            bracket_pair = Some(pair.clone());
 3428                            is_bracket_pair_end = true;
 3429                            break;
 3430                        }
 3431                    }
 3432                }
 3433
 3434                if let Some(bracket_pair) = bracket_pair {
 3435                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 3436                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 3437                    let auto_surround =
 3438                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 3439                    if selection.is_empty() {
 3440                        if is_bracket_pair_start {
 3441                            // If the inserted text is a suffix of an opening bracket and the
 3442                            // selection is preceded by the rest of the opening bracket, then
 3443                            // insert the closing bracket.
 3444                            let following_text_allows_autoclose = snapshot
 3445                                .chars_at(selection.start)
 3446                                .next()
 3447                                .map_or(true, |c| scope.should_autoclose_before(c));
 3448
 3449                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 3450                                && bracket_pair.start.len() == 1
 3451                            {
 3452                                let target = bracket_pair.start.chars().next().unwrap();
 3453                                let current_line_count = snapshot
 3454                                    .reversed_chars_at(selection.start)
 3455                                    .take_while(|&c| c != '\n')
 3456                                    .filter(|&c| c == target)
 3457                                    .count();
 3458                                current_line_count % 2 == 1
 3459                            } else {
 3460                                false
 3461                            };
 3462
 3463                            if autoclose
 3464                                && bracket_pair.close
 3465                                && following_text_allows_autoclose
 3466                                && !is_closing_quote
 3467                            {
 3468                                let anchor = snapshot.anchor_before(selection.end);
 3469                                new_selections.push((selection.map(|_| anchor), text.len()));
 3470                                new_autoclose_regions.push((
 3471                                    anchor,
 3472                                    text.len(),
 3473                                    selection.id,
 3474                                    bracket_pair.clone(),
 3475                                ));
 3476                                edits.push((
 3477                                    selection.range(),
 3478                                    format!("{}{}", text, bracket_pair.end).into(),
 3479                                ));
 3480                                bracket_inserted = true;
 3481                                continue;
 3482                            }
 3483                        }
 3484
 3485                        if let Some(region) = autoclose_region {
 3486                            // If the selection is followed by an auto-inserted closing bracket,
 3487                            // then don't insert that closing bracket again; just move the selection
 3488                            // past the closing bracket.
 3489                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3490                                && text.as_ref() == region.pair.end.as_str();
 3491                            if should_skip {
 3492                                let anchor = snapshot.anchor_after(selection.end);
 3493                                new_selections
 3494                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3495                                continue;
 3496                            }
 3497                        }
 3498
 3499                        let always_treat_brackets_as_autoclosed = snapshot
 3500                            .settings_at(selection.start, cx)
 3501                            .always_treat_brackets_as_autoclosed;
 3502                        if always_treat_brackets_as_autoclosed
 3503                            && is_bracket_pair_end
 3504                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3505                        {
 3506                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3507                            // and the inserted text is a closing bracket and the selection is followed
 3508                            // by the closing bracket then move the selection past the closing bracket.
 3509                            let anchor = snapshot.anchor_after(selection.end);
 3510                            new_selections.push((selection.map(|_| anchor), text.len()));
 3511                            continue;
 3512                        }
 3513                    }
 3514                    // If an opening bracket is 1 character long and is typed while
 3515                    // text is selected, then surround that text with the bracket pair.
 3516                    else if auto_surround
 3517                        && bracket_pair.surround
 3518                        && is_bracket_pair_start
 3519                        && bracket_pair.start.chars().count() == 1
 3520                    {
 3521                        edits.push((selection.start..selection.start, text.clone()));
 3522                        edits.push((
 3523                            selection.end..selection.end,
 3524                            bracket_pair.end.as_str().into(),
 3525                        ));
 3526                        bracket_inserted = true;
 3527                        new_selections.push((
 3528                            Selection {
 3529                                id: selection.id,
 3530                                start: snapshot.anchor_after(selection.start),
 3531                                end: snapshot.anchor_before(selection.end),
 3532                                reversed: selection.reversed,
 3533                                goal: selection.goal,
 3534                            },
 3535                            0,
 3536                        ));
 3537                        continue;
 3538                    }
 3539                }
 3540            }
 3541
 3542            if self.auto_replace_emoji_shortcode
 3543                && selection.is_empty()
 3544                && text.as_ref().ends_with(':')
 3545            {
 3546                if let Some(possible_emoji_short_code) =
 3547                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3548                {
 3549                    if !possible_emoji_short_code.is_empty() {
 3550                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3551                            let emoji_shortcode_start = Point::new(
 3552                                selection.start.row,
 3553                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3554                            );
 3555
 3556                            // Remove shortcode from buffer
 3557                            edits.push((
 3558                                emoji_shortcode_start..selection.start,
 3559                                "".to_string().into(),
 3560                            ));
 3561                            new_selections.push((
 3562                                Selection {
 3563                                    id: selection.id,
 3564                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3565                                    end: snapshot.anchor_before(selection.start),
 3566                                    reversed: selection.reversed,
 3567                                    goal: selection.goal,
 3568                                },
 3569                                0,
 3570                            ));
 3571
 3572                            // Insert emoji
 3573                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3574                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3575                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3576
 3577                            continue;
 3578                        }
 3579                    }
 3580                }
 3581            }
 3582
 3583            // If not handling any auto-close operation, then just replace the selected
 3584            // text with the given input and move the selection to the end of the
 3585            // newly inserted text.
 3586            let anchor = snapshot.anchor_after(selection.end);
 3587            if !self.linked_edit_ranges.is_empty() {
 3588                let start_anchor = snapshot.anchor_before(selection.start);
 3589
 3590                let is_word_char = text.chars().next().map_or(true, |char| {
 3591                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3592                    classifier.is_word(char)
 3593                });
 3594
 3595                if is_word_char {
 3596                    if let Some(ranges) = self
 3597                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3598                    {
 3599                        for (buffer, edits) in ranges {
 3600                            linked_edits
 3601                                .entry(buffer.clone())
 3602                                .or_default()
 3603                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3604                        }
 3605                    }
 3606                }
 3607            }
 3608
 3609            new_selections.push((selection.map(|_| anchor), 0));
 3610            edits.push((selection.start..selection.end, text.clone()));
 3611        }
 3612
 3613        drop(snapshot);
 3614
 3615        self.transact(cx, |this, cx| {
 3616            this.buffer.update(cx, |buffer, cx| {
 3617                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3618            });
 3619            for (buffer, edits) in linked_edits {
 3620                buffer.update(cx, |buffer, cx| {
 3621                    let snapshot = buffer.snapshot();
 3622                    let edits = edits
 3623                        .into_iter()
 3624                        .map(|(range, text)| {
 3625                            use text::ToPoint as TP;
 3626                            let end_point = TP::to_point(&range.end, &snapshot);
 3627                            let start_point = TP::to_point(&range.start, &snapshot);
 3628                            (start_point..end_point, text)
 3629                        })
 3630                        .sorted_by_key(|(range, _)| range.start)
 3631                        .collect::<Vec<_>>();
 3632                    buffer.edit(edits, None, cx);
 3633                })
 3634            }
 3635            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3636            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3637            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3638            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3639                .zip(new_selection_deltas)
 3640                .map(|(selection, delta)| Selection {
 3641                    id: selection.id,
 3642                    start: selection.start + delta,
 3643                    end: selection.end + delta,
 3644                    reversed: selection.reversed,
 3645                    goal: SelectionGoal::None,
 3646                })
 3647                .collect::<Vec<_>>();
 3648
 3649            let mut i = 0;
 3650            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3651                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3652                let start = map.buffer_snapshot.anchor_before(position);
 3653                let end = map.buffer_snapshot.anchor_after(position);
 3654                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3655                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3656                        Ordering::Less => i += 1,
 3657                        Ordering::Greater => break,
 3658                        Ordering::Equal => {
 3659                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3660                                Ordering::Less => i += 1,
 3661                                Ordering::Equal => break,
 3662                                Ordering::Greater => break,
 3663                            }
 3664                        }
 3665                    }
 3666                }
 3667                this.autoclose_regions.insert(
 3668                    i,
 3669                    AutocloseRegion {
 3670                        selection_id,
 3671                        range: start..end,
 3672                        pair,
 3673                    },
 3674                );
 3675            }
 3676
 3677            let had_active_inline_completion = this.has_active_inline_completion(cx);
 3678            this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
 3679                s.select(new_selections)
 3680            });
 3681
 3682            if !bracket_inserted {
 3683                if let Some(on_type_format_task) =
 3684                    this.trigger_on_type_formatting(text.to_string(), cx)
 3685                {
 3686                    on_type_format_task.detach_and_log_err(cx);
 3687                }
 3688            }
 3689
 3690            let editor_settings = EditorSettings::get_global(cx);
 3691            if bracket_inserted
 3692                && (editor_settings.auto_signature_help
 3693                    || editor_settings.show_signature_help_after_edits)
 3694            {
 3695                this.show_signature_help(&ShowSignatureHelp, cx);
 3696            }
 3697
 3698            let trigger_in_words = !had_active_inline_completion;
 3699            this.trigger_completion_on_input(&text, trigger_in_words, cx);
 3700            linked_editing_ranges::refresh_linked_ranges(this, cx);
 3701            this.refresh_inline_completion(true, false, cx);
 3702        });
 3703    }
 3704
 3705    fn find_possible_emoji_shortcode_at_position(
 3706        snapshot: &MultiBufferSnapshot,
 3707        position: Point,
 3708    ) -> Option<String> {
 3709        let mut chars = Vec::new();
 3710        let mut found_colon = false;
 3711        for char in snapshot.reversed_chars_at(position).take(100) {
 3712            // Found a possible emoji shortcode in the middle of the buffer
 3713            if found_colon {
 3714                if char.is_whitespace() {
 3715                    chars.reverse();
 3716                    return Some(chars.iter().collect());
 3717                }
 3718                // If the previous character is not a whitespace, we are in the middle of a word
 3719                // and we only want to complete the shortcode if the word is made up of other emojis
 3720                let mut containing_word = String::new();
 3721                for ch in snapshot
 3722                    .reversed_chars_at(position)
 3723                    .skip(chars.len() + 1)
 3724                    .take(100)
 3725                {
 3726                    if ch.is_whitespace() {
 3727                        break;
 3728                    }
 3729                    containing_word.push(ch);
 3730                }
 3731                let containing_word = containing_word.chars().rev().collect::<String>();
 3732                if util::word_consists_of_emojis(containing_word.as_str()) {
 3733                    chars.reverse();
 3734                    return Some(chars.iter().collect());
 3735                }
 3736            }
 3737
 3738            if char.is_whitespace() || !char.is_ascii() {
 3739                return None;
 3740            }
 3741            if char == ':' {
 3742                found_colon = true;
 3743            } else {
 3744                chars.push(char);
 3745            }
 3746        }
 3747        // Found a possible emoji shortcode at the beginning of the buffer
 3748        chars.reverse();
 3749        Some(chars.iter().collect())
 3750    }
 3751
 3752    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 3753        self.transact(cx, |this, cx| {
 3754            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3755                let selections = this.selections.all::<usize>(cx);
 3756                let multi_buffer = this.buffer.read(cx);
 3757                let buffer = multi_buffer.snapshot(cx);
 3758                selections
 3759                    .iter()
 3760                    .map(|selection| {
 3761                        let start_point = selection.start.to_point(&buffer);
 3762                        let mut indent =
 3763                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3764                        indent.len = cmp::min(indent.len, start_point.column);
 3765                        let start = selection.start;
 3766                        let end = selection.end;
 3767                        let selection_is_empty = start == end;
 3768                        let language_scope = buffer.language_scope_at(start);
 3769                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3770                            &language_scope
 3771                        {
 3772                            let leading_whitespace_len = buffer
 3773                                .reversed_chars_at(start)
 3774                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3775                                .map(|c| c.len_utf8())
 3776                                .sum::<usize>();
 3777
 3778                            let trailing_whitespace_len = buffer
 3779                                .chars_at(end)
 3780                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3781                                .map(|c| c.len_utf8())
 3782                                .sum::<usize>();
 3783
 3784                            let insert_extra_newline =
 3785                                language.brackets().any(|(pair, enabled)| {
 3786                                    let pair_start = pair.start.trim_end();
 3787                                    let pair_end = pair.end.trim_start();
 3788
 3789                                    enabled
 3790                                        && pair.newline
 3791                                        && buffer.contains_str_at(
 3792                                            end + trailing_whitespace_len,
 3793                                            pair_end,
 3794                                        )
 3795                                        && buffer.contains_str_at(
 3796                                            (start - leading_whitespace_len)
 3797                                                .saturating_sub(pair_start.len()),
 3798                                            pair_start,
 3799                                        )
 3800                                });
 3801
 3802                            // Comment extension on newline is allowed only for cursor selections
 3803                            let comment_delimiter = maybe!({
 3804                                if !selection_is_empty {
 3805                                    return None;
 3806                                }
 3807
 3808                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3809                                    return None;
 3810                                }
 3811
 3812                                let delimiters = language.line_comment_prefixes();
 3813                                let max_len_of_delimiter =
 3814                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3815                                let (snapshot, range) =
 3816                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3817
 3818                                let mut index_of_first_non_whitespace = 0;
 3819                                let comment_candidate = snapshot
 3820                                    .chars_for_range(range)
 3821                                    .skip_while(|c| {
 3822                                        let should_skip = c.is_whitespace();
 3823                                        if should_skip {
 3824                                            index_of_first_non_whitespace += 1;
 3825                                        }
 3826                                        should_skip
 3827                                    })
 3828                                    .take(max_len_of_delimiter)
 3829                                    .collect::<String>();
 3830                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3831                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3832                                })?;
 3833                                let cursor_is_placed_after_comment_marker =
 3834                                    index_of_first_non_whitespace + comment_prefix.len()
 3835                                        <= start_point.column as usize;
 3836                                if cursor_is_placed_after_comment_marker {
 3837                                    Some(comment_prefix.clone())
 3838                                } else {
 3839                                    None
 3840                                }
 3841                            });
 3842                            (comment_delimiter, insert_extra_newline)
 3843                        } else {
 3844                            (None, false)
 3845                        };
 3846
 3847                        let capacity_for_delimiter = comment_delimiter
 3848                            .as_deref()
 3849                            .map(str::len)
 3850                            .unwrap_or_default();
 3851                        let mut new_text =
 3852                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3853                        new_text.push('\n');
 3854                        new_text.extend(indent.chars());
 3855                        if let Some(delimiter) = &comment_delimiter {
 3856                            new_text.push_str(delimiter);
 3857                        }
 3858                        if insert_extra_newline {
 3859                            new_text = new_text.repeat(2);
 3860                        }
 3861
 3862                        let anchor = buffer.anchor_after(end);
 3863                        let new_selection = selection.map(|_| anchor);
 3864                        (
 3865                            (start..end, new_text),
 3866                            (insert_extra_newline, new_selection),
 3867                        )
 3868                    })
 3869                    .unzip()
 3870            };
 3871
 3872            this.edit_with_autoindent(edits, cx);
 3873            let buffer = this.buffer.read(cx).snapshot(cx);
 3874            let new_selections = selection_fixup_info
 3875                .into_iter()
 3876                .map(|(extra_newline_inserted, new_selection)| {
 3877                    let mut cursor = new_selection.end.to_point(&buffer);
 3878                    if extra_newline_inserted {
 3879                        cursor.row -= 1;
 3880                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3881                    }
 3882                    new_selection.map(|_| cursor)
 3883                })
 3884                .collect();
 3885
 3886            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3887            this.refresh_inline_completion(true, false, cx);
 3888        });
 3889    }
 3890
 3891    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3892        let buffer = self.buffer.read(cx);
 3893        let snapshot = buffer.snapshot(cx);
 3894
 3895        let mut edits = Vec::new();
 3896        let mut rows = Vec::new();
 3897
 3898        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3899            let cursor = selection.head();
 3900            let row = cursor.row;
 3901
 3902            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3903
 3904            let newline = "\n".to_string();
 3905            edits.push((start_of_line..start_of_line, newline));
 3906
 3907            rows.push(row + rows_inserted as u32);
 3908        }
 3909
 3910        self.transact(cx, |editor, cx| {
 3911            editor.edit(edits, cx);
 3912
 3913            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3914                let mut index = 0;
 3915                s.move_cursors_with(|map, _, _| {
 3916                    let row = rows[index];
 3917                    index += 1;
 3918
 3919                    let point = Point::new(row, 0);
 3920                    let boundary = map.next_line_boundary(point).1;
 3921                    let clipped = map.clip_point(boundary, Bias::Left);
 3922
 3923                    (clipped, SelectionGoal::None)
 3924                });
 3925            });
 3926
 3927            let mut indent_edits = Vec::new();
 3928            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3929            for row in rows {
 3930                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3931                for (row, indent) in indents {
 3932                    if indent.len == 0 {
 3933                        continue;
 3934                    }
 3935
 3936                    let text = match indent.kind {
 3937                        IndentKind::Space => " ".repeat(indent.len as usize),
 3938                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3939                    };
 3940                    let point = Point::new(row.0, 0);
 3941                    indent_edits.push((point..point, text));
 3942                }
 3943            }
 3944            editor.edit(indent_edits, cx);
 3945        });
 3946    }
 3947
 3948    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3949        let buffer = self.buffer.read(cx);
 3950        let snapshot = buffer.snapshot(cx);
 3951
 3952        let mut edits = Vec::new();
 3953        let mut rows = Vec::new();
 3954        let mut rows_inserted = 0;
 3955
 3956        for selection in self.selections.all_adjusted(cx) {
 3957            let cursor = selection.head();
 3958            let row = cursor.row;
 3959
 3960            let point = Point::new(row + 1, 0);
 3961            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3962
 3963            let newline = "\n".to_string();
 3964            edits.push((start_of_line..start_of_line, newline));
 3965
 3966            rows_inserted += 1;
 3967            rows.push(row + rows_inserted);
 3968        }
 3969
 3970        self.transact(cx, |editor, cx| {
 3971            editor.edit(edits, cx);
 3972
 3973            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3974                let mut index = 0;
 3975                s.move_cursors_with(|map, _, _| {
 3976                    let row = rows[index];
 3977                    index += 1;
 3978
 3979                    let point = Point::new(row, 0);
 3980                    let boundary = map.next_line_boundary(point).1;
 3981                    let clipped = map.clip_point(boundary, Bias::Left);
 3982
 3983                    (clipped, SelectionGoal::None)
 3984                });
 3985            });
 3986
 3987            let mut indent_edits = Vec::new();
 3988            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3989            for row in rows {
 3990                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3991                for (row, indent) in indents {
 3992                    if indent.len == 0 {
 3993                        continue;
 3994                    }
 3995
 3996                    let text = match indent.kind {
 3997                        IndentKind::Space => " ".repeat(indent.len as usize),
 3998                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3999                    };
 4000                    let point = Point::new(row.0, 0);
 4001                    indent_edits.push((point..point, text));
 4002                }
 4003            }
 4004            editor.edit(indent_edits, cx);
 4005        });
 4006    }
 4007
 4008    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 4009        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 4010            original_indent_columns: Vec::new(),
 4011        });
 4012        self.insert_with_autoindent_mode(text, autoindent, cx);
 4013    }
 4014
 4015    fn insert_with_autoindent_mode(
 4016        &mut self,
 4017        text: &str,
 4018        autoindent_mode: Option<AutoindentMode>,
 4019        cx: &mut ViewContext<Self>,
 4020    ) {
 4021        if self.read_only(cx) {
 4022            return;
 4023        }
 4024
 4025        let text: Arc<str> = text.into();
 4026        self.transact(cx, |this, cx| {
 4027            let old_selections = this.selections.all_adjusted(cx);
 4028            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 4029                let anchors = {
 4030                    let snapshot = buffer.read(cx);
 4031                    old_selections
 4032                        .iter()
 4033                        .map(|s| {
 4034                            let anchor = snapshot.anchor_after(s.head());
 4035                            s.map(|_| anchor)
 4036                        })
 4037                        .collect::<Vec<_>>()
 4038                };
 4039                buffer.edit(
 4040                    old_selections
 4041                        .iter()
 4042                        .map(|s| (s.start..s.end, text.clone())),
 4043                    autoindent_mode,
 4044                    cx,
 4045                );
 4046                anchors
 4047            });
 4048
 4049            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 4050                s.select_anchors(selection_anchors);
 4051            })
 4052        });
 4053    }
 4054
 4055    fn trigger_completion_on_input(
 4056        &mut self,
 4057        text: &str,
 4058        trigger_in_words: bool,
 4059        cx: &mut ViewContext<Self>,
 4060    ) {
 4061        if self.is_completion_trigger(text, trigger_in_words, cx) {
 4062            self.show_completions(
 4063                &ShowCompletions {
 4064                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 4065                },
 4066                cx,
 4067            );
 4068        } else {
 4069            self.hide_context_menu(cx);
 4070        }
 4071    }
 4072
 4073    fn is_completion_trigger(
 4074        &self,
 4075        text: &str,
 4076        trigger_in_words: bool,
 4077        cx: &mut ViewContext<Self>,
 4078    ) -> bool {
 4079        let position = self.selections.newest_anchor().head();
 4080        let multibuffer = self.buffer.read(cx);
 4081        let Some(buffer) = position
 4082            .buffer_id
 4083            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 4084        else {
 4085            return false;
 4086        };
 4087
 4088        if let Some(completion_provider) = &self.completion_provider {
 4089            completion_provider.is_completion_trigger(
 4090                &buffer,
 4091                position.text_anchor,
 4092                text,
 4093                trigger_in_words,
 4094                cx,
 4095            )
 4096        } else {
 4097            false
 4098        }
 4099    }
 4100
 4101    /// If any empty selections is touching the start of its innermost containing autoclose
 4102    /// region, expand it to select the brackets.
 4103    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 4104        let selections = self.selections.all::<usize>(cx);
 4105        let buffer = self.buffer.read(cx).read(cx);
 4106        let new_selections = self
 4107            .selections_with_autoclose_regions(selections, &buffer)
 4108            .map(|(mut selection, region)| {
 4109                if !selection.is_empty() {
 4110                    return selection;
 4111                }
 4112
 4113                if let Some(region) = region {
 4114                    let mut range = region.range.to_offset(&buffer);
 4115                    if selection.start == range.start && range.start >= region.pair.start.len() {
 4116                        range.start -= region.pair.start.len();
 4117                        if buffer.contains_str_at(range.start, &region.pair.start)
 4118                            && buffer.contains_str_at(range.end, &region.pair.end)
 4119                        {
 4120                            range.end += region.pair.end.len();
 4121                            selection.start = range.start;
 4122                            selection.end = range.end;
 4123
 4124                            return selection;
 4125                        }
 4126                    }
 4127                }
 4128
 4129                let always_treat_brackets_as_autoclosed = buffer
 4130                    .settings_at(selection.start, cx)
 4131                    .always_treat_brackets_as_autoclosed;
 4132
 4133                if !always_treat_brackets_as_autoclosed {
 4134                    return selection;
 4135                }
 4136
 4137                if let Some(scope) = buffer.language_scope_at(selection.start) {
 4138                    for (pair, enabled) in scope.brackets() {
 4139                        if !enabled || !pair.close {
 4140                            continue;
 4141                        }
 4142
 4143                        if buffer.contains_str_at(selection.start, &pair.end) {
 4144                            let pair_start_len = pair.start.len();
 4145                            if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
 4146                            {
 4147                                selection.start -= pair_start_len;
 4148                                selection.end += pair.end.len();
 4149
 4150                                return selection;
 4151                            }
 4152                        }
 4153                    }
 4154                }
 4155
 4156                selection
 4157            })
 4158            .collect();
 4159
 4160        drop(buffer);
 4161        self.change_selections(None, cx, |selections| selections.select(new_selections));
 4162    }
 4163
 4164    /// Iterate the given selections, and for each one, find the smallest surrounding
 4165    /// autoclose region. This uses the ordering of the selections and the autoclose
 4166    /// regions to avoid repeated comparisons.
 4167    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 4168        &'a self,
 4169        selections: impl IntoIterator<Item = Selection<D>>,
 4170        buffer: &'a MultiBufferSnapshot,
 4171    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 4172        let mut i = 0;
 4173        let mut regions = self.autoclose_regions.as_slice();
 4174        selections.into_iter().map(move |selection| {
 4175            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 4176
 4177            let mut enclosing = None;
 4178            while let Some(pair_state) = regions.get(i) {
 4179                if pair_state.range.end.to_offset(buffer) < range.start {
 4180                    regions = &regions[i + 1..];
 4181                    i = 0;
 4182                } else if pair_state.range.start.to_offset(buffer) > range.end {
 4183                    break;
 4184                } else {
 4185                    if pair_state.selection_id == selection.id {
 4186                        enclosing = Some(pair_state);
 4187                    }
 4188                    i += 1;
 4189                }
 4190            }
 4191
 4192            (selection, enclosing)
 4193        })
 4194    }
 4195
 4196    /// Remove any autoclose regions that no longer contain their selection.
 4197    fn invalidate_autoclose_regions(
 4198        &mut self,
 4199        mut selections: &[Selection<Anchor>],
 4200        buffer: &MultiBufferSnapshot,
 4201    ) {
 4202        self.autoclose_regions.retain(|state| {
 4203            let mut i = 0;
 4204            while let Some(selection) = selections.get(i) {
 4205                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 4206                    selections = &selections[1..];
 4207                    continue;
 4208                }
 4209                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 4210                    break;
 4211                }
 4212                if selection.id == state.selection_id {
 4213                    return true;
 4214                } else {
 4215                    i += 1;
 4216                }
 4217            }
 4218            false
 4219        });
 4220    }
 4221
 4222    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 4223        let offset = position.to_offset(buffer);
 4224        let (word_range, kind) = buffer.surrounding_word(offset, true);
 4225        if offset > word_range.start && kind == Some(CharKind::Word) {
 4226            Some(
 4227                buffer
 4228                    .text_for_range(word_range.start..offset)
 4229                    .collect::<String>(),
 4230            )
 4231        } else {
 4232            None
 4233        }
 4234    }
 4235
 4236    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 4237        self.refresh_inlay_hints(
 4238            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 4239            cx,
 4240        );
 4241    }
 4242
 4243    pub fn inlay_hints_enabled(&self) -> bool {
 4244        self.inlay_hint_cache.enabled
 4245    }
 4246
 4247    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 4248        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 4249            return;
 4250        }
 4251
 4252        let reason_description = reason.description();
 4253        let ignore_debounce = matches!(
 4254            reason,
 4255            InlayHintRefreshReason::SettingsChange(_)
 4256                | InlayHintRefreshReason::Toggle(_)
 4257                | InlayHintRefreshReason::ExcerptsRemoved(_)
 4258        );
 4259        let (invalidate_cache, required_languages) = match reason {
 4260            InlayHintRefreshReason::Toggle(enabled) => {
 4261                self.inlay_hint_cache.enabled = enabled;
 4262                if enabled {
 4263                    (InvalidationStrategy::RefreshRequested, None)
 4264                } else {
 4265                    self.inlay_hint_cache.clear();
 4266                    self.splice_inlays(
 4267                        self.visible_inlay_hints(cx)
 4268                            .iter()
 4269                            .map(|inlay| inlay.id)
 4270                            .collect(),
 4271                        Vec::new(),
 4272                        cx,
 4273                    );
 4274                    return;
 4275                }
 4276            }
 4277            InlayHintRefreshReason::SettingsChange(new_settings) => {
 4278                match self.inlay_hint_cache.update_settings(
 4279                    &self.buffer,
 4280                    new_settings,
 4281                    self.visible_inlay_hints(cx),
 4282                    cx,
 4283                ) {
 4284                    ControlFlow::Break(Some(InlaySplice {
 4285                        to_remove,
 4286                        to_insert,
 4287                    })) => {
 4288                        self.splice_inlays(to_remove, to_insert, cx);
 4289                        return;
 4290                    }
 4291                    ControlFlow::Break(None) => return,
 4292                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 4293                }
 4294            }
 4295            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 4296                if let Some(InlaySplice {
 4297                    to_remove,
 4298                    to_insert,
 4299                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 4300                {
 4301                    self.splice_inlays(to_remove, to_insert, cx);
 4302                }
 4303                return;
 4304            }
 4305            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 4306            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 4307                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 4308            }
 4309            InlayHintRefreshReason::RefreshRequested => {
 4310                (InvalidationStrategy::RefreshRequested, None)
 4311            }
 4312        };
 4313
 4314        if let Some(InlaySplice {
 4315            to_remove,
 4316            to_insert,
 4317        }) = self.inlay_hint_cache.spawn_hint_refresh(
 4318            reason_description,
 4319            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 4320            invalidate_cache,
 4321            ignore_debounce,
 4322            cx,
 4323        ) {
 4324            self.splice_inlays(to_remove, to_insert, cx);
 4325        }
 4326    }
 4327
 4328    fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
 4329        self.display_map
 4330            .read(cx)
 4331            .current_inlays()
 4332            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 4333            .cloned()
 4334            .collect()
 4335    }
 4336
 4337    pub fn excerpts_for_inlay_hints_query(
 4338        &self,
 4339        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 4340        cx: &mut ViewContext<Editor>,
 4341    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 4342        let Some(project) = self.project.as_ref() else {
 4343            return HashMap::default();
 4344        };
 4345        let project = project.read(cx);
 4346        let multi_buffer = self.buffer().read(cx);
 4347        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 4348        let multi_buffer_visible_start = self
 4349            .scroll_manager
 4350            .anchor()
 4351            .anchor
 4352            .to_point(&multi_buffer_snapshot);
 4353        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 4354            multi_buffer_visible_start
 4355                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 4356            Bias::Left,
 4357        );
 4358        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 4359        multi_buffer
 4360            .range_to_buffer_ranges(multi_buffer_visible_range, cx)
 4361            .into_iter()
 4362            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 4363            .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
 4364                let buffer = buffer_handle.read(cx);
 4365                let buffer_file = project::File::from_dyn(buffer.file())?;
 4366                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 4367                let worktree_entry = buffer_worktree
 4368                    .read(cx)
 4369                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 4370                if worktree_entry.is_ignored {
 4371                    return None;
 4372                }
 4373
 4374                let language = buffer.language()?;
 4375                if let Some(restrict_to_languages) = restrict_to_languages {
 4376                    if !restrict_to_languages.contains(language) {
 4377                        return None;
 4378                    }
 4379                }
 4380                Some((
 4381                    excerpt_id,
 4382                    (
 4383                        buffer_handle,
 4384                        buffer.version().clone(),
 4385                        excerpt_visible_range,
 4386                    ),
 4387                ))
 4388            })
 4389            .collect()
 4390    }
 4391
 4392    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 4393        TextLayoutDetails {
 4394            text_system: cx.text_system().clone(),
 4395            editor_style: self.style.clone().unwrap(),
 4396            rem_size: cx.rem_size(),
 4397            scroll_anchor: self.scroll_manager.anchor(),
 4398            visible_rows: self.visible_line_count(),
 4399            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 4400        }
 4401    }
 4402
 4403    fn splice_inlays(
 4404        &self,
 4405        to_remove: Vec<InlayId>,
 4406        to_insert: Vec<Inlay>,
 4407        cx: &mut ViewContext<Self>,
 4408    ) {
 4409        self.display_map.update(cx, |display_map, cx| {
 4410            display_map.splice_inlays(to_remove, to_insert, cx);
 4411        });
 4412        cx.notify();
 4413    }
 4414
 4415    fn trigger_on_type_formatting(
 4416        &self,
 4417        input: String,
 4418        cx: &mut ViewContext<Self>,
 4419    ) -> Option<Task<Result<()>>> {
 4420        if input.len() != 1 {
 4421            return None;
 4422        }
 4423
 4424        let project = self.project.as_ref()?;
 4425        let position = self.selections.newest_anchor().head();
 4426        let (buffer, buffer_position) = self
 4427            .buffer
 4428            .read(cx)
 4429            .text_anchor_for_position(position, cx)?;
 4430
 4431        let settings = language_settings::language_settings(
 4432            buffer
 4433                .read(cx)
 4434                .language_at(buffer_position)
 4435                .map(|l| l.name()),
 4436            buffer.read(cx).file(),
 4437            cx,
 4438        );
 4439        if !settings.use_on_type_format {
 4440            return None;
 4441        }
 4442
 4443        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 4444        // hence we do LSP request & edit on host side only — add formats to host's history.
 4445        let push_to_lsp_host_history = true;
 4446        // If this is not the host, append its history with new edits.
 4447        let push_to_client_history = project.read(cx).is_via_collab();
 4448
 4449        let on_type_formatting = project.update(cx, |project, cx| {
 4450            project.on_type_format(
 4451                buffer.clone(),
 4452                buffer_position,
 4453                input,
 4454                push_to_lsp_host_history,
 4455                cx,
 4456            )
 4457        });
 4458        Some(cx.spawn(|editor, mut cx| async move {
 4459            if let Some(transaction) = on_type_formatting.await? {
 4460                if push_to_client_history {
 4461                    buffer
 4462                        .update(&mut cx, |buffer, _| {
 4463                            buffer.push_transaction(transaction, Instant::now());
 4464                        })
 4465                        .ok();
 4466                }
 4467                editor.update(&mut cx, |editor, cx| {
 4468                    editor.refresh_document_highlights(cx);
 4469                })?;
 4470            }
 4471            Ok(())
 4472        }))
 4473    }
 4474
 4475    pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
 4476        if self.pending_rename.is_some() {
 4477            return;
 4478        }
 4479
 4480        let Some(provider) = self.completion_provider.as_ref() else {
 4481            return;
 4482        };
 4483
 4484        if !self.snippet_stack.is_empty() && self.context_menu.read().as_ref().is_some() {
 4485            return;
 4486        }
 4487
 4488        let position = self.selections.newest_anchor().head();
 4489        let (buffer, buffer_position) =
 4490            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4491                output
 4492            } else {
 4493                return;
 4494            };
 4495
 4496        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4497        let is_followup_invoke = {
 4498            let context_menu_state = self.context_menu.read();
 4499            matches!(
 4500                context_menu_state.deref(),
 4501                Some(ContextMenu::Completions(_))
 4502            )
 4503        };
 4504        let trigger_kind = match (&options.trigger, is_followup_invoke) {
 4505            (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
 4506            (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4507                CompletionTriggerKind::TRIGGER_CHARACTER
 4508            }
 4509
 4510            _ => CompletionTriggerKind::INVOKED,
 4511        };
 4512        let completion_context = CompletionContext {
 4513            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 4514                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4515                    Some(String::from(trigger))
 4516                } else {
 4517                    None
 4518                }
 4519            }),
 4520            trigger_kind,
 4521        };
 4522        let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
 4523        let sort_completions = provider.sort_completions();
 4524
 4525        let id = post_inc(&mut self.next_completion_id);
 4526        let task = cx.spawn(|this, mut cx| {
 4527            async move {
 4528                this.update(&mut cx, |this, _| {
 4529                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4530                })?;
 4531                let completions = completions.await.log_err();
 4532                let menu = if let Some(completions) = completions {
 4533                    let mut menu = CompletionsMenu::new(
 4534                        id,
 4535                        sort_completions,
 4536                        position,
 4537                        buffer.clone(),
 4538                        completions.into(),
 4539                    );
 4540                    menu.filter(query.as_deref(), cx.background_executor().clone())
 4541                        .await;
 4542
 4543                    if menu.matches.is_empty() {
 4544                        None
 4545                    } else {
 4546                        this.update(&mut cx, |editor, cx| {
 4547                            let completions = menu.completions.clone();
 4548                            let matches = menu.matches.clone();
 4549
 4550                            let delay_ms = EditorSettings::get_global(cx)
 4551                                .completion_documentation_secondary_query_debounce;
 4552                            let delay = Duration::from_millis(delay_ms);
 4553                            editor
 4554                                .completion_documentation_pre_resolve_debounce
 4555                                .fire_new(delay, cx, |editor, cx| {
 4556                                    CompletionsMenu::pre_resolve_completion_documentation(
 4557                                        buffer,
 4558                                        completions,
 4559                                        matches,
 4560                                        editor,
 4561                                        cx,
 4562                                    )
 4563                                });
 4564                        })
 4565                        .ok();
 4566                        Some(menu)
 4567                    }
 4568                } else {
 4569                    None
 4570                };
 4571
 4572                this.update(&mut cx, |this, cx| {
 4573                    let mut context_menu = this.context_menu.write();
 4574                    match context_menu.as_ref() {
 4575                        None => {}
 4576
 4577                        Some(ContextMenu::Completions(prev_menu)) => {
 4578                            if prev_menu.id > id {
 4579                                return;
 4580                            }
 4581                        }
 4582
 4583                        _ => return,
 4584                    }
 4585
 4586                    if this.focus_handle.is_focused(cx) && menu.is_some() {
 4587                        let menu = menu.unwrap();
 4588                        *context_menu = Some(ContextMenu::Completions(menu));
 4589                        drop(context_menu);
 4590                        this.discard_inline_completion(false, cx);
 4591                        cx.notify();
 4592                    } else if this.completion_tasks.len() <= 1 {
 4593                        // If there are no more completion tasks and the last menu was
 4594                        // empty, we should hide it. If it was already hidden, we should
 4595                        // also show the copilot completion when available.
 4596                        drop(context_menu);
 4597                        if this.hide_context_menu(cx).is_none() {
 4598                            this.update_visible_inline_completion(cx);
 4599                        }
 4600                    }
 4601                })?;
 4602
 4603                Ok::<_, anyhow::Error>(())
 4604            }
 4605            .log_err()
 4606        });
 4607
 4608        self.completion_tasks.push((id, task));
 4609    }
 4610
 4611    pub fn confirm_completion(
 4612        &mut self,
 4613        action: &ConfirmCompletion,
 4614        cx: &mut ViewContext<Self>,
 4615    ) -> Option<Task<Result<()>>> {
 4616        self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
 4617    }
 4618
 4619    pub fn compose_completion(
 4620        &mut self,
 4621        action: &ComposeCompletion,
 4622        cx: &mut ViewContext<Self>,
 4623    ) -> Option<Task<Result<()>>> {
 4624        self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
 4625    }
 4626
 4627    fn do_completion(
 4628        &mut self,
 4629        item_ix: Option<usize>,
 4630        intent: CompletionIntent,
 4631        cx: &mut ViewContext<Editor>,
 4632    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 4633        use language::ToOffset as _;
 4634
 4635        let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 4636            menu
 4637        } else {
 4638            return None;
 4639        };
 4640
 4641        let mat = completions_menu
 4642            .matches
 4643            .get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4644        let buffer_handle = completions_menu.buffer;
 4645        let completions = completions_menu.completions.read();
 4646        let completion = completions.get(mat.candidate_id)?;
 4647        cx.stop_propagation();
 4648
 4649        let snippet;
 4650        let text;
 4651
 4652        if completion.is_snippet() {
 4653            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4654            text = snippet.as_ref().unwrap().text.clone();
 4655        } else {
 4656            snippet = None;
 4657            text = completion.new_text.clone();
 4658        };
 4659        let selections = self.selections.all::<usize>(cx);
 4660        let buffer = buffer_handle.read(cx);
 4661        let old_range = completion.old_range.to_offset(buffer);
 4662        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4663
 4664        let newest_selection = self.selections.newest_anchor();
 4665        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4666            return None;
 4667        }
 4668
 4669        let lookbehind = newest_selection
 4670            .start
 4671            .text_anchor
 4672            .to_offset(buffer)
 4673            .saturating_sub(old_range.start);
 4674        let lookahead = old_range
 4675            .end
 4676            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4677        let mut common_prefix_len = old_text
 4678            .bytes()
 4679            .zip(text.bytes())
 4680            .take_while(|(a, b)| a == b)
 4681            .count();
 4682
 4683        let snapshot = self.buffer.read(cx).snapshot(cx);
 4684        let mut range_to_replace: Option<Range<isize>> = None;
 4685        let mut ranges = Vec::new();
 4686        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4687        for selection in &selections {
 4688            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4689                let start = selection.start.saturating_sub(lookbehind);
 4690                let end = selection.end + lookahead;
 4691                if selection.id == newest_selection.id {
 4692                    range_to_replace = Some(
 4693                        ((start + common_prefix_len) as isize - selection.start as isize)
 4694                            ..(end as isize - selection.start as isize),
 4695                    );
 4696                }
 4697                ranges.push(start + common_prefix_len..end);
 4698            } else {
 4699                common_prefix_len = 0;
 4700                ranges.clear();
 4701                ranges.extend(selections.iter().map(|s| {
 4702                    if s.id == newest_selection.id {
 4703                        range_to_replace = Some(
 4704                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4705                                - selection.start as isize
 4706                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4707                                    - selection.start as isize,
 4708                        );
 4709                        old_range.clone()
 4710                    } else {
 4711                        s.start..s.end
 4712                    }
 4713                }));
 4714                break;
 4715            }
 4716            if !self.linked_edit_ranges.is_empty() {
 4717                let start_anchor = snapshot.anchor_before(selection.head());
 4718                let end_anchor = snapshot.anchor_after(selection.tail());
 4719                if let Some(ranges) = self
 4720                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4721                {
 4722                    for (buffer, edits) in ranges {
 4723                        linked_edits.entry(buffer.clone()).or_default().extend(
 4724                            edits
 4725                                .into_iter()
 4726                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4727                        );
 4728                    }
 4729                }
 4730            }
 4731        }
 4732        let text = &text[common_prefix_len..];
 4733
 4734        cx.emit(EditorEvent::InputHandled {
 4735            utf16_range_to_replace: range_to_replace,
 4736            text: text.into(),
 4737        });
 4738
 4739        self.transact(cx, |this, cx| {
 4740            if let Some(mut snippet) = snippet {
 4741                snippet.text = text.to_string();
 4742                for tabstop in snippet
 4743                    .tabstops
 4744                    .iter_mut()
 4745                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4746                {
 4747                    tabstop.start -= common_prefix_len as isize;
 4748                    tabstop.end -= common_prefix_len as isize;
 4749                }
 4750
 4751                this.insert_snippet(&ranges, snippet, cx).log_err();
 4752            } else {
 4753                this.buffer.update(cx, |buffer, cx| {
 4754                    buffer.edit(
 4755                        ranges.iter().map(|range| (range.clone(), text)),
 4756                        this.autoindent_mode.clone(),
 4757                        cx,
 4758                    );
 4759                });
 4760            }
 4761            for (buffer, edits) in linked_edits {
 4762                buffer.update(cx, |buffer, cx| {
 4763                    let snapshot = buffer.snapshot();
 4764                    let edits = edits
 4765                        .into_iter()
 4766                        .map(|(range, text)| {
 4767                            use text::ToPoint as TP;
 4768                            let end_point = TP::to_point(&range.end, &snapshot);
 4769                            let start_point = TP::to_point(&range.start, &snapshot);
 4770                            (start_point..end_point, text)
 4771                        })
 4772                        .sorted_by_key(|(range, _)| range.start)
 4773                        .collect::<Vec<_>>();
 4774                    buffer.edit(edits, None, cx);
 4775                })
 4776            }
 4777
 4778            this.refresh_inline_completion(true, false, cx);
 4779        });
 4780
 4781        let show_new_completions_on_confirm = completion
 4782            .confirm
 4783            .as_ref()
 4784            .map_or(false, |confirm| confirm(intent, cx));
 4785        if show_new_completions_on_confirm {
 4786            self.show_completions(&ShowCompletions { trigger: None }, cx);
 4787        }
 4788
 4789        let provider = self.completion_provider.as_ref()?;
 4790        let apply_edits = provider.apply_additional_edits_for_completion(
 4791            buffer_handle,
 4792            completion.clone(),
 4793            true,
 4794            cx,
 4795        );
 4796
 4797        let editor_settings = EditorSettings::get_global(cx);
 4798        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4799            // After the code completion is finished, users often want to know what signatures are needed.
 4800            // so we should automatically call signature_help
 4801            self.show_signature_help(&ShowSignatureHelp, cx);
 4802        }
 4803
 4804        Some(cx.foreground_executor().spawn(async move {
 4805            apply_edits.await?;
 4806            Ok(())
 4807        }))
 4808    }
 4809
 4810    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 4811        let mut context_menu = self.context_menu.write();
 4812        if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4813            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4814                // Toggle if we're selecting the same one
 4815                *context_menu = None;
 4816                cx.notify();
 4817                return;
 4818            } else {
 4819                // Otherwise, clear it and start a new one
 4820                *context_menu = None;
 4821                cx.notify();
 4822            }
 4823        }
 4824        drop(context_menu);
 4825        let snapshot = self.snapshot(cx);
 4826        let deployed_from_indicator = action.deployed_from_indicator;
 4827        let mut task = self.code_actions_task.take();
 4828        let action = action.clone();
 4829        cx.spawn(|editor, mut cx| async move {
 4830            while let Some(prev_task) = task {
 4831                prev_task.await.log_err();
 4832                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4833            }
 4834
 4835            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 4836                if editor.focus_handle.is_focused(cx) {
 4837                    let multibuffer_point = action
 4838                        .deployed_from_indicator
 4839                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4840                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4841                    let (buffer, buffer_row) = snapshot
 4842                        .buffer_snapshot
 4843                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4844                        .and_then(|(buffer_snapshot, range)| {
 4845                            editor
 4846                                .buffer
 4847                                .read(cx)
 4848                                .buffer(buffer_snapshot.remote_id())
 4849                                .map(|buffer| (buffer, range.start.row))
 4850                        })?;
 4851                    let (_, code_actions) = editor
 4852                        .available_code_actions
 4853                        .clone()
 4854                        .and_then(|(location, code_actions)| {
 4855                            let snapshot = location.buffer.read(cx).snapshot();
 4856                            let point_range = location.range.to_point(&snapshot);
 4857                            let point_range = point_range.start.row..=point_range.end.row;
 4858                            if point_range.contains(&buffer_row) {
 4859                                Some((location, code_actions))
 4860                            } else {
 4861                                None
 4862                            }
 4863                        })
 4864                        .unzip();
 4865                    let buffer_id = buffer.read(cx).remote_id();
 4866                    let tasks = editor
 4867                        .tasks
 4868                        .get(&(buffer_id, buffer_row))
 4869                        .map(|t| Arc::new(t.to_owned()));
 4870                    if tasks.is_none() && code_actions.is_none() {
 4871                        return None;
 4872                    }
 4873
 4874                    editor.completion_tasks.clear();
 4875                    editor.discard_inline_completion(false, cx);
 4876                    let task_context =
 4877                        tasks
 4878                            .as_ref()
 4879                            .zip(editor.project.clone())
 4880                            .map(|(tasks, project)| {
 4881                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4882                            });
 4883
 4884                    Some(cx.spawn(|editor, mut cx| async move {
 4885                        let task_context = match task_context {
 4886                            Some(task_context) => task_context.await,
 4887                            None => None,
 4888                        };
 4889                        let resolved_tasks =
 4890                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4891                                Arc::new(ResolvedTasks {
 4892                                    templates: tasks.resolve(&task_context).collect(),
 4893                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4894                                        multibuffer_point.row,
 4895                                        tasks.column,
 4896                                    )),
 4897                                })
 4898                            });
 4899                        let spawn_straight_away = resolved_tasks
 4900                            .as_ref()
 4901                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4902                            && code_actions
 4903                                .as_ref()
 4904                                .map_or(true, |actions| actions.is_empty());
 4905                        if let Ok(task) = editor.update(&mut cx, |editor, cx| {
 4906                            *editor.context_menu.write() =
 4907                                Some(ContextMenu::CodeActions(CodeActionsMenu {
 4908                                    buffer,
 4909                                    actions: CodeActionContents {
 4910                                        tasks: resolved_tasks,
 4911                                        actions: code_actions,
 4912                                    },
 4913                                    selected_item: Default::default(),
 4914                                    scroll_handle: UniformListScrollHandle::default(),
 4915                                    deployed_from_indicator,
 4916                                }));
 4917                            if spawn_straight_away {
 4918                                if let Some(task) = editor.confirm_code_action(
 4919                                    &ConfirmCodeAction { item_ix: Some(0) },
 4920                                    cx,
 4921                                ) {
 4922                                    cx.notify();
 4923                                    return task;
 4924                                }
 4925                            }
 4926                            cx.notify();
 4927                            Task::ready(Ok(()))
 4928                        }) {
 4929                            task.await
 4930                        } else {
 4931                            Ok(())
 4932                        }
 4933                    }))
 4934                } else {
 4935                    Some(Task::ready(Ok(())))
 4936                }
 4937            })?;
 4938            if let Some(task) = spawned_test_task {
 4939                task.await?;
 4940            }
 4941
 4942            Ok::<_, anyhow::Error>(())
 4943        })
 4944        .detach_and_log_err(cx);
 4945    }
 4946
 4947    pub fn confirm_code_action(
 4948        &mut self,
 4949        action: &ConfirmCodeAction,
 4950        cx: &mut ViewContext<Self>,
 4951    ) -> Option<Task<Result<()>>> {
 4952        let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4953            menu
 4954        } else {
 4955            return None;
 4956        };
 4957        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4958        let action = actions_menu.actions.get(action_ix)?;
 4959        let title = action.label();
 4960        let buffer = actions_menu.buffer;
 4961        let workspace = self.workspace()?;
 4962
 4963        match action {
 4964            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4965                workspace.update(cx, |workspace, cx| {
 4966                    workspace::tasks::schedule_resolved_task(
 4967                        workspace,
 4968                        task_source_kind,
 4969                        resolved_task,
 4970                        false,
 4971                        cx,
 4972                    );
 4973
 4974                    Some(Task::ready(Ok(())))
 4975                })
 4976            }
 4977            CodeActionsItem::CodeAction {
 4978                excerpt_id,
 4979                action,
 4980                provider,
 4981            } => {
 4982                let apply_code_action =
 4983                    provider.apply_code_action(buffer, action, excerpt_id, true, cx);
 4984                let workspace = workspace.downgrade();
 4985                Some(cx.spawn(|editor, cx| async move {
 4986                    let project_transaction = apply_code_action.await?;
 4987                    Self::open_project_transaction(
 4988                        &editor,
 4989                        workspace,
 4990                        project_transaction,
 4991                        title,
 4992                        cx,
 4993                    )
 4994                    .await
 4995                }))
 4996            }
 4997        }
 4998    }
 4999
 5000    pub async fn open_project_transaction(
 5001        this: &WeakView<Editor>,
 5002        workspace: WeakView<Workspace>,
 5003        transaction: ProjectTransaction,
 5004        title: String,
 5005        mut cx: AsyncWindowContext,
 5006    ) -> Result<()> {
 5007        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 5008        cx.update(|cx| {
 5009            entries.sort_unstable_by_key(|(buffer, _)| {
 5010                buffer.read(cx).file().map(|f| f.path().clone())
 5011            });
 5012        })?;
 5013
 5014        // If the project transaction's edits are all contained within this editor, then
 5015        // avoid opening a new editor to display them.
 5016
 5017        if let Some((buffer, transaction)) = entries.first() {
 5018            if entries.len() == 1 {
 5019                let excerpt = this.update(&mut cx, |editor, cx| {
 5020                    editor
 5021                        .buffer()
 5022                        .read(cx)
 5023                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 5024                })?;
 5025                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 5026                    if excerpted_buffer == *buffer {
 5027                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 5028                            let excerpt_range = excerpt_range.to_offset(buffer);
 5029                            buffer
 5030                                .edited_ranges_for_transaction::<usize>(transaction)
 5031                                .all(|range| {
 5032                                    excerpt_range.start <= range.start
 5033                                        && excerpt_range.end >= range.end
 5034                                })
 5035                        })?;
 5036
 5037                        if all_edits_within_excerpt {
 5038                            return Ok(());
 5039                        }
 5040                    }
 5041                }
 5042            }
 5043        } else {
 5044            return Ok(());
 5045        }
 5046
 5047        let mut ranges_to_highlight = Vec::new();
 5048        let excerpt_buffer = cx.new_model(|cx| {
 5049            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 5050            for (buffer_handle, transaction) in &entries {
 5051                let buffer = buffer_handle.read(cx);
 5052                ranges_to_highlight.extend(
 5053                    multibuffer.push_excerpts_with_context_lines(
 5054                        buffer_handle.clone(),
 5055                        buffer
 5056                            .edited_ranges_for_transaction::<usize>(transaction)
 5057                            .collect(),
 5058                        DEFAULT_MULTIBUFFER_CONTEXT,
 5059                        cx,
 5060                    ),
 5061                );
 5062            }
 5063            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 5064            multibuffer
 5065        })?;
 5066
 5067        workspace.update(&mut cx, |workspace, cx| {
 5068            let project = workspace.project().clone();
 5069            let editor =
 5070                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 5071            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 5072            editor.update(cx, |editor, cx| {
 5073                editor.highlight_background::<Self>(
 5074                    &ranges_to_highlight,
 5075                    |theme| theme.editor_highlighted_line_background,
 5076                    cx,
 5077                );
 5078            });
 5079        })?;
 5080
 5081        Ok(())
 5082    }
 5083
 5084    pub fn clear_code_action_providers(&mut self) {
 5085        self.code_action_providers.clear();
 5086        self.available_code_actions.take();
 5087    }
 5088
 5089    pub fn push_code_action_provider(
 5090        &mut self,
 5091        provider: Arc<dyn CodeActionProvider>,
 5092        cx: &mut ViewContext<Self>,
 5093    ) {
 5094        self.code_action_providers.push(provider);
 5095        self.refresh_code_actions(cx);
 5096    }
 5097
 5098    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 5099        let buffer = self.buffer.read(cx);
 5100        let newest_selection = self.selections.newest_anchor().clone();
 5101        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 5102        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 5103        if start_buffer != end_buffer {
 5104            return None;
 5105        }
 5106
 5107        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 5108            cx.background_executor()
 5109                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 5110                .await;
 5111
 5112            let (providers, tasks) = this.update(&mut cx, |this, cx| {
 5113                let providers = this.code_action_providers.clone();
 5114                let tasks = this
 5115                    .code_action_providers
 5116                    .iter()
 5117                    .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
 5118                    .collect::<Vec<_>>();
 5119                (providers, tasks)
 5120            })?;
 5121
 5122            let mut actions = Vec::new();
 5123            for (provider, provider_actions) in
 5124                providers.into_iter().zip(future::join_all(tasks).await)
 5125            {
 5126                if let Some(provider_actions) = provider_actions.log_err() {
 5127                    actions.extend(provider_actions.into_iter().map(|action| {
 5128                        AvailableCodeAction {
 5129                            excerpt_id: newest_selection.start.excerpt_id,
 5130                            action,
 5131                            provider: provider.clone(),
 5132                        }
 5133                    }));
 5134                }
 5135            }
 5136
 5137            this.update(&mut cx, |this, cx| {
 5138                this.available_code_actions = if actions.is_empty() {
 5139                    None
 5140                } else {
 5141                    Some((
 5142                        Location {
 5143                            buffer: start_buffer,
 5144                            range: start..end,
 5145                        },
 5146                        actions.into(),
 5147                    ))
 5148                };
 5149                cx.notify();
 5150            })
 5151        }));
 5152        None
 5153    }
 5154
 5155    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 5156        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 5157            self.show_git_blame_inline = false;
 5158
 5159            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 5160                cx.background_executor().timer(delay).await;
 5161
 5162                this.update(&mut cx, |this, cx| {
 5163                    this.show_git_blame_inline = true;
 5164                    cx.notify();
 5165                })
 5166                .log_err();
 5167            }));
 5168        }
 5169    }
 5170
 5171    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 5172        if self.pending_rename.is_some() {
 5173            return None;
 5174        }
 5175
 5176        let provider = self.semantics_provider.clone()?;
 5177        let buffer = self.buffer.read(cx);
 5178        let newest_selection = self.selections.newest_anchor().clone();
 5179        let cursor_position = newest_selection.head();
 5180        let (cursor_buffer, cursor_buffer_position) =
 5181            buffer.text_anchor_for_position(cursor_position, cx)?;
 5182        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 5183        if cursor_buffer != tail_buffer {
 5184            return None;
 5185        }
 5186
 5187        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 5188            cx.background_executor()
 5189                .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
 5190                .await;
 5191
 5192            let highlights = if let Some(highlights) = cx
 5193                .update(|cx| {
 5194                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 5195                })
 5196                .ok()
 5197                .flatten()
 5198            {
 5199                highlights.await.log_err()
 5200            } else {
 5201                None
 5202            };
 5203
 5204            if let Some(highlights) = highlights {
 5205                this.update(&mut cx, |this, cx| {
 5206                    if this.pending_rename.is_some() {
 5207                        return;
 5208                    }
 5209
 5210                    let buffer_id = cursor_position.buffer_id;
 5211                    let buffer = this.buffer.read(cx);
 5212                    if !buffer
 5213                        .text_anchor_for_position(cursor_position, cx)
 5214                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 5215                    {
 5216                        return;
 5217                    }
 5218
 5219                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 5220                    let mut write_ranges = Vec::new();
 5221                    let mut read_ranges = Vec::new();
 5222                    for highlight in highlights {
 5223                        for (excerpt_id, excerpt_range) in
 5224                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 5225                        {
 5226                            let start = highlight
 5227                                .range
 5228                                .start
 5229                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 5230                            let end = highlight
 5231                                .range
 5232                                .end
 5233                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 5234                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 5235                                continue;
 5236                            }
 5237
 5238                            let range = Anchor {
 5239                                buffer_id,
 5240                                excerpt_id,
 5241                                text_anchor: start,
 5242                            }..Anchor {
 5243                                buffer_id,
 5244                                excerpt_id,
 5245                                text_anchor: end,
 5246                            };
 5247                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 5248                                write_ranges.push(range);
 5249                            } else {
 5250                                read_ranges.push(range);
 5251                            }
 5252                        }
 5253                    }
 5254
 5255                    this.highlight_background::<DocumentHighlightRead>(
 5256                        &read_ranges,
 5257                        |theme| theme.editor_document_highlight_read_background,
 5258                        cx,
 5259                    );
 5260                    this.highlight_background::<DocumentHighlightWrite>(
 5261                        &write_ranges,
 5262                        |theme| theme.editor_document_highlight_write_background,
 5263                        cx,
 5264                    );
 5265                    cx.notify();
 5266                })
 5267                .log_err();
 5268            }
 5269        }));
 5270        None
 5271    }
 5272
 5273    pub fn refresh_inline_completion(
 5274        &mut self,
 5275        debounce: bool,
 5276        user_requested: bool,
 5277        cx: &mut ViewContext<Self>,
 5278    ) -> Option<()> {
 5279        let provider = self.inline_completion_provider()?;
 5280        let cursor = self.selections.newest_anchor().head();
 5281        let (buffer, cursor_buffer_position) =
 5282            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5283
 5284        if !user_requested
 5285            && (!self.enable_inline_completions
 5286                || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx))
 5287        {
 5288            self.discard_inline_completion(false, cx);
 5289            return None;
 5290        }
 5291
 5292        self.update_visible_inline_completion(cx);
 5293        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 5294        Some(())
 5295    }
 5296
 5297    fn cycle_inline_completion(
 5298        &mut self,
 5299        direction: Direction,
 5300        cx: &mut ViewContext<Self>,
 5301    ) -> Option<()> {
 5302        let provider = self.inline_completion_provider()?;
 5303        let cursor = self.selections.newest_anchor().head();
 5304        let (buffer, cursor_buffer_position) =
 5305            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5306        if !self.enable_inline_completions
 5307            || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 5308        {
 5309            return None;
 5310        }
 5311
 5312        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5313        self.update_visible_inline_completion(cx);
 5314
 5315        Some(())
 5316    }
 5317
 5318    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 5319        if !self.has_active_inline_completion(cx) {
 5320            self.refresh_inline_completion(false, true, cx);
 5321            return;
 5322        }
 5323
 5324        self.update_visible_inline_completion(cx);
 5325    }
 5326
 5327    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 5328        self.show_cursor_names(cx);
 5329    }
 5330
 5331    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 5332        self.show_cursor_names = true;
 5333        cx.notify();
 5334        cx.spawn(|this, mut cx| async move {
 5335            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5336            this.update(&mut cx, |this, cx| {
 5337                this.show_cursor_names = false;
 5338                cx.notify()
 5339            })
 5340            .ok()
 5341        })
 5342        .detach();
 5343    }
 5344
 5345    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 5346        if self.has_active_inline_completion(cx) {
 5347            self.cycle_inline_completion(Direction::Next, cx);
 5348        } else {
 5349            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5350            if is_copilot_disabled {
 5351                cx.propagate();
 5352            }
 5353        }
 5354    }
 5355
 5356    pub fn previous_inline_completion(
 5357        &mut self,
 5358        _: &PreviousInlineCompletion,
 5359        cx: &mut ViewContext<Self>,
 5360    ) {
 5361        if self.has_active_inline_completion(cx) {
 5362            self.cycle_inline_completion(Direction::Prev, cx);
 5363        } else {
 5364            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5365            if is_copilot_disabled {
 5366                cx.propagate();
 5367            }
 5368        }
 5369    }
 5370
 5371    pub fn accept_inline_completion(
 5372        &mut self,
 5373        _: &AcceptInlineCompletion,
 5374        cx: &mut ViewContext<Self>,
 5375    ) {
 5376        let Some(completion) = self.take_active_inline_completion(cx) else {
 5377            return;
 5378        };
 5379        if let Some(provider) = self.inline_completion_provider() {
 5380            provider.accept(cx);
 5381        }
 5382
 5383        cx.emit(EditorEvent::InputHandled {
 5384            utf16_range_to_replace: None,
 5385            text: completion.text.to_string().into(),
 5386        });
 5387
 5388        if let Some(range) = completion.delete_range {
 5389            self.change_selections(None, cx, |s| s.select_ranges([range]))
 5390        }
 5391        self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
 5392        self.refresh_inline_completion(true, true, cx);
 5393        cx.notify();
 5394    }
 5395
 5396    pub fn accept_partial_inline_completion(
 5397        &mut self,
 5398        _: &AcceptPartialInlineCompletion,
 5399        cx: &mut ViewContext<Self>,
 5400    ) {
 5401        if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
 5402            if let Some(completion) = self.take_active_inline_completion(cx) {
 5403                let mut partial_completion = completion
 5404                    .text
 5405                    .chars()
 5406                    .by_ref()
 5407                    .take_while(|c| c.is_alphabetic())
 5408                    .collect::<String>();
 5409                if partial_completion.is_empty() {
 5410                    partial_completion = completion
 5411                        .text
 5412                        .chars()
 5413                        .by_ref()
 5414                        .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5415                        .collect::<String>();
 5416                }
 5417
 5418                cx.emit(EditorEvent::InputHandled {
 5419                    utf16_range_to_replace: None,
 5420                    text: partial_completion.clone().into(),
 5421                });
 5422
 5423                if let Some(range) = completion.delete_range {
 5424                    self.change_selections(None, cx, |s| s.select_ranges([range]))
 5425                }
 5426                self.insert_with_autoindent_mode(&partial_completion, None, cx);
 5427
 5428                self.refresh_inline_completion(true, true, cx);
 5429                cx.notify();
 5430            }
 5431        }
 5432    }
 5433
 5434    fn discard_inline_completion(
 5435        &mut self,
 5436        should_report_inline_completion_event: bool,
 5437        cx: &mut ViewContext<Self>,
 5438    ) -> bool {
 5439        if let Some(provider) = self.inline_completion_provider() {
 5440            provider.discard(should_report_inline_completion_event, cx);
 5441        }
 5442
 5443        self.take_active_inline_completion(cx).is_some()
 5444    }
 5445
 5446    pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
 5447        if let Some(completion) = self.active_inline_completion.as_ref() {
 5448            let buffer = self.buffer.read(cx).read(cx);
 5449            completion.position.is_valid(&buffer)
 5450        } else {
 5451            false
 5452        }
 5453    }
 5454
 5455    fn take_active_inline_completion(
 5456        &mut self,
 5457        cx: &mut ViewContext<Self>,
 5458    ) -> Option<CompletionState> {
 5459        let completion = self.active_inline_completion.take()?;
 5460        let render_inlay_ids = completion.render_inlay_ids.clone();
 5461        self.display_map.update(cx, |map, cx| {
 5462            map.splice_inlays(render_inlay_ids, Default::default(), cx);
 5463        });
 5464        let buffer = self.buffer.read(cx).read(cx);
 5465
 5466        if completion.position.is_valid(&buffer) {
 5467            Some(completion)
 5468        } else {
 5469            None
 5470        }
 5471    }
 5472
 5473    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
 5474        let selection = self.selections.newest_anchor();
 5475        let cursor = selection.head();
 5476
 5477        let excerpt_id = cursor.excerpt_id;
 5478
 5479        if self.context_menu.read().is_none()
 5480            && self.completion_tasks.is_empty()
 5481            && selection.start == selection.end
 5482        {
 5483            if let Some(provider) = self.inline_completion_provider() {
 5484                if let Some((buffer, cursor_buffer_position)) =
 5485                    self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5486                {
 5487                    if let Some(proposal) =
 5488                        provider.active_completion_text(&buffer, cursor_buffer_position, cx)
 5489                    {
 5490                        let mut to_remove = Vec::new();
 5491                        if let Some(completion) = self.active_inline_completion.take() {
 5492                            to_remove.extend(completion.render_inlay_ids.iter());
 5493                        }
 5494
 5495                        let to_add = proposal
 5496                            .inlays
 5497                            .iter()
 5498                            .filter_map(|inlay| {
 5499                                let snapshot = self.buffer.read(cx).snapshot(cx);
 5500                                let id = post_inc(&mut self.next_inlay_id);
 5501                                match inlay {
 5502                                    InlayProposal::Hint(position, hint) => {
 5503                                        let position =
 5504                                            snapshot.anchor_in_excerpt(excerpt_id, *position)?;
 5505                                        Some(Inlay::hint(id, position, hint))
 5506                                    }
 5507                                    InlayProposal::Suggestion(position, text) => {
 5508                                        let position =
 5509                                            snapshot.anchor_in_excerpt(excerpt_id, *position)?;
 5510                                        Some(Inlay::suggestion(id, position, text.clone()))
 5511                                    }
 5512                                }
 5513                            })
 5514                            .collect_vec();
 5515
 5516                        self.active_inline_completion = Some(CompletionState {
 5517                            position: cursor,
 5518                            text: proposal.text,
 5519                            delete_range: proposal.delete_range.and_then(|range| {
 5520                                let snapshot = self.buffer.read(cx).snapshot(cx);
 5521                                let start = snapshot.anchor_in_excerpt(excerpt_id, range.start);
 5522                                let end = snapshot.anchor_in_excerpt(excerpt_id, range.end);
 5523                                Some(start?..end?)
 5524                            }),
 5525                            render_inlay_ids: to_add.iter().map(|i| i.id).collect(),
 5526                        });
 5527
 5528                        self.display_map
 5529                            .update(cx, move |map, cx| map.splice_inlays(to_remove, to_add, cx));
 5530
 5531                        cx.notify();
 5532                        return;
 5533                    }
 5534                }
 5535            }
 5536        }
 5537
 5538        self.discard_inline_completion(false, cx);
 5539    }
 5540
 5541    fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5542        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 5543    }
 5544
 5545    fn render_code_actions_indicator(
 5546        &self,
 5547        _style: &EditorStyle,
 5548        row: DisplayRow,
 5549        is_active: bool,
 5550        cx: &mut ViewContext<Self>,
 5551    ) -> Option<IconButton> {
 5552        if self.available_code_actions.is_some() {
 5553            Some(
 5554                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5555                    .shape(ui::IconButtonShape::Square)
 5556                    .icon_size(IconSize::XSmall)
 5557                    .icon_color(Color::Muted)
 5558                    .selected(is_active)
 5559                    .tooltip({
 5560                        let focus_handle = self.focus_handle.clone();
 5561                        move |cx| {
 5562                            Tooltip::for_action_in(
 5563                                "Toggle Code Actions",
 5564                                &ToggleCodeActions {
 5565                                    deployed_from_indicator: None,
 5566                                },
 5567                                &focus_handle,
 5568                                cx,
 5569                            )
 5570                        }
 5571                    })
 5572                    .on_click(cx.listener(move |editor, _e, cx| {
 5573                        editor.focus(cx);
 5574                        editor.toggle_code_actions(
 5575                            &ToggleCodeActions {
 5576                                deployed_from_indicator: Some(row),
 5577                            },
 5578                            cx,
 5579                        );
 5580                    })),
 5581            )
 5582        } else {
 5583            None
 5584        }
 5585    }
 5586
 5587    fn clear_tasks(&mut self) {
 5588        self.tasks.clear()
 5589    }
 5590
 5591    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5592        if self.tasks.insert(key, value).is_some() {
 5593            // This case should hopefully be rare, but just in case...
 5594            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5595        }
 5596    }
 5597
 5598    fn build_tasks_context(
 5599        project: &Model<Project>,
 5600        buffer: &Model<Buffer>,
 5601        buffer_row: u32,
 5602        tasks: &Arc<RunnableTasks>,
 5603        cx: &mut ViewContext<Self>,
 5604    ) -> Task<Option<task::TaskContext>> {
 5605        let position = Point::new(buffer_row, tasks.column);
 5606        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5607        let location = Location {
 5608            buffer: buffer.clone(),
 5609            range: range_start..range_start,
 5610        };
 5611        // Fill in the environmental variables from the tree-sitter captures
 5612        let mut captured_task_variables = TaskVariables::default();
 5613        for (capture_name, value) in tasks.extra_variables.clone() {
 5614            captured_task_variables.insert(
 5615                task::VariableName::Custom(capture_name.into()),
 5616                value.clone(),
 5617            );
 5618        }
 5619        project.update(cx, |project, cx| {
 5620            project.task_store().update(cx, |task_store, cx| {
 5621                task_store.task_context_for_location(captured_task_variables, location, cx)
 5622            })
 5623        })
 5624    }
 5625
 5626    pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
 5627        let Some((workspace, _)) = self.workspace.clone() else {
 5628            return;
 5629        };
 5630        let Some(project) = self.project.clone() else {
 5631            return;
 5632        };
 5633
 5634        // Try to find a closest, enclosing node using tree-sitter that has a
 5635        // task
 5636        let Some((buffer, buffer_row, tasks)) = self
 5637            .find_enclosing_node_task(cx)
 5638            // Or find the task that's closest in row-distance.
 5639            .or_else(|| self.find_closest_task(cx))
 5640        else {
 5641            return;
 5642        };
 5643
 5644        let reveal_strategy = action.reveal;
 5645        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5646        cx.spawn(|_, mut cx| async move {
 5647            let context = task_context.await?;
 5648            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5649
 5650            let resolved = resolved_task.resolved.as_mut()?;
 5651            resolved.reveal = reveal_strategy;
 5652
 5653            workspace
 5654                .update(&mut cx, |workspace, cx| {
 5655                    workspace::tasks::schedule_resolved_task(
 5656                        workspace,
 5657                        task_source_kind,
 5658                        resolved_task,
 5659                        false,
 5660                        cx,
 5661                    );
 5662                })
 5663                .ok()
 5664        })
 5665        .detach();
 5666    }
 5667
 5668    fn find_closest_task(
 5669        &mut self,
 5670        cx: &mut ViewContext<Self>,
 5671    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5672        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5673
 5674        let ((buffer_id, row), tasks) = self
 5675            .tasks
 5676            .iter()
 5677            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5678
 5679        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5680        let tasks = Arc::new(tasks.to_owned());
 5681        Some((buffer, *row, tasks))
 5682    }
 5683
 5684    fn find_enclosing_node_task(
 5685        &mut self,
 5686        cx: &mut ViewContext<Self>,
 5687    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5688        let snapshot = self.buffer.read(cx).snapshot(cx);
 5689        let offset = self.selections.newest::<usize>(cx).head();
 5690        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5691        let buffer_id = excerpt.buffer().remote_id();
 5692
 5693        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5694        let mut cursor = layer.node().walk();
 5695
 5696        while cursor.goto_first_child_for_byte(offset).is_some() {
 5697            if cursor.node().end_byte() == offset {
 5698                cursor.goto_next_sibling();
 5699            }
 5700        }
 5701
 5702        // Ascend to the smallest ancestor that contains the range and has a task.
 5703        loop {
 5704            let node = cursor.node();
 5705            let node_range = node.byte_range();
 5706            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5707
 5708            // Check if this node contains our offset
 5709            if node_range.start <= offset && node_range.end >= offset {
 5710                // If it contains offset, check for task
 5711                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5712                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5713                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5714                }
 5715            }
 5716
 5717            if !cursor.goto_parent() {
 5718                break;
 5719            }
 5720        }
 5721        None
 5722    }
 5723
 5724    fn render_run_indicator(
 5725        &self,
 5726        _style: &EditorStyle,
 5727        is_active: bool,
 5728        row: DisplayRow,
 5729        cx: &mut ViewContext<Self>,
 5730    ) -> IconButton {
 5731        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5732            .shape(ui::IconButtonShape::Square)
 5733            .icon_size(IconSize::XSmall)
 5734            .icon_color(Color::Muted)
 5735            .selected(is_active)
 5736            .on_click(cx.listener(move |editor, _e, cx| {
 5737                editor.focus(cx);
 5738                editor.toggle_code_actions(
 5739                    &ToggleCodeActions {
 5740                        deployed_from_indicator: Some(row),
 5741                    },
 5742                    cx,
 5743                );
 5744            }))
 5745    }
 5746
 5747    pub fn context_menu_visible(&self) -> bool {
 5748        self.context_menu
 5749            .read()
 5750            .as_ref()
 5751            .map_or(false, |menu| menu.visible())
 5752    }
 5753
 5754    fn render_context_menu(
 5755        &self,
 5756        cursor_position: DisplayPoint,
 5757        style: &EditorStyle,
 5758        max_height: Pixels,
 5759        cx: &mut ViewContext<Editor>,
 5760    ) -> Option<(ContextMenuOrigin, AnyElement)> {
 5761        self.context_menu.read().as_ref().map(|menu| {
 5762            menu.render(
 5763                cursor_position,
 5764                style,
 5765                max_height,
 5766                self.workspace.as_ref().map(|(w, _)| w.clone()),
 5767                cx,
 5768            )
 5769        })
 5770    }
 5771
 5772    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
 5773        cx.notify();
 5774        self.completion_tasks.clear();
 5775        let context_menu = self.context_menu.write().take();
 5776        if context_menu.is_some() {
 5777            self.update_visible_inline_completion(cx);
 5778        }
 5779        context_menu
 5780    }
 5781
 5782    fn show_snippet_choices(
 5783        &mut self,
 5784        choices: &Vec<String>,
 5785        selection: Range<Anchor>,
 5786        cx: &mut ViewContext<Self>,
 5787    ) {
 5788        if selection.start.buffer_id.is_none() {
 5789            return;
 5790        }
 5791        let buffer_id = selection.start.buffer_id.unwrap();
 5792        let buffer = self.buffer().read(cx).buffer(buffer_id);
 5793        let id = post_inc(&mut self.next_completion_id);
 5794
 5795        if let Some(buffer) = buffer {
 5796            *self.context_menu.write() = Some(ContextMenu::Completions(
 5797                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer)
 5798                    .suppress_documentation_resolution(),
 5799            ));
 5800        }
 5801    }
 5802
 5803    pub fn insert_snippet(
 5804        &mut self,
 5805        insertion_ranges: &[Range<usize>],
 5806        snippet: Snippet,
 5807        cx: &mut ViewContext<Self>,
 5808    ) -> Result<()> {
 5809        struct Tabstop<T> {
 5810            is_end_tabstop: bool,
 5811            ranges: Vec<Range<T>>,
 5812            choices: Option<Vec<String>>,
 5813        }
 5814
 5815        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5816            let snippet_text: Arc<str> = snippet.text.clone().into();
 5817            buffer.edit(
 5818                insertion_ranges
 5819                    .iter()
 5820                    .cloned()
 5821                    .map(|range| (range, snippet_text.clone())),
 5822                Some(AutoindentMode::EachLine),
 5823                cx,
 5824            );
 5825
 5826            let snapshot = &*buffer.read(cx);
 5827            let snippet = &snippet;
 5828            snippet
 5829                .tabstops
 5830                .iter()
 5831                .map(|tabstop| {
 5832                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 5833                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5834                    });
 5835                    let mut tabstop_ranges = tabstop
 5836                        .ranges
 5837                        .iter()
 5838                        .flat_map(|tabstop_range| {
 5839                            let mut delta = 0_isize;
 5840                            insertion_ranges.iter().map(move |insertion_range| {
 5841                                let insertion_start = insertion_range.start as isize + delta;
 5842                                delta +=
 5843                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5844
 5845                                let start = ((insertion_start + tabstop_range.start) as usize)
 5846                                    .min(snapshot.len());
 5847                                let end = ((insertion_start + tabstop_range.end) as usize)
 5848                                    .min(snapshot.len());
 5849                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5850                            })
 5851                        })
 5852                        .collect::<Vec<_>>();
 5853                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5854
 5855                    Tabstop {
 5856                        is_end_tabstop,
 5857                        ranges: tabstop_ranges,
 5858                        choices: tabstop.choices.clone(),
 5859                    }
 5860                })
 5861                .collect::<Vec<_>>()
 5862        });
 5863        if let Some(tabstop) = tabstops.first() {
 5864            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5865                s.select_ranges(tabstop.ranges.iter().cloned());
 5866            });
 5867
 5868            if let Some(choices) = &tabstop.choices {
 5869                if let Some(selection) = tabstop.ranges.first() {
 5870                    self.show_snippet_choices(choices, selection.clone(), cx)
 5871                }
 5872            }
 5873
 5874            // If we're already at the last tabstop and it's at the end of the snippet,
 5875            // we're done, we don't need to keep the state around.
 5876            if !tabstop.is_end_tabstop {
 5877                let choices = tabstops
 5878                    .iter()
 5879                    .map(|tabstop| tabstop.choices.clone())
 5880                    .collect();
 5881
 5882                let ranges = tabstops
 5883                    .into_iter()
 5884                    .map(|tabstop| tabstop.ranges)
 5885                    .collect::<Vec<_>>();
 5886
 5887                self.snippet_stack.push(SnippetState {
 5888                    active_index: 0,
 5889                    ranges,
 5890                    choices,
 5891                });
 5892            }
 5893
 5894            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5895            if self.autoclose_regions.is_empty() {
 5896                let snapshot = self.buffer.read(cx).snapshot(cx);
 5897                for selection in &mut self.selections.all::<Point>(cx) {
 5898                    let selection_head = selection.head();
 5899                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5900                        continue;
 5901                    };
 5902
 5903                    let mut bracket_pair = None;
 5904                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5905                    let prev_chars = snapshot
 5906                        .reversed_chars_at(selection_head)
 5907                        .collect::<String>();
 5908                    for (pair, enabled) in scope.brackets() {
 5909                        if enabled
 5910                            && pair.close
 5911                            && prev_chars.starts_with(pair.start.as_str())
 5912                            && next_chars.starts_with(pair.end.as_str())
 5913                        {
 5914                            bracket_pair = Some(pair.clone());
 5915                            break;
 5916                        }
 5917                    }
 5918                    if let Some(pair) = bracket_pair {
 5919                        let start = snapshot.anchor_after(selection_head);
 5920                        let end = snapshot.anchor_after(selection_head);
 5921                        self.autoclose_regions.push(AutocloseRegion {
 5922                            selection_id: selection.id,
 5923                            range: start..end,
 5924                            pair,
 5925                        });
 5926                    }
 5927                }
 5928            }
 5929        }
 5930        Ok(())
 5931    }
 5932
 5933    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5934        self.move_to_snippet_tabstop(Bias::Right, cx)
 5935    }
 5936
 5937    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5938        self.move_to_snippet_tabstop(Bias::Left, cx)
 5939    }
 5940
 5941    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5942        if let Some(mut snippet) = self.snippet_stack.pop() {
 5943            match bias {
 5944                Bias::Left => {
 5945                    if snippet.active_index > 0 {
 5946                        snippet.active_index -= 1;
 5947                    } else {
 5948                        self.snippet_stack.push(snippet);
 5949                        return false;
 5950                    }
 5951                }
 5952                Bias::Right => {
 5953                    if snippet.active_index + 1 < snippet.ranges.len() {
 5954                        snippet.active_index += 1;
 5955                    } else {
 5956                        self.snippet_stack.push(snippet);
 5957                        return false;
 5958                    }
 5959                }
 5960            }
 5961            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5962                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5963                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5964                });
 5965
 5966                if let Some(choices) = &snippet.choices[snippet.active_index] {
 5967                    if let Some(selection) = current_ranges.first() {
 5968                        self.show_snippet_choices(&choices, selection.clone(), cx);
 5969                    }
 5970                }
 5971
 5972                // If snippet state is not at the last tabstop, push it back on the stack
 5973                if snippet.active_index + 1 < snippet.ranges.len() {
 5974                    self.snippet_stack.push(snippet);
 5975                }
 5976                return true;
 5977            }
 5978        }
 5979
 5980        false
 5981    }
 5982
 5983    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 5984        self.transact(cx, |this, cx| {
 5985            this.select_all(&SelectAll, cx);
 5986            this.insert("", cx);
 5987        });
 5988    }
 5989
 5990    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 5991        self.transact(cx, |this, cx| {
 5992            this.select_autoclose_pair(cx);
 5993            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5994            if !this.linked_edit_ranges.is_empty() {
 5995                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5996                let snapshot = this.buffer.read(cx).snapshot(cx);
 5997
 5998                for selection in selections.iter() {
 5999                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 6000                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 6001                    if selection_start.buffer_id != selection_end.buffer_id {
 6002                        continue;
 6003                    }
 6004                    if let Some(ranges) =
 6005                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 6006                    {
 6007                        for (buffer, entries) in ranges {
 6008                            linked_ranges.entry(buffer).or_default().extend(entries);
 6009                        }
 6010                    }
 6011                }
 6012            }
 6013
 6014            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 6015            if !this.selections.line_mode {
 6016                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 6017                for selection in &mut selections {
 6018                    if selection.is_empty() {
 6019                        let old_head = selection.head();
 6020                        let mut new_head =
 6021                            movement::left(&display_map, old_head.to_display_point(&display_map))
 6022                                .to_point(&display_map);
 6023                        if let Some((buffer, line_buffer_range)) = display_map
 6024                            .buffer_snapshot
 6025                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 6026                        {
 6027                            let indent_size =
 6028                                buffer.indent_size_for_line(line_buffer_range.start.row);
 6029                            let indent_len = match indent_size.kind {
 6030                                IndentKind::Space => {
 6031                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 6032                                }
 6033                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 6034                            };
 6035                            if old_head.column <= indent_size.len && old_head.column > 0 {
 6036                                let indent_len = indent_len.get();
 6037                                new_head = cmp::min(
 6038                                    new_head,
 6039                                    MultiBufferPoint::new(
 6040                                        old_head.row,
 6041                                        ((old_head.column - 1) / indent_len) * indent_len,
 6042                                    ),
 6043                                );
 6044                            }
 6045                        }
 6046
 6047                        selection.set_head(new_head, SelectionGoal::None);
 6048                    }
 6049                }
 6050            }
 6051
 6052            this.signature_help_state.set_backspace_pressed(true);
 6053            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6054            this.insert("", cx);
 6055            let empty_str: Arc<str> = Arc::from("");
 6056            for (buffer, edits) in linked_ranges {
 6057                let snapshot = buffer.read(cx).snapshot();
 6058                use text::ToPoint as TP;
 6059
 6060                let edits = edits
 6061                    .into_iter()
 6062                    .map(|range| {
 6063                        let end_point = TP::to_point(&range.end, &snapshot);
 6064                        let mut start_point = TP::to_point(&range.start, &snapshot);
 6065
 6066                        if end_point == start_point {
 6067                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 6068                                .saturating_sub(1);
 6069                            start_point = TP::to_point(&offset, &snapshot);
 6070                        };
 6071
 6072                        (start_point..end_point, empty_str.clone())
 6073                    })
 6074                    .sorted_by_key(|(range, _)| range.start)
 6075                    .collect::<Vec<_>>();
 6076                buffer.update(cx, |this, cx| {
 6077                    this.edit(edits, None, cx);
 6078                })
 6079            }
 6080            this.refresh_inline_completion(true, false, cx);
 6081            linked_editing_ranges::refresh_linked_ranges(this, cx);
 6082        });
 6083    }
 6084
 6085    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 6086        self.transact(cx, |this, cx| {
 6087            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6088                let line_mode = s.line_mode;
 6089                s.move_with(|map, selection| {
 6090                    if selection.is_empty() && !line_mode {
 6091                        let cursor = movement::right(map, selection.head());
 6092                        selection.end = cursor;
 6093                        selection.reversed = true;
 6094                        selection.goal = SelectionGoal::None;
 6095                    }
 6096                })
 6097            });
 6098            this.insert("", cx);
 6099            this.refresh_inline_completion(true, false, cx);
 6100        });
 6101    }
 6102
 6103    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 6104        if self.move_to_prev_snippet_tabstop(cx) {
 6105            return;
 6106        }
 6107
 6108        self.outdent(&Outdent, cx);
 6109    }
 6110
 6111    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 6112        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 6113            return;
 6114        }
 6115
 6116        let mut selections = self.selections.all_adjusted(cx);
 6117        let buffer = self.buffer.read(cx);
 6118        let snapshot = buffer.snapshot(cx);
 6119        let rows_iter = selections.iter().map(|s| s.head().row);
 6120        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 6121
 6122        let mut edits = Vec::new();
 6123        let mut prev_edited_row = 0;
 6124        let mut row_delta = 0;
 6125        for selection in &mut selections {
 6126            if selection.start.row != prev_edited_row {
 6127                row_delta = 0;
 6128            }
 6129            prev_edited_row = selection.end.row;
 6130
 6131            // If the selection is non-empty, then increase the indentation of the selected lines.
 6132            if !selection.is_empty() {
 6133                row_delta =
 6134                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6135                continue;
 6136            }
 6137
 6138            // If the selection is empty and the cursor is in the leading whitespace before the
 6139            // suggested indentation, then auto-indent the line.
 6140            let cursor = selection.head();
 6141            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 6142            if let Some(suggested_indent) =
 6143                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 6144            {
 6145                if cursor.column < suggested_indent.len
 6146                    && cursor.column <= current_indent.len
 6147                    && current_indent.len <= suggested_indent.len
 6148                {
 6149                    selection.start = Point::new(cursor.row, suggested_indent.len);
 6150                    selection.end = selection.start;
 6151                    if row_delta == 0 {
 6152                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 6153                            cursor.row,
 6154                            current_indent,
 6155                            suggested_indent,
 6156                        ));
 6157                        row_delta = suggested_indent.len - current_indent.len;
 6158                    }
 6159                    continue;
 6160                }
 6161            }
 6162
 6163            // Otherwise, insert a hard or soft tab.
 6164            let settings = buffer.settings_at(cursor, cx);
 6165            let tab_size = if settings.hard_tabs {
 6166                IndentSize::tab()
 6167            } else {
 6168                let tab_size = settings.tab_size.get();
 6169                let char_column = snapshot
 6170                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 6171                    .flat_map(str::chars)
 6172                    .count()
 6173                    + row_delta as usize;
 6174                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 6175                IndentSize::spaces(chars_to_next_tab_stop)
 6176            };
 6177            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 6178            selection.end = selection.start;
 6179            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 6180            row_delta += tab_size.len;
 6181        }
 6182
 6183        self.transact(cx, |this, cx| {
 6184            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6185            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6186            this.refresh_inline_completion(true, false, cx);
 6187        });
 6188    }
 6189
 6190    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 6191        if self.read_only(cx) {
 6192            return;
 6193        }
 6194        let mut selections = self.selections.all::<Point>(cx);
 6195        let mut prev_edited_row = 0;
 6196        let mut row_delta = 0;
 6197        let mut edits = Vec::new();
 6198        let buffer = self.buffer.read(cx);
 6199        let snapshot = buffer.snapshot(cx);
 6200        for selection in &mut selections {
 6201            if selection.start.row != prev_edited_row {
 6202                row_delta = 0;
 6203            }
 6204            prev_edited_row = selection.end.row;
 6205
 6206            row_delta =
 6207                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6208        }
 6209
 6210        self.transact(cx, |this, cx| {
 6211            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6212            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6213        });
 6214    }
 6215
 6216    fn indent_selection(
 6217        buffer: &MultiBuffer,
 6218        snapshot: &MultiBufferSnapshot,
 6219        selection: &mut Selection<Point>,
 6220        edits: &mut Vec<(Range<Point>, String)>,
 6221        delta_for_start_row: u32,
 6222        cx: &AppContext,
 6223    ) -> u32 {
 6224        let settings = buffer.settings_at(selection.start, cx);
 6225        let tab_size = settings.tab_size.get();
 6226        let indent_kind = if settings.hard_tabs {
 6227            IndentKind::Tab
 6228        } else {
 6229            IndentKind::Space
 6230        };
 6231        let mut start_row = selection.start.row;
 6232        let mut end_row = selection.end.row + 1;
 6233
 6234        // If a selection ends at the beginning of a line, don't indent
 6235        // that last line.
 6236        if selection.end.column == 0 && selection.end.row > selection.start.row {
 6237            end_row -= 1;
 6238        }
 6239
 6240        // Avoid re-indenting a row that has already been indented by a
 6241        // previous selection, but still update this selection's column
 6242        // to reflect that indentation.
 6243        if delta_for_start_row > 0 {
 6244            start_row += 1;
 6245            selection.start.column += delta_for_start_row;
 6246            if selection.end.row == selection.start.row {
 6247                selection.end.column += delta_for_start_row;
 6248            }
 6249        }
 6250
 6251        let mut delta_for_end_row = 0;
 6252        let has_multiple_rows = start_row + 1 != end_row;
 6253        for row in start_row..end_row {
 6254            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 6255            let indent_delta = match (current_indent.kind, indent_kind) {
 6256                (IndentKind::Space, IndentKind::Space) => {
 6257                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 6258                    IndentSize::spaces(columns_to_next_tab_stop)
 6259                }
 6260                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 6261                (_, IndentKind::Tab) => IndentSize::tab(),
 6262            };
 6263
 6264            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 6265                0
 6266            } else {
 6267                selection.start.column
 6268            };
 6269            let row_start = Point::new(row, start);
 6270            edits.push((
 6271                row_start..row_start,
 6272                indent_delta.chars().collect::<String>(),
 6273            ));
 6274
 6275            // Update this selection's endpoints to reflect the indentation.
 6276            if row == selection.start.row {
 6277                selection.start.column += indent_delta.len;
 6278            }
 6279            if row == selection.end.row {
 6280                selection.end.column += indent_delta.len;
 6281                delta_for_end_row = indent_delta.len;
 6282            }
 6283        }
 6284
 6285        if selection.start.row == selection.end.row {
 6286            delta_for_start_row + delta_for_end_row
 6287        } else {
 6288            delta_for_end_row
 6289        }
 6290    }
 6291
 6292    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 6293        if self.read_only(cx) {
 6294            return;
 6295        }
 6296        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6297        let selections = self.selections.all::<Point>(cx);
 6298        let mut deletion_ranges = Vec::new();
 6299        let mut last_outdent = None;
 6300        {
 6301            let buffer = self.buffer.read(cx);
 6302            let snapshot = buffer.snapshot(cx);
 6303            for selection in &selections {
 6304                let settings = buffer.settings_at(selection.start, cx);
 6305                let tab_size = settings.tab_size.get();
 6306                let mut rows = selection.spanned_rows(false, &display_map);
 6307
 6308                // Avoid re-outdenting a row that has already been outdented by a
 6309                // previous selection.
 6310                if let Some(last_row) = last_outdent {
 6311                    if last_row == rows.start {
 6312                        rows.start = rows.start.next_row();
 6313                    }
 6314                }
 6315                let has_multiple_rows = rows.len() > 1;
 6316                for row in rows.iter_rows() {
 6317                    let indent_size = snapshot.indent_size_for_line(row);
 6318                    if indent_size.len > 0 {
 6319                        let deletion_len = match indent_size.kind {
 6320                            IndentKind::Space => {
 6321                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 6322                                if columns_to_prev_tab_stop == 0 {
 6323                                    tab_size
 6324                                } else {
 6325                                    columns_to_prev_tab_stop
 6326                                }
 6327                            }
 6328                            IndentKind::Tab => 1,
 6329                        };
 6330                        let start = if has_multiple_rows
 6331                            || deletion_len > selection.start.column
 6332                            || indent_size.len < selection.start.column
 6333                        {
 6334                            0
 6335                        } else {
 6336                            selection.start.column - deletion_len
 6337                        };
 6338                        deletion_ranges.push(
 6339                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 6340                        );
 6341                        last_outdent = Some(row);
 6342                    }
 6343                }
 6344            }
 6345        }
 6346
 6347        self.transact(cx, |this, cx| {
 6348            this.buffer.update(cx, |buffer, cx| {
 6349                let empty_str: Arc<str> = Arc::default();
 6350                buffer.edit(
 6351                    deletion_ranges
 6352                        .into_iter()
 6353                        .map(|range| (range, empty_str.clone())),
 6354                    None,
 6355                    cx,
 6356                );
 6357            });
 6358            let selections = this.selections.all::<usize>(cx);
 6359            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6360        });
 6361    }
 6362
 6363    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 6364        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6365        let selections = self.selections.all::<Point>(cx);
 6366
 6367        let mut new_cursors = Vec::new();
 6368        let mut edit_ranges = Vec::new();
 6369        let mut selections = selections.iter().peekable();
 6370        while let Some(selection) = selections.next() {
 6371            let mut rows = selection.spanned_rows(false, &display_map);
 6372            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6373
 6374            // Accumulate contiguous regions of rows that we want to delete.
 6375            while let Some(next_selection) = selections.peek() {
 6376                let next_rows = next_selection.spanned_rows(false, &display_map);
 6377                if next_rows.start <= rows.end {
 6378                    rows.end = next_rows.end;
 6379                    selections.next().unwrap();
 6380                } else {
 6381                    break;
 6382                }
 6383            }
 6384
 6385            let buffer = &display_map.buffer_snapshot;
 6386            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6387            let edit_end;
 6388            let cursor_buffer_row;
 6389            if buffer.max_point().row >= rows.end.0 {
 6390                // If there's a line after the range, delete the \n from the end of the row range
 6391                // and position the cursor on the next line.
 6392                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6393                cursor_buffer_row = rows.end;
 6394            } else {
 6395                // If there isn't a line after the range, delete the \n from the line before the
 6396                // start of the row range and position the cursor there.
 6397                edit_start = edit_start.saturating_sub(1);
 6398                edit_end = buffer.len();
 6399                cursor_buffer_row = rows.start.previous_row();
 6400            }
 6401
 6402            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6403            *cursor.column_mut() =
 6404                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6405
 6406            new_cursors.push((
 6407                selection.id,
 6408                buffer.anchor_after(cursor.to_point(&display_map)),
 6409            ));
 6410            edit_ranges.push(edit_start..edit_end);
 6411        }
 6412
 6413        self.transact(cx, |this, cx| {
 6414            let buffer = this.buffer.update(cx, |buffer, cx| {
 6415                let empty_str: Arc<str> = Arc::default();
 6416                buffer.edit(
 6417                    edit_ranges
 6418                        .into_iter()
 6419                        .map(|range| (range, empty_str.clone())),
 6420                    None,
 6421                    cx,
 6422                );
 6423                buffer.snapshot(cx)
 6424            });
 6425            let new_selections = new_cursors
 6426                .into_iter()
 6427                .map(|(id, cursor)| {
 6428                    let cursor = cursor.to_point(&buffer);
 6429                    Selection {
 6430                        id,
 6431                        start: cursor,
 6432                        end: cursor,
 6433                        reversed: false,
 6434                        goal: SelectionGoal::None,
 6435                    }
 6436                })
 6437                .collect();
 6438
 6439            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6440                s.select(new_selections);
 6441            });
 6442        });
 6443    }
 6444
 6445    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 6446        if self.read_only(cx) {
 6447            return;
 6448        }
 6449        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6450        for selection in self.selections.all::<Point>(cx) {
 6451            let start = MultiBufferRow(selection.start.row);
 6452            // Treat single line selections as if they include the next line. Otherwise this action
 6453            // would do nothing for single line selections individual cursors.
 6454            let end = if selection.start.row == selection.end.row {
 6455                MultiBufferRow(selection.start.row + 1)
 6456            } else {
 6457                MultiBufferRow(selection.end.row)
 6458            };
 6459
 6460            if let Some(last_row_range) = row_ranges.last_mut() {
 6461                if start <= last_row_range.end {
 6462                    last_row_range.end = end;
 6463                    continue;
 6464                }
 6465            }
 6466            row_ranges.push(start..end);
 6467        }
 6468
 6469        let snapshot = self.buffer.read(cx).snapshot(cx);
 6470        let mut cursor_positions = Vec::new();
 6471        for row_range in &row_ranges {
 6472            let anchor = snapshot.anchor_before(Point::new(
 6473                row_range.end.previous_row().0,
 6474                snapshot.line_len(row_range.end.previous_row()),
 6475            ));
 6476            cursor_positions.push(anchor..anchor);
 6477        }
 6478
 6479        self.transact(cx, |this, cx| {
 6480            for row_range in row_ranges.into_iter().rev() {
 6481                for row in row_range.iter_rows().rev() {
 6482                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6483                    let next_line_row = row.next_row();
 6484                    let indent = snapshot.indent_size_for_line(next_line_row);
 6485                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 6486
 6487                    let replace = if snapshot.line_len(next_line_row) > indent.len {
 6488                        " "
 6489                    } else {
 6490                        ""
 6491                    };
 6492
 6493                    this.buffer.update(cx, |buffer, cx| {
 6494                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6495                    });
 6496                }
 6497            }
 6498
 6499            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6500                s.select_anchor_ranges(cursor_positions)
 6501            });
 6502        });
 6503    }
 6504
 6505    pub fn sort_lines_case_sensitive(
 6506        &mut self,
 6507        _: &SortLinesCaseSensitive,
 6508        cx: &mut ViewContext<Self>,
 6509    ) {
 6510        self.manipulate_lines(cx, |lines| lines.sort())
 6511    }
 6512
 6513    pub fn sort_lines_case_insensitive(
 6514        &mut self,
 6515        _: &SortLinesCaseInsensitive,
 6516        cx: &mut ViewContext<Self>,
 6517    ) {
 6518        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 6519    }
 6520
 6521    pub fn unique_lines_case_insensitive(
 6522        &mut self,
 6523        _: &UniqueLinesCaseInsensitive,
 6524        cx: &mut ViewContext<Self>,
 6525    ) {
 6526        self.manipulate_lines(cx, |lines| {
 6527            let mut seen = HashSet::default();
 6528            lines.retain(|line| seen.insert(line.to_lowercase()));
 6529        })
 6530    }
 6531
 6532    pub fn unique_lines_case_sensitive(
 6533        &mut self,
 6534        _: &UniqueLinesCaseSensitive,
 6535        cx: &mut ViewContext<Self>,
 6536    ) {
 6537        self.manipulate_lines(cx, |lines| {
 6538            let mut seen = HashSet::default();
 6539            lines.retain(|line| seen.insert(*line));
 6540        })
 6541    }
 6542
 6543    pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
 6544        let mut revert_changes = HashMap::default();
 6545        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 6546        for hunk in hunks_for_rows(
 6547            Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
 6548            &multi_buffer_snapshot,
 6549        ) {
 6550            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 6551        }
 6552        if !revert_changes.is_empty() {
 6553            self.transact(cx, |editor, cx| {
 6554                editor.revert(revert_changes, cx);
 6555            });
 6556        }
 6557    }
 6558
 6559    pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
 6560        let Some(project) = self.project.clone() else {
 6561            return;
 6562        };
 6563        self.reload(project, cx).detach_and_notify_err(cx);
 6564    }
 6565
 6566    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 6567        let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
 6568        if !revert_changes.is_empty() {
 6569            self.transact(cx, |editor, cx| {
 6570                editor.revert(revert_changes, cx);
 6571            });
 6572        }
 6573    }
 6574
 6575    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 6576        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6577            let project_path = buffer.read(cx).project_path(cx)?;
 6578            let project = self.project.as_ref()?.read(cx);
 6579            let entry = project.entry_for_path(&project_path, cx)?;
 6580            let parent = match &entry.canonical_path {
 6581                Some(canonical_path) => canonical_path.to_path_buf(),
 6582                None => project.absolute_path(&project_path, cx)?,
 6583            }
 6584            .parent()?
 6585            .to_path_buf();
 6586            Some(parent)
 6587        }) {
 6588            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 6589        }
 6590    }
 6591
 6592    fn gather_revert_changes(
 6593        &mut self,
 6594        selections: &[Selection<Anchor>],
 6595        cx: &mut ViewContext<'_, Editor>,
 6596    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 6597        let mut revert_changes = HashMap::default();
 6598        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 6599        for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
 6600            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 6601        }
 6602        revert_changes
 6603    }
 6604
 6605    pub fn prepare_revert_change(
 6606        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6607        multi_buffer: &Model<MultiBuffer>,
 6608        hunk: &MultiBufferDiffHunk,
 6609        cx: &AppContext,
 6610    ) -> Option<()> {
 6611        let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
 6612        let buffer = buffer.read(cx);
 6613        let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
 6614        let buffer_snapshot = buffer.snapshot();
 6615        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6616        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6617            probe
 6618                .0
 6619                .start
 6620                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6621                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6622        }) {
 6623            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6624            Some(())
 6625        } else {
 6626            None
 6627        }
 6628    }
 6629
 6630    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 6631        self.manipulate_lines(cx, |lines| lines.reverse())
 6632    }
 6633
 6634    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 6635        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 6636    }
 6637
 6638    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6639    where
 6640        Fn: FnMut(&mut Vec<&str>),
 6641    {
 6642        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6643        let buffer = self.buffer.read(cx).snapshot(cx);
 6644
 6645        let mut edits = Vec::new();
 6646
 6647        let selections = self.selections.all::<Point>(cx);
 6648        let mut selections = selections.iter().peekable();
 6649        let mut contiguous_row_selections = Vec::new();
 6650        let mut new_selections = Vec::new();
 6651        let mut added_lines = 0;
 6652        let mut removed_lines = 0;
 6653
 6654        while let Some(selection) = selections.next() {
 6655            let (start_row, end_row) = consume_contiguous_rows(
 6656                &mut contiguous_row_selections,
 6657                selection,
 6658                &display_map,
 6659                &mut selections,
 6660            );
 6661
 6662            let start_point = Point::new(start_row.0, 0);
 6663            let end_point = Point::new(
 6664                end_row.previous_row().0,
 6665                buffer.line_len(end_row.previous_row()),
 6666            );
 6667            let text = buffer
 6668                .text_for_range(start_point..end_point)
 6669                .collect::<String>();
 6670
 6671            let mut lines = text.split('\n').collect_vec();
 6672
 6673            let lines_before = lines.len();
 6674            callback(&mut lines);
 6675            let lines_after = lines.len();
 6676
 6677            edits.push((start_point..end_point, lines.join("\n")));
 6678
 6679            // Selections must change based on added and removed line count
 6680            let start_row =
 6681                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6682            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6683            new_selections.push(Selection {
 6684                id: selection.id,
 6685                start: start_row,
 6686                end: end_row,
 6687                goal: SelectionGoal::None,
 6688                reversed: selection.reversed,
 6689            });
 6690
 6691            if lines_after > lines_before {
 6692                added_lines += lines_after - lines_before;
 6693            } else if lines_before > lines_after {
 6694                removed_lines += lines_before - lines_after;
 6695            }
 6696        }
 6697
 6698        self.transact(cx, |this, cx| {
 6699            let buffer = this.buffer.update(cx, |buffer, cx| {
 6700                buffer.edit(edits, None, cx);
 6701                buffer.snapshot(cx)
 6702            });
 6703
 6704            // Recalculate offsets on newly edited buffer
 6705            let new_selections = new_selections
 6706                .iter()
 6707                .map(|s| {
 6708                    let start_point = Point::new(s.start.0, 0);
 6709                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6710                    Selection {
 6711                        id: s.id,
 6712                        start: buffer.point_to_offset(start_point),
 6713                        end: buffer.point_to_offset(end_point),
 6714                        goal: s.goal,
 6715                        reversed: s.reversed,
 6716                    }
 6717                })
 6718                .collect();
 6719
 6720            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6721                s.select(new_selections);
 6722            });
 6723
 6724            this.request_autoscroll(Autoscroll::fit(), cx);
 6725        });
 6726    }
 6727
 6728    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 6729        self.manipulate_text(cx, |text| text.to_uppercase())
 6730    }
 6731
 6732    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 6733        self.manipulate_text(cx, |text| text.to_lowercase())
 6734    }
 6735
 6736    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 6737        self.manipulate_text(cx, |text| {
 6738            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6739            // https://github.com/rutrum/convert-case/issues/16
 6740            text.split('\n')
 6741                .map(|line| line.to_case(Case::Title))
 6742                .join("\n")
 6743        })
 6744    }
 6745
 6746    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6747        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6748    }
 6749
 6750    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6751        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6752    }
 6753
 6754    pub fn convert_to_upper_camel_case(
 6755        &mut self,
 6756        _: &ConvertToUpperCamelCase,
 6757        cx: &mut ViewContext<Self>,
 6758    ) {
 6759        self.manipulate_text(cx, |text| {
 6760            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6761            // https://github.com/rutrum/convert-case/issues/16
 6762            text.split('\n')
 6763                .map(|line| line.to_case(Case::UpperCamel))
 6764                .join("\n")
 6765        })
 6766    }
 6767
 6768    pub fn convert_to_lower_camel_case(
 6769        &mut self,
 6770        _: &ConvertToLowerCamelCase,
 6771        cx: &mut ViewContext<Self>,
 6772    ) {
 6773        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6774    }
 6775
 6776    pub fn convert_to_opposite_case(
 6777        &mut self,
 6778        _: &ConvertToOppositeCase,
 6779        cx: &mut ViewContext<Self>,
 6780    ) {
 6781        self.manipulate_text(cx, |text| {
 6782            text.chars()
 6783                .fold(String::with_capacity(text.len()), |mut t, c| {
 6784                    if c.is_uppercase() {
 6785                        t.extend(c.to_lowercase());
 6786                    } else {
 6787                        t.extend(c.to_uppercase());
 6788                    }
 6789                    t
 6790                })
 6791        })
 6792    }
 6793
 6794    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6795    where
 6796        Fn: FnMut(&str) -> String,
 6797    {
 6798        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6799        let buffer = self.buffer.read(cx).snapshot(cx);
 6800
 6801        let mut new_selections = Vec::new();
 6802        let mut edits = Vec::new();
 6803        let mut selection_adjustment = 0i32;
 6804
 6805        for selection in self.selections.all::<usize>(cx) {
 6806            let selection_is_empty = selection.is_empty();
 6807
 6808            let (start, end) = if selection_is_empty {
 6809                let word_range = movement::surrounding_word(
 6810                    &display_map,
 6811                    selection.start.to_display_point(&display_map),
 6812                );
 6813                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6814                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6815                (start, end)
 6816            } else {
 6817                (selection.start, selection.end)
 6818            };
 6819
 6820            let text = buffer.text_for_range(start..end).collect::<String>();
 6821            let old_length = text.len() as i32;
 6822            let text = callback(&text);
 6823
 6824            new_selections.push(Selection {
 6825                start: (start as i32 - selection_adjustment) as usize,
 6826                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6827                goal: SelectionGoal::None,
 6828                ..selection
 6829            });
 6830
 6831            selection_adjustment += old_length - text.len() as i32;
 6832
 6833            edits.push((start..end, text));
 6834        }
 6835
 6836        self.transact(cx, |this, cx| {
 6837            this.buffer.update(cx, |buffer, cx| {
 6838                buffer.edit(edits, None, cx);
 6839            });
 6840
 6841            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6842                s.select(new_selections);
 6843            });
 6844
 6845            this.request_autoscroll(Autoscroll::fit(), cx);
 6846        });
 6847    }
 6848
 6849    pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
 6850        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6851        let buffer = &display_map.buffer_snapshot;
 6852        let selections = self.selections.all::<Point>(cx);
 6853
 6854        let mut edits = Vec::new();
 6855        let mut selections_iter = selections.iter().peekable();
 6856        while let Some(selection) = selections_iter.next() {
 6857            // Avoid duplicating the same lines twice.
 6858            let mut rows = selection.spanned_rows(false, &display_map);
 6859
 6860            while let Some(next_selection) = selections_iter.peek() {
 6861                let next_rows = next_selection.spanned_rows(false, &display_map);
 6862                if next_rows.start < rows.end {
 6863                    rows.end = next_rows.end;
 6864                    selections_iter.next().unwrap();
 6865                } else {
 6866                    break;
 6867                }
 6868            }
 6869
 6870            // Copy the text from the selected row region and splice it either at the start
 6871            // or end of the region.
 6872            let start = Point::new(rows.start.0, 0);
 6873            let end = Point::new(
 6874                rows.end.previous_row().0,
 6875                buffer.line_len(rows.end.previous_row()),
 6876            );
 6877            let text = buffer
 6878                .text_for_range(start..end)
 6879                .chain(Some("\n"))
 6880                .collect::<String>();
 6881            let insert_location = if upwards {
 6882                Point::new(rows.end.0, 0)
 6883            } else {
 6884                start
 6885            };
 6886            edits.push((insert_location..insert_location, text));
 6887        }
 6888
 6889        self.transact(cx, |this, cx| {
 6890            this.buffer.update(cx, |buffer, cx| {
 6891                buffer.edit(edits, None, cx);
 6892            });
 6893
 6894            this.request_autoscroll(Autoscroll::fit(), cx);
 6895        });
 6896    }
 6897
 6898    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6899        self.duplicate_line(true, cx);
 6900    }
 6901
 6902    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6903        self.duplicate_line(false, cx);
 6904    }
 6905
 6906    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6907        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6908        let buffer = self.buffer.read(cx).snapshot(cx);
 6909
 6910        let mut edits = Vec::new();
 6911        let mut unfold_ranges = Vec::new();
 6912        let mut refold_creases = Vec::new();
 6913
 6914        let selections = self.selections.all::<Point>(cx);
 6915        let mut selections = selections.iter().peekable();
 6916        let mut contiguous_row_selections = Vec::new();
 6917        let mut new_selections = Vec::new();
 6918
 6919        while let Some(selection) = selections.next() {
 6920            // Find all the selections that span a contiguous row range
 6921            let (start_row, end_row) = consume_contiguous_rows(
 6922                &mut contiguous_row_selections,
 6923                selection,
 6924                &display_map,
 6925                &mut selections,
 6926            );
 6927
 6928            // Move the text spanned by the row range to be before the line preceding the row range
 6929            if start_row.0 > 0 {
 6930                let range_to_move = Point::new(
 6931                    start_row.previous_row().0,
 6932                    buffer.line_len(start_row.previous_row()),
 6933                )
 6934                    ..Point::new(
 6935                        end_row.previous_row().0,
 6936                        buffer.line_len(end_row.previous_row()),
 6937                    );
 6938                let insertion_point = display_map
 6939                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6940                    .0;
 6941
 6942                // Don't move lines across excerpts
 6943                if buffer
 6944                    .excerpt_boundaries_in_range((
 6945                        Bound::Excluded(insertion_point),
 6946                        Bound::Included(range_to_move.end),
 6947                    ))
 6948                    .next()
 6949                    .is_none()
 6950                {
 6951                    let text = buffer
 6952                        .text_for_range(range_to_move.clone())
 6953                        .flat_map(|s| s.chars())
 6954                        .skip(1)
 6955                        .chain(['\n'])
 6956                        .collect::<String>();
 6957
 6958                    edits.push((
 6959                        buffer.anchor_after(range_to_move.start)
 6960                            ..buffer.anchor_before(range_to_move.end),
 6961                        String::new(),
 6962                    ));
 6963                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6964                    edits.push((insertion_anchor..insertion_anchor, text));
 6965
 6966                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6967
 6968                    // Move selections up
 6969                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6970                        |mut selection| {
 6971                            selection.start.row -= row_delta;
 6972                            selection.end.row -= row_delta;
 6973                            selection
 6974                        },
 6975                    ));
 6976
 6977                    // Move folds up
 6978                    unfold_ranges.push(range_to_move.clone());
 6979                    for fold in display_map.folds_in_range(
 6980                        buffer.anchor_before(range_to_move.start)
 6981                            ..buffer.anchor_after(range_to_move.end),
 6982                    ) {
 6983                        let mut start = fold.range.start.to_point(&buffer);
 6984                        let mut end = fold.range.end.to_point(&buffer);
 6985                        start.row -= row_delta;
 6986                        end.row -= row_delta;
 6987                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6988                    }
 6989                }
 6990            }
 6991
 6992            // If we didn't move line(s), preserve the existing selections
 6993            new_selections.append(&mut contiguous_row_selections);
 6994        }
 6995
 6996        self.transact(cx, |this, cx| {
 6997            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6998            this.buffer.update(cx, |buffer, cx| {
 6999                for (range, text) in edits {
 7000                    buffer.edit([(range, text)], None, cx);
 7001                }
 7002            });
 7003            this.fold_creases(refold_creases, true, cx);
 7004            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7005                s.select(new_selections);
 7006            })
 7007        });
 7008    }
 7009
 7010    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 7011        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7012        let buffer = self.buffer.read(cx).snapshot(cx);
 7013
 7014        let mut edits = Vec::new();
 7015        let mut unfold_ranges = Vec::new();
 7016        let mut refold_creases = Vec::new();
 7017
 7018        let selections = self.selections.all::<Point>(cx);
 7019        let mut selections = selections.iter().peekable();
 7020        let mut contiguous_row_selections = Vec::new();
 7021        let mut new_selections = Vec::new();
 7022
 7023        while let Some(selection) = selections.next() {
 7024            // Find all the selections that span a contiguous row range
 7025            let (start_row, end_row) = consume_contiguous_rows(
 7026                &mut contiguous_row_selections,
 7027                selection,
 7028                &display_map,
 7029                &mut selections,
 7030            );
 7031
 7032            // Move the text spanned by the row range to be after the last line of the row range
 7033            if end_row.0 <= buffer.max_point().row {
 7034                let range_to_move =
 7035                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 7036                let insertion_point = display_map
 7037                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 7038                    .0;
 7039
 7040                // Don't move lines across excerpt boundaries
 7041                if buffer
 7042                    .excerpt_boundaries_in_range((
 7043                        Bound::Excluded(range_to_move.start),
 7044                        Bound::Included(insertion_point),
 7045                    ))
 7046                    .next()
 7047                    .is_none()
 7048                {
 7049                    let mut text = String::from("\n");
 7050                    text.extend(buffer.text_for_range(range_to_move.clone()));
 7051                    text.pop(); // Drop trailing newline
 7052                    edits.push((
 7053                        buffer.anchor_after(range_to_move.start)
 7054                            ..buffer.anchor_before(range_to_move.end),
 7055                        String::new(),
 7056                    ));
 7057                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7058                    edits.push((insertion_anchor..insertion_anchor, text));
 7059
 7060                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 7061
 7062                    // Move selections down
 7063                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7064                        |mut selection| {
 7065                            selection.start.row += row_delta;
 7066                            selection.end.row += row_delta;
 7067                            selection
 7068                        },
 7069                    ));
 7070
 7071                    // Move folds down
 7072                    unfold_ranges.push(range_to_move.clone());
 7073                    for fold in display_map.folds_in_range(
 7074                        buffer.anchor_before(range_to_move.start)
 7075                            ..buffer.anchor_after(range_to_move.end),
 7076                    ) {
 7077                        let mut start = fold.range.start.to_point(&buffer);
 7078                        let mut end = fold.range.end.to_point(&buffer);
 7079                        start.row += row_delta;
 7080                        end.row += row_delta;
 7081                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7082                    }
 7083                }
 7084            }
 7085
 7086            // If we didn't move line(s), preserve the existing selections
 7087            new_selections.append(&mut contiguous_row_selections);
 7088        }
 7089
 7090        self.transact(cx, |this, cx| {
 7091            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7092            this.buffer.update(cx, |buffer, cx| {
 7093                for (range, text) in edits {
 7094                    buffer.edit([(range, text)], None, cx);
 7095                }
 7096            });
 7097            this.fold_creases(refold_creases, true, cx);
 7098            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 7099        });
 7100    }
 7101
 7102    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 7103        let text_layout_details = &self.text_layout_details(cx);
 7104        self.transact(cx, |this, cx| {
 7105            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7106                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 7107                let line_mode = s.line_mode;
 7108                s.move_with(|display_map, selection| {
 7109                    if !selection.is_empty() || line_mode {
 7110                        return;
 7111                    }
 7112
 7113                    let mut head = selection.head();
 7114                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 7115                    if head.column() == display_map.line_len(head.row()) {
 7116                        transpose_offset = display_map
 7117                            .buffer_snapshot
 7118                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7119                    }
 7120
 7121                    if transpose_offset == 0 {
 7122                        return;
 7123                    }
 7124
 7125                    *head.column_mut() += 1;
 7126                    head = display_map.clip_point(head, Bias::Right);
 7127                    let goal = SelectionGoal::HorizontalPosition(
 7128                        display_map
 7129                            .x_for_display_point(head, text_layout_details)
 7130                            .into(),
 7131                    );
 7132                    selection.collapse_to(head, goal);
 7133
 7134                    let transpose_start = display_map
 7135                        .buffer_snapshot
 7136                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7137                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 7138                        let transpose_end = display_map
 7139                            .buffer_snapshot
 7140                            .clip_offset(transpose_offset + 1, Bias::Right);
 7141                        if let Some(ch) =
 7142                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 7143                        {
 7144                            edits.push((transpose_start..transpose_offset, String::new()));
 7145                            edits.push((transpose_end..transpose_end, ch.to_string()));
 7146                        }
 7147                    }
 7148                });
 7149                edits
 7150            });
 7151            this.buffer
 7152                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7153            let selections = this.selections.all::<usize>(cx);
 7154            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7155                s.select(selections);
 7156            });
 7157        });
 7158    }
 7159
 7160    pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
 7161        self.rewrap_impl(IsVimMode::No, cx)
 7162    }
 7163
 7164    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
 7165        let buffer = self.buffer.read(cx).snapshot(cx);
 7166        let selections = self.selections.all::<Point>(cx);
 7167        let mut selections = selections.iter().peekable();
 7168
 7169        let mut edits = Vec::new();
 7170        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 7171
 7172        while let Some(selection) = selections.next() {
 7173            let mut start_row = selection.start.row;
 7174            let mut end_row = selection.end.row;
 7175
 7176            // Skip selections that overlap with a range that has already been rewrapped.
 7177            let selection_range = start_row..end_row;
 7178            if rewrapped_row_ranges
 7179                .iter()
 7180                .any(|range| range.overlaps(&selection_range))
 7181            {
 7182                continue;
 7183            }
 7184
 7185            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 7186
 7187            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 7188                match language_scope.language_name().0.as_ref() {
 7189                    "Markdown" | "Plain Text" => {
 7190                        should_rewrap = true;
 7191                    }
 7192                    _ => {}
 7193                }
 7194            }
 7195
 7196            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 7197
 7198            // Since not all lines in the selection may be at the same indent
 7199            // level, choose the indent size that is the most common between all
 7200            // of the lines.
 7201            //
 7202            // If there is a tie, we use the deepest indent.
 7203            let (indent_size, indent_end) = {
 7204                let mut indent_size_occurrences = HashMap::default();
 7205                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 7206
 7207                for row in start_row..=end_row {
 7208                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 7209                    rows_by_indent_size.entry(indent).or_default().push(row);
 7210                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 7211                }
 7212
 7213                let indent_size = indent_size_occurrences
 7214                    .into_iter()
 7215                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 7216                    .map(|(indent, _)| indent)
 7217                    .unwrap_or_default();
 7218                let row = rows_by_indent_size[&indent_size][0];
 7219                let indent_end = Point::new(row, indent_size.len);
 7220
 7221                (indent_size, indent_end)
 7222            };
 7223
 7224            let mut line_prefix = indent_size.chars().collect::<String>();
 7225
 7226            if let Some(comment_prefix) =
 7227                buffer
 7228                    .language_scope_at(selection.head())
 7229                    .and_then(|language| {
 7230                        language
 7231                            .line_comment_prefixes()
 7232                            .iter()
 7233                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 7234                            .cloned()
 7235                    })
 7236            {
 7237                line_prefix.push_str(&comment_prefix);
 7238                should_rewrap = true;
 7239            }
 7240
 7241            if !should_rewrap {
 7242                continue;
 7243            }
 7244
 7245            if selection.is_empty() {
 7246                'expand_upwards: while start_row > 0 {
 7247                    let prev_row = start_row - 1;
 7248                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 7249                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 7250                    {
 7251                        start_row = prev_row;
 7252                    } else {
 7253                        break 'expand_upwards;
 7254                    }
 7255                }
 7256
 7257                'expand_downwards: while end_row < buffer.max_point().row {
 7258                    let next_row = end_row + 1;
 7259                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 7260                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 7261                    {
 7262                        end_row = next_row;
 7263                    } else {
 7264                        break 'expand_downwards;
 7265                    }
 7266                }
 7267            }
 7268
 7269            let start = Point::new(start_row, 0);
 7270            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 7271            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 7272            let Some(lines_without_prefixes) = selection_text
 7273                .lines()
 7274                .map(|line| {
 7275                    line.strip_prefix(&line_prefix)
 7276                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 7277                        .ok_or_else(|| {
 7278                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 7279                        })
 7280                })
 7281                .collect::<Result<Vec<_>, _>>()
 7282                .log_err()
 7283            else {
 7284                continue;
 7285            };
 7286
 7287            let wrap_column = buffer
 7288                .settings_at(Point::new(start_row, 0), cx)
 7289                .preferred_line_length as usize;
 7290            let wrapped_text = wrap_with_prefix(
 7291                line_prefix,
 7292                lines_without_prefixes.join(" "),
 7293                wrap_column,
 7294                tab_size,
 7295            );
 7296
 7297            // TODO: should always use char-based diff while still supporting cursor behavior that
 7298            // matches vim.
 7299            let diff = match is_vim_mode {
 7300                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 7301                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 7302            };
 7303            let mut offset = start.to_offset(&buffer);
 7304            let mut moved_since_edit = true;
 7305
 7306            for change in diff.iter_all_changes() {
 7307                let value = change.value();
 7308                match change.tag() {
 7309                    ChangeTag::Equal => {
 7310                        offset += value.len();
 7311                        moved_since_edit = true;
 7312                    }
 7313                    ChangeTag::Delete => {
 7314                        let start = buffer.anchor_after(offset);
 7315                        let end = buffer.anchor_before(offset + value.len());
 7316
 7317                        if moved_since_edit {
 7318                            edits.push((start..end, String::new()));
 7319                        } else {
 7320                            edits.last_mut().unwrap().0.end = end;
 7321                        }
 7322
 7323                        offset += value.len();
 7324                        moved_since_edit = false;
 7325                    }
 7326                    ChangeTag::Insert => {
 7327                        if moved_since_edit {
 7328                            let anchor = buffer.anchor_after(offset);
 7329                            edits.push((anchor..anchor, value.to_string()));
 7330                        } else {
 7331                            edits.last_mut().unwrap().1.push_str(value);
 7332                        }
 7333
 7334                        moved_since_edit = false;
 7335                    }
 7336                }
 7337            }
 7338
 7339            rewrapped_row_ranges.push(start_row..=end_row);
 7340        }
 7341
 7342        self.buffer
 7343            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7344    }
 7345
 7346    pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
 7347        let mut text = String::new();
 7348        let buffer = self.buffer.read(cx).snapshot(cx);
 7349        let mut selections = self.selections.all::<Point>(cx);
 7350        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7351        {
 7352            let max_point = buffer.max_point();
 7353            let mut is_first = true;
 7354            for selection in &mut selections {
 7355                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7356                if is_entire_line {
 7357                    selection.start = Point::new(selection.start.row, 0);
 7358                    if !selection.is_empty() && selection.end.column == 0 {
 7359                        selection.end = cmp::min(max_point, selection.end);
 7360                    } else {
 7361                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7362                    }
 7363                    selection.goal = SelectionGoal::None;
 7364                }
 7365                if is_first {
 7366                    is_first = false;
 7367                } else {
 7368                    text += "\n";
 7369                }
 7370                let mut len = 0;
 7371                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7372                    text.push_str(chunk);
 7373                    len += chunk.len();
 7374                }
 7375                clipboard_selections.push(ClipboardSelection {
 7376                    len,
 7377                    is_entire_line,
 7378                    first_line_indent: buffer
 7379                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7380                        .len,
 7381                });
 7382            }
 7383        }
 7384
 7385        self.transact(cx, |this, cx| {
 7386            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7387                s.select(selections);
 7388            });
 7389            this.insert("", cx);
 7390        });
 7391        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 7392    }
 7393
 7394    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 7395        let item = self.cut_common(cx);
 7396        cx.write_to_clipboard(item);
 7397    }
 7398
 7399    pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
 7400        self.change_selections(None, cx, |s| {
 7401            s.move_with(|snapshot, sel| {
 7402                if sel.is_empty() {
 7403                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 7404                }
 7405            });
 7406        });
 7407        let item = self.cut_common(cx);
 7408        cx.set_global(KillRing(item))
 7409    }
 7410
 7411    pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
 7412        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 7413            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 7414                (kill_ring.text().to_string(), kill_ring.metadata_json())
 7415            } else {
 7416                return;
 7417            }
 7418        } else {
 7419            return;
 7420        };
 7421        self.do_paste(&text, metadata, false, cx);
 7422    }
 7423
 7424    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 7425        let selections = self.selections.all::<Point>(cx);
 7426        let buffer = self.buffer.read(cx).read(cx);
 7427        let mut text = String::new();
 7428
 7429        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7430        {
 7431            let max_point = buffer.max_point();
 7432            let mut is_first = true;
 7433            for selection in selections.iter() {
 7434                let mut start = selection.start;
 7435                let mut end = selection.end;
 7436                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7437                if is_entire_line {
 7438                    start = Point::new(start.row, 0);
 7439                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 7440                }
 7441                if is_first {
 7442                    is_first = false;
 7443                } else {
 7444                    text += "\n";
 7445                }
 7446                let mut len = 0;
 7447                for chunk in buffer.text_for_range(start..end) {
 7448                    text.push_str(chunk);
 7449                    len += chunk.len();
 7450                }
 7451                clipboard_selections.push(ClipboardSelection {
 7452                    len,
 7453                    is_entire_line,
 7454                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 7455                });
 7456            }
 7457        }
 7458
 7459        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7460            text,
 7461            clipboard_selections,
 7462        ));
 7463    }
 7464
 7465    pub fn do_paste(
 7466        &mut self,
 7467        text: &String,
 7468        clipboard_selections: Option<Vec<ClipboardSelection>>,
 7469        handle_entire_lines: bool,
 7470        cx: &mut ViewContext<Self>,
 7471    ) {
 7472        if self.read_only(cx) {
 7473            return;
 7474        }
 7475
 7476        let clipboard_text = Cow::Borrowed(text);
 7477
 7478        self.transact(cx, |this, cx| {
 7479            if let Some(mut clipboard_selections) = clipboard_selections {
 7480                let old_selections = this.selections.all::<usize>(cx);
 7481                let all_selections_were_entire_line =
 7482                    clipboard_selections.iter().all(|s| s.is_entire_line);
 7483                let first_selection_indent_column =
 7484                    clipboard_selections.first().map(|s| s.first_line_indent);
 7485                if clipboard_selections.len() != old_selections.len() {
 7486                    clipboard_selections.drain(..);
 7487                }
 7488                let cursor_offset = this.selections.last::<usize>(cx).head();
 7489                let mut auto_indent_on_paste = true;
 7490
 7491                this.buffer.update(cx, |buffer, cx| {
 7492                    let snapshot = buffer.read(cx);
 7493                    auto_indent_on_paste =
 7494                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 7495
 7496                    let mut start_offset = 0;
 7497                    let mut edits = Vec::new();
 7498                    let mut original_indent_columns = Vec::new();
 7499                    for (ix, selection) in old_selections.iter().enumerate() {
 7500                        let to_insert;
 7501                        let entire_line;
 7502                        let original_indent_column;
 7503                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 7504                            let end_offset = start_offset + clipboard_selection.len;
 7505                            to_insert = &clipboard_text[start_offset..end_offset];
 7506                            entire_line = clipboard_selection.is_entire_line;
 7507                            start_offset = end_offset + 1;
 7508                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7509                        } else {
 7510                            to_insert = clipboard_text.as_str();
 7511                            entire_line = all_selections_were_entire_line;
 7512                            original_indent_column = first_selection_indent_column
 7513                        }
 7514
 7515                        // If the corresponding selection was empty when this slice of the
 7516                        // clipboard text was written, then the entire line containing the
 7517                        // selection was copied. If this selection is also currently empty,
 7518                        // then paste the line before the current line of the buffer.
 7519                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7520                            let column = selection.start.to_point(&snapshot).column as usize;
 7521                            let line_start = selection.start - column;
 7522                            line_start..line_start
 7523                        } else {
 7524                            selection.range()
 7525                        };
 7526
 7527                        edits.push((range, to_insert));
 7528                        original_indent_columns.extend(original_indent_column);
 7529                    }
 7530                    drop(snapshot);
 7531
 7532                    buffer.edit(
 7533                        edits,
 7534                        if auto_indent_on_paste {
 7535                            Some(AutoindentMode::Block {
 7536                                original_indent_columns,
 7537                            })
 7538                        } else {
 7539                            None
 7540                        },
 7541                        cx,
 7542                    );
 7543                });
 7544
 7545                let selections = this.selections.all::<usize>(cx);
 7546                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 7547            } else {
 7548                this.insert(&clipboard_text, cx);
 7549            }
 7550        });
 7551    }
 7552
 7553    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 7554        if let Some(item) = cx.read_from_clipboard() {
 7555            let entries = item.entries();
 7556
 7557            match entries.first() {
 7558                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7559                // of all the pasted entries.
 7560                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7561                    .do_paste(
 7562                        clipboard_string.text(),
 7563                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7564                        true,
 7565                        cx,
 7566                    ),
 7567                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
 7568            }
 7569        }
 7570    }
 7571
 7572    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 7573        if self.read_only(cx) {
 7574            return;
 7575        }
 7576
 7577        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7578            if let Some((selections, _)) =
 7579                self.selection_history.transaction(transaction_id).cloned()
 7580            {
 7581                self.change_selections(None, cx, |s| {
 7582                    s.select_anchors(selections.to_vec());
 7583                });
 7584            }
 7585            self.request_autoscroll(Autoscroll::fit(), cx);
 7586            self.unmark_text(cx);
 7587            self.refresh_inline_completion(true, false, cx);
 7588            cx.emit(EditorEvent::Edited { transaction_id });
 7589            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7590        }
 7591    }
 7592
 7593    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 7594        if self.read_only(cx) {
 7595            return;
 7596        }
 7597
 7598        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7599            if let Some((_, Some(selections))) =
 7600                self.selection_history.transaction(transaction_id).cloned()
 7601            {
 7602                self.change_selections(None, cx, |s| {
 7603                    s.select_anchors(selections.to_vec());
 7604                });
 7605            }
 7606            self.request_autoscroll(Autoscroll::fit(), cx);
 7607            self.unmark_text(cx);
 7608            self.refresh_inline_completion(true, false, cx);
 7609            cx.emit(EditorEvent::Edited { transaction_id });
 7610        }
 7611    }
 7612
 7613    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 7614        self.buffer
 7615            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7616    }
 7617
 7618    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 7619        self.buffer
 7620            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7621    }
 7622
 7623    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 7624        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7625            let line_mode = s.line_mode;
 7626            s.move_with(|map, selection| {
 7627                let cursor = if selection.is_empty() && !line_mode {
 7628                    movement::left(map, selection.start)
 7629                } else {
 7630                    selection.start
 7631                };
 7632                selection.collapse_to(cursor, SelectionGoal::None);
 7633            });
 7634        })
 7635    }
 7636
 7637    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 7638        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7639            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7640        })
 7641    }
 7642
 7643    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 7644        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7645            let line_mode = s.line_mode;
 7646            s.move_with(|map, selection| {
 7647                let cursor = if selection.is_empty() && !line_mode {
 7648                    movement::right(map, selection.end)
 7649                } else {
 7650                    selection.end
 7651                };
 7652                selection.collapse_to(cursor, SelectionGoal::None)
 7653            });
 7654        })
 7655    }
 7656
 7657    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 7658        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7659            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7660        })
 7661    }
 7662
 7663    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 7664        if self.take_rename(true, cx).is_some() {
 7665            return;
 7666        }
 7667
 7668        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7669            cx.propagate();
 7670            return;
 7671        }
 7672
 7673        let text_layout_details = &self.text_layout_details(cx);
 7674        let selection_count = self.selections.count();
 7675        let first_selection = self.selections.first_anchor();
 7676
 7677        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7678            let line_mode = s.line_mode;
 7679            s.move_with(|map, selection| {
 7680                if !selection.is_empty() && !line_mode {
 7681                    selection.goal = SelectionGoal::None;
 7682                }
 7683                let (cursor, goal) = movement::up(
 7684                    map,
 7685                    selection.start,
 7686                    selection.goal,
 7687                    false,
 7688                    text_layout_details,
 7689                );
 7690                selection.collapse_to(cursor, goal);
 7691            });
 7692        });
 7693
 7694        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7695        {
 7696            cx.propagate();
 7697        }
 7698    }
 7699
 7700    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 7701        if self.take_rename(true, cx).is_some() {
 7702            return;
 7703        }
 7704
 7705        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7706            cx.propagate();
 7707            return;
 7708        }
 7709
 7710        let text_layout_details = &self.text_layout_details(cx);
 7711
 7712        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7713            let line_mode = s.line_mode;
 7714            s.move_with(|map, selection| {
 7715                if !selection.is_empty() && !line_mode {
 7716                    selection.goal = SelectionGoal::None;
 7717                }
 7718                let (cursor, goal) = movement::up_by_rows(
 7719                    map,
 7720                    selection.start,
 7721                    action.lines,
 7722                    selection.goal,
 7723                    false,
 7724                    text_layout_details,
 7725                );
 7726                selection.collapse_to(cursor, goal);
 7727            });
 7728        })
 7729    }
 7730
 7731    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 7732        if self.take_rename(true, cx).is_some() {
 7733            return;
 7734        }
 7735
 7736        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7737            cx.propagate();
 7738            return;
 7739        }
 7740
 7741        let text_layout_details = &self.text_layout_details(cx);
 7742
 7743        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7744            let line_mode = s.line_mode;
 7745            s.move_with(|map, selection| {
 7746                if !selection.is_empty() && !line_mode {
 7747                    selection.goal = SelectionGoal::None;
 7748                }
 7749                let (cursor, goal) = movement::down_by_rows(
 7750                    map,
 7751                    selection.start,
 7752                    action.lines,
 7753                    selection.goal,
 7754                    false,
 7755                    text_layout_details,
 7756                );
 7757                selection.collapse_to(cursor, goal);
 7758            });
 7759        })
 7760    }
 7761
 7762    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 7763        let text_layout_details = &self.text_layout_details(cx);
 7764        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7765            s.move_heads_with(|map, head, goal| {
 7766                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7767            })
 7768        })
 7769    }
 7770
 7771    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 7772        let text_layout_details = &self.text_layout_details(cx);
 7773        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7774            s.move_heads_with(|map, head, goal| {
 7775                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7776            })
 7777        })
 7778    }
 7779
 7780    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 7781        let Some(row_count) = self.visible_row_count() else {
 7782            return;
 7783        };
 7784
 7785        let text_layout_details = &self.text_layout_details(cx);
 7786
 7787        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7788            s.move_heads_with(|map, head, goal| {
 7789                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7790            })
 7791        })
 7792    }
 7793
 7794    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 7795        if self.take_rename(true, cx).is_some() {
 7796            return;
 7797        }
 7798
 7799        if self
 7800            .context_menu
 7801            .write()
 7802            .as_mut()
 7803            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 7804            .unwrap_or(false)
 7805        {
 7806            return;
 7807        }
 7808
 7809        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7810            cx.propagate();
 7811            return;
 7812        }
 7813
 7814        let Some(row_count) = self.visible_row_count() else {
 7815            return;
 7816        };
 7817
 7818        let autoscroll = if action.center_cursor {
 7819            Autoscroll::center()
 7820        } else {
 7821            Autoscroll::fit()
 7822        };
 7823
 7824        let text_layout_details = &self.text_layout_details(cx);
 7825
 7826        self.change_selections(Some(autoscroll), cx, |s| {
 7827            let line_mode = s.line_mode;
 7828            s.move_with(|map, selection| {
 7829                if !selection.is_empty() && !line_mode {
 7830                    selection.goal = SelectionGoal::None;
 7831                }
 7832                let (cursor, goal) = movement::up_by_rows(
 7833                    map,
 7834                    selection.end,
 7835                    row_count,
 7836                    selection.goal,
 7837                    false,
 7838                    text_layout_details,
 7839                );
 7840                selection.collapse_to(cursor, goal);
 7841            });
 7842        });
 7843    }
 7844
 7845    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 7846        let text_layout_details = &self.text_layout_details(cx);
 7847        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7848            s.move_heads_with(|map, head, goal| {
 7849                movement::up(map, head, goal, false, text_layout_details)
 7850            })
 7851        })
 7852    }
 7853
 7854    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 7855        self.take_rename(true, cx);
 7856
 7857        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7858            cx.propagate();
 7859            return;
 7860        }
 7861
 7862        let text_layout_details = &self.text_layout_details(cx);
 7863        let selection_count = self.selections.count();
 7864        let first_selection = self.selections.first_anchor();
 7865
 7866        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7867            let line_mode = s.line_mode;
 7868            s.move_with(|map, selection| {
 7869                if !selection.is_empty() && !line_mode {
 7870                    selection.goal = SelectionGoal::None;
 7871                }
 7872                let (cursor, goal) = movement::down(
 7873                    map,
 7874                    selection.end,
 7875                    selection.goal,
 7876                    false,
 7877                    text_layout_details,
 7878                );
 7879                selection.collapse_to(cursor, goal);
 7880            });
 7881        });
 7882
 7883        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7884        {
 7885            cx.propagate();
 7886        }
 7887    }
 7888
 7889    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 7890        let Some(row_count) = self.visible_row_count() else {
 7891            return;
 7892        };
 7893
 7894        let text_layout_details = &self.text_layout_details(cx);
 7895
 7896        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7897            s.move_heads_with(|map, head, goal| {
 7898                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 7899            })
 7900        })
 7901    }
 7902
 7903    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 7904        if self.take_rename(true, cx).is_some() {
 7905            return;
 7906        }
 7907
 7908        if self
 7909            .context_menu
 7910            .write()
 7911            .as_mut()
 7912            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 7913            .unwrap_or(false)
 7914        {
 7915            return;
 7916        }
 7917
 7918        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7919            cx.propagate();
 7920            return;
 7921        }
 7922
 7923        let Some(row_count) = self.visible_row_count() else {
 7924            return;
 7925        };
 7926
 7927        let autoscroll = if action.center_cursor {
 7928            Autoscroll::center()
 7929        } else {
 7930            Autoscroll::fit()
 7931        };
 7932
 7933        let text_layout_details = &self.text_layout_details(cx);
 7934        self.change_selections(Some(autoscroll), cx, |s| {
 7935            let line_mode = s.line_mode;
 7936            s.move_with(|map, selection| {
 7937                if !selection.is_empty() && !line_mode {
 7938                    selection.goal = SelectionGoal::None;
 7939                }
 7940                let (cursor, goal) = movement::down_by_rows(
 7941                    map,
 7942                    selection.end,
 7943                    row_count,
 7944                    selection.goal,
 7945                    false,
 7946                    text_layout_details,
 7947                );
 7948                selection.collapse_to(cursor, goal);
 7949            });
 7950        });
 7951    }
 7952
 7953    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 7954        let text_layout_details = &self.text_layout_details(cx);
 7955        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7956            s.move_heads_with(|map, head, goal| {
 7957                movement::down(map, head, goal, false, text_layout_details)
 7958            })
 7959        });
 7960    }
 7961
 7962    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 7963        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7964            context_menu.select_first(self.completion_provider.as_deref(), cx);
 7965        }
 7966    }
 7967
 7968    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 7969        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7970            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 7971        }
 7972    }
 7973
 7974    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7975        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7976            context_menu.select_next(self.completion_provider.as_deref(), cx);
 7977        }
 7978    }
 7979
 7980    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 7981        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7982            context_menu.select_last(self.completion_provider.as_deref(), cx);
 7983        }
 7984    }
 7985
 7986    pub fn move_to_previous_word_start(
 7987        &mut self,
 7988        _: &MoveToPreviousWordStart,
 7989        cx: &mut ViewContext<Self>,
 7990    ) {
 7991        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7992            s.move_cursors_with(|map, head, _| {
 7993                (
 7994                    movement::previous_word_start(map, head),
 7995                    SelectionGoal::None,
 7996                )
 7997            });
 7998        })
 7999    }
 8000
 8001    pub fn move_to_previous_subword_start(
 8002        &mut self,
 8003        _: &MoveToPreviousSubwordStart,
 8004        cx: &mut ViewContext<Self>,
 8005    ) {
 8006        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8007            s.move_cursors_with(|map, head, _| {
 8008                (
 8009                    movement::previous_subword_start(map, head),
 8010                    SelectionGoal::None,
 8011                )
 8012            });
 8013        })
 8014    }
 8015
 8016    pub fn select_to_previous_word_start(
 8017        &mut self,
 8018        _: &SelectToPreviousWordStart,
 8019        cx: &mut ViewContext<Self>,
 8020    ) {
 8021        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8022            s.move_heads_with(|map, head, _| {
 8023                (
 8024                    movement::previous_word_start(map, head),
 8025                    SelectionGoal::None,
 8026                )
 8027            });
 8028        })
 8029    }
 8030
 8031    pub fn select_to_previous_subword_start(
 8032        &mut self,
 8033        _: &SelectToPreviousSubwordStart,
 8034        cx: &mut ViewContext<Self>,
 8035    ) {
 8036        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8037            s.move_heads_with(|map, head, _| {
 8038                (
 8039                    movement::previous_subword_start(map, head),
 8040                    SelectionGoal::None,
 8041                )
 8042            });
 8043        })
 8044    }
 8045
 8046    pub fn delete_to_previous_word_start(
 8047        &mut self,
 8048        action: &DeleteToPreviousWordStart,
 8049        cx: &mut ViewContext<Self>,
 8050    ) {
 8051        self.transact(cx, |this, cx| {
 8052            this.select_autoclose_pair(cx);
 8053            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8054                let line_mode = s.line_mode;
 8055                s.move_with(|map, selection| {
 8056                    if selection.is_empty() && !line_mode {
 8057                        let cursor = if action.ignore_newlines {
 8058                            movement::previous_word_start(map, selection.head())
 8059                        } else {
 8060                            movement::previous_word_start_or_newline(map, selection.head())
 8061                        };
 8062                        selection.set_head(cursor, SelectionGoal::None);
 8063                    }
 8064                });
 8065            });
 8066            this.insert("", cx);
 8067        });
 8068    }
 8069
 8070    pub fn delete_to_previous_subword_start(
 8071        &mut self,
 8072        _: &DeleteToPreviousSubwordStart,
 8073        cx: &mut ViewContext<Self>,
 8074    ) {
 8075        self.transact(cx, |this, cx| {
 8076            this.select_autoclose_pair(cx);
 8077            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8078                let line_mode = s.line_mode;
 8079                s.move_with(|map, selection| {
 8080                    if selection.is_empty() && !line_mode {
 8081                        let cursor = movement::previous_subword_start(map, selection.head());
 8082                        selection.set_head(cursor, SelectionGoal::None);
 8083                    }
 8084                });
 8085            });
 8086            this.insert("", cx);
 8087        });
 8088    }
 8089
 8090    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 8091        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8092            s.move_cursors_with(|map, head, _| {
 8093                (movement::next_word_end(map, head), SelectionGoal::None)
 8094            });
 8095        })
 8096    }
 8097
 8098    pub fn move_to_next_subword_end(
 8099        &mut self,
 8100        _: &MoveToNextSubwordEnd,
 8101        cx: &mut ViewContext<Self>,
 8102    ) {
 8103        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8104            s.move_cursors_with(|map, head, _| {
 8105                (movement::next_subword_end(map, head), SelectionGoal::None)
 8106            });
 8107        })
 8108    }
 8109
 8110    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 8111        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8112            s.move_heads_with(|map, head, _| {
 8113                (movement::next_word_end(map, head), SelectionGoal::None)
 8114            });
 8115        })
 8116    }
 8117
 8118    pub fn select_to_next_subword_end(
 8119        &mut self,
 8120        _: &SelectToNextSubwordEnd,
 8121        cx: &mut ViewContext<Self>,
 8122    ) {
 8123        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8124            s.move_heads_with(|map, head, _| {
 8125                (movement::next_subword_end(map, head), SelectionGoal::None)
 8126            });
 8127        })
 8128    }
 8129
 8130    pub fn delete_to_next_word_end(
 8131        &mut self,
 8132        action: &DeleteToNextWordEnd,
 8133        cx: &mut ViewContext<Self>,
 8134    ) {
 8135        self.transact(cx, |this, cx| {
 8136            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8137                let line_mode = s.line_mode;
 8138                s.move_with(|map, selection| {
 8139                    if selection.is_empty() && !line_mode {
 8140                        let cursor = if action.ignore_newlines {
 8141                            movement::next_word_end(map, selection.head())
 8142                        } else {
 8143                            movement::next_word_end_or_newline(map, selection.head())
 8144                        };
 8145                        selection.set_head(cursor, SelectionGoal::None);
 8146                    }
 8147                });
 8148            });
 8149            this.insert("", cx);
 8150        });
 8151    }
 8152
 8153    pub fn delete_to_next_subword_end(
 8154        &mut self,
 8155        _: &DeleteToNextSubwordEnd,
 8156        cx: &mut ViewContext<Self>,
 8157    ) {
 8158        self.transact(cx, |this, cx| {
 8159            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8160                s.move_with(|map, selection| {
 8161                    if selection.is_empty() {
 8162                        let cursor = movement::next_subword_end(map, selection.head());
 8163                        selection.set_head(cursor, SelectionGoal::None);
 8164                    }
 8165                });
 8166            });
 8167            this.insert("", cx);
 8168        });
 8169    }
 8170
 8171    pub fn move_to_beginning_of_line(
 8172        &mut self,
 8173        action: &MoveToBeginningOfLine,
 8174        cx: &mut ViewContext<Self>,
 8175    ) {
 8176        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8177            s.move_cursors_with(|map, head, _| {
 8178                (
 8179                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8180                    SelectionGoal::None,
 8181                )
 8182            });
 8183        })
 8184    }
 8185
 8186    pub fn select_to_beginning_of_line(
 8187        &mut self,
 8188        action: &SelectToBeginningOfLine,
 8189        cx: &mut ViewContext<Self>,
 8190    ) {
 8191        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8192            s.move_heads_with(|map, head, _| {
 8193                (
 8194                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8195                    SelectionGoal::None,
 8196                )
 8197            });
 8198        });
 8199    }
 8200
 8201    pub fn delete_to_beginning_of_line(
 8202        &mut self,
 8203        _: &DeleteToBeginningOfLine,
 8204        cx: &mut ViewContext<Self>,
 8205    ) {
 8206        self.transact(cx, |this, cx| {
 8207            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8208                s.move_with(|_, selection| {
 8209                    selection.reversed = true;
 8210                });
 8211            });
 8212
 8213            this.select_to_beginning_of_line(
 8214                &SelectToBeginningOfLine {
 8215                    stop_at_soft_wraps: false,
 8216                },
 8217                cx,
 8218            );
 8219            this.backspace(&Backspace, cx);
 8220        });
 8221    }
 8222
 8223    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 8224        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8225            s.move_cursors_with(|map, head, _| {
 8226                (
 8227                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8228                    SelectionGoal::None,
 8229                )
 8230            });
 8231        })
 8232    }
 8233
 8234    pub fn select_to_end_of_line(
 8235        &mut self,
 8236        action: &SelectToEndOfLine,
 8237        cx: &mut ViewContext<Self>,
 8238    ) {
 8239        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8240            s.move_heads_with(|map, head, _| {
 8241                (
 8242                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8243                    SelectionGoal::None,
 8244                )
 8245            });
 8246        })
 8247    }
 8248
 8249    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 8250        self.transact(cx, |this, cx| {
 8251            this.select_to_end_of_line(
 8252                &SelectToEndOfLine {
 8253                    stop_at_soft_wraps: false,
 8254                },
 8255                cx,
 8256            );
 8257            this.delete(&Delete, cx);
 8258        });
 8259    }
 8260
 8261    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 8262        self.transact(cx, |this, cx| {
 8263            this.select_to_end_of_line(
 8264                &SelectToEndOfLine {
 8265                    stop_at_soft_wraps: false,
 8266                },
 8267                cx,
 8268            );
 8269            this.cut(&Cut, cx);
 8270        });
 8271    }
 8272
 8273    pub fn move_to_start_of_paragraph(
 8274        &mut self,
 8275        _: &MoveToStartOfParagraph,
 8276        cx: &mut ViewContext<Self>,
 8277    ) {
 8278        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8279            cx.propagate();
 8280            return;
 8281        }
 8282
 8283        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8284            s.move_with(|map, selection| {
 8285                selection.collapse_to(
 8286                    movement::start_of_paragraph(map, selection.head(), 1),
 8287                    SelectionGoal::None,
 8288                )
 8289            });
 8290        })
 8291    }
 8292
 8293    pub fn move_to_end_of_paragraph(
 8294        &mut self,
 8295        _: &MoveToEndOfParagraph,
 8296        cx: &mut ViewContext<Self>,
 8297    ) {
 8298        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8299            cx.propagate();
 8300            return;
 8301        }
 8302
 8303        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8304            s.move_with(|map, selection| {
 8305                selection.collapse_to(
 8306                    movement::end_of_paragraph(map, selection.head(), 1),
 8307                    SelectionGoal::None,
 8308                )
 8309            });
 8310        })
 8311    }
 8312
 8313    pub fn select_to_start_of_paragraph(
 8314        &mut self,
 8315        _: &SelectToStartOfParagraph,
 8316        cx: &mut ViewContext<Self>,
 8317    ) {
 8318        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8319            cx.propagate();
 8320            return;
 8321        }
 8322
 8323        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8324            s.move_heads_with(|map, head, _| {
 8325                (
 8326                    movement::start_of_paragraph(map, head, 1),
 8327                    SelectionGoal::None,
 8328                )
 8329            });
 8330        })
 8331    }
 8332
 8333    pub fn select_to_end_of_paragraph(
 8334        &mut self,
 8335        _: &SelectToEndOfParagraph,
 8336        cx: &mut ViewContext<Self>,
 8337    ) {
 8338        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8339            cx.propagate();
 8340            return;
 8341        }
 8342
 8343        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8344            s.move_heads_with(|map, head, _| {
 8345                (
 8346                    movement::end_of_paragraph(map, head, 1),
 8347                    SelectionGoal::None,
 8348                )
 8349            });
 8350        })
 8351    }
 8352
 8353    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 8354        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8355            cx.propagate();
 8356            return;
 8357        }
 8358
 8359        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8360            s.select_ranges(vec![0..0]);
 8361        });
 8362    }
 8363
 8364    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 8365        let mut selection = self.selections.last::<Point>(cx);
 8366        selection.set_head(Point::zero(), SelectionGoal::None);
 8367
 8368        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8369            s.select(vec![selection]);
 8370        });
 8371    }
 8372
 8373    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 8374        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8375            cx.propagate();
 8376            return;
 8377        }
 8378
 8379        let cursor = self.buffer.read(cx).read(cx).len();
 8380        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8381            s.select_ranges(vec![cursor..cursor])
 8382        });
 8383    }
 8384
 8385    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 8386        self.nav_history = nav_history;
 8387    }
 8388
 8389    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 8390        self.nav_history.as_ref()
 8391    }
 8392
 8393    fn push_to_nav_history(
 8394        &mut self,
 8395        cursor_anchor: Anchor,
 8396        new_position: Option<Point>,
 8397        cx: &mut ViewContext<Self>,
 8398    ) {
 8399        if let Some(nav_history) = self.nav_history.as_mut() {
 8400            let buffer = self.buffer.read(cx).read(cx);
 8401            let cursor_position = cursor_anchor.to_point(&buffer);
 8402            let scroll_state = self.scroll_manager.anchor();
 8403            let scroll_top_row = scroll_state.top_row(&buffer);
 8404            drop(buffer);
 8405
 8406            if let Some(new_position) = new_position {
 8407                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 8408                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 8409                    return;
 8410                }
 8411            }
 8412
 8413            nav_history.push(
 8414                Some(NavigationData {
 8415                    cursor_anchor,
 8416                    cursor_position,
 8417                    scroll_anchor: scroll_state,
 8418                    scroll_top_row,
 8419                }),
 8420                cx,
 8421            );
 8422        }
 8423    }
 8424
 8425    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 8426        let buffer = self.buffer.read(cx).snapshot(cx);
 8427        let mut selection = self.selections.first::<usize>(cx);
 8428        selection.set_head(buffer.len(), SelectionGoal::None);
 8429        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8430            s.select(vec![selection]);
 8431        });
 8432    }
 8433
 8434    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 8435        let end = self.buffer.read(cx).read(cx).len();
 8436        self.change_selections(None, cx, |s| {
 8437            s.select_ranges(vec![0..end]);
 8438        });
 8439    }
 8440
 8441    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 8442        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8443        let mut selections = self.selections.all::<Point>(cx);
 8444        let max_point = display_map.buffer_snapshot.max_point();
 8445        for selection in &mut selections {
 8446            let rows = selection.spanned_rows(true, &display_map);
 8447            selection.start = Point::new(rows.start.0, 0);
 8448            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 8449            selection.reversed = false;
 8450        }
 8451        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8452            s.select(selections);
 8453        });
 8454    }
 8455
 8456    pub fn split_selection_into_lines(
 8457        &mut self,
 8458        _: &SplitSelectionIntoLines,
 8459        cx: &mut ViewContext<Self>,
 8460    ) {
 8461        let mut to_unfold = Vec::new();
 8462        let mut new_selection_ranges = Vec::new();
 8463        {
 8464            let selections = self.selections.all::<Point>(cx);
 8465            let buffer = self.buffer.read(cx).read(cx);
 8466            for selection in selections {
 8467                for row in selection.start.row..selection.end.row {
 8468                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 8469                    new_selection_ranges.push(cursor..cursor);
 8470                }
 8471                new_selection_ranges.push(selection.end..selection.end);
 8472                to_unfold.push(selection.start..selection.end);
 8473            }
 8474        }
 8475        self.unfold_ranges(&to_unfold, true, true, cx);
 8476        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8477            s.select_ranges(new_selection_ranges);
 8478        });
 8479    }
 8480
 8481    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 8482        self.add_selection(true, cx);
 8483    }
 8484
 8485    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 8486        self.add_selection(false, cx);
 8487    }
 8488
 8489    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 8490        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8491        let mut selections = self.selections.all::<Point>(cx);
 8492        let text_layout_details = self.text_layout_details(cx);
 8493        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 8494            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 8495            let range = oldest_selection.display_range(&display_map).sorted();
 8496
 8497            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 8498            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 8499            let positions = start_x.min(end_x)..start_x.max(end_x);
 8500
 8501            selections.clear();
 8502            let mut stack = Vec::new();
 8503            for row in range.start.row().0..=range.end.row().0 {
 8504                if let Some(selection) = self.selections.build_columnar_selection(
 8505                    &display_map,
 8506                    DisplayRow(row),
 8507                    &positions,
 8508                    oldest_selection.reversed,
 8509                    &text_layout_details,
 8510                ) {
 8511                    stack.push(selection.id);
 8512                    selections.push(selection);
 8513                }
 8514            }
 8515
 8516            if above {
 8517                stack.reverse();
 8518            }
 8519
 8520            AddSelectionsState { above, stack }
 8521        });
 8522
 8523        let last_added_selection = *state.stack.last().unwrap();
 8524        let mut new_selections = Vec::new();
 8525        if above == state.above {
 8526            let end_row = if above {
 8527                DisplayRow(0)
 8528            } else {
 8529                display_map.max_point().row()
 8530            };
 8531
 8532            'outer: for selection in selections {
 8533                if selection.id == last_added_selection {
 8534                    let range = selection.display_range(&display_map).sorted();
 8535                    debug_assert_eq!(range.start.row(), range.end.row());
 8536                    let mut row = range.start.row();
 8537                    let positions =
 8538                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 8539                            px(start)..px(end)
 8540                        } else {
 8541                            let start_x =
 8542                                display_map.x_for_display_point(range.start, &text_layout_details);
 8543                            let end_x =
 8544                                display_map.x_for_display_point(range.end, &text_layout_details);
 8545                            start_x.min(end_x)..start_x.max(end_x)
 8546                        };
 8547
 8548                    while row != end_row {
 8549                        if above {
 8550                            row.0 -= 1;
 8551                        } else {
 8552                            row.0 += 1;
 8553                        }
 8554
 8555                        if let Some(new_selection) = self.selections.build_columnar_selection(
 8556                            &display_map,
 8557                            row,
 8558                            &positions,
 8559                            selection.reversed,
 8560                            &text_layout_details,
 8561                        ) {
 8562                            state.stack.push(new_selection.id);
 8563                            if above {
 8564                                new_selections.push(new_selection);
 8565                                new_selections.push(selection);
 8566                            } else {
 8567                                new_selections.push(selection);
 8568                                new_selections.push(new_selection);
 8569                            }
 8570
 8571                            continue 'outer;
 8572                        }
 8573                    }
 8574                }
 8575
 8576                new_selections.push(selection);
 8577            }
 8578        } else {
 8579            new_selections = selections;
 8580            new_selections.retain(|s| s.id != last_added_selection);
 8581            state.stack.pop();
 8582        }
 8583
 8584        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8585            s.select(new_selections);
 8586        });
 8587        if state.stack.len() > 1 {
 8588            self.add_selections_state = Some(state);
 8589        }
 8590    }
 8591
 8592    pub fn select_next_match_internal(
 8593        &mut self,
 8594        display_map: &DisplaySnapshot,
 8595        replace_newest: bool,
 8596        autoscroll: Option<Autoscroll>,
 8597        cx: &mut ViewContext<Self>,
 8598    ) -> Result<()> {
 8599        fn select_next_match_ranges(
 8600            this: &mut Editor,
 8601            range: Range<usize>,
 8602            replace_newest: bool,
 8603            auto_scroll: Option<Autoscroll>,
 8604            cx: &mut ViewContext<Editor>,
 8605        ) {
 8606            this.unfold_ranges(&[range.clone()], false, true, cx);
 8607            this.change_selections(auto_scroll, cx, |s| {
 8608                if replace_newest {
 8609                    s.delete(s.newest_anchor().id);
 8610                }
 8611                s.insert_range(range.clone());
 8612            });
 8613        }
 8614
 8615        let buffer = &display_map.buffer_snapshot;
 8616        let mut selections = self.selections.all::<usize>(cx);
 8617        if let Some(mut select_next_state) = self.select_next_state.take() {
 8618            let query = &select_next_state.query;
 8619            if !select_next_state.done {
 8620                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8621                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8622                let mut next_selected_range = None;
 8623
 8624                let bytes_after_last_selection =
 8625                    buffer.bytes_in_range(last_selection.end..buffer.len());
 8626                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 8627                let query_matches = query
 8628                    .stream_find_iter(bytes_after_last_selection)
 8629                    .map(|result| (last_selection.end, result))
 8630                    .chain(
 8631                        query
 8632                            .stream_find_iter(bytes_before_first_selection)
 8633                            .map(|result| (0, result)),
 8634                    );
 8635
 8636                for (start_offset, query_match) in query_matches {
 8637                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8638                    let offset_range =
 8639                        start_offset + query_match.start()..start_offset + query_match.end();
 8640                    let display_range = offset_range.start.to_display_point(display_map)
 8641                        ..offset_range.end.to_display_point(display_map);
 8642
 8643                    if !select_next_state.wordwise
 8644                        || (!movement::is_inside_word(display_map, display_range.start)
 8645                            && !movement::is_inside_word(display_map, display_range.end))
 8646                    {
 8647                        // TODO: This is n^2, because we might check all the selections
 8648                        if !selections
 8649                            .iter()
 8650                            .any(|selection| selection.range().overlaps(&offset_range))
 8651                        {
 8652                            next_selected_range = Some(offset_range);
 8653                            break;
 8654                        }
 8655                    }
 8656                }
 8657
 8658                if let Some(next_selected_range) = next_selected_range {
 8659                    select_next_match_ranges(
 8660                        self,
 8661                        next_selected_range,
 8662                        replace_newest,
 8663                        autoscroll,
 8664                        cx,
 8665                    );
 8666                } else {
 8667                    select_next_state.done = true;
 8668                }
 8669            }
 8670
 8671            self.select_next_state = Some(select_next_state);
 8672        } else {
 8673            let mut only_carets = true;
 8674            let mut same_text_selected = true;
 8675            let mut selected_text = None;
 8676
 8677            let mut selections_iter = selections.iter().peekable();
 8678            while let Some(selection) = selections_iter.next() {
 8679                if selection.start != selection.end {
 8680                    only_carets = false;
 8681                }
 8682
 8683                if same_text_selected {
 8684                    if selected_text.is_none() {
 8685                        selected_text =
 8686                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8687                    }
 8688
 8689                    if let Some(next_selection) = selections_iter.peek() {
 8690                        if next_selection.range().len() == selection.range().len() {
 8691                            let next_selected_text = buffer
 8692                                .text_for_range(next_selection.range())
 8693                                .collect::<String>();
 8694                            if Some(next_selected_text) != selected_text {
 8695                                same_text_selected = false;
 8696                                selected_text = None;
 8697                            }
 8698                        } else {
 8699                            same_text_selected = false;
 8700                            selected_text = None;
 8701                        }
 8702                    }
 8703                }
 8704            }
 8705
 8706            if only_carets {
 8707                for selection in &mut selections {
 8708                    let word_range = movement::surrounding_word(
 8709                        display_map,
 8710                        selection.start.to_display_point(display_map),
 8711                    );
 8712                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 8713                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 8714                    selection.goal = SelectionGoal::None;
 8715                    selection.reversed = false;
 8716                    select_next_match_ranges(
 8717                        self,
 8718                        selection.start..selection.end,
 8719                        replace_newest,
 8720                        autoscroll,
 8721                        cx,
 8722                    );
 8723                }
 8724
 8725                if selections.len() == 1 {
 8726                    let selection = selections
 8727                        .last()
 8728                        .expect("ensured that there's only one selection");
 8729                    let query = buffer
 8730                        .text_for_range(selection.start..selection.end)
 8731                        .collect::<String>();
 8732                    let is_empty = query.is_empty();
 8733                    let select_state = SelectNextState {
 8734                        query: AhoCorasick::new(&[query])?,
 8735                        wordwise: true,
 8736                        done: is_empty,
 8737                    };
 8738                    self.select_next_state = Some(select_state);
 8739                } else {
 8740                    self.select_next_state = None;
 8741                }
 8742            } else if let Some(selected_text) = selected_text {
 8743                self.select_next_state = Some(SelectNextState {
 8744                    query: AhoCorasick::new(&[selected_text])?,
 8745                    wordwise: false,
 8746                    done: false,
 8747                });
 8748                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 8749            }
 8750        }
 8751        Ok(())
 8752    }
 8753
 8754    pub fn select_all_matches(
 8755        &mut self,
 8756        _action: &SelectAllMatches,
 8757        cx: &mut ViewContext<Self>,
 8758    ) -> Result<()> {
 8759        self.push_to_selection_history();
 8760        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8761
 8762        self.select_next_match_internal(&display_map, false, None, cx)?;
 8763        let Some(select_next_state) = self.select_next_state.as_mut() else {
 8764            return Ok(());
 8765        };
 8766        if select_next_state.done {
 8767            return Ok(());
 8768        }
 8769
 8770        let mut new_selections = self.selections.all::<usize>(cx);
 8771
 8772        let buffer = &display_map.buffer_snapshot;
 8773        let query_matches = select_next_state
 8774            .query
 8775            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 8776
 8777        for query_match in query_matches {
 8778            let query_match = query_match.unwrap(); // can only fail due to I/O
 8779            let offset_range = query_match.start()..query_match.end();
 8780            let display_range = offset_range.start.to_display_point(&display_map)
 8781                ..offset_range.end.to_display_point(&display_map);
 8782
 8783            if !select_next_state.wordwise
 8784                || (!movement::is_inside_word(&display_map, display_range.start)
 8785                    && !movement::is_inside_word(&display_map, display_range.end))
 8786            {
 8787                self.selections.change_with(cx, |selections| {
 8788                    new_selections.push(Selection {
 8789                        id: selections.new_selection_id(),
 8790                        start: offset_range.start,
 8791                        end: offset_range.end,
 8792                        reversed: false,
 8793                        goal: SelectionGoal::None,
 8794                    });
 8795                });
 8796            }
 8797        }
 8798
 8799        new_selections.sort_by_key(|selection| selection.start);
 8800        let mut ix = 0;
 8801        while ix + 1 < new_selections.len() {
 8802            let current_selection = &new_selections[ix];
 8803            let next_selection = &new_selections[ix + 1];
 8804            if current_selection.range().overlaps(&next_selection.range()) {
 8805                if current_selection.id < next_selection.id {
 8806                    new_selections.remove(ix + 1);
 8807                } else {
 8808                    new_selections.remove(ix);
 8809                }
 8810            } else {
 8811                ix += 1;
 8812            }
 8813        }
 8814
 8815        select_next_state.done = true;
 8816        self.unfold_ranges(
 8817            &new_selections
 8818                .iter()
 8819                .map(|selection| selection.range())
 8820                .collect::<Vec<_>>(),
 8821            false,
 8822            false,
 8823            cx,
 8824        );
 8825        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 8826            selections.select(new_selections)
 8827        });
 8828
 8829        Ok(())
 8830    }
 8831
 8832    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 8833        self.push_to_selection_history();
 8834        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8835        self.select_next_match_internal(
 8836            &display_map,
 8837            action.replace_newest,
 8838            Some(Autoscroll::newest()),
 8839            cx,
 8840        )?;
 8841        Ok(())
 8842    }
 8843
 8844    pub fn select_previous(
 8845        &mut self,
 8846        action: &SelectPrevious,
 8847        cx: &mut ViewContext<Self>,
 8848    ) -> Result<()> {
 8849        self.push_to_selection_history();
 8850        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8851        let buffer = &display_map.buffer_snapshot;
 8852        let mut selections = self.selections.all::<usize>(cx);
 8853        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8854            let query = &select_prev_state.query;
 8855            if !select_prev_state.done {
 8856                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8857                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8858                let mut next_selected_range = None;
 8859                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8860                let bytes_before_last_selection =
 8861                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8862                let bytes_after_first_selection =
 8863                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8864                let query_matches = query
 8865                    .stream_find_iter(bytes_before_last_selection)
 8866                    .map(|result| (last_selection.start, result))
 8867                    .chain(
 8868                        query
 8869                            .stream_find_iter(bytes_after_first_selection)
 8870                            .map(|result| (buffer.len(), result)),
 8871                    );
 8872                for (end_offset, query_match) in query_matches {
 8873                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8874                    let offset_range =
 8875                        end_offset - query_match.end()..end_offset - query_match.start();
 8876                    let display_range = offset_range.start.to_display_point(&display_map)
 8877                        ..offset_range.end.to_display_point(&display_map);
 8878
 8879                    if !select_prev_state.wordwise
 8880                        || (!movement::is_inside_word(&display_map, display_range.start)
 8881                            && !movement::is_inside_word(&display_map, display_range.end))
 8882                    {
 8883                        next_selected_range = Some(offset_range);
 8884                        break;
 8885                    }
 8886                }
 8887
 8888                if let Some(next_selected_range) = next_selected_range {
 8889                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 8890                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8891                        if action.replace_newest {
 8892                            s.delete(s.newest_anchor().id);
 8893                        }
 8894                        s.insert_range(next_selected_range);
 8895                    });
 8896                } else {
 8897                    select_prev_state.done = true;
 8898                }
 8899            }
 8900
 8901            self.select_prev_state = Some(select_prev_state);
 8902        } else {
 8903            let mut only_carets = true;
 8904            let mut same_text_selected = true;
 8905            let mut selected_text = None;
 8906
 8907            let mut selections_iter = selections.iter().peekable();
 8908            while let Some(selection) = selections_iter.next() {
 8909                if selection.start != selection.end {
 8910                    only_carets = false;
 8911                }
 8912
 8913                if same_text_selected {
 8914                    if selected_text.is_none() {
 8915                        selected_text =
 8916                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8917                    }
 8918
 8919                    if let Some(next_selection) = selections_iter.peek() {
 8920                        if next_selection.range().len() == selection.range().len() {
 8921                            let next_selected_text = buffer
 8922                                .text_for_range(next_selection.range())
 8923                                .collect::<String>();
 8924                            if Some(next_selected_text) != selected_text {
 8925                                same_text_selected = false;
 8926                                selected_text = None;
 8927                            }
 8928                        } else {
 8929                            same_text_selected = false;
 8930                            selected_text = None;
 8931                        }
 8932                    }
 8933                }
 8934            }
 8935
 8936            if only_carets {
 8937                for selection in &mut selections {
 8938                    let word_range = movement::surrounding_word(
 8939                        &display_map,
 8940                        selection.start.to_display_point(&display_map),
 8941                    );
 8942                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8943                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8944                    selection.goal = SelectionGoal::None;
 8945                    selection.reversed = false;
 8946                }
 8947                if selections.len() == 1 {
 8948                    let selection = selections
 8949                        .last()
 8950                        .expect("ensured that there's only one selection");
 8951                    let query = buffer
 8952                        .text_for_range(selection.start..selection.end)
 8953                        .collect::<String>();
 8954                    let is_empty = query.is_empty();
 8955                    let select_state = SelectNextState {
 8956                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8957                        wordwise: true,
 8958                        done: is_empty,
 8959                    };
 8960                    self.select_prev_state = Some(select_state);
 8961                } else {
 8962                    self.select_prev_state = None;
 8963                }
 8964
 8965                self.unfold_ranges(
 8966                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8967                    false,
 8968                    true,
 8969                    cx,
 8970                );
 8971                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8972                    s.select(selections);
 8973                });
 8974            } else if let Some(selected_text) = selected_text {
 8975                self.select_prev_state = Some(SelectNextState {
 8976                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8977                    wordwise: false,
 8978                    done: false,
 8979                });
 8980                self.select_previous(action, cx)?;
 8981            }
 8982        }
 8983        Ok(())
 8984    }
 8985
 8986    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 8987        if self.read_only(cx) {
 8988            return;
 8989        }
 8990        let text_layout_details = &self.text_layout_details(cx);
 8991        self.transact(cx, |this, cx| {
 8992            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8993            let mut edits = Vec::new();
 8994            let mut selection_edit_ranges = Vec::new();
 8995            let mut last_toggled_row = None;
 8996            let snapshot = this.buffer.read(cx).read(cx);
 8997            let empty_str: Arc<str> = Arc::default();
 8998            let mut suffixes_inserted = Vec::new();
 8999            let ignore_indent = action.ignore_indent;
 9000
 9001            fn comment_prefix_range(
 9002                snapshot: &MultiBufferSnapshot,
 9003                row: MultiBufferRow,
 9004                comment_prefix: &str,
 9005                comment_prefix_whitespace: &str,
 9006                ignore_indent: bool,
 9007            ) -> Range<Point> {
 9008                let indent_size = if ignore_indent {
 9009                    0
 9010                } else {
 9011                    snapshot.indent_size_for_line(row).len
 9012                };
 9013
 9014                let start = Point::new(row.0, indent_size);
 9015
 9016                let mut line_bytes = snapshot
 9017                    .bytes_in_range(start..snapshot.max_point())
 9018                    .flatten()
 9019                    .copied();
 9020
 9021                // If this line currently begins with the line comment prefix, then record
 9022                // the range containing the prefix.
 9023                if line_bytes
 9024                    .by_ref()
 9025                    .take(comment_prefix.len())
 9026                    .eq(comment_prefix.bytes())
 9027                {
 9028                    // Include any whitespace that matches the comment prefix.
 9029                    let matching_whitespace_len = line_bytes
 9030                        .zip(comment_prefix_whitespace.bytes())
 9031                        .take_while(|(a, b)| a == b)
 9032                        .count() as u32;
 9033                    let end = Point::new(
 9034                        start.row,
 9035                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 9036                    );
 9037                    start..end
 9038                } else {
 9039                    start..start
 9040                }
 9041            }
 9042
 9043            fn comment_suffix_range(
 9044                snapshot: &MultiBufferSnapshot,
 9045                row: MultiBufferRow,
 9046                comment_suffix: &str,
 9047                comment_suffix_has_leading_space: bool,
 9048            ) -> Range<Point> {
 9049                let end = Point::new(row.0, snapshot.line_len(row));
 9050                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 9051
 9052                let mut line_end_bytes = snapshot
 9053                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 9054                    .flatten()
 9055                    .copied();
 9056
 9057                let leading_space_len = if suffix_start_column > 0
 9058                    && line_end_bytes.next() == Some(b' ')
 9059                    && comment_suffix_has_leading_space
 9060                {
 9061                    1
 9062                } else {
 9063                    0
 9064                };
 9065
 9066                // If this line currently begins with the line comment prefix, then record
 9067                // the range containing the prefix.
 9068                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 9069                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 9070                    start..end
 9071                } else {
 9072                    end..end
 9073                }
 9074            }
 9075
 9076            // TODO: Handle selections that cross excerpts
 9077            for selection in &mut selections {
 9078                let start_column = snapshot
 9079                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 9080                    .len;
 9081                let language = if let Some(language) =
 9082                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 9083                {
 9084                    language
 9085                } else {
 9086                    continue;
 9087                };
 9088
 9089                selection_edit_ranges.clear();
 9090
 9091                // If multiple selections contain a given row, avoid processing that
 9092                // row more than once.
 9093                let mut start_row = MultiBufferRow(selection.start.row);
 9094                if last_toggled_row == Some(start_row) {
 9095                    start_row = start_row.next_row();
 9096                }
 9097                let end_row =
 9098                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 9099                        MultiBufferRow(selection.end.row - 1)
 9100                    } else {
 9101                        MultiBufferRow(selection.end.row)
 9102                    };
 9103                last_toggled_row = Some(end_row);
 9104
 9105                if start_row > end_row {
 9106                    continue;
 9107                }
 9108
 9109                // If the language has line comments, toggle those.
 9110                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 9111
 9112                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 9113                if ignore_indent {
 9114                    full_comment_prefixes = full_comment_prefixes
 9115                        .into_iter()
 9116                        .map(|s| Arc::from(s.trim_end()))
 9117                        .collect();
 9118                }
 9119
 9120                if !full_comment_prefixes.is_empty() {
 9121                    let first_prefix = full_comment_prefixes
 9122                        .first()
 9123                        .expect("prefixes is non-empty");
 9124                    let prefix_trimmed_lengths = full_comment_prefixes
 9125                        .iter()
 9126                        .map(|p| p.trim_end_matches(' ').len())
 9127                        .collect::<SmallVec<[usize; 4]>>();
 9128
 9129                    let mut all_selection_lines_are_comments = true;
 9130
 9131                    for row in start_row.0..=end_row.0 {
 9132                        let row = MultiBufferRow(row);
 9133                        if start_row < end_row && snapshot.is_line_blank(row) {
 9134                            continue;
 9135                        }
 9136
 9137                        let prefix_range = full_comment_prefixes
 9138                            .iter()
 9139                            .zip(prefix_trimmed_lengths.iter().copied())
 9140                            .map(|(prefix, trimmed_prefix_len)| {
 9141                                comment_prefix_range(
 9142                                    snapshot.deref(),
 9143                                    row,
 9144                                    &prefix[..trimmed_prefix_len],
 9145                                    &prefix[trimmed_prefix_len..],
 9146                                    ignore_indent,
 9147                                )
 9148                            })
 9149                            .max_by_key(|range| range.end.column - range.start.column)
 9150                            .expect("prefixes is non-empty");
 9151
 9152                        if prefix_range.is_empty() {
 9153                            all_selection_lines_are_comments = false;
 9154                        }
 9155
 9156                        selection_edit_ranges.push(prefix_range);
 9157                    }
 9158
 9159                    if all_selection_lines_are_comments {
 9160                        edits.extend(
 9161                            selection_edit_ranges
 9162                                .iter()
 9163                                .cloned()
 9164                                .map(|range| (range, empty_str.clone())),
 9165                        );
 9166                    } else {
 9167                        let min_column = selection_edit_ranges
 9168                            .iter()
 9169                            .map(|range| range.start.column)
 9170                            .min()
 9171                            .unwrap_or(0);
 9172                        edits.extend(selection_edit_ranges.iter().map(|range| {
 9173                            let position = Point::new(range.start.row, min_column);
 9174                            (position..position, first_prefix.clone())
 9175                        }));
 9176                    }
 9177                } else if let Some((full_comment_prefix, comment_suffix)) =
 9178                    language.block_comment_delimiters()
 9179                {
 9180                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 9181                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 9182                    let prefix_range = comment_prefix_range(
 9183                        snapshot.deref(),
 9184                        start_row,
 9185                        comment_prefix,
 9186                        comment_prefix_whitespace,
 9187                        ignore_indent,
 9188                    );
 9189                    let suffix_range = comment_suffix_range(
 9190                        snapshot.deref(),
 9191                        end_row,
 9192                        comment_suffix.trim_start_matches(' '),
 9193                        comment_suffix.starts_with(' '),
 9194                    );
 9195
 9196                    if prefix_range.is_empty() || suffix_range.is_empty() {
 9197                        edits.push((
 9198                            prefix_range.start..prefix_range.start,
 9199                            full_comment_prefix.clone(),
 9200                        ));
 9201                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 9202                        suffixes_inserted.push((end_row, comment_suffix.len()));
 9203                    } else {
 9204                        edits.push((prefix_range, empty_str.clone()));
 9205                        edits.push((suffix_range, empty_str.clone()));
 9206                    }
 9207                } else {
 9208                    continue;
 9209                }
 9210            }
 9211
 9212            drop(snapshot);
 9213            this.buffer.update(cx, |buffer, cx| {
 9214                buffer.edit(edits, None, cx);
 9215            });
 9216
 9217            // Adjust selections so that they end before any comment suffixes that
 9218            // were inserted.
 9219            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 9220            let mut selections = this.selections.all::<Point>(cx);
 9221            let snapshot = this.buffer.read(cx).read(cx);
 9222            for selection in &mut selections {
 9223                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 9224                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 9225                        Ordering::Less => {
 9226                            suffixes_inserted.next();
 9227                            continue;
 9228                        }
 9229                        Ordering::Greater => break,
 9230                        Ordering::Equal => {
 9231                            if selection.end.column == snapshot.line_len(row) {
 9232                                if selection.is_empty() {
 9233                                    selection.start.column -= suffix_len as u32;
 9234                                }
 9235                                selection.end.column -= suffix_len as u32;
 9236                            }
 9237                            break;
 9238                        }
 9239                    }
 9240                }
 9241            }
 9242
 9243            drop(snapshot);
 9244            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 9245
 9246            let selections = this.selections.all::<Point>(cx);
 9247            let selections_on_single_row = selections.windows(2).all(|selections| {
 9248                selections[0].start.row == selections[1].start.row
 9249                    && selections[0].end.row == selections[1].end.row
 9250                    && selections[0].start.row == selections[0].end.row
 9251            });
 9252            let selections_selecting = selections
 9253                .iter()
 9254                .any(|selection| selection.start != selection.end);
 9255            let advance_downwards = action.advance_downwards
 9256                && selections_on_single_row
 9257                && !selections_selecting
 9258                && !matches!(this.mode, EditorMode::SingleLine { .. });
 9259
 9260            if advance_downwards {
 9261                let snapshot = this.buffer.read(cx).snapshot(cx);
 9262
 9263                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9264                    s.move_cursors_with(|display_snapshot, display_point, _| {
 9265                        let mut point = display_point.to_point(display_snapshot);
 9266                        point.row += 1;
 9267                        point = snapshot.clip_point(point, Bias::Left);
 9268                        let display_point = point.to_display_point(display_snapshot);
 9269                        let goal = SelectionGoal::HorizontalPosition(
 9270                            display_snapshot
 9271                                .x_for_display_point(display_point, text_layout_details)
 9272                                .into(),
 9273                        );
 9274                        (display_point, goal)
 9275                    })
 9276                });
 9277            }
 9278        });
 9279    }
 9280
 9281    pub fn select_enclosing_symbol(
 9282        &mut self,
 9283        _: &SelectEnclosingSymbol,
 9284        cx: &mut ViewContext<Self>,
 9285    ) {
 9286        let buffer = self.buffer.read(cx).snapshot(cx);
 9287        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9288
 9289        fn update_selection(
 9290            selection: &Selection<usize>,
 9291            buffer_snap: &MultiBufferSnapshot,
 9292        ) -> Option<Selection<usize>> {
 9293            let cursor = selection.head();
 9294            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 9295            for symbol in symbols.iter().rev() {
 9296                let start = symbol.range.start.to_offset(buffer_snap);
 9297                let end = symbol.range.end.to_offset(buffer_snap);
 9298                let new_range = start..end;
 9299                if start < selection.start || end > selection.end {
 9300                    return Some(Selection {
 9301                        id: selection.id,
 9302                        start: new_range.start,
 9303                        end: new_range.end,
 9304                        goal: SelectionGoal::None,
 9305                        reversed: selection.reversed,
 9306                    });
 9307                }
 9308            }
 9309            None
 9310        }
 9311
 9312        let mut selected_larger_symbol = false;
 9313        let new_selections = old_selections
 9314            .iter()
 9315            .map(|selection| match update_selection(selection, &buffer) {
 9316                Some(new_selection) => {
 9317                    if new_selection.range() != selection.range() {
 9318                        selected_larger_symbol = true;
 9319                    }
 9320                    new_selection
 9321                }
 9322                None => selection.clone(),
 9323            })
 9324            .collect::<Vec<_>>();
 9325
 9326        if selected_larger_symbol {
 9327            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9328                s.select(new_selections);
 9329            });
 9330        }
 9331    }
 9332
 9333    pub fn select_larger_syntax_node(
 9334        &mut self,
 9335        _: &SelectLargerSyntaxNode,
 9336        cx: &mut ViewContext<Self>,
 9337    ) {
 9338        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9339        let buffer = self.buffer.read(cx).snapshot(cx);
 9340        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9341
 9342        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9343        let mut selected_larger_node = false;
 9344        let new_selections = old_selections
 9345            .iter()
 9346            .map(|selection| {
 9347                let old_range = selection.start..selection.end;
 9348                let mut new_range = old_range.clone();
 9349                while let Some(containing_range) =
 9350                    buffer.range_for_syntax_ancestor(new_range.clone())
 9351                {
 9352                    new_range = containing_range;
 9353                    if !display_map.intersects_fold(new_range.start)
 9354                        && !display_map.intersects_fold(new_range.end)
 9355                    {
 9356                        break;
 9357                    }
 9358                }
 9359
 9360                selected_larger_node |= new_range != old_range;
 9361                Selection {
 9362                    id: selection.id,
 9363                    start: new_range.start,
 9364                    end: new_range.end,
 9365                    goal: SelectionGoal::None,
 9366                    reversed: selection.reversed,
 9367                }
 9368            })
 9369            .collect::<Vec<_>>();
 9370
 9371        if selected_larger_node {
 9372            stack.push(old_selections);
 9373            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9374                s.select(new_selections);
 9375            });
 9376        }
 9377        self.select_larger_syntax_node_stack = stack;
 9378    }
 9379
 9380    pub fn select_smaller_syntax_node(
 9381        &mut self,
 9382        _: &SelectSmallerSyntaxNode,
 9383        cx: &mut ViewContext<Self>,
 9384    ) {
 9385        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9386        if let Some(selections) = stack.pop() {
 9387            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9388                s.select(selections.to_vec());
 9389            });
 9390        }
 9391        self.select_larger_syntax_node_stack = stack;
 9392    }
 9393
 9394    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 9395        if !EditorSettings::get_global(cx).gutter.runnables {
 9396            self.clear_tasks();
 9397            return Task::ready(());
 9398        }
 9399        let project = self.project.as_ref().map(Model::downgrade);
 9400        cx.spawn(|this, mut cx| async move {
 9401            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
 9402            let Some(project) = project.and_then(|p| p.upgrade()) else {
 9403                return;
 9404            };
 9405            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 9406                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 9407            }) else {
 9408                return;
 9409            };
 9410
 9411            let hide_runnables = project
 9412                .update(&mut cx, |project, cx| {
 9413                    // Do not display any test indicators in non-dev server remote projects.
 9414                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 9415                })
 9416                .unwrap_or(true);
 9417            if hide_runnables {
 9418                return;
 9419            }
 9420            let new_rows =
 9421                cx.background_executor()
 9422                    .spawn({
 9423                        let snapshot = display_snapshot.clone();
 9424                        async move {
 9425                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 9426                        }
 9427                    })
 9428                    .await;
 9429            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 9430
 9431            this.update(&mut cx, |this, _| {
 9432                this.clear_tasks();
 9433                for (key, value) in rows {
 9434                    this.insert_tasks(key, value);
 9435                }
 9436            })
 9437            .ok();
 9438        })
 9439    }
 9440    fn fetch_runnable_ranges(
 9441        snapshot: &DisplaySnapshot,
 9442        range: Range<Anchor>,
 9443    ) -> Vec<language::RunnableRange> {
 9444        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 9445    }
 9446
 9447    fn runnable_rows(
 9448        project: Model<Project>,
 9449        snapshot: DisplaySnapshot,
 9450        runnable_ranges: Vec<RunnableRange>,
 9451        mut cx: AsyncWindowContext,
 9452    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 9453        runnable_ranges
 9454            .into_iter()
 9455            .filter_map(|mut runnable| {
 9456                let tasks = cx
 9457                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 9458                    .ok()?;
 9459                if tasks.is_empty() {
 9460                    return None;
 9461                }
 9462
 9463                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 9464
 9465                let row = snapshot
 9466                    .buffer_snapshot
 9467                    .buffer_line_for_row(MultiBufferRow(point.row))?
 9468                    .1
 9469                    .start
 9470                    .row;
 9471
 9472                let context_range =
 9473                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 9474                Some((
 9475                    (runnable.buffer_id, row),
 9476                    RunnableTasks {
 9477                        templates: tasks,
 9478                        offset: MultiBufferOffset(runnable.run_range.start),
 9479                        context_range,
 9480                        column: point.column,
 9481                        extra_variables: runnable.extra_captures,
 9482                    },
 9483                ))
 9484            })
 9485            .collect()
 9486    }
 9487
 9488    fn templates_with_tags(
 9489        project: &Model<Project>,
 9490        runnable: &mut Runnable,
 9491        cx: &WindowContext<'_>,
 9492    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 9493        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 9494            let (worktree_id, file) = project
 9495                .buffer_for_id(runnable.buffer, cx)
 9496                .and_then(|buffer| buffer.read(cx).file())
 9497                .map(|file| (file.worktree_id(cx), file.clone()))
 9498                .unzip();
 9499
 9500            (
 9501                project.task_store().read(cx).task_inventory().cloned(),
 9502                worktree_id,
 9503                file,
 9504            )
 9505        });
 9506
 9507        let tags = mem::take(&mut runnable.tags);
 9508        let mut tags: Vec<_> = tags
 9509            .into_iter()
 9510            .flat_map(|tag| {
 9511                let tag = tag.0.clone();
 9512                inventory
 9513                    .as_ref()
 9514                    .into_iter()
 9515                    .flat_map(|inventory| {
 9516                        inventory.read(cx).list_tasks(
 9517                            file.clone(),
 9518                            Some(runnable.language.clone()),
 9519                            worktree_id,
 9520                            cx,
 9521                        )
 9522                    })
 9523                    .filter(move |(_, template)| {
 9524                        template.tags.iter().any(|source_tag| source_tag == &tag)
 9525                    })
 9526            })
 9527            .sorted_by_key(|(kind, _)| kind.to_owned())
 9528            .collect();
 9529        if let Some((leading_tag_source, _)) = tags.first() {
 9530            // Strongest source wins; if we have worktree tag binding, prefer that to
 9531            // global and language bindings;
 9532            // if we have a global binding, prefer that to language binding.
 9533            let first_mismatch = tags
 9534                .iter()
 9535                .position(|(tag_source, _)| tag_source != leading_tag_source);
 9536            if let Some(index) = first_mismatch {
 9537                tags.truncate(index);
 9538            }
 9539        }
 9540
 9541        tags
 9542    }
 9543
 9544    pub fn move_to_enclosing_bracket(
 9545        &mut self,
 9546        _: &MoveToEnclosingBracket,
 9547        cx: &mut ViewContext<Self>,
 9548    ) {
 9549        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9550            s.move_offsets_with(|snapshot, selection| {
 9551                let Some(enclosing_bracket_ranges) =
 9552                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 9553                else {
 9554                    return;
 9555                };
 9556
 9557                let mut best_length = usize::MAX;
 9558                let mut best_inside = false;
 9559                let mut best_in_bracket_range = false;
 9560                let mut best_destination = None;
 9561                for (open, close) in enclosing_bracket_ranges {
 9562                    let close = close.to_inclusive();
 9563                    let length = close.end() - open.start;
 9564                    let inside = selection.start >= open.end && selection.end <= *close.start();
 9565                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 9566                        || close.contains(&selection.head());
 9567
 9568                    // If best is next to a bracket and current isn't, skip
 9569                    if !in_bracket_range && best_in_bracket_range {
 9570                        continue;
 9571                    }
 9572
 9573                    // Prefer smaller lengths unless best is inside and current isn't
 9574                    if length > best_length && (best_inside || !inside) {
 9575                        continue;
 9576                    }
 9577
 9578                    best_length = length;
 9579                    best_inside = inside;
 9580                    best_in_bracket_range = in_bracket_range;
 9581                    best_destination = Some(
 9582                        if close.contains(&selection.start) && close.contains(&selection.end) {
 9583                            if inside {
 9584                                open.end
 9585                            } else {
 9586                                open.start
 9587                            }
 9588                        } else if inside {
 9589                            *close.start()
 9590                        } else {
 9591                            *close.end()
 9592                        },
 9593                    );
 9594                }
 9595
 9596                if let Some(destination) = best_destination {
 9597                    selection.collapse_to(destination, SelectionGoal::None);
 9598                }
 9599            })
 9600        });
 9601    }
 9602
 9603    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 9604        self.end_selection(cx);
 9605        self.selection_history.mode = SelectionHistoryMode::Undoing;
 9606        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 9607            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9608            self.select_next_state = entry.select_next_state;
 9609            self.select_prev_state = entry.select_prev_state;
 9610            self.add_selections_state = entry.add_selections_state;
 9611            self.request_autoscroll(Autoscroll::newest(), cx);
 9612        }
 9613        self.selection_history.mode = SelectionHistoryMode::Normal;
 9614    }
 9615
 9616    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 9617        self.end_selection(cx);
 9618        self.selection_history.mode = SelectionHistoryMode::Redoing;
 9619        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 9620            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9621            self.select_next_state = entry.select_next_state;
 9622            self.select_prev_state = entry.select_prev_state;
 9623            self.add_selections_state = entry.add_selections_state;
 9624            self.request_autoscroll(Autoscroll::newest(), cx);
 9625        }
 9626        self.selection_history.mode = SelectionHistoryMode::Normal;
 9627    }
 9628
 9629    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 9630        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 9631    }
 9632
 9633    pub fn expand_excerpts_down(
 9634        &mut self,
 9635        action: &ExpandExcerptsDown,
 9636        cx: &mut ViewContext<Self>,
 9637    ) {
 9638        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 9639    }
 9640
 9641    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 9642        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 9643    }
 9644
 9645    pub fn expand_excerpts_for_direction(
 9646        &mut self,
 9647        lines: u32,
 9648        direction: ExpandExcerptDirection,
 9649        cx: &mut ViewContext<Self>,
 9650    ) {
 9651        let selections = self.selections.disjoint_anchors();
 9652
 9653        let lines = if lines == 0 {
 9654            EditorSettings::get_global(cx).expand_excerpt_lines
 9655        } else {
 9656            lines
 9657        };
 9658
 9659        self.buffer.update(cx, |buffer, cx| {
 9660            buffer.expand_excerpts(
 9661                selections
 9662                    .iter()
 9663                    .map(|selection| selection.head().excerpt_id)
 9664                    .dedup(),
 9665                lines,
 9666                direction,
 9667                cx,
 9668            )
 9669        })
 9670    }
 9671
 9672    pub fn expand_excerpt(
 9673        &mut self,
 9674        excerpt: ExcerptId,
 9675        direction: ExpandExcerptDirection,
 9676        cx: &mut ViewContext<Self>,
 9677    ) {
 9678        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 9679        self.buffer.update(cx, |buffer, cx| {
 9680            buffer.expand_excerpts([excerpt], lines, direction, cx)
 9681        })
 9682    }
 9683
 9684    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 9685        self.go_to_diagnostic_impl(Direction::Next, cx)
 9686    }
 9687
 9688    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 9689        self.go_to_diagnostic_impl(Direction::Prev, cx)
 9690    }
 9691
 9692    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 9693        let buffer = self.buffer.read(cx).snapshot(cx);
 9694        let selection = self.selections.newest::<usize>(cx);
 9695
 9696        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 9697        if direction == Direction::Next {
 9698            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 9699                let (group_id, jump_to) = popover.activation_info();
 9700                if self.activate_diagnostics(group_id, cx) {
 9701                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9702                        let mut new_selection = s.newest_anchor().clone();
 9703                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 9704                        s.select_anchors(vec![new_selection.clone()]);
 9705                    });
 9706                }
 9707                return;
 9708            }
 9709        }
 9710
 9711        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 9712            active_diagnostics
 9713                .primary_range
 9714                .to_offset(&buffer)
 9715                .to_inclusive()
 9716        });
 9717        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 9718            if active_primary_range.contains(&selection.head()) {
 9719                *active_primary_range.start()
 9720            } else {
 9721                selection.head()
 9722            }
 9723        } else {
 9724            selection.head()
 9725        };
 9726        let snapshot = self.snapshot(cx);
 9727        loop {
 9728            let diagnostics = if direction == Direction::Prev {
 9729                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 9730            } else {
 9731                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 9732            }
 9733            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 9734            let group = diagnostics
 9735                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 9736                // be sorted in a stable way
 9737                // skip until we are at current active diagnostic, if it exists
 9738                .skip_while(|entry| {
 9739                    (match direction {
 9740                        Direction::Prev => entry.range.start >= search_start,
 9741                        Direction::Next => entry.range.start <= search_start,
 9742                    }) && self
 9743                        .active_diagnostics
 9744                        .as_ref()
 9745                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 9746                })
 9747                .find_map(|entry| {
 9748                    if entry.diagnostic.is_primary
 9749                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 9750                        && !entry.range.is_empty()
 9751                        // if we match with the active diagnostic, skip it
 9752                        && Some(entry.diagnostic.group_id)
 9753                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 9754                    {
 9755                        Some((entry.range, entry.diagnostic.group_id))
 9756                    } else {
 9757                        None
 9758                    }
 9759                });
 9760
 9761            if let Some((primary_range, group_id)) = group {
 9762                if self.activate_diagnostics(group_id, cx) {
 9763                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9764                        s.select(vec![Selection {
 9765                            id: selection.id,
 9766                            start: primary_range.start,
 9767                            end: primary_range.start,
 9768                            reversed: false,
 9769                            goal: SelectionGoal::None,
 9770                        }]);
 9771                    });
 9772                }
 9773                break;
 9774            } else {
 9775                // Cycle around to the start of the buffer, potentially moving back to the start of
 9776                // the currently active diagnostic.
 9777                active_primary_range.take();
 9778                if direction == Direction::Prev {
 9779                    if search_start == buffer.len() {
 9780                        break;
 9781                    } else {
 9782                        search_start = buffer.len();
 9783                    }
 9784                } else if search_start == 0 {
 9785                    break;
 9786                } else {
 9787                    search_start = 0;
 9788                }
 9789            }
 9790        }
 9791    }
 9792
 9793    fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 9794        let snapshot = self
 9795            .display_map
 9796            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9797        let selection = self.selections.newest::<Point>(cx);
 9798        self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
 9799    }
 9800
 9801    fn go_to_hunk_after_position(
 9802        &mut self,
 9803        snapshot: &DisplaySnapshot,
 9804        position: Point,
 9805        cx: &mut ViewContext<'_, Editor>,
 9806    ) -> Option<MultiBufferDiffHunk> {
 9807        if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9808            snapshot,
 9809            position,
 9810            false,
 9811            snapshot
 9812                .buffer_snapshot
 9813                .git_diff_hunks_in_range(MultiBufferRow(position.row + 1)..MultiBufferRow::MAX),
 9814            cx,
 9815        ) {
 9816            return Some(hunk);
 9817        }
 9818
 9819        let wrapped_point = Point::zero();
 9820        self.go_to_next_hunk_in_direction(
 9821            snapshot,
 9822            wrapped_point,
 9823            true,
 9824            snapshot.buffer_snapshot.git_diff_hunks_in_range(
 9825                MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
 9826            ),
 9827            cx,
 9828        )
 9829    }
 9830
 9831    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 9832        let snapshot = self
 9833            .display_map
 9834            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9835        let selection = self.selections.newest::<Point>(cx);
 9836
 9837        self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
 9838    }
 9839
 9840    fn go_to_hunk_before_position(
 9841        &mut self,
 9842        snapshot: &DisplaySnapshot,
 9843        position: Point,
 9844        cx: &mut ViewContext<'_, Editor>,
 9845    ) -> Option<MultiBufferDiffHunk> {
 9846        if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9847            snapshot,
 9848            position,
 9849            false,
 9850            snapshot
 9851                .buffer_snapshot
 9852                .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(position.row)),
 9853            cx,
 9854        ) {
 9855            return Some(hunk);
 9856        }
 9857
 9858        let wrapped_point = snapshot.buffer_snapshot.max_point();
 9859        self.go_to_next_hunk_in_direction(
 9860            snapshot,
 9861            wrapped_point,
 9862            true,
 9863            snapshot
 9864                .buffer_snapshot
 9865                .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(wrapped_point.row)),
 9866            cx,
 9867        )
 9868    }
 9869
 9870    fn go_to_next_hunk_in_direction(
 9871        &mut self,
 9872        snapshot: &DisplaySnapshot,
 9873        initial_point: Point,
 9874        is_wrapped: bool,
 9875        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
 9876        cx: &mut ViewContext<Editor>,
 9877    ) -> Option<MultiBufferDiffHunk> {
 9878        let display_point = initial_point.to_display_point(snapshot);
 9879        let mut hunks = hunks
 9880            .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
 9881            .filter(|(display_hunk, _)| {
 9882                is_wrapped || !display_hunk.contains_display_row(display_point.row())
 9883            })
 9884            .dedup();
 9885
 9886        if let Some((display_hunk, hunk)) = hunks.next() {
 9887            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9888                let row = display_hunk.start_display_row();
 9889                let point = DisplayPoint::new(row, 0);
 9890                s.select_display_ranges([point..point]);
 9891            });
 9892
 9893            Some(hunk)
 9894        } else {
 9895            None
 9896        }
 9897    }
 9898
 9899    pub fn go_to_definition(
 9900        &mut self,
 9901        _: &GoToDefinition,
 9902        cx: &mut ViewContext<Self>,
 9903    ) -> Task<Result<Navigated>> {
 9904        let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
 9905        cx.spawn(|editor, mut cx| async move {
 9906            if definition.await? == Navigated::Yes {
 9907                return Ok(Navigated::Yes);
 9908            }
 9909            match editor.update(&mut cx, |editor, cx| {
 9910                editor.find_all_references(&FindAllReferences, cx)
 9911            })? {
 9912                Some(references) => references.await,
 9913                None => Ok(Navigated::No),
 9914            }
 9915        })
 9916    }
 9917
 9918    pub fn go_to_declaration(
 9919        &mut self,
 9920        _: &GoToDeclaration,
 9921        cx: &mut ViewContext<Self>,
 9922    ) -> Task<Result<Navigated>> {
 9923        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
 9924    }
 9925
 9926    pub fn go_to_declaration_split(
 9927        &mut self,
 9928        _: &GoToDeclaration,
 9929        cx: &mut ViewContext<Self>,
 9930    ) -> Task<Result<Navigated>> {
 9931        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
 9932    }
 9933
 9934    pub fn go_to_implementation(
 9935        &mut self,
 9936        _: &GoToImplementation,
 9937        cx: &mut ViewContext<Self>,
 9938    ) -> Task<Result<Navigated>> {
 9939        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 9940    }
 9941
 9942    pub fn go_to_implementation_split(
 9943        &mut self,
 9944        _: &GoToImplementationSplit,
 9945        cx: &mut ViewContext<Self>,
 9946    ) -> Task<Result<Navigated>> {
 9947        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 9948    }
 9949
 9950    pub fn go_to_type_definition(
 9951        &mut self,
 9952        _: &GoToTypeDefinition,
 9953        cx: &mut ViewContext<Self>,
 9954    ) -> Task<Result<Navigated>> {
 9955        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 9956    }
 9957
 9958    pub fn go_to_definition_split(
 9959        &mut self,
 9960        _: &GoToDefinitionSplit,
 9961        cx: &mut ViewContext<Self>,
 9962    ) -> Task<Result<Navigated>> {
 9963        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 9964    }
 9965
 9966    pub fn go_to_type_definition_split(
 9967        &mut self,
 9968        _: &GoToTypeDefinitionSplit,
 9969        cx: &mut ViewContext<Self>,
 9970    ) -> Task<Result<Navigated>> {
 9971        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 9972    }
 9973
 9974    fn go_to_definition_of_kind(
 9975        &mut self,
 9976        kind: GotoDefinitionKind,
 9977        split: bool,
 9978        cx: &mut ViewContext<Self>,
 9979    ) -> Task<Result<Navigated>> {
 9980        let Some(provider) = self.semantics_provider.clone() else {
 9981            return Task::ready(Ok(Navigated::No));
 9982        };
 9983        let head = self.selections.newest::<usize>(cx).head();
 9984        let buffer = self.buffer.read(cx);
 9985        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 9986            text_anchor
 9987        } else {
 9988            return Task::ready(Ok(Navigated::No));
 9989        };
 9990
 9991        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
 9992            return Task::ready(Ok(Navigated::No));
 9993        };
 9994
 9995        cx.spawn(|editor, mut cx| async move {
 9996            let definitions = definitions.await?;
 9997            let navigated = editor
 9998                .update(&mut cx, |editor, cx| {
 9999                    editor.navigate_to_hover_links(
10000                        Some(kind),
10001                        definitions
10002                            .into_iter()
10003                            .filter(|location| {
10004                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10005                            })
10006                            .map(HoverLink::Text)
10007                            .collect::<Vec<_>>(),
10008                        split,
10009                        cx,
10010                    )
10011                })?
10012                .await?;
10013            anyhow::Ok(navigated)
10014        })
10015    }
10016
10017    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
10018        let position = self.selections.newest_anchor().head();
10019        let Some((buffer, buffer_position)) =
10020            self.buffer.read(cx).text_anchor_for_position(position, cx)
10021        else {
10022            return;
10023        };
10024
10025        cx.spawn(|editor, mut cx| async move {
10026            if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
10027                editor.update(&mut cx, |_, cx| {
10028                    cx.open_url(&url);
10029                })
10030            } else {
10031                Ok(())
10032            }
10033        })
10034        .detach();
10035    }
10036
10037    pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
10038        let Some(workspace) = self.workspace() else {
10039            return;
10040        };
10041
10042        let position = self.selections.newest_anchor().head();
10043
10044        let Some((buffer, buffer_position)) =
10045            self.buffer.read(cx).text_anchor_for_position(position, cx)
10046        else {
10047            return;
10048        };
10049
10050        let project = self.project.clone();
10051
10052        cx.spawn(|_, mut cx| async move {
10053            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10054
10055            if let Some((_, path)) = result {
10056                workspace
10057                    .update(&mut cx, |workspace, cx| {
10058                        workspace.open_resolved_path(path, cx)
10059                    })?
10060                    .await?;
10061            }
10062            anyhow::Ok(())
10063        })
10064        .detach();
10065    }
10066
10067    pub(crate) fn navigate_to_hover_links(
10068        &mut self,
10069        kind: Option<GotoDefinitionKind>,
10070        mut definitions: Vec<HoverLink>,
10071        split: bool,
10072        cx: &mut ViewContext<Editor>,
10073    ) -> Task<Result<Navigated>> {
10074        // If there is one definition, just open it directly
10075        if definitions.len() == 1 {
10076            let definition = definitions.pop().unwrap();
10077
10078            enum TargetTaskResult {
10079                Location(Option<Location>),
10080                AlreadyNavigated,
10081            }
10082
10083            let target_task = match definition {
10084                HoverLink::Text(link) => {
10085                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10086                }
10087                HoverLink::InlayHint(lsp_location, server_id) => {
10088                    let computation = self.compute_target_location(lsp_location, server_id, cx);
10089                    cx.background_executor().spawn(async move {
10090                        let location = computation.await?;
10091                        Ok(TargetTaskResult::Location(location))
10092                    })
10093                }
10094                HoverLink::Url(url) => {
10095                    cx.open_url(&url);
10096                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10097                }
10098                HoverLink::File(path) => {
10099                    if let Some(workspace) = self.workspace() {
10100                        cx.spawn(|_, mut cx| async move {
10101                            workspace
10102                                .update(&mut cx, |workspace, cx| {
10103                                    workspace.open_resolved_path(path, cx)
10104                                })?
10105                                .await
10106                                .map(|_| TargetTaskResult::AlreadyNavigated)
10107                        })
10108                    } else {
10109                        Task::ready(Ok(TargetTaskResult::Location(None)))
10110                    }
10111                }
10112            };
10113            cx.spawn(|editor, mut cx| async move {
10114                let target = match target_task.await.context("target resolution task")? {
10115                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10116                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
10117                    TargetTaskResult::Location(Some(target)) => target,
10118                };
10119
10120                editor.update(&mut cx, |editor, cx| {
10121                    let Some(workspace) = editor.workspace() else {
10122                        return Navigated::No;
10123                    };
10124                    let pane = workspace.read(cx).active_pane().clone();
10125
10126                    let range = target.range.to_offset(target.buffer.read(cx));
10127                    let range = editor.range_for_match(&range);
10128
10129                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10130                        let buffer = target.buffer.read(cx);
10131                        let range = check_multiline_range(buffer, range);
10132                        editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10133                            s.select_ranges([range]);
10134                        });
10135                    } else {
10136                        cx.window_context().defer(move |cx| {
10137                            let target_editor: View<Self> =
10138                                workspace.update(cx, |workspace, cx| {
10139                                    let pane = if split {
10140                                        workspace.adjacent_pane(cx)
10141                                    } else {
10142                                        workspace.active_pane().clone()
10143                                    };
10144
10145                                    workspace.open_project_item(
10146                                        pane,
10147                                        target.buffer.clone(),
10148                                        true,
10149                                        true,
10150                                        cx,
10151                                    )
10152                                });
10153                            target_editor.update(cx, |target_editor, cx| {
10154                                // When selecting a definition in a different buffer, disable the nav history
10155                                // to avoid creating a history entry at the previous cursor location.
10156                                pane.update(cx, |pane, _| pane.disable_history());
10157                                let buffer = target.buffer.read(cx);
10158                                let range = check_multiline_range(buffer, range);
10159                                target_editor.change_selections(
10160                                    Some(Autoscroll::focused()),
10161                                    cx,
10162                                    |s| {
10163                                        s.select_ranges([range]);
10164                                    },
10165                                );
10166                                pane.update(cx, |pane, _| pane.enable_history());
10167                            });
10168                        });
10169                    }
10170                    Navigated::Yes
10171                })
10172            })
10173        } else if !definitions.is_empty() {
10174            cx.spawn(|editor, mut cx| async move {
10175                let (title, location_tasks, workspace) = editor
10176                    .update(&mut cx, |editor, cx| {
10177                        let tab_kind = match kind {
10178                            Some(GotoDefinitionKind::Implementation) => "Implementations",
10179                            _ => "Definitions",
10180                        };
10181                        let title = definitions
10182                            .iter()
10183                            .find_map(|definition| match definition {
10184                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10185                                    let buffer = origin.buffer.read(cx);
10186                                    format!(
10187                                        "{} for {}",
10188                                        tab_kind,
10189                                        buffer
10190                                            .text_for_range(origin.range.clone())
10191                                            .collect::<String>()
10192                                    )
10193                                }),
10194                                HoverLink::InlayHint(_, _) => None,
10195                                HoverLink::Url(_) => None,
10196                                HoverLink::File(_) => None,
10197                            })
10198                            .unwrap_or(tab_kind.to_string());
10199                        let location_tasks = definitions
10200                            .into_iter()
10201                            .map(|definition| match definition {
10202                                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
10203                                HoverLink::InlayHint(lsp_location, server_id) => {
10204                                    editor.compute_target_location(lsp_location, server_id, cx)
10205                                }
10206                                HoverLink::Url(_) => Task::ready(Ok(None)),
10207                                HoverLink::File(_) => Task::ready(Ok(None)),
10208                            })
10209                            .collect::<Vec<_>>();
10210                        (title, location_tasks, editor.workspace().clone())
10211                    })
10212                    .context("location tasks preparation")?;
10213
10214                let locations = future::join_all(location_tasks)
10215                    .await
10216                    .into_iter()
10217                    .filter_map(|location| location.transpose())
10218                    .collect::<Result<_>>()
10219                    .context("location tasks")?;
10220
10221                let Some(workspace) = workspace else {
10222                    return Ok(Navigated::No);
10223                };
10224                let opened = workspace
10225                    .update(&mut cx, |workspace, cx| {
10226                        Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
10227                    })
10228                    .ok();
10229
10230                anyhow::Ok(Navigated::from_bool(opened.is_some()))
10231            })
10232        } else {
10233            Task::ready(Ok(Navigated::No))
10234        }
10235    }
10236
10237    fn compute_target_location(
10238        &self,
10239        lsp_location: lsp::Location,
10240        server_id: LanguageServerId,
10241        cx: &mut ViewContext<Self>,
10242    ) -> Task<anyhow::Result<Option<Location>>> {
10243        let Some(project) = self.project.clone() else {
10244            return Task::Ready(Some(Ok(None)));
10245        };
10246
10247        cx.spawn(move |editor, mut cx| async move {
10248            let location_task = editor.update(&mut cx, |_, cx| {
10249                project.update(cx, |project, cx| {
10250                    let language_server_name = project
10251                        .language_server_statuses(cx)
10252                        .find(|(id, _)| server_id == *id)
10253                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10254                    language_server_name.map(|language_server_name| {
10255                        project.open_local_buffer_via_lsp(
10256                            lsp_location.uri.clone(),
10257                            server_id,
10258                            language_server_name,
10259                            cx,
10260                        )
10261                    })
10262                })
10263            })?;
10264            let location = match location_task {
10265                Some(task) => Some({
10266                    let target_buffer_handle = task.await.context("open local buffer")?;
10267                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10268                        let target_start = target_buffer
10269                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10270                        let target_end = target_buffer
10271                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10272                        target_buffer.anchor_after(target_start)
10273                            ..target_buffer.anchor_before(target_end)
10274                    })?;
10275                    Location {
10276                        buffer: target_buffer_handle,
10277                        range,
10278                    }
10279                }),
10280                None => None,
10281            };
10282            Ok(location)
10283        })
10284    }
10285
10286    pub fn find_all_references(
10287        &mut self,
10288        _: &FindAllReferences,
10289        cx: &mut ViewContext<Self>,
10290    ) -> Option<Task<Result<Navigated>>> {
10291        let selection = self.selections.newest::<usize>(cx);
10292        let multi_buffer = self.buffer.read(cx);
10293        let head = selection.head();
10294
10295        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10296        let head_anchor = multi_buffer_snapshot.anchor_at(
10297            head,
10298            if head < selection.tail() {
10299                Bias::Right
10300            } else {
10301                Bias::Left
10302            },
10303        );
10304
10305        match self
10306            .find_all_references_task_sources
10307            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10308        {
10309            Ok(_) => {
10310                log::info!(
10311                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
10312                );
10313                return None;
10314            }
10315            Err(i) => {
10316                self.find_all_references_task_sources.insert(i, head_anchor);
10317            }
10318        }
10319
10320        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10321        let workspace = self.workspace()?;
10322        let project = workspace.read(cx).project().clone();
10323        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10324        Some(cx.spawn(|editor, mut cx| async move {
10325            let _cleanup = defer({
10326                let mut cx = cx.clone();
10327                move || {
10328                    let _ = editor.update(&mut cx, |editor, _| {
10329                        if let Ok(i) =
10330                            editor
10331                                .find_all_references_task_sources
10332                                .binary_search_by(|anchor| {
10333                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10334                                })
10335                        {
10336                            editor.find_all_references_task_sources.remove(i);
10337                        }
10338                    });
10339                }
10340            });
10341
10342            let locations = references.await?;
10343            if locations.is_empty() {
10344                return anyhow::Ok(Navigated::No);
10345            }
10346
10347            workspace.update(&mut cx, |workspace, cx| {
10348                let title = locations
10349                    .first()
10350                    .as_ref()
10351                    .map(|location| {
10352                        let buffer = location.buffer.read(cx);
10353                        format!(
10354                            "References to `{}`",
10355                            buffer
10356                                .text_for_range(location.range.clone())
10357                                .collect::<String>()
10358                        )
10359                    })
10360                    .unwrap();
10361                Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
10362                Navigated::Yes
10363            })
10364        }))
10365    }
10366
10367    /// Opens a multibuffer with the given project locations in it
10368    pub fn open_locations_in_multibuffer(
10369        workspace: &mut Workspace,
10370        mut locations: Vec<Location>,
10371        title: String,
10372        split: bool,
10373        cx: &mut ViewContext<Workspace>,
10374    ) {
10375        // If there are multiple definitions, open them in a multibuffer
10376        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10377        let mut locations = locations.into_iter().peekable();
10378        let mut ranges_to_highlight = Vec::new();
10379        let capability = workspace.project().read(cx).capability();
10380
10381        let excerpt_buffer = cx.new_model(|cx| {
10382            let mut multibuffer = MultiBuffer::new(capability);
10383            while let Some(location) = locations.next() {
10384                let buffer = location.buffer.read(cx);
10385                let mut ranges_for_buffer = Vec::new();
10386                let range = location.range.to_offset(buffer);
10387                ranges_for_buffer.push(range.clone());
10388
10389                while let Some(next_location) = locations.peek() {
10390                    if next_location.buffer == location.buffer {
10391                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
10392                        locations.next();
10393                    } else {
10394                        break;
10395                    }
10396                }
10397
10398                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10399                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
10400                    location.buffer.clone(),
10401                    ranges_for_buffer,
10402                    DEFAULT_MULTIBUFFER_CONTEXT,
10403                    cx,
10404                ))
10405            }
10406
10407            multibuffer.with_title(title)
10408        });
10409
10410        let editor = cx.new_view(|cx| {
10411            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
10412        });
10413        editor.update(cx, |editor, cx| {
10414            if let Some(first_range) = ranges_to_highlight.first() {
10415                editor.change_selections(None, cx, |selections| {
10416                    selections.clear_disjoint();
10417                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10418                });
10419            }
10420            editor.highlight_background::<Self>(
10421                &ranges_to_highlight,
10422                |theme| theme.editor_highlighted_line_background,
10423                cx,
10424            );
10425        });
10426
10427        let item = Box::new(editor);
10428        let item_id = item.item_id();
10429
10430        if split {
10431            workspace.split_item(SplitDirection::Right, item.clone(), cx);
10432        } else {
10433            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10434                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10435                    pane.close_current_preview_item(cx)
10436                } else {
10437                    None
10438                }
10439            });
10440            workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
10441        }
10442        workspace.active_pane().update(cx, |pane, cx| {
10443            pane.set_preview_item_id(Some(item_id), cx);
10444        });
10445    }
10446
10447    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10448        use language::ToOffset as _;
10449
10450        let provider = self.semantics_provider.clone()?;
10451        let selection = self.selections.newest_anchor().clone();
10452        let (cursor_buffer, cursor_buffer_position) = self
10453            .buffer
10454            .read(cx)
10455            .text_anchor_for_position(selection.head(), cx)?;
10456        let (tail_buffer, cursor_buffer_position_end) = self
10457            .buffer
10458            .read(cx)
10459            .text_anchor_for_position(selection.tail(), cx)?;
10460        if tail_buffer != cursor_buffer {
10461            return None;
10462        }
10463
10464        let snapshot = cursor_buffer.read(cx).snapshot();
10465        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10466        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10467        let prepare_rename = provider
10468            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10469            .unwrap_or_else(|| Task::ready(Ok(None)));
10470        drop(snapshot);
10471
10472        Some(cx.spawn(|this, mut cx| async move {
10473            let rename_range = if let Some(range) = prepare_rename.await? {
10474                Some(range)
10475            } else {
10476                this.update(&mut cx, |this, cx| {
10477                    let buffer = this.buffer.read(cx).snapshot(cx);
10478                    let mut buffer_highlights = this
10479                        .document_highlights_for_position(selection.head(), &buffer)
10480                        .filter(|highlight| {
10481                            highlight.start.excerpt_id == selection.head().excerpt_id
10482                                && highlight.end.excerpt_id == selection.head().excerpt_id
10483                        });
10484                    buffer_highlights
10485                        .next()
10486                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10487                })?
10488            };
10489            if let Some(rename_range) = rename_range {
10490                this.update(&mut cx, |this, cx| {
10491                    let snapshot = cursor_buffer.read(cx).snapshot();
10492                    let rename_buffer_range = rename_range.to_offset(&snapshot);
10493                    let cursor_offset_in_rename_range =
10494                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10495                    let cursor_offset_in_rename_range_end =
10496                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10497
10498                    this.take_rename(false, cx);
10499                    let buffer = this.buffer.read(cx).read(cx);
10500                    let cursor_offset = selection.head().to_offset(&buffer);
10501                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10502                    let rename_end = rename_start + rename_buffer_range.len();
10503                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10504                    let mut old_highlight_id = None;
10505                    let old_name: Arc<str> = buffer
10506                        .chunks(rename_start..rename_end, true)
10507                        .map(|chunk| {
10508                            if old_highlight_id.is_none() {
10509                                old_highlight_id = chunk.syntax_highlight_id;
10510                            }
10511                            chunk.text
10512                        })
10513                        .collect::<String>()
10514                        .into();
10515
10516                    drop(buffer);
10517
10518                    // Position the selection in the rename editor so that it matches the current selection.
10519                    this.show_local_selections = false;
10520                    let rename_editor = cx.new_view(|cx| {
10521                        let mut editor = Editor::single_line(cx);
10522                        editor.buffer.update(cx, |buffer, cx| {
10523                            buffer.edit([(0..0, old_name.clone())], None, cx)
10524                        });
10525                        let rename_selection_range = match cursor_offset_in_rename_range
10526                            .cmp(&cursor_offset_in_rename_range_end)
10527                        {
10528                            Ordering::Equal => {
10529                                editor.select_all(&SelectAll, cx);
10530                                return editor;
10531                            }
10532                            Ordering::Less => {
10533                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10534                            }
10535                            Ordering::Greater => {
10536                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10537                            }
10538                        };
10539                        if rename_selection_range.end > old_name.len() {
10540                            editor.select_all(&SelectAll, cx);
10541                        } else {
10542                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10543                                s.select_ranges([rename_selection_range]);
10544                            });
10545                        }
10546                        editor
10547                    });
10548                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10549                        if e == &EditorEvent::Focused {
10550                            cx.emit(EditorEvent::FocusedIn)
10551                        }
10552                    })
10553                    .detach();
10554
10555                    let write_highlights =
10556                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10557                    let read_highlights =
10558                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
10559                    let ranges = write_highlights
10560                        .iter()
10561                        .flat_map(|(_, ranges)| ranges.iter())
10562                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10563                        .cloned()
10564                        .collect();
10565
10566                    this.highlight_text::<Rename>(
10567                        ranges,
10568                        HighlightStyle {
10569                            fade_out: Some(0.6),
10570                            ..Default::default()
10571                        },
10572                        cx,
10573                    );
10574                    let rename_focus_handle = rename_editor.focus_handle(cx);
10575                    cx.focus(&rename_focus_handle);
10576                    let block_id = this.insert_blocks(
10577                        [BlockProperties {
10578                            style: BlockStyle::Flex,
10579                            placement: BlockPlacement::Below(range.start),
10580                            height: 1,
10581                            render: Arc::new({
10582                                let rename_editor = rename_editor.clone();
10583                                move |cx: &mut BlockContext| {
10584                                    let mut text_style = cx.editor_style.text.clone();
10585                                    if let Some(highlight_style) = old_highlight_id
10586                                        .and_then(|h| h.style(&cx.editor_style.syntax))
10587                                    {
10588                                        text_style = text_style.highlight(highlight_style);
10589                                    }
10590                                    div()
10591                                        .block_mouse_down()
10592                                        .pl(cx.anchor_x)
10593                                        .child(EditorElement::new(
10594                                            &rename_editor,
10595                                            EditorStyle {
10596                                                background: cx.theme().system().transparent,
10597                                                local_player: cx.editor_style.local_player,
10598                                                text: text_style,
10599                                                scrollbar_width: cx.editor_style.scrollbar_width,
10600                                                syntax: cx.editor_style.syntax.clone(),
10601                                                status: cx.editor_style.status.clone(),
10602                                                inlay_hints_style: HighlightStyle {
10603                                                    font_weight: Some(FontWeight::BOLD),
10604                                                    ..make_inlay_hints_style(cx)
10605                                                },
10606                                                suggestions_style: HighlightStyle {
10607                                                    color: Some(cx.theme().status().predictive),
10608                                                    ..HighlightStyle::default()
10609                                                },
10610                                                ..EditorStyle::default()
10611                                            },
10612                                        ))
10613                                        .into_any_element()
10614                                }
10615                            }),
10616                            priority: 0,
10617                        }],
10618                        Some(Autoscroll::fit()),
10619                        cx,
10620                    )[0];
10621                    this.pending_rename = Some(RenameState {
10622                        range,
10623                        old_name,
10624                        editor: rename_editor,
10625                        block_id,
10626                    });
10627                })?;
10628            }
10629
10630            Ok(())
10631        }))
10632    }
10633
10634    pub fn confirm_rename(
10635        &mut self,
10636        _: &ConfirmRename,
10637        cx: &mut ViewContext<Self>,
10638    ) -> Option<Task<Result<()>>> {
10639        let rename = self.take_rename(false, cx)?;
10640        let workspace = self.workspace()?.downgrade();
10641        let (buffer, start) = self
10642            .buffer
10643            .read(cx)
10644            .text_anchor_for_position(rename.range.start, cx)?;
10645        let (end_buffer, _) = self
10646            .buffer
10647            .read(cx)
10648            .text_anchor_for_position(rename.range.end, cx)?;
10649        if buffer != end_buffer {
10650            return None;
10651        }
10652
10653        let old_name = rename.old_name;
10654        let new_name = rename.editor.read(cx).text(cx);
10655
10656        let rename = self.semantics_provider.as_ref()?.perform_rename(
10657            &buffer,
10658            start,
10659            new_name.clone(),
10660            cx,
10661        )?;
10662
10663        Some(cx.spawn(|editor, mut cx| async move {
10664            let project_transaction = rename.await?;
10665            Self::open_project_transaction(
10666                &editor,
10667                workspace,
10668                project_transaction,
10669                format!("Rename: {}{}", old_name, new_name),
10670                cx.clone(),
10671            )
10672            .await?;
10673
10674            editor.update(&mut cx, |editor, cx| {
10675                editor.refresh_document_highlights(cx);
10676            })?;
10677            Ok(())
10678        }))
10679    }
10680
10681    fn take_rename(
10682        &mut self,
10683        moving_cursor: bool,
10684        cx: &mut ViewContext<Self>,
10685    ) -> Option<RenameState> {
10686        let rename = self.pending_rename.take()?;
10687        if rename.editor.focus_handle(cx).is_focused(cx) {
10688            cx.focus(&self.focus_handle);
10689        }
10690
10691        self.remove_blocks(
10692            [rename.block_id].into_iter().collect(),
10693            Some(Autoscroll::fit()),
10694            cx,
10695        );
10696        self.clear_highlights::<Rename>(cx);
10697        self.show_local_selections = true;
10698
10699        if moving_cursor {
10700            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10701                editor.selections.newest::<usize>(cx).head()
10702            });
10703
10704            // Update the selection to match the position of the selection inside
10705            // the rename editor.
10706            let snapshot = self.buffer.read(cx).read(cx);
10707            let rename_range = rename.range.to_offset(&snapshot);
10708            let cursor_in_editor = snapshot
10709                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10710                .min(rename_range.end);
10711            drop(snapshot);
10712
10713            self.change_selections(None, cx, |s| {
10714                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10715            });
10716        } else {
10717            self.refresh_document_highlights(cx);
10718        }
10719
10720        Some(rename)
10721    }
10722
10723    pub fn pending_rename(&self) -> Option<&RenameState> {
10724        self.pending_rename.as_ref()
10725    }
10726
10727    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10728        let project = match &self.project {
10729            Some(project) => project.clone(),
10730            None => return None,
10731        };
10732
10733        Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10734    }
10735
10736    fn format_selections(
10737        &mut self,
10738        _: &FormatSelections,
10739        cx: &mut ViewContext<Self>,
10740    ) -> Option<Task<Result<()>>> {
10741        let project = match &self.project {
10742            Some(project) => project.clone(),
10743            None => return None,
10744        };
10745
10746        let selections = self
10747            .selections
10748            .all_adjusted(cx)
10749            .into_iter()
10750            .filter(|s| !s.is_empty())
10751            .collect_vec();
10752
10753        Some(self.perform_format(
10754            project,
10755            FormatTrigger::Manual,
10756            FormatTarget::Ranges(selections),
10757            cx,
10758        ))
10759    }
10760
10761    fn perform_format(
10762        &mut self,
10763        project: Model<Project>,
10764        trigger: FormatTrigger,
10765        target: FormatTarget,
10766        cx: &mut ViewContext<Self>,
10767    ) -> Task<Result<()>> {
10768        let buffer = self.buffer().clone();
10769        let mut buffers = buffer.read(cx).all_buffers();
10770        if trigger == FormatTrigger::Save {
10771            buffers.retain(|buffer| buffer.read(cx).is_dirty());
10772        }
10773
10774        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10775        let format = project.update(cx, |project, cx| {
10776            project.format(buffers, true, trigger, target, cx)
10777        });
10778
10779        cx.spawn(|_, mut cx| async move {
10780            let transaction = futures::select_biased! {
10781                () = timeout => {
10782                    log::warn!("timed out waiting for formatting");
10783                    None
10784                }
10785                transaction = format.log_err().fuse() => transaction,
10786            };
10787
10788            buffer
10789                .update(&mut cx, |buffer, cx| {
10790                    if let Some(transaction) = transaction {
10791                        if !buffer.is_singleton() {
10792                            buffer.push_transaction(&transaction.0, cx);
10793                        }
10794                    }
10795
10796                    cx.notify();
10797                })
10798                .ok();
10799
10800            Ok(())
10801        })
10802    }
10803
10804    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10805        if let Some(project) = self.project.clone() {
10806            self.buffer.update(cx, |multi_buffer, cx| {
10807                project.update(cx, |project, cx| {
10808                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10809                });
10810            })
10811        }
10812    }
10813
10814    fn cancel_language_server_work(
10815        &mut self,
10816        _: &actions::CancelLanguageServerWork,
10817        cx: &mut ViewContext<Self>,
10818    ) {
10819        if let Some(project) = self.project.clone() {
10820            self.buffer.update(cx, |multi_buffer, cx| {
10821                project.update(cx, |project, cx| {
10822                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10823                });
10824            })
10825        }
10826    }
10827
10828    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10829        cx.show_character_palette();
10830    }
10831
10832    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10833        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10834            let buffer = self.buffer.read(cx).snapshot(cx);
10835            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10836            let is_valid = buffer
10837                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10838                .any(|entry| {
10839                    entry.diagnostic.is_primary
10840                        && !entry.range.is_empty()
10841                        && entry.range.start == primary_range_start
10842                        && entry.diagnostic.message == active_diagnostics.primary_message
10843                });
10844
10845            if is_valid != active_diagnostics.is_valid {
10846                active_diagnostics.is_valid = is_valid;
10847                let mut new_styles = HashMap::default();
10848                for (block_id, diagnostic) in &active_diagnostics.blocks {
10849                    new_styles.insert(
10850                        *block_id,
10851                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10852                    );
10853                }
10854                self.display_map.update(cx, |display_map, _cx| {
10855                    display_map.replace_blocks(new_styles)
10856                });
10857            }
10858        }
10859    }
10860
10861    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10862        self.dismiss_diagnostics(cx);
10863        let snapshot = self.snapshot(cx);
10864        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10865            let buffer = self.buffer.read(cx).snapshot(cx);
10866
10867            let mut primary_range = None;
10868            let mut primary_message = None;
10869            let mut group_end = Point::zero();
10870            let diagnostic_group = buffer
10871                .diagnostic_group::<MultiBufferPoint>(group_id)
10872                .filter_map(|entry| {
10873                    if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10874                        && (entry.range.start.row == entry.range.end.row
10875                            || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10876                    {
10877                        return None;
10878                    }
10879                    if entry.range.end > group_end {
10880                        group_end = entry.range.end;
10881                    }
10882                    if entry.diagnostic.is_primary {
10883                        primary_range = Some(entry.range.clone());
10884                        primary_message = Some(entry.diagnostic.message.clone());
10885                    }
10886                    Some(entry)
10887                })
10888                .collect::<Vec<_>>();
10889            let primary_range = primary_range?;
10890            let primary_message = primary_message?;
10891            let primary_range =
10892                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10893
10894            let blocks = display_map
10895                .insert_blocks(
10896                    diagnostic_group.iter().map(|entry| {
10897                        let diagnostic = entry.diagnostic.clone();
10898                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10899                        BlockProperties {
10900                            style: BlockStyle::Fixed,
10901                            placement: BlockPlacement::Below(
10902                                buffer.anchor_after(entry.range.start),
10903                            ),
10904                            height: message_height,
10905                            render: diagnostic_block_renderer(diagnostic, None, true, true),
10906                            priority: 0,
10907                        }
10908                    }),
10909                    cx,
10910                )
10911                .into_iter()
10912                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10913                .collect();
10914
10915            Some(ActiveDiagnosticGroup {
10916                primary_range,
10917                primary_message,
10918                group_id,
10919                blocks,
10920                is_valid: true,
10921            })
10922        });
10923        self.active_diagnostics.is_some()
10924    }
10925
10926    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10927        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10928            self.display_map.update(cx, |display_map, cx| {
10929                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10930            });
10931            cx.notify();
10932        }
10933    }
10934
10935    pub fn set_selections_from_remote(
10936        &mut self,
10937        selections: Vec<Selection<Anchor>>,
10938        pending_selection: Option<Selection<Anchor>>,
10939        cx: &mut ViewContext<Self>,
10940    ) {
10941        let old_cursor_position = self.selections.newest_anchor().head();
10942        self.selections.change_with(cx, |s| {
10943            s.select_anchors(selections);
10944            if let Some(pending_selection) = pending_selection {
10945                s.set_pending(pending_selection, SelectMode::Character);
10946            } else {
10947                s.clear_pending();
10948            }
10949        });
10950        self.selections_did_change(false, &old_cursor_position, true, cx);
10951    }
10952
10953    fn push_to_selection_history(&mut self) {
10954        self.selection_history.push(SelectionHistoryEntry {
10955            selections: self.selections.disjoint_anchors(),
10956            select_next_state: self.select_next_state.clone(),
10957            select_prev_state: self.select_prev_state.clone(),
10958            add_selections_state: self.add_selections_state.clone(),
10959        });
10960    }
10961
10962    pub fn transact(
10963        &mut self,
10964        cx: &mut ViewContext<Self>,
10965        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10966    ) -> Option<TransactionId> {
10967        self.start_transaction_at(Instant::now(), cx);
10968        update(self, cx);
10969        self.end_transaction_at(Instant::now(), cx)
10970    }
10971
10972    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10973        self.end_selection(cx);
10974        if let Some(tx_id) = self
10975            .buffer
10976            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10977        {
10978            self.selection_history
10979                .insert_transaction(tx_id, self.selections.disjoint_anchors());
10980            cx.emit(EditorEvent::TransactionBegun {
10981                transaction_id: tx_id,
10982            })
10983        }
10984    }
10985
10986    fn end_transaction_at(
10987        &mut self,
10988        now: Instant,
10989        cx: &mut ViewContext<Self>,
10990    ) -> Option<TransactionId> {
10991        if let Some(transaction_id) = self
10992            .buffer
10993            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10994        {
10995            if let Some((_, end_selections)) =
10996                self.selection_history.transaction_mut(transaction_id)
10997            {
10998                *end_selections = Some(self.selections.disjoint_anchors());
10999            } else {
11000                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11001            }
11002
11003            cx.emit(EditorEvent::Edited { transaction_id });
11004            Some(transaction_id)
11005        } else {
11006            None
11007        }
11008    }
11009
11010    pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
11011        let selection = self.selections.newest::<Point>(cx);
11012
11013        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11014        let range = if selection.is_empty() {
11015            let point = selection.head().to_display_point(&display_map);
11016            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11017            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11018                .to_point(&display_map);
11019            start..end
11020        } else {
11021            selection.range()
11022        };
11023        if display_map.folds_in_range(range).next().is_some() {
11024            self.unfold_lines(&Default::default(), cx)
11025        } else {
11026            self.fold(&Default::default(), cx)
11027        }
11028    }
11029
11030    pub fn toggle_fold_recursive(
11031        &mut self,
11032        _: &actions::ToggleFoldRecursive,
11033        cx: &mut ViewContext<Self>,
11034    ) {
11035        let selection = self.selections.newest::<Point>(cx);
11036
11037        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11038        let range = if selection.is_empty() {
11039            let point = selection.head().to_display_point(&display_map);
11040            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11041            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11042                .to_point(&display_map);
11043            start..end
11044        } else {
11045            selection.range()
11046        };
11047        if display_map.folds_in_range(range).next().is_some() {
11048            self.unfold_recursive(&Default::default(), cx)
11049        } else {
11050            self.fold_recursive(&Default::default(), cx)
11051        }
11052    }
11053
11054    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
11055        let mut to_fold = Vec::new();
11056        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11057        let selections = self.selections.all_adjusted(cx);
11058
11059        for selection in selections {
11060            let range = selection.range().sorted();
11061            let buffer_start_row = range.start.row;
11062
11063            if range.start.row != range.end.row {
11064                let mut found = false;
11065                let mut row = range.start.row;
11066                while row <= range.end.row {
11067                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11068                        found = true;
11069                        row = crease.range().end.row + 1;
11070                        to_fold.push(crease);
11071                    } else {
11072                        row += 1
11073                    }
11074                }
11075                if found {
11076                    continue;
11077                }
11078            }
11079
11080            for row in (0..=range.start.row).rev() {
11081                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11082                    if crease.range().end.row >= buffer_start_row {
11083                        to_fold.push(crease);
11084                        if row <= range.start.row {
11085                            break;
11086                        }
11087                    }
11088                }
11089            }
11090        }
11091
11092        self.fold_creases(to_fold, true, cx);
11093    }
11094
11095    fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
11096        let fold_at_level = fold_at.level;
11097        let snapshot = self.buffer.read(cx).snapshot(cx);
11098        let mut to_fold = Vec::new();
11099        let mut stack = vec![(0, snapshot.max_buffer_row().0, 1)];
11100
11101        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
11102            while start_row < end_row {
11103                match self
11104                    .snapshot(cx)
11105                    .crease_for_buffer_row(MultiBufferRow(start_row))
11106                {
11107                    Some(crease) => {
11108                        let nested_start_row = crease.range().start.row + 1;
11109                        let nested_end_row = crease.range().end.row;
11110
11111                        if current_level < fold_at_level {
11112                            stack.push((nested_start_row, nested_end_row, current_level + 1));
11113                        } else if current_level == fold_at_level {
11114                            to_fold.push(crease);
11115                        }
11116
11117                        start_row = nested_end_row + 1;
11118                    }
11119                    None => start_row += 1,
11120                }
11121            }
11122        }
11123
11124        self.fold_creases(to_fold, true, cx);
11125    }
11126
11127    pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
11128        let mut fold_ranges = Vec::new();
11129        let snapshot = self.buffer.read(cx).snapshot(cx);
11130
11131        for row in 0..snapshot.max_buffer_row().0 {
11132            if let Some(foldable_range) =
11133                self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
11134            {
11135                fold_ranges.push(foldable_range);
11136            }
11137        }
11138
11139        self.fold_creases(fold_ranges, true, cx);
11140    }
11141
11142    pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
11143        let mut to_fold = Vec::new();
11144        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11145        let selections = self.selections.all_adjusted(cx);
11146
11147        for selection in selections {
11148            let range = selection.range().sorted();
11149            let buffer_start_row = range.start.row;
11150
11151            if range.start.row != range.end.row {
11152                let mut found = false;
11153                for row in range.start.row..=range.end.row {
11154                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11155                        found = true;
11156                        to_fold.push(crease);
11157                    }
11158                }
11159                if found {
11160                    continue;
11161                }
11162            }
11163
11164            for row in (0..=range.start.row).rev() {
11165                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11166                    if crease.range().end.row >= buffer_start_row {
11167                        to_fold.push(crease);
11168                    } else {
11169                        break;
11170                    }
11171                }
11172            }
11173        }
11174
11175        self.fold_creases(to_fold, true, cx);
11176    }
11177
11178    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
11179        let buffer_row = fold_at.buffer_row;
11180        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11181
11182        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
11183            let autoscroll = self
11184                .selections
11185                .all::<Point>(cx)
11186                .iter()
11187                .any(|selection| crease.range().overlaps(&selection.range()));
11188
11189            self.fold_creases(vec![crease], autoscroll, cx);
11190        }
11191    }
11192
11193    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
11194        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11195        let buffer = &display_map.buffer_snapshot;
11196        let selections = self.selections.all::<Point>(cx);
11197        let ranges = selections
11198            .iter()
11199            .map(|s| {
11200                let range = s.display_range(&display_map).sorted();
11201                let mut start = range.start.to_point(&display_map);
11202                let mut end = range.end.to_point(&display_map);
11203                start.column = 0;
11204                end.column = buffer.line_len(MultiBufferRow(end.row));
11205                start..end
11206            })
11207            .collect::<Vec<_>>();
11208
11209        self.unfold_ranges(&ranges, true, true, cx);
11210    }
11211
11212    pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
11213        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11214        let selections = self.selections.all::<Point>(cx);
11215        let ranges = selections
11216            .iter()
11217            .map(|s| {
11218                let mut range = s.display_range(&display_map).sorted();
11219                *range.start.column_mut() = 0;
11220                *range.end.column_mut() = display_map.line_len(range.end.row());
11221                let start = range.start.to_point(&display_map);
11222                let end = range.end.to_point(&display_map);
11223                start..end
11224            })
11225            .collect::<Vec<_>>();
11226
11227        self.unfold_ranges(&ranges, true, true, cx);
11228    }
11229
11230    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
11231        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11232
11233        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
11234            ..Point::new(
11235                unfold_at.buffer_row.0,
11236                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
11237            );
11238
11239        let autoscroll = self
11240            .selections
11241            .all::<Point>(cx)
11242            .iter()
11243            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
11244
11245        self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
11246    }
11247
11248    pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
11249        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11250        self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
11251    }
11252
11253    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
11254        let selections = self.selections.all::<Point>(cx);
11255        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11256        let line_mode = self.selections.line_mode;
11257        let ranges = selections
11258            .into_iter()
11259            .map(|s| {
11260                if line_mode {
11261                    let start = Point::new(s.start.row, 0);
11262                    let end = Point::new(
11263                        s.end.row,
11264                        display_map
11265                            .buffer_snapshot
11266                            .line_len(MultiBufferRow(s.end.row)),
11267                    );
11268                    Crease::simple(start..end, display_map.fold_placeholder.clone())
11269                } else {
11270                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
11271                }
11272            })
11273            .collect::<Vec<_>>();
11274        self.fold_creases(ranges, true, cx);
11275    }
11276
11277    pub fn fold_creases<T: ToOffset + Clone>(
11278        &mut self,
11279        creases: Vec<Crease<T>>,
11280        auto_scroll: bool,
11281        cx: &mut ViewContext<Self>,
11282    ) {
11283        if creases.is_empty() {
11284            return;
11285        }
11286
11287        let mut buffers_affected = HashMap::default();
11288        let multi_buffer = self.buffer().read(cx);
11289        for crease in &creases {
11290            if let Some((_, buffer, _)) =
11291                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
11292            {
11293                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
11294            };
11295        }
11296
11297        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
11298
11299        if auto_scroll {
11300            self.request_autoscroll(Autoscroll::fit(), cx);
11301        }
11302
11303        for buffer in buffers_affected.into_values() {
11304            self.sync_expanded_diff_hunks(buffer, cx);
11305        }
11306
11307        cx.notify();
11308
11309        if let Some(active_diagnostics) = self.active_diagnostics.take() {
11310            // Clear diagnostics block when folding a range that contains it.
11311            let snapshot = self.snapshot(cx);
11312            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
11313                drop(snapshot);
11314                self.active_diagnostics = Some(active_diagnostics);
11315                self.dismiss_diagnostics(cx);
11316            } else {
11317                self.active_diagnostics = Some(active_diagnostics);
11318            }
11319        }
11320
11321        self.scrollbar_marker_state.dirty = true;
11322    }
11323
11324    /// Removes any folds whose ranges intersect any of the given ranges.
11325    pub fn unfold_ranges<T: ToOffset + Clone>(
11326        &mut self,
11327        ranges: &[Range<T>],
11328        inclusive: bool,
11329        auto_scroll: bool,
11330        cx: &mut ViewContext<Self>,
11331    ) {
11332        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11333            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
11334        });
11335    }
11336
11337    /// Removes any folds with the given ranges.
11338    pub fn remove_folds_with_type<T: ToOffset + Clone>(
11339        &mut self,
11340        ranges: &[Range<T>],
11341        type_id: TypeId,
11342        auto_scroll: bool,
11343        cx: &mut ViewContext<Self>,
11344    ) {
11345        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11346            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
11347        });
11348    }
11349
11350    fn remove_folds_with<T: ToOffset + Clone>(
11351        &mut self,
11352        ranges: &[Range<T>],
11353        auto_scroll: bool,
11354        cx: &mut ViewContext<Self>,
11355        update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
11356    ) {
11357        if ranges.is_empty() {
11358            return;
11359        }
11360
11361        let mut buffers_affected = HashMap::default();
11362        let multi_buffer = self.buffer().read(cx);
11363        for range in ranges {
11364            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11365                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
11366            };
11367        }
11368
11369        self.display_map.update(cx, update);
11370
11371        if auto_scroll {
11372            self.request_autoscroll(Autoscroll::fit(), cx);
11373        }
11374
11375        for buffer in buffers_affected.into_values() {
11376            self.sync_expanded_diff_hunks(buffer, cx);
11377        }
11378
11379        cx.notify();
11380        self.scrollbar_marker_state.dirty = true;
11381        self.active_indent_guides_state.dirty = true;
11382    }
11383
11384    pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
11385        self.display_map.read(cx).fold_placeholder.clone()
11386    }
11387
11388    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11389        if hovered != self.gutter_hovered {
11390            self.gutter_hovered = hovered;
11391            cx.notify();
11392        }
11393    }
11394
11395    pub fn insert_blocks(
11396        &mut self,
11397        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11398        autoscroll: Option<Autoscroll>,
11399        cx: &mut ViewContext<Self>,
11400    ) -> Vec<CustomBlockId> {
11401        let blocks = self
11402            .display_map
11403            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11404        if let Some(autoscroll) = autoscroll {
11405            self.request_autoscroll(autoscroll, cx);
11406        }
11407        cx.notify();
11408        blocks
11409    }
11410
11411    pub fn resize_blocks(
11412        &mut self,
11413        heights: HashMap<CustomBlockId, u32>,
11414        autoscroll: Option<Autoscroll>,
11415        cx: &mut ViewContext<Self>,
11416    ) {
11417        self.display_map
11418            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11419        if let Some(autoscroll) = autoscroll {
11420            self.request_autoscroll(autoscroll, cx);
11421        }
11422        cx.notify();
11423    }
11424
11425    pub fn replace_blocks(
11426        &mut self,
11427        renderers: HashMap<CustomBlockId, RenderBlock>,
11428        autoscroll: Option<Autoscroll>,
11429        cx: &mut ViewContext<Self>,
11430    ) {
11431        self.display_map
11432            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11433        if let Some(autoscroll) = autoscroll {
11434            self.request_autoscroll(autoscroll, cx);
11435        }
11436        cx.notify();
11437    }
11438
11439    pub fn remove_blocks(
11440        &mut self,
11441        block_ids: HashSet<CustomBlockId>,
11442        autoscroll: Option<Autoscroll>,
11443        cx: &mut ViewContext<Self>,
11444    ) {
11445        self.display_map.update(cx, |display_map, cx| {
11446            display_map.remove_blocks(block_ids, cx)
11447        });
11448        if let Some(autoscroll) = autoscroll {
11449            self.request_autoscroll(autoscroll, cx);
11450        }
11451        cx.notify();
11452    }
11453
11454    pub fn row_for_block(
11455        &self,
11456        block_id: CustomBlockId,
11457        cx: &mut ViewContext<Self>,
11458    ) -> Option<DisplayRow> {
11459        self.display_map
11460            .update(cx, |map, cx| map.row_for_block(block_id, cx))
11461    }
11462
11463    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11464        self.focused_block = Some(focused_block);
11465    }
11466
11467    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11468        self.focused_block.take()
11469    }
11470
11471    pub fn insert_creases(
11472        &mut self,
11473        creases: impl IntoIterator<Item = Crease<Anchor>>,
11474        cx: &mut ViewContext<Self>,
11475    ) -> Vec<CreaseId> {
11476        self.display_map
11477            .update(cx, |map, cx| map.insert_creases(creases, cx))
11478    }
11479
11480    pub fn remove_creases(
11481        &mut self,
11482        ids: impl IntoIterator<Item = CreaseId>,
11483        cx: &mut ViewContext<Self>,
11484    ) {
11485        self.display_map
11486            .update(cx, |map, cx| map.remove_creases(ids, cx));
11487    }
11488
11489    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11490        self.display_map
11491            .update(cx, |map, cx| map.snapshot(cx))
11492            .longest_row()
11493    }
11494
11495    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11496        self.display_map
11497            .update(cx, |map, cx| map.snapshot(cx))
11498            .max_point()
11499    }
11500
11501    pub fn text(&self, cx: &AppContext) -> String {
11502        self.buffer.read(cx).read(cx).text()
11503    }
11504
11505    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11506        let text = self.text(cx);
11507        let text = text.trim();
11508
11509        if text.is_empty() {
11510            return None;
11511        }
11512
11513        Some(text.to_string())
11514    }
11515
11516    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11517        self.transact(cx, |this, cx| {
11518            this.buffer
11519                .read(cx)
11520                .as_singleton()
11521                .expect("you can only call set_text on editors for singleton buffers")
11522                .update(cx, |buffer, cx| buffer.set_text(text, cx));
11523        });
11524    }
11525
11526    pub fn display_text(&self, cx: &mut AppContext) -> String {
11527        self.display_map
11528            .update(cx, |map, cx| map.snapshot(cx))
11529            .text()
11530    }
11531
11532    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11533        let mut wrap_guides = smallvec::smallvec![];
11534
11535        if self.show_wrap_guides == Some(false) {
11536            return wrap_guides;
11537        }
11538
11539        let settings = self.buffer.read(cx).settings_at(0, cx);
11540        if settings.show_wrap_guides {
11541            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11542                wrap_guides.push((soft_wrap as usize, true));
11543            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11544                wrap_guides.push((soft_wrap as usize, true));
11545            }
11546            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11547        }
11548
11549        wrap_guides
11550    }
11551
11552    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11553        let settings = self.buffer.read(cx).settings_at(0, cx);
11554        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11555        match mode {
11556            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11557                SoftWrap::None
11558            }
11559            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11560            language_settings::SoftWrap::PreferredLineLength => {
11561                SoftWrap::Column(settings.preferred_line_length)
11562            }
11563            language_settings::SoftWrap::Bounded => {
11564                SoftWrap::Bounded(settings.preferred_line_length)
11565            }
11566        }
11567    }
11568
11569    pub fn set_soft_wrap_mode(
11570        &mut self,
11571        mode: language_settings::SoftWrap,
11572        cx: &mut ViewContext<Self>,
11573    ) {
11574        self.soft_wrap_mode_override = Some(mode);
11575        cx.notify();
11576    }
11577
11578    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11579        self.text_style_refinement = Some(style);
11580    }
11581
11582    /// called by the Element so we know what style we were most recently rendered with.
11583    pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11584        let rem_size = cx.rem_size();
11585        self.display_map.update(cx, |map, cx| {
11586            map.set_font(
11587                style.text.font(),
11588                style.text.font_size.to_pixels(rem_size),
11589                cx,
11590            )
11591        });
11592        self.style = Some(style);
11593    }
11594
11595    pub fn style(&self) -> Option<&EditorStyle> {
11596        self.style.as_ref()
11597    }
11598
11599    // Called by the element. This method is not designed to be called outside of the editor
11600    // element's layout code because it does not notify when rewrapping is computed synchronously.
11601    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11602        self.display_map
11603            .update(cx, |map, cx| map.set_wrap_width(width, cx))
11604    }
11605
11606    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11607        if self.soft_wrap_mode_override.is_some() {
11608            self.soft_wrap_mode_override.take();
11609        } else {
11610            let soft_wrap = match self.soft_wrap_mode(cx) {
11611                SoftWrap::GitDiff => return,
11612                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11613                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11614                    language_settings::SoftWrap::None
11615                }
11616            };
11617            self.soft_wrap_mode_override = Some(soft_wrap);
11618        }
11619        cx.notify();
11620    }
11621
11622    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11623        let Some(workspace) = self.workspace() else {
11624            return;
11625        };
11626        let fs = workspace.read(cx).app_state().fs.clone();
11627        let current_show = TabBarSettings::get_global(cx).show;
11628        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11629            setting.show = Some(!current_show);
11630        });
11631    }
11632
11633    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11634        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11635            self.buffer
11636                .read(cx)
11637                .settings_at(0, cx)
11638                .indent_guides
11639                .enabled
11640        });
11641        self.show_indent_guides = Some(!currently_enabled);
11642        cx.notify();
11643    }
11644
11645    fn should_show_indent_guides(&self) -> Option<bool> {
11646        self.show_indent_guides
11647    }
11648
11649    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11650        let mut editor_settings = EditorSettings::get_global(cx).clone();
11651        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11652        EditorSettings::override_global(editor_settings, cx);
11653    }
11654
11655    pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11656        self.use_relative_line_numbers
11657            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11658    }
11659
11660    pub fn toggle_relative_line_numbers(
11661        &mut self,
11662        _: &ToggleRelativeLineNumbers,
11663        cx: &mut ViewContext<Self>,
11664    ) {
11665        let is_relative = self.should_use_relative_line_numbers(cx);
11666        self.set_relative_line_number(Some(!is_relative), cx)
11667    }
11668
11669    pub fn set_relative_line_number(
11670        &mut self,
11671        is_relative: Option<bool>,
11672        cx: &mut ViewContext<Self>,
11673    ) {
11674        self.use_relative_line_numbers = is_relative;
11675        cx.notify();
11676    }
11677
11678    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11679        self.show_gutter = show_gutter;
11680        cx.notify();
11681    }
11682
11683    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11684        self.show_line_numbers = Some(show_line_numbers);
11685        cx.notify();
11686    }
11687
11688    pub fn set_show_git_diff_gutter(
11689        &mut self,
11690        show_git_diff_gutter: bool,
11691        cx: &mut ViewContext<Self>,
11692    ) {
11693        self.show_git_diff_gutter = Some(show_git_diff_gutter);
11694        cx.notify();
11695    }
11696
11697    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11698        self.show_code_actions = Some(show_code_actions);
11699        cx.notify();
11700    }
11701
11702    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11703        self.show_runnables = Some(show_runnables);
11704        cx.notify();
11705    }
11706
11707    pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11708        if self.display_map.read(cx).masked != masked {
11709            self.display_map.update(cx, |map, _| map.masked = masked);
11710        }
11711        cx.notify()
11712    }
11713
11714    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11715        self.show_wrap_guides = Some(show_wrap_guides);
11716        cx.notify();
11717    }
11718
11719    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11720        self.show_indent_guides = Some(show_indent_guides);
11721        cx.notify();
11722    }
11723
11724    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11725        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11726            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11727                if let Some(dir) = file.abs_path(cx).parent() {
11728                    return Some(dir.to_owned());
11729                }
11730            }
11731
11732            if let Some(project_path) = buffer.read(cx).project_path(cx) {
11733                return Some(project_path.path.to_path_buf());
11734            }
11735        }
11736
11737        None
11738    }
11739
11740    fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11741        self.active_excerpt(cx)?
11742            .1
11743            .read(cx)
11744            .file()
11745            .and_then(|f| f.as_local())
11746    }
11747
11748    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11749        if let Some(target) = self.target_file(cx) {
11750            cx.reveal_path(&target.abs_path(cx));
11751        }
11752    }
11753
11754    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11755        if let Some(file) = self.target_file(cx) {
11756            if let Some(path) = file.abs_path(cx).to_str() {
11757                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11758            }
11759        }
11760    }
11761
11762    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11763        if let Some(file) = self.target_file(cx) {
11764            if let Some(path) = file.path().to_str() {
11765                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11766            }
11767        }
11768    }
11769
11770    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11771        self.show_git_blame_gutter = !self.show_git_blame_gutter;
11772
11773        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11774            self.start_git_blame(true, cx);
11775        }
11776
11777        cx.notify();
11778    }
11779
11780    pub fn toggle_git_blame_inline(
11781        &mut self,
11782        _: &ToggleGitBlameInline,
11783        cx: &mut ViewContext<Self>,
11784    ) {
11785        self.toggle_git_blame_inline_internal(true, cx);
11786        cx.notify();
11787    }
11788
11789    pub fn git_blame_inline_enabled(&self) -> bool {
11790        self.git_blame_inline_enabled
11791    }
11792
11793    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11794        self.show_selection_menu = self
11795            .show_selection_menu
11796            .map(|show_selections_menu| !show_selections_menu)
11797            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11798
11799        cx.notify();
11800    }
11801
11802    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11803        self.show_selection_menu
11804            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11805    }
11806
11807    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11808        if let Some(project) = self.project.as_ref() {
11809            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11810                return;
11811            };
11812
11813            if buffer.read(cx).file().is_none() {
11814                return;
11815            }
11816
11817            let focused = self.focus_handle(cx).contains_focused(cx);
11818
11819            let project = project.clone();
11820            let blame =
11821                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11822            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11823            self.blame = Some(blame);
11824        }
11825    }
11826
11827    fn toggle_git_blame_inline_internal(
11828        &mut self,
11829        user_triggered: bool,
11830        cx: &mut ViewContext<Self>,
11831    ) {
11832        if self.git_blame_inline_enabled {
11833            self.git_blame_inline_enabled = false;
11834            self.show_git_blame_inline = false;
11835            self.show_git_blame_inline_delay_task.take();
11836        } else {
11837            self.git_blame_inline_enabled = true;
11838            self.start_git_blame_inline(user_triggered, cx);
11839        }
11840
11841        cx.notify();
11842    }
11843
11844    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11845        self.start_git_blame(user_triggered, cx);
11846
11847        if ProjectSettings::get_global(cx)
11848            .git
11849            .inline_blame_delay()
11850            .is_some()
11851        {
11852            self.start_inline_blame_timer(cx);
11853        } else {
11854            self.show_git_blame_inline = true
11855        }
11856    }
11857
11858    pub fn blame(&self) -> Option<&Model<GitBlame>> {
11859        self.blame.as_ref()
11860    }
11861
11862    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11863        self.show_git_blame_gutter && self.has_blame_entries(cx)
11864    }
11865
11866    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11867        self.show_git_blame_inline
11868            && self.focus_handle.is_focused(cx)
11869            && !self.newest_selection_head_on_empty_line(cx)
11870            && self.has_blame_entries(cx)
11871    }
11872
11873    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11874        self.blame()
11875            .map_or(false, |blame| blame.read(cx).has_generated_entries())
11876    }
11877
11878    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11879        let cursor_anchor = self.selections.newest_anchor().head();
11880
11881        let snapshot = self.buffer.read(cx).snapshot(cx);
11882        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11883
11884        snapshot.line_len(buffer_row) == 0
11885    }
11886
11887    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11888        let buffer_and_selection = maybe!({
11889            let selection = self.selections.newest::<Point>(cx);
11890            let selection_range = selection.range();
11891
11892            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11893                (buffer, selection_range.start.row..selection_range.end.row)
11894            } else {
11895                let buffer_ranges = self
11896                    .buffer()
11897                    .read(cx)
11898                    .range_to_buffer_ranges(selection_range, cx);
11899
11900                let (buffer, range, _) = if selection.reversed {
11901                    buffer_ranges.first()
11902                } else {
11903                    buffer_ranges.last()
11904                }?;
11905
11906                let snapshot = buffer.read(cx).snapshot();
11907                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11908                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
11909                (buffer.clone(), selection)
11910            };
11911
11912            Some((buffer, selection))
11913        });
11914
11915        let Some((buffer, selection)) = buffer_and_selection else {
11916            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11917        };
11918
11919        let Some(project) = self.project.as_ref() else {
11920            return Task::ready(Err(anyhow!("editor does not have project")));
11921        };
11922
11923        project.update(cx, |project, cx| {
11924            project.get_permalink_to_line(&buffer, selection, cx)
11925        })
11926    }
11927
11928    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11929        let permalink_task = self.get_permalink_to_line(cx);
11930        let workspace = self.workspace();
11931
11932        cx.spawn(|_, mut cx| async move {
11933            match permalink_task.await {
11934                Ok(permalink) => {
11935                    cx.update(|cx| {
11936                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11937                    })
11938                    .ok();
11939                }
11940                Err(err) => {
11941                    let message = format!("Failed to copy permalink: {err}");
11942
11943                    Err::<(), anyhow::Error>(err).log_err();
11944
11945                    if let Some(workspace) = workspace {
11946                        workspace
11947                            .update(&mut cx, |workspace, cx| {
11948                                struct CopyPermalinkToLine;
11949
11950                                workspace.show_toast(
11951                                    Toast::new(
11952                                        NotificationId::unique::<CopyPermalinkToLine>(),
11953                                        message,
11954                                    ),
11955                                    cx,
11956                                )
11957                            })
11958                            .ok();
11959                    }
11960                }
11961            }
11962        })
11963        .detach();
11964    }
11965
11966    pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11967        let selection = self.selections.newest::<Point>(cx).start.row + 1;
11968        if let Some(file) = self.target_file(cx) {
11969            if let Some(path) = file.path().to_str() {
11970                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11971            }
11972        }
11973    }
11974
11975    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11976        let permalink_task = self.get_permalink_to_line(cx);
11977        let workspace = self.workspace();
11978
11979        cx.spawn(|_, mut cx| async move {
11980            match permalink_task.await {
11981                Ok(permalink) => {
11982                    cx.update(|cx| {
11983                        cx.open_url(permalink.as_ref());
11984                    })
11985                    .ok();
11986                }
11987                Err(err) => {
11988                    let message = format!("Failed to open permalink: {err}");
11989
11990                    Err::<(), anyhow::Error>(err).log_err();
11991
11992                    if let Some(workspace) = workspace {
11993                        workspace
11994                            .update(&mut cx, |workspace, cx| {
11995                                struct OpenPermalinkToLine;
11996
11997                                workspace.show_toast(
11998                                    Toast::new(
11999                                        NotificationId::unique::<OpenPermalinkToLine>(),
12000                                        message,
12001                                    ),
12002                                    cx,
12003                                )
12004                            })
12005                            .ok();
12006                    }
12007                }
12008            }
12009        })
12010        .detach();
12011    }
12012
12013    /// Adds a row highlight for the given range. If a row has multiple highlights, the
12014    /// last highlight added will be used.
12015    ///
12016    /// If the range ends at the beginning of a line, then that line will not be highlighted.
12017    pub fn highlight_rows<T: 'static>(
12018        &mut self,
12019        range: Range<Anchor>,
12020        color: Hsla,
12021        should_autoscroll: bool,
12022        cx: &mut ViewContext<Self>,
12023    ) {
12024        let snapshot = self.buffer().read(cx).snapshot(cx);
12025        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
12026        let ix = row_highlights.binary_search_by(|highlight| {
12027            Ordering::Equal
12028                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
12029                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
12030        });
12031
12032        if let Err(mut ix) = ix {
12033            let index = post_inc(&mut self.highlight_order);
12034
12035            // If this range intersects with the preceding highlight, then merge it with
12036            // the preceding highlight. Otherwise insert a new highlight.
12037            let mut merged = false;
12038            if ix > 0 {
12039                let prev_highlight = &mut row_highlights[ix - 1];
12040                if prev_highlight
12041                    .range
12042                    .end
12043                    .cmp(&range.start, &snapshot)
12044                    .is_ge()
12045                {
12046                    ix -= 1;
12047                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
12048                        prev_highlight.range.end = range.end;
12049                    }
12050                    merged = true;
12051                    prev_highlight.index = index;
12052                    prev_highlight.color = color;
12053                    prev_highlight.should_autoscroll = should_autoscroll;
12054                }
12055            }
12056
12057            if !merged {
12058                row_highlights.insert(
12059                    ix,
12060                    RowHighlight {
12061                        range: range.clone(),
12062                        index,
12063                        color,
12064                        should_autoscroll,
12065                    },
12066                );
12067            }
12068
12069            // If any of the following highlights intersect with this one, merge them.
12070            while let Some(next_highlight) = row_highlights.get(ix + 1) {
12071                let highlight = &row_highlights[ix];
12072                if next_highlight
12073                    .range
12074                    .start
12075                    .cmp(&highlight.range.end, &snapshot)
12076                    .is_le()
12077                {
12078                    if next_highlight
12079                        .range
12080                        .end
12081                        .cmp(&highlight.range.end, &snapshot)
12082                        .is_gt()
12083                    {
12084                        row_highlights[ix].range.end = next_highlight.range.end;
12085                    }
12086                    row_highlights.remove(ix + 1);
12087                } else {
12088                    break;
12089                }
12090            }
12091        }
12092    }
12093
12094    /// Remove any highlighted row ranges of the given type that intersect the
12095    /// given ranges.
12096    pub fn remove_highlighted_rows<T: 'static>(
12097        &mut self,
12098        ranges_to_remove: Vec<Range<Anchor>>,
12099        cx: &mut ViewContext<Self>,
12100    ) {
12101        let snapshot = self.buffer().read(cx).snapshot(cx);
12102        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
12103        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
12104        row_highlights.retain(|highlight| {
12105            while let Some(range_to_remove) = ranges_to_remove.peek() {
12106                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
12107                    Ordering::Less | Ordering::Equal => {
12108                        ranges_to_remove.next();
12109                    }
12110                    Ordering::Greater => {
12111                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
12112                            Ordering::Less | Ordering::Equal => {
12113                                return false;
12114                            }
12115                            Ordering::Greater => break,
12116                        }
12117                    }
12118                }
12119            }
12120
12121            true
12122        })
12123    }
12124
12125    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
12126    pub fn clear_row_highlights<T: 'static>(&mut self) {
12127        self.highlighted_rows.remove(&TypeId::of::<T>());
12128    }
12129
12130    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
12131    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
12132        self.highlighted_rows
12133            .get(&TypeId::of::<T>())
12134            .map_or(&[] as &[_], |vec| vec.as_slice())
12135            .iter()
12136            .map(|highlight| (highlight.range.clone(), highlight.color))
12137    }
12138
12139    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
12140    /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
12141    /// Allows to ignore certain kinds of highlights.
12142    pub fn highlighted_display_rows(
12143        &mut self,
12144        cx: &mut WindowContext,
12145    ) -> BTreeMap<DisplayRow, Hsla> {
12146        let snapshot = self.snapshot(cx);
12147        let mut used_highlight_orders = HashMap::default();
12148        self.highlighted_rows
12149            .iter()
12150            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
12151            .fold(
12152                BTreeMap::<DisplayRow, Hsla>::new(),
12153                |mut unique_rows, highlight| {
12154                    let start = highlight.range.start.to_display_point(&snapshot);
12155                    let end = highlight.range.end.to_display_point(&snapshot);
12156                    let start_row = start.row().0;
12157                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
12158                        && end.column() == 0
12159                    {
12160                        end.row().0.saturating_sub(1)
12161                    } else {
12162                        end.row().0
12163                    };
12164                    for row in start_row..=end_row {
12165                        let used_index =
12166                            used_highlight_orders.entry(row).or_insert(highlight.index);
12167                        if highlight.index >= *used_index {
12168                            *used_index = highlight.index;
12169                            unique_rows.insert(DisplayRow(row), highlight.color);
12170                        }
12171                    }
12172                    unique_rows
12173                },
12174            )
12175    }
12176
12177    pub fn highlighted_display_row_for_autoscroll(
12178        &self,
12179        snapshot: &DisplaySnapshot,
12180    ) -> Option<DisplayRow> {
12181        self.highlighted_rows
12182            .values()
12183            .flat_map(|highlighted_rows| highlighted_rows.iter())
12184            .filter_map(|highlight| {
12185                if highlight.should_autoscroll {
12186                    Some(highlight.range.start.to_display_point(snapshot).row())
12187                } else {
12188                    None
12189                }
12190            })
12191            .min()
12192    }
12193
12194    pub fn set_search_within_ranges(
12195        &mut self,
12196        ranges: &[Range<Anchor>],
12197        cx: &mut ViewContext<Self>,
12198    ) {
12199        self.highlight_background::<SearchWithinRange>(
12200            ranges,
12201            |colors| colors.editor_document_highlight_read_background,
12202            cx,
12203        )
12204    }
12205
12206    pub fn set_breadcrumb_header(&mut self, new_header: String) {
12207        self.breadcrumb_header = Some(new_header);
12208    }
12209
12210    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
12211        self.clear_background_highlights::<SearchWithinRange>(cx);
12212    }
12213
12214    pub fn highlight_background<T: 'static>(
12215        &mut self,
12216        ranges: &[Range<Anchor>],
12217        color_fetcher: fn(&ThemeColors) -> Hsla,
12218        cx: &mut ViewContext<Self>,
12219    ) {
12220        self.background_highlights
12221            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12222        self.scrollbar_marker_state.dirty = true;
12223        cx.notify();
12224    }
12225
12226    pub fn clear_background_highlights<T: 'static>(
12227        &mut self,
12228        cx: &mut ViewContext<Self>,
12229    ) -> Option<BackgroundHighlight> {
12230        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
12231        if !text_highlights.1.is_empty() {
12232            self.scrollbar_marker_state.dirty = true;
12233            cx.notify();
12234        }
12235        Some(text_highlights)
12236    }
12237
12238    pub fn highlight_gutter<T: 'static>(
12239        &mut self,
12240        ranges: &[Range<Anchor>],
12241        color_fetcher: fn(&AppContext) -> Hsla,
12242        cx: &mut ViewContext<Self>,
12243    ) {
12244        self.gutter_highlights
12245            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12246        cx.notify();
12247    }
12248
12249    pub fn clear_gutter_highlights<T: 'static>(
12250        &mut self,
12251        cx: &mut ViewContext<Self>,
12252    ) -> Option<GutterHighlight> {
12253        cx.notify();
12254        self.gutter_highlights.remove(&TypeId::of::<T>())
12255    }
12256
12257    #[cfg(feature = "test-support")]
12258    pub fn all_text_background_highlights(
12259        &mut self,
12260        cx: &mut ViewContext<Self>,
12261    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12262        let snapshot = self.snapshot(cx);
12263        let buffer = &snapshot.buffer_snapshot;
12264        let start = buffer.anchor_before(0);
12265        let end = buffer.anchor_after(buffer.len());
12266        let theme = cx.theme().colors();
12267        self.background_highlights_in_range(start..end, &snapshot, theme)
12268    }
12269
12270    #[cfg(feature = "test-support")]
12271    pub fn search_background_highlights(
12272        &mut self,
12273        cx: &mut ViewContext<Self>,
12274    ) -> Vec<Range<Point>> {
12275        let snapshot = self.buffer().read(cx).snapshot(cx);
12276
12277        let highlights = self
12278            .background_highlights
12279            .get(&TypeId::of::<items::BufferSearchHighlights>());
12280
12281        if let Some((_color, ranges)) = highlights {
12282            ranges
12283                .iter()
12284                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
12285                .collect_vec()
12286        } else {
12287            vec![]
12288        }
12289    }
12290
12291    fn document_highlights_for_position<'a>(
12292        &'a self,
12293        position: Anchor,
12294        buffer: &'a MultiBufferSnapshot,
12295    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
12296        let read_highlights = self
12297            .background_highlights
12298            .get(&TypeId::of::<DocumentHighlightRead>())
12299            .map(|h| &h.1);
12300        let write_highlights = self
12301            .background_highlights
12302            .get(&TypeId::of::<DocumentHighlightWrite>())
12303            .map(|h| &h.1);
12304        let left_position = position.bias_left(buffer);
12305        let right_position = position.bias_right(buffer);
12306        read_highlights
12307            .into_iter()
12308            .chain(write_highlights)
12309            .flat_map(move |ranges| {
12310                let start_ix = match ranges.binary_search_by(|probe| {
12311                    let cmp = probe.end.cmp(&left_position, buffer);
12312                    if cmp.is_ge() {
12313                        Ordering::Greater
12314                    } else {
12315                        Ordering::Less
12316                    }
12317                }) {
12318                    Ok(i) | Err(i) => i,
12319                };
12320
12321                ranges[start_ix..]
12322                    .iter()
12323                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
12324            })
12325    }
12326
12327    pub fn has_background_highlights<T: 'static>(&self) -> bool {
12328        self.background_highlights
12329            .get(&TypeId::of::<T>())
12330            .map_or(false, |(_, highlights)| !highlights.is_empty())
12331    }
12332
12333    pub fn background_highlights_in_range(
12334        &self,
12335        search_range: Range<Anchor>,
12336        display_snapshot: &DisplaySnapshot,
12337        theme: &ThemeColors,
12338    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12339        let mut results = Vec::new();
12340        for (color_fetcher, ranges) in self.background_highlights.values() {
12341            let color = color_fetcher(theme);
12342            let start_ix = match ranges.binary_search_by(|probe| {
12343                let cmp = probe
12344                    .end
12345                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12346                if cmp.is_gt() {
12347                    Ordering::Greater
12348                } else {
12349                    Ordering::Less
12350                }
12351            }) {
12352                Ok(i) | Err(i) => i,
12353            };
12354            for range in &ranges[start_ix..] {
12355                if range
12356                    .start
12357                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12358                    .is_ge()
12359                {
12360                    break;
12361                }
12362
12363                let start = range.start.to_display_point(display_snapshot);
12364                let end = range.end.to_display_point(display_snapshot);
12365                results.push((start..end, color))
12366            }
12367        }
12368        results
12369    }
12370
12371    pub fn background_highlight_row_ranges<T: 'static>(
12372        &self,
12373        search_range: Range<Anchor>,
12374        display_snapshot: &DisplaySnapshot,
12375        count: usize,
12376    ) -> Vec<RangeInclusive<DisplayPoint>> {
12377        let mut results = Vec::new();
12378        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12379            return vec![];
12380        };
12381
12382        let start_ix = match ranges.binary_search_by(|probe| {
12383            let cmp = probe
12384                .end
12385                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12386            if cmp.is_gt() {
12387                Ordering::Greater
12388            } else {
12389                Ordering::Less
12390            }
12391        }) {
12392            Ok(i) | Err(i) => i,
12393        };
12394        let mut push_region = |start: Option<Point>, end: Option<Point>| {
12395            if let (Some(start_display), Some(end_display)) = (start, end) {
12396                results.push(
12397                    start_display.to_display_point(display_snapshot)
12398                        ..=end_display.to_display_point(display_snapshot),
12399                );
12400            }
12401        };
12402        let mut start_row: Option<Point> = None;
12403        let mut end_row: Option<Point> = None;
12404        if ranges.len() > count {
12405            return Vec::new();
12406        }
12407        for range in &ranges[start_ix..] {
12408            if range
12409                .start
12410                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12411                .is_ge()
12412            {
12413                break;
12414            }
12415            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12416            if let Some(current_row) = &end_row {
12417                if end.row == current_row.row {
12418                    continue;
12419                }
12420            }
12421            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12422            if start_row.is_none() {
12423                assert_eq!(end_row, None);
12424                start_row = Some(start);
12425                end_row = Some(end);
12426                continue;
12427            }
12428            if let Some(current_end) = end_row.as_mut() {
12429                if start.row > current_end.row + 1 {
12430                    push_region(start_row, end_row);
12431                    start_row = Some(start);
12432                    end_row = Some(end);
12433                } else {
12434                    // Merge two hunks.
12435                    *current_end = end;
12436                }
12437            } else {
12438                unreachable!();
12439            }
12440        }
12441        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12442        push_region(start_row, end_row);
12443        results
12444    }
12445
12446    pub fn gutter_highlights_in_range(
12447        &self,
12448        search_range: Range<Anchor>,
12449        display_snapshot: &DisplaySnapshot,
12450        cx: &AppContext,
12451    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12452        let mut results = Vec::new();
12453        for (color_fetcher, ranges) in self.gutter_highlights.values() {
12454            let color = color_fetcher(cx);
12455            let start_ix = match ranges.binary_search_by(|probe| {
12456                let cmp = probe
12457                    .end
12458                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12459                if cmp.is_gt() {
12460                    Ordering::Greater
12461                } else {
12462                    Ordering::Less
12463                }
12464            }) {
12465                Ok(i) | Err(i) => i,
12466            };
12467            for range in &ranges[start_ix..] {
12468                if range
12469                    .start
12470                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12471                    .is_ge()
12472                {
12473                    break;
12474                }
12475
12476                let start = range.start.to_display_point(display_snapshot);
12477                let end = range.end.to_display_point(display_snapshot);
12478                results.push((start..end, color))
12479            }
12480        }
12481        results
12482    }
12483
12484    /// Get the text ranges corresponding to the redaction query
12485    pub fn redacted_ranges(
12486        &self,
12487        search_range: Range<Anchor>,
12488        display_snapshot: &DisplaySnapshot,
12489        cx: &WindowContext,
12490    ) -> Vec<Range<DisplayPoint>> {
12491        display_snapshot
12492            .buffer_snapshot
12493            .redacted_ranges(search_range, |file| {
12494                if let Some(file) = file {
12495                    file.is_private()
12496                        && EditorSettings::get(
12497                            Some(SettingsLocation {
12498                                worktree_id: file.worktree_id(cx),
12499                                path: file.path().as_ref(),
12500                            }),
12501                            cx,
12502                        )
12503                        .redact_private_values
12504                } else {
12505                    false
12506                }
12507            })
12508            .map(|range| {
12509                range.start.to_display_point(display_snapshot)
12510                    ..range.end.to_display_point(display_snapshot)
12511            })
12512            .collect()
12513    }
12514
12515    pub fn highlight_text<T: 'static>(
12516        &mut self,
12517        ranges: Vec<Range<Anchor>>,
12518        style: HighlightStyle,
12519        cx: &mut ViewContext<Self>,
12520    ) {
12521        self.display_map.update(cx, |map, _| {
12522            map.highlight_text(TypeId::of::<T>(), ranges, style)
12523        });
12524        cx.notify();
12525    }
12526
12527    pub(crate) fn highlight_inlays<T: 'static>(
12528        &mut self,
12529        highlights: Vec<InlayHighlight>,
12530        style: HighlightStyle,
12531        cx: &mut ViewContext<Self>,
12532    ) {
12533        self.display_map.update(cx, |map, _| {
12534            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12535        });
12536        cx.notify();
12537    }
12538
12539    pub fn text_highlights<'a, T: 'static>(
12540        &'a self,
12541        cx: &'a AppContext,
12542    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12543        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12544    }
12545
12546    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12547        let cleared = self
12548            .display_map
12549            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12550        if cleared {
12551            cx.notify();
12552        }
12553    }
12554
12555    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12556        (self.read_only(cx) || self.blink_manager.read(cx).visible())
12557            && self.focus_handle.is_focused(cx)
12558    }
12559
12560    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12561        self.show_cursor_when_unfocused = is_enabled;
12562        cx.notify();
12563    }
12564
12565    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12566        cx.notify();
12567    }
12568
12569    fn on_buffer_event(
12570        &mut self,
12571        multibuffer: Model<MultiBuffer>,
12572        event: &multi_buffer::Event,
12573        cx: &mut ViewContext<Self>,
12574    ) {
12575        match event {
12576            multi_buffer::Event::Edited {
12577                singleton_buffer_edited,
12578            } => {
12579                self.scrollbar_marker_state.dirty = true;
12580                self.active_indent_guides_state.dirty = true;
12581                self.refresh_active_diagnostics(cx);
12582                self.refresh_code_actions(cx);
12583                if self.has_active_inline_completion(cx) {
12584                    self.update_visible_inline_completion(cx);
12585                }
12586                cx.emit(EditorEvent::BufferEdited);
12587                cx.emit(SearchEvent::MatchesInvalidated);
12588                if *singleton_buffer_edited {
12589                    if let Some(project) = &self.project {
12590                        let project = project.read(cx);
12591                        #[allow(clippy::mutable_key_type)]
12592                        let languages_affected = multibuffer
12593                            .read(cx)
12594                            .all_buffers()
12595                            .into_iter()
12596                            .filter_map(|buffer| {
12597                                let buffer = buffer.read(cx);
12598                                let language = buffer.language()?;
12599                                if project.is_local()
12600                                    && project.language_servers_for_buffer(buffer, cx).count() == 0
12601                                {
12602                                    None
12603                                } else {
12604                                    Some(language)
12605                                }
12606                            })
12607                            .cloned()
12608                            .collect::<HashSet<_>>();
12609                        if !languages_affected.is_empty() {
12610                            self.refresh_inlay_hints(
12611                                InlayHintRefreshReason::BufferEdited(languages_affected),
12612                                cx,
12613                            );
12614                        }
12615                    }
12616                }
12617
12618                let Some(project) = &self.project else { return };
12619                let (telemetry, is_via_ssh) = {
12620                    let project = project.read(cx);
12621                    let telemetry = project.client().telemetry().clone();
12622                    let is_via_ssh = project.is_via_ssh();
12623                    (telemetry, is_via_ssh)
12624                };
12625                refresh_linked_ranges(self, cx);
12626                telemetry.log_edit_event("editor", is_via_ssh);
12627            }
12628            multi_buffer::Event::ExcerptsAdded {
12629                buffer,
12630                predecessor,
12631                excerpts,
12632            } => {
12633                self.tasks_update_task = Some(self.refresh_runnables(cx));
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::DiffUpdated { buffer } => {
12672                self.sync_expanded_diff_hunks(buffer.clone(), cx);
12673                cx.notify();
12674            }
12675            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12676            multi_buffer::Event::DiagnosticsUpdated => {
12677                self.refresh_active_diagnostics(cx);
12678                self.scrollbar_marker_state.dirty = true;
12679                cx.notify();
12680            }
12681            _ => {}
12682        };
12683    }
12684
12685    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12686        cx.notify();
12687    }
12688
12689    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12690        self.tasks_update_task = Some(self.refresh_runnables(cx));
12691        self.refresh_inline_completion(true, false, cx);
12692        self.refresh_inlay_hints(
12693            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12694                self.selections.newest_anchor().head(),
12695                &self.buffer.read(cx).snapshot(cx),
12696                cx,
12697            )),
12698            cx,
12699        );
12700
12701        let old_cursor_shape = self.cursor_shape;
12702
12703        {
12704            let editor_settings = EditorSettings::get_global(cx);
12705            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12706            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12707            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12708        }
12709
12710        if old_cursor_shape != self.cursor_shape {
12711            cx.emit(EditorEvent::CursorShapeChanged);
12712        }
12713
12714        let project_settings = ProjectSettings::get_global(cx);
12715        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12716
12717        if self.mode == EditorMode::Full {
12718            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12719            if self.git_blame_inline_enabled != inline_blame_enabled {
12720                self.toggle_git_blame_inline_internal(false, cx);
12721            }
12722        }
12723
12724        cx.notify();
12725    }
12726
12727    pub fn set_searchable(&mut self, searchable: bool) {
12728        self.searchable = searchable;
12729    }
12730
12731    pub fn searchable(&self) -> bool {
12732        self.searchable
12733    }
12734
12735    fn open_proposed_changes_editor(
12736        &mut self,
12737        _: &OpenProposedChangesEditor,
12738        cx: &mut ViewContext<Self>,
12739    ) {
12740        let Some(workspace) = self.workspace() else {
12741            cx.propagate();
12742            return;
12743        };
12744
12745        let selections = self.selections.all::<usize>(cx);
12746        let buffer = self.buffer.read(cx);
12747        let mut new_selections_by_buffer = HashMap::default();
12748        for selection in selections {
12749            for (buffer, range, _) in
12750                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12751            {
12752                let mut range = range.to_point(buffer.read(cx));
12753                range.start.column = 0;
12754                range.end.column = buffer.read(cx).line_len(range.end.row);
12755                new_selections_by_buffer
12756                    .entry(buffer)
12757                    .or_insert(Vec::new())
12758                    .push(range)
12759            }
12760        }
12761
12762        let proposed_changes_buffers = new_selections_by_buffer
12763            .into_iter()
12764            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12765            .collect::<Vec<_>>();
12766        let proposed_changes_editor = cx.new_view(|cx| {
12767            ProposedChangesEditor::new(
12768                "Proposed changes",
12769                proposed_changes_buffers,
12770                self.project.clone(),
12771                cx,
12772            )
12773        });
12774
12775        cx.window_context().defer(move |cx| {
12776            workspace.update(cx, |workspace, cx| {
12777                workspace.active_pane().update(cx, |pane, cx| {
12778                    pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12779                });
12780            });
12781        });
12782    }
12783
12784    pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12785        self.open_excerpts_common(None, true, cx)
12786    }
12787
12788    pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12789        self.open_excerpts_common(None, false, cx)
12790    }
12791
12792    fn open_excerpts_common(
12793        &mut self,
12794        jump_data: Option<JumpData>,
12795        split: bool,
12796        cx: &mut ViewContext<Self>,
12797    ) {
12798        let Some(workspace) = self.workspace() else {
12799            cx.propagate();
12800            return;
12801        };
12802
12803        if self.buffer.read(cx).is_singleton() {
12804            cx.propagate();
12805            return;
12806        }
12807
12808        let mut new_selections_by_buffer = HashMap::default();
12809        match &jump_data {
12810            Some(jump_data) => {
12811                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12812                if let Some(buffer) = multi_buffer_snapshot
12813                    .buffer_id_for_excerpt(jump_data.excerpt_id)
12814                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12815                {
12816                    let buffer_snapshot = buffer.read(cx).snapshot();
12817                    let jump_to_point = if buffer_snapshot.can_resolve(&jump_data.anchor) {
12818                        language::ToPoint::to_point(&jump_data.anchor, &buffer_snapshot)
12819                    } else {
12820                        buffer_snapshot.clip_point(jump_data.position, Bias::Left)
12821                    };
12822                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12823                    new_selections_by_buffer.insert(
12824                        buffer,
12825                        (
12826                            vec![jump_to_offset..jump_to_offset],
12827                            Some(jump_data.line_offset_from_top),
12828                        ),
12829                    );
12830                }
12831            }
12832            None => {
12833                let selections = self.selections.all::<usize>(cx);
12834                let buffer = self.buffer.read(cx);
12835                for selection in selections {
12836                    for (mut buffer_handle, mut range, _) in
12837                        buffer.range_to_buffer_ranges(selection.range(), cx)
12838                    {
12839                        // When editing branch buffers, jump to the corresponding location
12840                        // in their base buffer.
12841                        let buffer = buffer_handle.read(cx);
12842                        if let Some(base_buffer) = buffer.diff_base_buffer() {
12843                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12844                            buffer_handle = base_buffer;
12845                        }
12846
12847                        if selection.reversed {
12848                            mem::swap(&mut range.start, &mut range.end);
12849                        }
12850                        new_selections_by_buffer
12851                            .entry(buffer_handle)
12852                            .or_insert((Vec::new(), None))
12853                            .0
12854                            .push(range)
12855                    }
12856                }
12857            }
12858        }
12859
12860        if new_selections_by_buffer.is_empty() {
12861            return;
12862        }
12863
12864        // We defer the pane interaction because we ourselves are a workspace item
12865        // and activating a new item causes the pane to call a method on us reentrantly,
12866        // which panics if we're on the stack.
12867        cx.window_context().defer(move |cx| {
12868            workspace.update(cx, |workspace, cx| {
12869                let pane = if split {
12870                    workspace.adjacent_pane(cx)
12871                } else {
12872                    workspace.active_pane().clone()
12873                };
12874
12875                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12876                    let editor =
12877                        workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
12878                    editor.update(cx, |editor, cx| {
12879                        let autoscroll = match scroll_offset {
12880                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12881                            None => Autoscroll::newest(),
12882                        };
12883                        let nav_history = editor.nav_history.take();
12884                        editor.change_selections(Some(autoscroll), cx, |s| {
12885                            s.select_ranges(ranges);
12886                        });
12887                        editor.nav_history = nav_history;
12888                    });
12889                }
12890            })
12891        });
12892    }
12893
12894    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12895        let snapshot = self.buffer.read(cx).read(cx);
12896        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12897        Some(
12898            ranges
12899                .iter()
12900                .map(move |range| {
12901                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12902                })
12903                .collect(),
12904        )
12905    }
12906
12907    fn selection_replacement_ranges(
12908        &self,
12909        range: Range<OffsetUtf16>,
12910        cx: &mut AppContext,
12911    ) -> Vec<Range<OffsetUtf16>> {
12912        let selections = self.selections.all::<OffsetUtf16>(cx);
12913        let newest_selection = selections
12914            .iter()
12915            .max_by_key(|selection| selection.id)
12916            .unwrap();
12917        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12918        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12919        let snapshot = self.buffer.read(cx).read(cx);
12920        selections
12921            .into_iter()
12922            .map(|mut selection| {
12923                selection.start.0 =
12924                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
12925                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12926                snapshot.clip_offset_utf16(selection.start, Bias::Left)
12927                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12928            })
12929            .collect()
12930    }
12931
12932    fn report_editor_event(
12933        &self,
12934        operation: &'static str,
12935        file_extension: Option<String>,
12936        cx: &AppContext,
12937    ) {
12938        if cfg!(any(test, feature = "test-support")) {
12939            return;
12940        }
12941
12942        let Some(project) = &self.project else { return };
12943
12944        // If None, we are in a file without an extension
12945        let file = self
12946            .buffer
12947            .read(cx)
12948            .as_singleton()
12949            .and_then(|b| b.read(cx).file());
12950        let file_extension = file_extension.or(file
12951            .as_ref()
12952            .and_then(|file| Path::new(file.file_name(cx)).extension())
12953            .and_then(|e| e.to_str())
12954            .map(|a| a.to_string()));
12955
12956        let vim_mode = cx
12957            .global::<SettingsStore>()
12958            .raw_user_settings()
12959            .get("vim_mode")
12960            == Some(&serde_json::Value::Bool(true));
12961
12962        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12963            == language::language_settings::InlineCompletionProvider::Copilot;
12964        let copilot_enabled_for_language = self
12965            .buffer
12966            .read(cx)
12967            .settings_at(0, cx)
12968            .show_inline_completions;
12969
12970        let project = project.read(cx);
12971        let telemetry = project.client().telemetry().clone();
12972        telemetry.report_editor_event(
12973            file_extension,
12974            vim_mode,
12975            operation,
12976            copilot_enabled,
12977            copilot_enabled_for_language,
12978            project.is_via_ssh(),
12979        )
12980    }
12981
12982    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12983    /// with each line being an array of {text, highlight} objects.
12984    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12985        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12986            return;
12987        };
12988
12989        #[derive(Serialize)]
12990        struct Chunk<'a> {
12991            text: String,
12992            highlight: Option<&'a str>,
12993        }
12994
12995        let snapshot = buffer.read(cx).snapshot();
12996        let range = self
12997            .selected_text_range(false, cx)
12998            .and_then(|selection| {
12999                if selection.range.is_empty() {
13000                    None
13001                } else {
13002                    Some(selection.range)
13003                }
13004            })
13005            .unwrap_or_else(|| 0..snapshot.len());
13006
13007        let chunks = snapshot.chunks(range, true);
13008        let mut lines = Vec::new();
13009        let mut line: VecDeque<Chunk> = VecDeque::new();
13010
13011        let Some(style) = self.style.as_ref() else {
13012            return;
13013        };
13014
13015        for chunk in chunks {
13016            let highlight = chunk
13017                .syntax_highlight_id
13018                .and_then(|id| id.name(&style.syntax));
13019            let mut chunk_lines = chunk.text.split('\n').peekable();
13020            while let Some(text) = chunk_lines.next() {
13021                let mut merged_with_last_token = false;
13022                if let Some(last_token) = line.back_mut() {
13023                    if last_token.highlight == highlight {
13024                        last_token.text.push_str(text);
13025                        merged_with_last_token = true;
13026                    }
13027                }
13028
13029                if !merged_with_last_token {
13030                    line.push_back(Chunk {
13031                        text: text.into(),
13032                        highlight,
13033                    });
13034                }
13035
13036                if chunk_lines.peek().is_some() {
13037                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
13038                        line.pop_front();
13039                    }
13040                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
13041                        line.pop_back();
13042                    }
13043
13044                    lines.push(mem::take(&mut line));
13045                }
13046            }
13047        }
13048
13049        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
13050            return;
13051        };
13052        cx.write_to_clipboard(ClipboardItem::new_string(lines));
13053    }
13054
13055    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
13056        &self.inlay_hint_cache
13057    }
13058
13059    pub fn replay_insert_event(
13060        &mut self,
13061        text: &str,
13062        relative_utf16_range: Option<Range<isize>>,
13063        cx: &mut ViewContext<Self>,
13064    ) {
13065        if !self.input_enabled {
13066            cx.emit(EditorEvent::InputIgnored { text: text.into() });
13067            return;
13068        }
13069        if let Some(relative_utf16_range) = relative_utf16_range {
13070            let selections = self.selections.all::<OffsetUtf16>(cx);
13071            self.change_selections(None, cx, |s| {
13072                let new_ranges = selections.into_iter().map(|range| {
13073                    let start = OffsetUtf16(
13074                        range
13075                            .head()
13076                            .0
13077                            .saturating_add_signed(relative_utf16_range.start),
13078                    );
13079                    let end = OffsetUtf16(
13080                        range
13081                            .head()
13082                            .0
13083                            .saturating_add_signed(relative_utf16_range.end),
13084                    );
13085                    start..end
13086                });
13087                s.select_ranges(new_ranges);
13088            });
13089        }
13090
13091        self.handle_input(text, cx);
13092    }
13093
13094    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
13095        let Some(provider) = self.semantics_provider.as_ref() else {
13096            return false;
13097        };
13098
13099        let mut supports = false;
13100        self.buffer().read(cx).for_each_buffer(|buffer| {
13101            supports |= provider.supports_inlay_hints(buffer, cx);
13102        });
13103        supports
13104    }
13105
13106    pub fn focus(&self, cx: &mut WindowContext) {
13107        cx.focus(&self.focus_handle)
13108    }
13109
13110    pub fn is_focused(&self, cx: &WindowContext) -> bool {
13111        self.focus_handle.is_focused(cx)
13112    }
13113
13114    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
13115        cx.emit(EditorEvent::Focused);
13116
13117        if let Some(descendant) = self
13118            .last_focused_descendant
13119            .take()
13120            .and_then(|descendant| descendant.upgrade())
13121        {
13122            cx.focus(&descendant);
13123        } else {
13124            if let Some(blame) = self.blame.as_ref() {
13125                blame.update(cx, GitBlame::focus)
13126            }
13127
13128            self.blink_manager.update(cx, BlinkManager::enable);
13129            self.show_cursor_names(cx);
13130            self.buffer.update(cx, |buffer, cx| {
13131                buffer.finalize_last_transaction(cx);
13132                if self.leader_peer_id.is_none() {
13133                    buffer.set_active_selections(
13134                        &self.selections.disjoint_anchors(),
13135                        self.selections.line_mode,
13136                        self.cursor_shape,
13137                        cx,
13138                    );
13139                }
13140            });
13141        }
13142    }
13143
13144    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
13145        cx.emit(EditorEvent::FocusedIn)
13146    }
13147
13148    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
13149        if event.blurred != self.focus_handle {
13150            self.last_focused_descendant = Some(event.blurred);
13151        }
13152    }
13153
13154    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
13155        self.blink_manager.update(cx, BlinkManager::disable);
13156        self.buffer
13157            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
13158
13159        if let Some(blame) = self.blame.as_ref() {
13160            blame.update(cx, GitBlame::blur)
13161        }
13162        if !self.hover_state.focused(cx) {
13163            hide_hover(self, cx);
13164        }
13165
13166        self.hide_context_menu(cx);
13167        cx.emit(EditorEvent::Blurred);
13168        cx.notify();
13169    }
13170
13171    pub fn register_action<A: Action>(
13172        &mut self,
13173        listener: impl Fn(&A, &mut WindowContext) + 'static,
13174    ) -> Subscription {
13175        let id = self.next_editor_action_id.post_inc();
13176        let listener = Arc::new(listener);
13177        self.editor_actions.borrow_mut().insert(
13178            id,
13179            Box::new(move |cx| {
13180                let cx = cx.window_context();
13181                let listener = listener.clone();
13182                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
13183                    let action = action.downcast_ref().unwrap();
13184                    if phase == DispatchPhase::Bubble {
13185                        listener(action, cx)
13186                    }
13187                })
13188            }),
13189        );
13190
13191        let editor_actions = self.editor_actions.clone();
13192        Subscription::new(move || {
13193            editor_actions.borrow_mut().remove(&id);
13194        })
13195    }
13196
13197    pub fn file_header_size(&self) -> u32 {
13198        FILE_HEADER_HEIGHT
13199    }
13200
13201    pub fn revert(
13202        &mut self,
13203        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
13204        cx: &mut ViewContext<Self>,
13205    ) {
13206        self.buffer().update(cx, |multi_buffer, cx| {
13207            for (buffer_id, changes) in revert_changes {
13208                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13209                    buffer.update(cx, |buffer, cx| {
13210                        buffer.edit(
13211                            changes.into_iter().map(|(range, text)| {
13212                                (range, text.to_string().map(Arc::<str>::from))
13213                            }),
13214                            None,
13215                            cx,
13216                        );
13217                    });
13218                }
13219            }
13220        });
13221        self.change_selections(None, cx, |selections| selections.refresh());
13222    }
13223
13224    pub fn to_pixel_point(
13225        &mut self,
13226        source: multi_buffer::Anchor,
13227        editor_snapshot: &EditorSnapshot,
13228        cx: &mut ViewContext<Self>,
13229    ) -> Option<gpui::Point<Pixels>> {
13230        let source_point = source.to_display_point(editor_snapshot);
13231        self.display_to_pixel_point(source_point, editor_snapshot, cx)
13232    }
13233
13234    pub fn display_to_pixel_point(
13235        &mut self,
13236        source: DisplayPoint,
13237        editor_snapshot: &EditorSnapshot,
13238        cx: &mut ViewContext<Self>,
13239    ) -> Option<gpui::Point<Pixels>> {
13240        let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
13241        let text_layout_details = self.text_layout_details(cx);
13242        let scroll_top = text_layout_details
13243            .scroll_anchor
13244            .scroll_position(editor_snapshot)
13245            .y;
13246
13247        if source.row().as_f32() < scroll_top.floor() {
13248            return None;
13249        }
13250        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
13251        let source_y = line_height * (source.row().as_f32() - scroll_top);
13252        Some(gpui::Point::new(source_x, source_y))
13253    }
13254
13255    pub fn has_active_completions_menu(&self) -> bool {
13256        self.context_menu.read().as_ref().map_or(false, |menu| {
13257            menu.visible() && matches!(menu, ContextMenu::Completions(_))
13258        })
13259    }
13260
13261    pub fn register_addon<T: Addon>(&mut self, instance: T) {
13262        self.addons
13263            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
13264    }
13265
13266    pub fn unregister_addon<T: Addon>(&mut self) {
13267        self.addons.remove(&std::any::TypeId::of::<T>());
13268    }
13269
13270    pub fn addon<T: Addon>(&self) -> Option<&T> {
13271        let type_id = std::any::TypeId::of::<T>();
13272        self.addons
13273            .get(&type_id)
13274            .and_then(|item| item.to_any().downcast_ref::<T>())
13275    }
13276}
13277
13278fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13279    let tab_size = tab_size.get() as usize;
13280    let mut width = offset;
13281
13282    for ch in text.chars() {
13283        width += if ch == '\t' {
13284            tab_size - (width % tab_size)
13285        } else {
13286            1
13287        };
13288    }
13289
13290    width - offset
13291}
13292
13293#[cfg(test)]
13294mod tests {
13295    use super::*;
13296
13297    #[test]
13298    fn test_string_size_with_expanded_tabs() {
13299        let nz = |val| NonZeroU32::new(val).unwrap();
13300        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13301        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13302        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13303        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13304        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13305        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13306        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13307        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13308    }
13309}
13310
13311/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13312struct WordBreakingTokenizer<'a> {
13313    input: &'a str,
13314}
13315
13316impl<'a> WordBreakingTokenizer<'a> {
13317    fn new(input: &'a str) -> Self {
13318        Self { input }
13319    }
13320}
13321
13322fn is_char_ideographic(ch: char) -> bool {
13323    use unicode_script::Script::*;
13324    use unicode_script::UnicodeScript;
13325    matches!(ch.script(), Han | Tangut | Yi)
13326}
13327
13328fn is_grapheme_ideographic(text: &str) -> bool {
13329    text.chars().any(is_char_ideographic)
13330}
13331
13332fn is_grapheme_whitespace(text: &str) -> bool {
13333    text.chars().any(|x| x.is_whitespace())
13334}
13335
13336fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13337    text.chars().next().map_or(false, |ch| {
13338        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13339    })
13340}
13341
13342#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13343struct WordBreakToken<'a> {
13344    token: &'a str,
13345    grapheme_len: usize,
13346    is_whitespace: bool,
13347}
13348
13349impl<'a> Iterator for WordBreakingTokenizer<'a> {
13350    /// Yields a span, the count of graphemes in the token, and whether it was
13351    /// whitespace. Note that it also breaks at word boundaries.
13352    type Item = WordBreakToken<'a>;
13353
13354    fn next(&mut self) -> Option<Self::Item> {
13355        use unicode_segmentation::UnicodeSegmentation;
13356        if self.input.is_empty() {
13357            return None;
13358        }
13359
13360        let mut iter = self.input.graphemes(true).peekable();
13361        let mut offset = 0;
13362        let mut graphemes = 0;
13363        if let Some(first_grapheme) = iter.next() {
13364            let is_whitespace = is_grapheme_whitespace(first_grapheme);
13365            offset += first_grapheme.len();
13366            graphemes += 1;
13367            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13368                if let Some(grapheme) = iter.peek().copied() {
13369                    if should_stay_with_preceding_ideograph(grapheme) {
13370                        offset += grapheme.len();
13371                        graphemes += 1;
13372                    }
13373                }
13374            } else {
13375                let mut words = self.input[offset..].split_word_bound_indices().peekable();
13376                let mut next_word_bound = words.peek().copied();
13377                if next_word_bound.map_or(false, |(i, _)| i == 0) {
13378                    next_word_bound = words.next();
13379                }
13380                while let Some(grapheme) = iter.peek().copied() {
13381                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
13382                        break;
13383                    };
13384                    if is_grapheme_whitespace(grapheme) != is_whitespace {
13385                        break;
13386                    };
13387                    offset += grapheme.len();
13388                    graphemes += 1;
13389                    iter.next();
13390                }
13391            }
13392            let token = &self.input[..offset];
13393            self.input = &self.input[offset..];
13394            if is_whitespace {
13395                Some(WordBreakToken {
13396                    token: " ",
13397                    grapheme_len: 1,
13398                    is_whitespace: true,
13399                })
13400            } else {
13401                Some(WordBreakToken {
13402                    token,
13403                    grapheme_len: graphemes,
13404                    is_whitespace: false,
13405                })
13406            }
13407        } else {
13408            None
13409        }
13410    }
13411}
13412
13413#[test]
13414fn test_word_breaking_tokenizer() {
13415    let tests: &[(&str, &[(&str, usize, bool)])] = &[
13416        ("", &[]),
13417        ("  ", &[(" ", 1, true)]),
13418        ("Ʒ", &[("Ʒ", 1, false)]),
13419        ("Ǽ", &[("Ǽ", 1, false)]),
13420        ("", &[("", 1, false)]),
13421        ("⋑⋑", &[("⋑⋑", 2, false)]),
13422        (
13423            "原理,进而",
13424            &[
13425                ("", 1, false),
13426                ("理,", 2, false),
13427                ("", 1, false),
13428                ("", 1, false),
13429            ],
13430        ),
13431        (
13432            "hello world",
13433            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13434        ),
13435        (
13436            "hello, world",
13437            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13438        ),
13439        (
13440            "  hello world",
13441            &[
13442                (" ", 1, true),
13443                ("hello", 5, false),
13444                (" ", 1, true),
13445                ("world", 5, false),
13446            ],
13447        ),
13448        (
13449            "这是什么 \n 钢笔",
13450            &[
13451                ("", 1, false),
13452                ("", 1, false),
13453                ("", 1, false),
13454                ("", 1, false),
13455                (" ", 1, true),
13456                ("", 1, false),
13457                ("", 1, false),
13458            ],
13459        ),
13460        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13461    ];
13462
13463    for (input, result) in tests {
13464        assert_eq!(
13465            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13466            result
13467                .iter()
13468                .copied()
13469                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13470                    token,
13471                    grapheme_len,
13472                    is_whitespace,
13473                })
13474                .collect::<Vec<_>>()
13475        );
13476    }
13477}
13478
13479fn wrap_with_prefix(
13480    line_prefix: String,
13481    unwrapped_text: String,
13482    wrap_column: usize,
13483    tab_size: NonZeroU32,
13484) -> String {
13485    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13486    let mut wrapped_text = String::new();
13487    let mut current_line = line_prefix.clone();
13488
13489    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13490    let mut current_line_len = line_prefix_len;
13491    for WordBreakToken {
13492        token,
13493        grapheme_len,
13494        is_whitespace,
13495    } in tokenizer
13496    {
13497        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13498            wrapped_text.push_str(current_line.trim_end());
13499            wrapped_text.push('\n');
13500            current_line.truncate(line_prefix.len());
13501            current_line_len = line_prefix_len;
13502            if !is_whitespace {
13503                current_line.push_str(token);
13504                current_line_len += grapheme_len;
13505            }
13506        } else if !is_whitespace {
13507            current_line.push_str(token);
13508            current_line_len += grapheme_len;
13509        } else if current_line_len != line_prefix_len {
13510            current_line.push(' ');
13511            current_line_len += 1;
13512        }
13513    }
13514
13515    if !current_line.is_empty() {
13516        wrapped_text.push_str(&current_line);
13517    }
13518    wrapped_text
13519}
13520
13521#[test]
13522fn test_wrap_with_prefix() {
13523    assert_eq!(
13524        wrap_with_prefix(
13525            "# ".to_string(),
13526            "abcdefg".to_string(),
13527            4,
13528            NonZeroU32::new(4).unwrap()
13529        ),
13530        "# abcdefg"
13531    );
13532    assert_eq!(
13533        wrap_with_prefix(
13534            "".to_string(),
13535            "\thello world".to_string(),
13536            8,
13537            NonZeroU32::new(4).unwrap()
13538        ),
13539        "hello\nworld"
13540    );
13541    assert_eq!(
13542        wrap_with_prefix(
13543            "// ".to_string(),
13544            "xx \nyy zz aa bb cc".to_string(),
13545            12,
13546            NonZeroU32::new(4).unwrap()
13547        ),
13548        "// xx yy zz\n// aa bb cc"
13549    );
13550    assert_eq!(
13551        wrap_with_prefix(
13552            String::new(),
13553            "这是什么 \n 钢笔".to_string(),
13554            3,
13555            NonZeroU32::new(4).unwrap()
13556        ),
13557        "这是什\n么 钢\n"
13558    );
13559}
13560
13561fn hunks_for_selections(
13562    multi_buffer_snapshot: &MultiBufferSnapshot,
13563    selections: &[Selection<Anchor>],
13564) -> Vec<MultiBufferDiffHunk> {
13565    let buffer_rows_for_selections = selections.iter().map(|selection| {
13566        let head = selection.head();
13567        let tail = selection.tail();
13568        let start = MultiBufferRow(tail.to_point(multi_buffer_snapshot).row);
13569        let end = MultiBufferRow(head.to_point(multi_buffer_snapshot).row);
13570        if start > end {
13571            end..start
13572        } else {
13573            start..end
13574        }
13575    });
13576
13577    hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
13578}
13579
13580pub fn hunks_for_rows(
13581    rows: impl Iterator<Item = Range<MultiBufferRow>>,
13582    multi_buffer_snapshot: &MultiBufferSnapshot,
13583) -> Vec<MultiBufferDiffHunk> {
13584    let mut hunks = Vec::new();
13585    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13586        HashMap::default();
13587    for selected_multi_buffer_rows in rows {
13588        let query_rows =
13589            selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
13590        for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
13591            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13592            // when the caret is just above or just below the deleted hunk.
13593            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13594            let related_to_selection = if allow_adjacent {
13595                hunk.row_range.overlaps(&query_rows)
13596                    || hunk.row_range.start == query_rows.end
13597                    || hunk.row_range.end == query_rows.start
13598            } else {
13599                // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
13600                // `hunk.row_range` is exclusive (e.g. [2..3] means 2nd row is selected)
13601                hunk.row_range.overlaps(&selected_multi_buffer_rows)
13602                    || selected_multi_buffer_rows.end == hunk.row_range.start
13603            };
13604            if related_to_selection {
13605                if !processed_buffer_rows
13606                    .entry(hunk.buffer_id)
13607                    .or_default()
13608                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13609                {
13610                    continue;
13611                }
13612                hunks.push(hunk);
13613            }
13614        }
13615    }
13616
13617    hunks
13618}
13619
13620pub trait CollaborationHub {
13621    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13622    fn user_participant_indices<'a>(
13623        &self,
13624        cx: &'a AppContext,
13625    ) -> &'a HashMap<u64, ParticipantIndex>;
13626    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13627}
13628
13629impl CollaborationHub for Model<Project> {
13630    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13631        self.read(cx).collaborators()
13632    }
13633
13634    fn user_participant_indices<'a>(
13635        &self,
13636        cx: &'a AppContext,
13637    ) -> &'a HashMap<u64, ParticipantIndex> {
13638        self.read(cx).user_store().read(cx).participant_indices()
13639    }
13640
13641    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13642        let this = self.read(cx);
13643        let user_ids = this.collaborators().values().map(|c| c.user_id);
13644        this.user_store().read_with(cx, |user_store, cx| {
13645            user_store.participant_names(user_ids, cx)
13646        })
13647    }
13648}
13649
13650pub trait SemanticsProvider {
13651    fn hover(
13652        &self,
13653        buffer: &Model<Buffer>,
13654        position: text::Anchor,
13655        cx: &mut AppContext,
13656    ) -> Option<Task<Vec<project::Hover>>>;
13657
13658    fn inlay_hints(
13659        &self,
13660        buffer_handle: Model<Buffer>,
13661        range: Range<text::Anchor>,
13662        cx: &mut AppContext,
13663    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13664
13665    fn resolve_inlay_hint(
13666        &self,
13667        hint: InlayHint,
13668        buffer_handle: Model<Buffer>,
13669        server_id: LanguageServerId,
13670        cx: &mut AppContext,
13671    ) -> Option<Task<anyhow::Result<InlayHint>>>;
13672
13673    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13674
13675    fn document_highlights(
13676        &self,
13677        buffer: &Model<Buffer>,
13678        position: text::Anchor,
13679        cx: &mut AppContext,
13680    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13681
13682    fn definitions(
13683        &self,
13684        buffer: &Model<Buffer>,
13685        position: text::Anchor,
13686        kind: GotoDefinitionKind,
13687        cx: &mut AppContext,
13688    ) -> Option<Task<Result<Vec<LocationLink>>>>;
13689
13690    fn range_for_rename(
13691        &self,
13692        buffer: &Model<Buffer>,
13693        position: text::Anchor,
13694        cx: &mut AppContext,
13695    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13696
13697    fn perform_rename(
13698        &self,
13699        buffer: &Model<Buffer>,
13700        position: text::Anchor,
13701        new_name: String,
13702        cx: &mut AppContext,
13703    ) -> Option<Task<Result<ProjectTransaction>>>;
13704}
13705
13706pub trait CompletionProvider {
13707    fn completions(
13708        &self,
13709        buffer: &Model<Buffer>,
13710        buffer_position: text::Anchor,
13711        trigger: CompletionContext,
13712        cx: &mut ViewContext<Editor>,
13713    ) -> Task<Result<Vec<Completion>>>;
13714
13715    fn resolve_completions(
13716        &self,
13717        buffer: Model<Buffer>,
13718        completion_indices: Vec<usize>,
13719        completions: Arc<RwLock<Box<[Completion]>>>,
13720        cx: &mut ViewContext<Editor>,
13721    ) -> Task<Result<bool>>;
13722
13723    fn apply_additional_edits_for_completion(
13724        &self,
13725        buffer: Model<Buffer>,
13726        completion: Completion,
13727        push_to_history: bool,
13728        cx: &mut ViewContext<Editor>,
13729    ) -> Task<Result<Option<language::Transaction>>>;
13730
13731    fn is_completion_trigger(
13732        &self,
13733        buffer: &Model<Buffer>,
13734        position: language::Anchor,
13735        text: &str,
13736        trigger_in_words: bool,
13737        cx: &mut ViewContext<Editor>,
13738    ) -> bool;
13739
13740    fn sort_completions(&self) -> bool {
13741        true
13742    }
13743}
13744
13745pub trait CodeActionProvider {
13746    fn code_actions(
13747        &self,
13748        buffer: &Model<Buffer>,
13749        range: Range<text::Anchor>,
13750        cx: &mut WindowContext,
13751    ) -> Task<Result<Vec<CodeAction>>>;
13752
13753    fn apply_code_action(
13754        &self,
13755        buffer_handle: Model<Buffer>,
13756        action: CodeAction,
13757        excerpt_id: ExcerptId,
13758        push_to_history: bool,
13759        cx: &mut WindowContext,
13760    ) -> Task<Result<ProjectTransaction>>;
13761}
13762
13763impl CodeActionProvider for Model<Project> {
13764    fn code_actions(
13765        &self,
13766        buffer: &Model<Buffer>,
13767        range: Range<text::Anchor>,
13768        cx: &mut WindowContext,
13769    ) -> Task<Result<Vec<CodeAction>>> {
13770        self.update(cx, |project, cx| {
13771            project.code_actions(buffer, range, None, cx)
13772        })
13773    }
13774
13775    fn apply_code_action(
13776        &self,
13777        buffer_handle: Model<Buffer>,
13778        action: CodeAction,
13779        _excerpt_id: ExcerptId,
13780        push_to_history: bool,
13781        cx: &mut WindowContext,
13782    ) -> Task<Result<ProjectTransaction>> {
13783        self.update(cx, |project, cx| {
13784            project.apply_code_action(buffer_handle, action, push_to_history, cx)
13785        })
13786    }
13787}
13788
13789fn snippet_completions(
13790    project: &Project,
13791    buffer: &Model<Buffer>,
13792    buffer_position: text::Anchor,
13793    cx: &mut AppContext,
13794) -> Vec<Completion> {
13795    let language = buffer.read(cx).language_at(buffer_position);
13796    let language_name = language.as_ref().map(|language| language.lsp_id());
13797    let snippet_store = project.snippets().read(cx);
13798    let snippets = snippet_store.snippets_for(language_name, cx);
13799
13800    if snippets.is_empty() {
13801        return vec![];
13802    }
13803    let snapshot = buffer.read(cx).text_snapshot();
13804    let chars = snapshot.reversed_chars_for_range(text::Anchor::MIN..buffer_position);
13805
13806    let scope = language.map(|language| language.default_scope());
13807    let classifier = CharClassifier::new(scope).for_completion(true);
13808    let mut last_word = chars
13809        .take_while(|c| classifier.is_word(*c))
13810        .collect::<String>();
13811    last_word = last_word.chars().rev().collect();
13812    let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13813    let to_lsp = |point: &text::Anchor| {
13814        let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13815        point_to_lsp(end)
13816    };
13817    let lsp_end = to_lsp(&buffer_position);
13818    snippets
13819        .into_iter()
13820        .filter_map(|snippet| {
13821            let matching_prefix = snippet
13822                .prefix
13823                .iter()
13824                .find(|prefix| prefix.starts_with(&last_word))?;
13825            let start = as_offset - last_word.len();
13826            let start = snapshot.anchor_before(start);
13827            let range = start..buffer_position;
13828            let lsp_start = to_lsp(&start);
13829            let lsp_range = lsp::Range {
13830                start: lsp_start,
13831                end: lsp_end,
13832            };
13833            Some(Completion {
13834                old_range: range,
13835                new_text: snippet.body.clone(),
13836                label: CodeLabel {
13837                    text: matching_prefix.clone(),
13838                    runs: vec![],
13839                    filter_range: 0..matching_prefix.len(),
13840                },
13841                server_id: LanguageServerId(usize::MAX),
13842                documentation: snippet.description.clone().map(Documentation::SingleLine),
13843                lsp_completion: lsp::CompletionItem {
13844                    label: snippet.prefix.first().unwrap().clone(),
13845                    kind: Some(CompletionItemKind::SNIPPET),
13846                    label_details: snippet.description.as_ref().map(|description| {
13847                        lsp::CompletionItemLabelDetails {
13848                            detail: Some(description.clone()),
13849                            description: None,
13850                        }
13851                    }),
13852                    insert_text_format: Some(InsertTextFormat::SNIPPET),
13853                    text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13854                        lsp::InsertReplaceEdit {
13855                            new_text: snippet.body.clone(),
13856                            insert: lsp_range,
13857                            replace: lsp_range,
13858                        },
13859                    )),
13860                    filter_text: Some(snippet.body.clone()),
13861                    sort_text: Some(char::MAX.to_string()),
13862                    ..Default::default()
13863                },
13864                confirm: None,
13865            })
13866        })
13867        .collect()
13868}
13869
13870impl CompletionProvider for Model<Project> {
13871    fn completions(
13872        &self,
13873        buffer: &Model<Buffer>,
13874        buffer_position: text::Anchor,
13875        options: CompletionContext,
13876        cx: &mut ViewContext<Editor>,
13877    ) -> Task<Result<Vec<Completion>>> {
13878        self.update(cx, |project, cx| {
13879            let snippets = snippet_completions(project, buffer, buffer_position, cx);
13880            let project_completions = project.completions(buffer, buffer_position, options, cx);
13881            cx.background_executor().spawn(async move {
13882                let mut completions = project_completions.await?;
13883                //let snippets = snippets.into_iter().;
13884                completions.extend(snippets);
13885                Ok(completions)
13886            })
13887        })
13888    }
13889
13890    fn resolve_completions(
13891        &self,
13892        buffer: Model<Buffer>,
13893        completion_indices: Vec<usize>,
13894        completions: Arc<RwLock<Box<[Completion]>>>,
13895        cx: &mut ViewContext<Editor>,
13896    ) -> Task<Result<bool>> {
13897        self.update(cx, |project, cx| {
13898            project.resolve_completions(buffer, completion_indices, completions, cx)
13899        })
13900    }
13901
13902    fn apply_additional_edits_for_completion(
13903        &self,
13904        buffer: Model<Buffer>,
13905        completion: Completion,
13906        push_to_history: bool,
13907        cx: &mut ViewContext<Editor>,
13908    ) -> Task<Result<Option<language::Transaction>>> {
13909        self.update(cx, |project, cx| {
13910            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13911        })
13912    }
13913
13914    fn is_completion_trigger(
13915        &self,
13916        buffer: &Model<Buffer>,
13917        position: language::Anchor,
13918        text: &str,
13919        trigger_in_words: bool,
13920        cx: &mut ViewContext<Editor>,
13921    ) -> bool {
13922        if !EditorSettings::get_global(cx).show_completions_on_input {
13923            return false;
13924        }
13925
13926        let mut chars = text.chars();
13927        let char = if let Some(char) = chars.next() {
13928            char
13929        } else {
13930            return false;
13931        };
13932        if chars.next().is_some() {
13933            return false;
13934        }
13935
13936        let buffer = buffer.read(cx);
13937        let classifier = buffer
13938            .snapshot()
13939            .char_classifier_at(position)
13940            .for_completion(true);
13941        if trigger_in_words && classifier.is_word(char) {
13942            return true;
13943        }
13944
13945        buffer.completion_triggers().contains(text)
13946    }
13947}
13948
13949impl SemanticsProvider for Model<Project> {
13950    fn hover(
13951        &self,
13952        buffer: &Model<Buffer>,
13953        position: text::Anchor,
13954        cx: &mut AppContext,
13955    ) -> Option<Task<Vec<project::Hover>>> {
13956        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13957    }
13958
13959    fn document_highlights(
13960        &self,
13961        buffer: &Model<Buffer>,
13962        position: text::Anchor,
13963        cx: &mut AppContext,
13964    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13965        Some(self.update(cx, |project, cx| {
13966            project.document_highlights(buffer, position, cx)
13967        }))
13968    }
13969
13970    fn definitions(
13971        &self,
13972        buffer: &Model<Buffer>,
13973        position: text::Anchor,
13974        kind: GotoDefinitionKind,
13975        cx: &mut AppContext,
13976    ) -> Option<Task<Result<Vec<LocationLink>>>> {
13977        Some(self.update(cx, |project, cx| match kind {
13978            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13979            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13980            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13981            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13982        }))
13983    }
13984
13985    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13986        // TODO: make this work for remote projects
13987        self.read(cx)
13988            .language_servers_for_buffer(buffer.read(cx), cx)
13989            .any(
13990                |(_, server)| match server.capabilities().inlay_hint_provider {
13991                    Some(lsp::OneOf::Left(enabled)) => enabled,
13992                    Some(lsp::OneOf::Right(_)) => true,
13993                    None => false,
13994                },
13995            )
13996    }
13997
13998    fn inlay_hints(
13999        &self,
14000        buffer_handle: Model<Buffer>,
14001        range: Range<text::Anchor>,
14002        cx: &mut AppContext,
14003    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
14004        Some(self.update(cx, |project, cx| {
14005            project.inlay_hints(buffer_handle, range, cx)
14006        }))
14007    }
14008
14009    fn resolve_inlay_hint(
14010        &self,
14011        hint: InlayHint,
14012        buffer_handle: Model<Buffer>,
14013        server_id: LanguageServerId,
14014        cx: &mut AppContext,
14015    ) -> Option<Task<anyhow::Result<InlayHint>>> {
14016        Some(self.update(cx, |project, cx| {
14017            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
14018        }))
14019    }
14020
14021    fn range_for_rename(
14022        &self,
14023        buffer: &Model<Buffer>,
14024        position: text::Anchor,
14025        cx: &mut AppContext,
14026    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
14027        Some(self.update(cx, |project, cx| {
14028            project.prepare_rename(buffer.clone(), position, cx)
14029        }))
14030    }
14031
14032    fn perform_rename(
14033        &self,
14034        buffer: &Model<Buffer>,
14035        position: text::Anchor,
14036        new_name: String,
14037        cx: &mut AppContext,
14038    ) -> Option<Task<Result<ProjectTransaction>>> {
14039        Some(self.update(cx, |project, cx| {
14040            project.perform_rename(buffer.clone(), position, new_name, cx)
14041        }))
14042    }
14043}
14044
14045fn inlay_hint_settings(
14046    location: Anchor,
14047    snapshot: &MultiBufferSnapshot,
14048    cx: &mut ViewContext<'_, Editor>,
14049) -> InlayHintSettings {
14050    let file = snapshot.file_at(location);
14051    let language = snapshot.language_at(location).map(|l| l.name());
14052    language_settings(language, file, cx).inlay_hints
14053}
14054
14055fn consume_contiguous_rows(
14056    contiguous_row_selections: &mut Vec<Selection<Point>>,
14057    selection: &Selection<Point>,
14058    display_map: &DisplaySnapshot,
14059    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
14060) -> (MultiBufferRow, MultiBufferRow) {
14061    contiguous_row_selections.push(selection.clone());
14062    let start_row = MultiBufferRow(selection.start.row);
14063    let mut end_row = ending_row(selection, display_map);
14064
14065    while let Some(next_selection) = selections.peek() {
14066        if next_selection.start.row <= end_row.0 {
14067            end_row = ending_row(next_selection, display_map);
14068            contiguous_row_selections.push(selections.next().unwrap().clone());
14069        } else {
14070            break;
14071        }
14072    }
14073    (start_row, end_row)
14074}
14075
14076fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
14077    if next_selection.end.column > 0 || next_selection.is_empty() {
14078        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
14079    } else {
14080        MultiBufferRow(next_selection.end.row)
14081    }
14082}
14083
14084impl EditorSnapshot {
14085    pub fn remote_selections_in_range<'a>(
14086        &'a self,
14087        range: &'a Range<Anchor>,
14088        collaboration_hub: &dyn CollaborationHub,
14089        cx: &'a AppContext,
14090    ) -> impl 'a + Iterator<Item = RemoteSelection> {
14091        let participant_names = collaboration_hub.user_names(cx);
14092        let participant_indices = collaboration_hub.user_participant_indices(cx);
14093        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
14094        let collaborators_by_replica_id = collaborators_by_peer_id
14095            .iter()
14096            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
14097            .collect::<HashMap<_, _>>();
14098        self.buffer_snapshot
14099            .selections_in_range(range, false)
14100            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
14101                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
14102                let participant_index = participant_indices.get(&collaborator.user_id).copied();
14103                let user_name = participant_names.get(&collaborator.user_id).cloned();
14104                Some(RemoteSelection {
14105                    replica_id,
14106                    selection,
14107                    cursor_shape,
14108                    line_mode,
14109                    participant_index,
14110                    peer_id: collaborator.peer_id,
14111                    user_name,
14112                })
14113            })
14114    }
14115
14116    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
14117        self.display_snapshot.buffer_snapshot.language_at(position)
14118    }
14119
14120    pub fn is_focused(&self) -> bool {
14121        self.is_focused
14122    }
14123
14124    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
14125        self.placeholder_text.as_ref()
14126    }
14127
14128    pub fn scroll_position(&self) -> gpui::Point<f32> {
14129        self.scroll_anchor.scroll_position(&self.display_snapshot)
14130    }
14131
14132    fn gutter_dimensions(
14133        &self,
14134        font_id: FontId,
14135        font_size: Pixels,
14136        em_width: Pixels,
14137        em_advance: Pixels,
14138        max_line_number_width: Pixels,
14139        cx: &AppContext,
14140    ) -> GutterDimensions {
14141        if !self.show_gutter {
14142            return GutterDimensions::default();
14143        }
14144        let descent = cx.text_system().descent(font_id, font_size);
14145
14146        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
14147            matches!(
14148                ProjectSettings::get_global(cx).git.git_gutter,
14149                Some(GitGutterSetting::TrackedFiles)
14150            )
14151        });
14152        let gutter_settings = EditorSettings::get_global(cx).gutter;
14153        let show_line_numbers = self
14154            .show_line_numbers
14155            .unwrap_or(gutter_settings.line_numbers);
14156        let line_gutter_width = if show_line_numbers {
14157            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
14158            let min_width_for_number_on_gutter = em_advance * 4.0;
14159            max_line_number_width.max(min_width_for_number_on_gutter)
14160        } else {
14161            0.0.into()
14162        };
14163
14164        let show_code_actions = self
14165            .show_code_actions
14166            .unwrap_or(gutter_settings.code_actions);
14167
14168        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
14169
14170        let git_blame_entries_width =
14171            self.git_blame_gutter_max_author_length
14172                .map(|max_author_length| {
14173                    // Length of the author name, but also space for the commit hash,
14174                    // the spacing and the timestamp.
14175                    let max_char_count = max_author_length
14176                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
14177                        + 7 // length of commit sha
14178                        + 14 // length of max relative timestamp ("60 minutes ago")
14179                        + 4; // gaps and margins
14180
14181                    em_advance * max_char_count
14182                });
14183
14184        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
14185        left_padding += if show_code_actions || show_runnables {
14186            em_width * 3.0
14187        } else if show_git_gutter && show_line_numbers {
14188            em_width * 2.0
14189        } else if show_git_gutter || show_line_numbers {
14190            em_width
14191        } else {
14192            px(0.)
14193        };
14194
14195        let right_padding = if gutter_settings.folds && show_line_numbers {
14196            em_width * 4.0
14197        } else if gutter_settings.folds {
14198            em_width * 3.0
14199        } else if show_line_numbers {
14200            em_width
14201        } else {
14202            px(0.)
14203        };
14204
14205        GutterDimensions {
14206            left_padding,
14207            right_padding,
14208            width: line_gutter_width + left_padding + right_padding,
14209            margin: -descent,
14210            git_blame_entries_width,
14211        }
14212    }
14213
14214    pub fn render_crease_toggle(
14215        &self,
14216        buffer_row: MultiBufferRow,
14217        row_contains_cursor: bool,
14218        editor: View<Editor>,
14219        cx: &mut WindowContext,
14220    ) -> Option<AnyElement> {
14221        let folded = self.is_line_folded(buffer_row);
14222        let mut is_foldable = false;
14223
14224        if let Some(crease) = self
14225            .crease_snapshot
14226            .query_row(buffer_row, &self.buffer_snapshot)
14227        {
14228            is_foldable = true;
14229            match crease {
14230                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
14231                    if let Some(render_toggle) = render_toggle {
14232                        let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14233                            if folded {
14234                                editor.update(cx, |editor, cx| {
14235                                    editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14236                                });
14237                            } else {
14238                                editor.update(cx, |editor, cx| {
14239                                    editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14240                                });
14241                            }
14242                        });
14243                        return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
14244                    }
14245                }
14246            }
14247        }
14248
14249        is_foldable |= self.starts_indent(buffer_row);
14250
14251        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
14252            Some(
14253                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
14254                    .selected(folded)
14255                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14256                        if folded {
14257                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
14258                        } else {
14259                            this.fold_at(&FoldAt { buffer_row }, cx);
14260                        }
14261                    }))
14262                    .into_any_element(),
14263            )
14264        } else {
14265            None
14266        }
14267    }
14268
14269    pub fn render_crease_trailer(
14270        &self,
14271        buffer_row: MultiBufferRow,
14272        cx: &mut WindowContext,
14273    ) -> Option<AnyElement> {
14274        let folded = self.is_line_folded(buffer_row);
14275        if let Crease::Inline { render_trailer, .. } = self
14276            .crease_snapshot
14277            .query_row(buffer_row, &self.buffer_snapshot)?
14278        {
14279            let render_trailer = render_trailer.as_ref()?;
14280            Some(render_trailer(buffer_row, folded, cx))
14281        } else {
14282            None
14283        }
14284    }
14285}
14286
14287impl Deref for EditorSnapshot {
14288    type Target = DisplaySnapshot;
14289
14290    fn deref(&self) -> &Self::Target {
14291        &self.display_snapshot
14292    }
14293}
14294
14295#[derive(Clone, Debug, PartialEq, Eq)]
14296pub enum EditorEvent {
14297    InputIgnored {
14298        text: Arc<str>,
14299    },
14300    InputHandled {
14301        utf16_range_to_replace: Option<Range<isize>>,
14302        text: Arc<str>,
14303    },
14304    ExcerptsAdded {
14305        buffer: Model<Buffer>,
14306        predecessor: ExcerptId,
14307        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14308    },
14309    ExcerptsRemoved {
14310        ids: Vec<ExcerptId>,
14311    },
14312    ExcerptsEdited {
14313        ids: Vec<ExcerptId>,
14314    },
14315    ExcerptsExpanded {
14316        ids: Vec<ExcerptId>,
14317    },
14318    BufferEdited,
14319    Edited {
14320        transaction_id: clock::Lamport,
14321    },
14322    Reparsed(BufferId),
14323    Focused,
14324    FocusedIn,
14325    Blurred,
14326    DirtyChanged,
14327    Saved,
14328    TitleChanged,
14329    DiffBaseChanged,
14330    SelectionsChanged {
14331        local: bool,
14332    },
14333    ScrollPositionChanged {
14334        local: bool,
14335        autoscroll: bool,
14336    },
14337    Closed,
14338    TransactionUndone {
14339        transaction_id: clock::Lamport,
14340    },
14341    TransactionBegun {
14342        transaction_id: clock::Lamport,
14343    },
14344    Reloaded,
14345    CursorShapeChanged,
14346}
14347
14348impl EventEmitter<EditorEvent> for Editor {}
14349
14350impl FocusableView for Editor {
14351    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14352        self.focus_handle.clone()
14353    }
14354}
14355
14356impl Render for Editor {
14357    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14358        let settings = ThemeSettings::get_global(cx);
14359
14360        let mut text_style = match self.mode {
14361            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14362                color: cx.theme().colors().editor_foreground,
14363                font_family: settings.ui_font.family.clone(),
14364                font_features: settings.ui_font.features.clone(),
14365                font_fallbacks: settings.ui_font.fallbacks.clone(),
14366                font_size: rems(0.875).into(),
14367                font_weight: settings.ui_font.weight,
14368                line_height: relative(settings.buffer_line_height.value()),
14369                ..Default::default()
14370            },
14371            EditorMode::Full => TextStyle {
14372                color: cx.theme().colors().editor_foreground,
14373                font_family: settings.buffer_font.family.clone(),
14374                font_features: settings.buffer_font.features.clone(),
14375                font_fallbacks: settings.buffer_font.fallbacks.clone(),
14376                font_size: settings.buffer_font_size(cx).into(),
14377                font_weight: settings.buffer_font.weight,
14378                line_height: relative(settings.buffer_line_height.value()),
14379                ..Default::default()
14380            },
14381        };
14382        if let Some(text_style_refinement) = &self.text_style_refinement {
14383            text_style.refine(text_style_refinement)
14384        }
14385
14386        let background = match self.mode {
14387            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14388            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14389            EditorMode::Full => cx.theme().colors().editor_background,
14390        };
14391
14392        EditorElement::new(
14393            cx.view(),
14394            EditorStyle {
14395                background,
14396                local_player: cx.theme().players().local(),
14397                text: text_style,
14398                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14399                syntax: cx.theme().syntax().clone(),
14400                status: cx.theme().status().clone(),
14401                inlay_hints_style: make_inlay_hints_style(cx),
14402                suggestions_style: HighlightStyle {
14403                    color: Some(cx.theme().status().predictive),
14404                    ..HighlightStyle::default()
14405                },
14406                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14407            },
14408        )
14409    }
14410}
14411
14412impl ViewInputHandler for Editor {
14413    fn text_for_range(
14414        &mut self,
14415        range_utf16: Range<usize>,
14416        adjusted_range: &mut Option<Range<usize>>,
14417        cx: &mut ViewContext<Self>,
14418    ) -> Option<String> {
14419        let snapshot = self.buffer.read(cx).read(cx);
14420        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
14421        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
14422        if (start.0..end.0) != range_utf16 {
14423            adjusted_range.replace(start.0..end.0);
14424        }
14425        Some(snapshot.text_for_range(start..end).collect())
14426    }
14427
14428    fn selected_text_range(
14429        &mut self,
14430        ignore_disabled_input: bool,
14431        cx: &mut ViewContext<Self>,
14432    ) -> Option<UTF16Selection> {
14433        // Prevent the IME menu from appearing when holding down an alphabetic key
14434        // while input is disabled.
14435        if !ignore_disabled_input && !self.input_enabled {
14436            return None;
14437        }
14438
14439        let selection = self.selections.newest::<OffsetUtf16>(cx);
14440        let range = selection.range();
14441
14442        Some(UTF16Selection {
14443            range: range.start.0..range.end.0,
14444            reversed: selection.reversed,
14445        })
14446    }
14447
14448    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14449        let snapshot = self.buffer.read(cx).read(cx);
14450        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14451        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14452    }
14453
14454    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14455        self.clear_highlights::<InputComposition>(cx);
14456        self.ime_transaction.take();
14457    }
14458
14459    fn replace_text_in_range(
14460        &mut self,
14461        range_utf16: Option<Range<usize>>,
14462        text: &str,
14463        cx: &mut ViewContext<Self>,
14464    ) {
14465        if !self.input_enabled {
14466            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14467            return;
14468        }
14469
14470        self.transact(cx, |this, cx| {
14471            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14472                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14473                Some(this.selection_replacement_ranges(range_utf16, cx))
14474            } else {
14475                this.marked_text_ranges(cx)
14476            };
14477
14478            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14479                let newest_selection_id = this.selections.newest_anchor().id;
14480                this.selections
14481                    .all::<OffsetUtf16>(cx)
14482                    .iter()
14483                    .zip(ranges_to_replace.iter())
14484                    .find_map(|(selection, range)| {
14485                        if selection.id == newest_selection_id {
14486                            Some(
14487                                (range.start.0 as isize - selection.head().0 as isize)
14488                                    ..(range.end.0 as isize - selection.head().0 as isize),
14489                            )
14490                        } else {
14491                            None
14492                        }
14493                    })
14494            });
14495
14496            cx.emit(EditorEvent::InputHandled {
14497                utf16_range_to_replace: range_to_replace,
14498                text: text.into(),
14499            });
14500
14501            if let Some(new_selected_ranges) = new_selected_ranges {
14502                this.change_selections(None, cx, |selections| {
14503                    selections.select_ranges(new_selected_ranges)
14504                });
14505                this.backspace(&Default::default(), cx);
14506            }
14507
14508            this.handle_input(text, cx);
14509        });
14510
14511        if let Some(transaction) = self.ime_transaction {
14512            self.buffer.update(cx, |buffer, cx| {
14513                buffer.group_until_transaction(transaction, cx);
14514            });
14515        }
14516
14517        self.unmark_text(cx);
14518    }
14519
14520    fn replace_and_mark_text_in_range(
14521        &mut self,
14522        range_utf16: Option<Range<usize>>,
14523        text: &str,
14524        new_selected_range_utf16: Option<Range<usize>>,
14525        cx: &mut ViewContext<Self>,
14526    ) {
14527        if !self.input_enabled {
14528            return;
14529        }
14530
14531        let transaction = self.transact(cx, |this, cx| {
14532            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14533                let snapshot = this.buffer.read(cx).read(cx);
14534                if let Some(relative_range_utf16) = range_utf16.as_ref() {
14535                    for marked_range in &mut marked_ranges {
14536                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14537                        marked_range.start.0 += relative_range_utf16.start;
14538                        marked_range.start =
14539                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14540                        marked_range.end =
14541                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14542                    }
14543                }
14544                Some(marked_ranges)
14545            } else if let Some(range_utf16) = range_utf16 {
14546                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14547                Some(this.selection_replacement_ranges(range_utf16, cx))
14548            } else {
14549                None
14550            };
14551
14552            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14553                let newest_selection_id = this.selections.newest_anchor().id;
14554                this.selections
14555                    .all::<OffsetUtf16>(cx)
14556                    .iter()
14557                    .zip(ranges_to_replace.iter())
14558                    .find_map(|(selection, range)| {
14559                        if selection.id == newest_selection_id {
14560                            Some(
14561                                (range.start.0 as isize - selection.head().0 as isize)
14562                                    ..(range.end.0 as isize - selection.head().0 as isize),
14563                            )
14564                        } else {
14565                            None
14566                        }
14567                    })
14568            });
14569
14570            cx.emit(EditorEvent::InputHandled {
14571                utf16_range_to_replace: range_to_replace,
14572                text: text.into(),
14573            });
14574
14575            if let Some(ranges) = ranges_to_replace {
14576                this.change_selections(None, cx, |s| s.select_ranges(ranges));
14577            }
14578
14579            let marked_ranges = {
14580                let snapshot = this.buffer.read(cx).read(cx);
14581                this.selections
14582                    .disjoint_anchors()
14583                    .iter()
14584                    .map(|selection| {
14585                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14586                    })
14587                    .collect::<Vec<_>>()
14588            };
14589
14590            if text.is_empty() {
14591                this.unmark_text(cx);
14592            } else {
14593                this.highlight_text::<InputComposition>(
14594                    marked_ranges.clone(),
14595                    HighlightStyle {
14596                        underline: Some(UnderlineStyle {
14597                            thickness: px(1.),
14598                            color: None,
14599                            wavy: false,
14600                        }),
14601                        ..Default::default()
14602                    },
14603                    cx,
14604                );
14605            }
14606
14607            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14608            let use_autoclose = this.use_autoclose;
14609            let use_auto_surround = this.use_auto_surround;
14610            this.set_use_autoclose(false);
14611            this.set_use_auto_surround(false);
14612            this.handle_input(text, cx);
14613            this.set_use_autoclose(use_autoclose);
14614            this.set_use_auto_surround(use_auto_surround);
14615
14616            if let Some(new_selected_range) = new_selected_range_utf16 {
14617                let snapshot = this.buffer.read(cx).read(cx);
14618                let new_selected_ranges = marked_ranges
14619                    .into_iter()
14620                    .map(|marked_range| {
14621                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14622                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14623                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14624                        snapshot.clip_offset_utf16(new_start, Bias::Left)
14625                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14626                    })
14627                    .collect::<Vec<_>>();
14628
14629                drop(snapshot);
14630                this.change_selections(None, cx, |selections| {
14631                    selections.select_ranges(new_selected_ranges)
14632                });
14633            }
14634        });
14635
14636        self.ime_transaction = self.ime_transaction.or(transaction);
14637        if let Some(transaction) = self.ime_transaction {
14638            self.buffer.update(cx, |buffer, cx| {
14639                buffer.group_until_transaction(transaction, cx);
14640            });
14641        }
14642
14643        if self.text_highlights::<InputComposition>(cx).is_none() {
14644            self.ime_transaction.take();
14645        }
14646    }
14647
14648    fn bounds_for_range(
14649        &mut self,
14650        range_utf16: Range<usize>,
14651        element_bounds: gpui::Bounds<Pixels>,
14652        cx: &mut ViewContext<Self>,
14653    ) -> Option<gpui::Bounds<Pixels>> {
14654        let text_layout_details = self.text_layout_details(cx);
14655        let style = &text_layout_details.editor_style;
14656        let font_id = cx.text_system().resolve_font(&style.text.font());
14657        let font_size = style.text.font_size.to_pixels(cx.rem_size());
14658        let line_height = style.text.line_height_in_pixels(cx.rem_size());
14659
14660        let em_width = cx
14661            .text_system()
14662            .typographic_bounds(font_id, font_size, 'm')
14663            .unwrap()
14664            .size
14665            .width;
14666
14667        let snapshot = self.snapshot(cx);
14668        let scroll_position = snapshot.scroll_position();
14669        let scroll_left = scroll_position.x * em_width;
14670
14671        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14672        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14673            + self.gutter_dimensions.width;
14674        let y = line_height * (start.row().as_f32() - scroll_position.y);
14675
14676        Some(Bounds {
14677            origin: element_bounds.origin + point(x, y),
14678            size: size(em_width, line_height),
14679        })
14680    }
14681}
14682
14683trait SelectionExt {
14684    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14685    fn spanned_rows(
14686        &self,
14687        include_end_if_at_line_start: bool,
14688        map: &DisplaySnapshot,
14689    ) -> Range<MultiBufferRow>;
14690}
14691
14692impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14693    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14694        let start = self
14695            .start
14696            .to_point(&map.buffer_snapshot)
14697            .to_display_point(map);
14698        let end = self
14699            .end
14700            .to_point(&map.buffer_snapshot)
14701            .to_display_point(map);
14702        if self.reversed {
14703            end..start
14704        } else {
14705            start..end
14706        }
14707    }
14708
14709    fn spanned_rows(
14710        &self,
14711        include_end_if_at_line_start: bool,
14712        map: &DisplaySnapshot,
14713    ) -> Range<MultiBufferRow> {
14714        let start = self.start.to_point(&map.buffer_snapshot);
14715        let mut end = self.end.to_point(&map.buffer_snapshot);
14716        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14717            end.row -= 1;
14718        }
14719
14720        let buffer_start = map.prev_line_boundary(start).0;
14721        let buffer_end = map.next_line_boundary(end).0;
14722        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14723    }
14724}
14725
14726impl<T: InvalidationRegion> InvalidationStack<T> {
14727    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14728    where
14729        S: Clone + ToOffset,
14730    {
14731        while let Some(region) = self.last() {
14732            let all_selections_inside_invalidation_ranges =
14733                if selections.len() == region.ranges().len() {
14734                    selections
14735                        .iter()
14736                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14737                        .all(|(selection, invalidation_range)| {
14738                            let head = selection.head().to_offset(buffer);
14739                            invalidation_range.start <= head && invalidation_range.end >= head
14740                        })
14741                } else {
14742                    false
14743                };
14744
14745            if all_selections_inside_invalidation_ranges {
14746                break;
14747            } else {
14748                self.pop();
14749            }
14750        }
14751    }
14752}
14753
14754impl<T> Default for InvalidationStack<T> {
14755    fn default() -> Self {
14756        Self(Default::default())
14757    }
14758}
14759
14760impl<T> Deref for InvalidationStack<T> {
14761    type Target = Vec<T>;
14762
14763    fn deref(&self) -> &Self::Target {
14764        &self.0
14765    }
14766}
14767
14768impl<T> DerefMut for InvalidationStack<T> {
14769    fn deref_mut(&mut self) -> &mut Self::Target {
14770        &mut self.0
14771    }
14772}
14773
14774impl InvalidationRegion for SnippetState {
14775    fn ranges(&self) -> &[Range<Anchor>] {
14776        &self.ranges[self.active_index]
14777    }
14778}
14779
14780pub fn diagnostic_block_renderer(
14781    diagnostic: Diagnostic,
14782    max_message_rows: Option<u8>,
14783    allow_closing: bool,
14784    _is_valid: bool,
14785) -> RenderBlock {
14786    let (text_without_backticks, code_ranges) =
14787        highlight_diagnostic_message(&diagnostic, max_message_rows);
14788
14789    Arc::new(move |cx: &mut BlockContext| {
14790        let group_id: SharedString = cx.block_id.to_string().into();
14791
14792        let mut text_style = cx.text_style().clone();
14793        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14794        let theme_settings = ThemeSettings::get_global(cx);
14795        text_style.font_family = theme_settings.buffer_font.family.clone();
14796        text_style.font_style = theme_settings.buffer_font.style;
14797        text_style.font_features = theme_settings.buffer_font.features.clone();
14798        text_style.font_weight = theme_settings.buffer_font.weight;
14799
14800        let multi_line_diagnostic = diagnostic.message.contains('\n');
14801
14802        let buttons = |diagnostic: &Diagnostic| {
14803            if multi_line_diagnostic {
14804                v_flex()
14805            } else {
14806                h_flex()
14807            }
14808            .when(allow_closing, |div| {
14809                div.children(diagnostic.is_primary.then(|| {
14810                    IconButton::new("close-block", IconName::XCircle)
14811                        .icon_color(Color::Muted)
14812                        .size(ButtonSize::Compact)
14813                        .style(ButtonStyle::Transparent)
14814                        .visible_on_hover(group_id.clone())
14815                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14816                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14817                }))
14818            })
14819            .child(
14820                IconButton::new("copy-block", IconName::Copy)
14821                    .icon_color(Color::Muted)
14822                    .size(ButtonSize::Compact)
14823                    .style(ButtonStyle::Transparent)
14824                    .visible_on_hover(group_id.clone())
14825                    .on_click({
14826                        let message = diagnostic.message.clone();
14827                        move |_click, cx| {
14828                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14829                        }
14830                    })
14831                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14832            )
14833        };
14834
14835        let icon_size = buttons(&diagnostic)
14836            .into_any_element()
14837            .layout_as_root(AvailableSpace::min_size(), cx);
14838
14839        h_flex()
14840            .id(cx.block_id)
14841            .group(group_id.clone())
14842            .relative()
14843            .size_full()
14844            .block_mouse_down()
14845            .pl(cx.gutter_dimensions.width)
14846            .w(cx.max_width - cx.gutter_dimensions.full_width())
14847            .child(
14848                div()
14849                    .flex()
14850                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14851                    .flex_shrink(),
14852            )
14853            .child(buttons(&diagnostic))
14854            .child(div().flex().flex_shrink_0().child(
14855                StyledText::new(text_without_backticks.clone()).with_highlights(
14856                    &text_style,
14857                    code_ranges.iter().map(|range| {
14858                        (
14859                            range.clone(),
14860                            HighlightStyle {
14861                                font_weight: Some(FontWeight::BOLD),
14862                                ..Default::default()
14863                            },
14864                        )
14865                    }),
14866                ),
14867            ))
14868            .into_any_element()
14869    })
14870}
14871
14872pub fn highlight_diagnostic_message(
14873    diagnostic: &Diagnostic,
14874    mut max_message_rows: Option<u8>,
14875) -> (SharedString, Vec<Range<usize>>) {
14876    let mut text_without_backticks = String::new();
14877    let mut code_ranges = Vec::new();
14878
14879    if let Some(source) = &diagnostic.source {
14880        text_without_backticks.push_str(source);
14881        code_ranges.push(0..source.len());
14882        text_without_backticks.push_str(": ");
14883    }
14884
14885    let mut prev_offset = 0;
14886    let mut in_code_block = false;
14887    let has_row_limit = max_message_rows.is_some();
14888    let mut newline_indices = diagnostic
14889        .message
14890        .match_indices('\n')
14891        .filter(|_| has_row_limit)
14892        .map(|(ix, _)| ix)
14893        .fuse()
14894        .peekable();
14895
14896    for (quote_ix, _) in diagnostic
14897        .message
14898        .match_indices('`')
14899        .chain([(diagnostic.message.len(), "")])
14900    {
14901        let mut first_newline_ix = None;
14902        let mut last_newline_ix = None;
14903        while let Some(newline_ix) = newline_indices.peek() {
14904            if *newline_ix < quote_ix {
14905                if first_newline_ix.is_none() {
14906                    first_newline_ix = Some(*newline_ix);
14907                }
14908                last_newline_ix = Some(*newline_ix);
14909
14910                if let Some(rows_left) = &mut max_message_rows {
14911                    if *rows_left == 0 {
14912                        break;
14913                    } else {
14914                        *rows_left -= 1;
14915                    }
14916                }
14917                let _ = newline_indices.next();
14918            } else {
14919                break;
14920            }
14921        }
14922        let prev_len = text_without_backticks.len();
14923        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14924        text_without_backticks.push_str(new_text);
14925        if in_code_block {
14926            code_ranges.push(prev_len..text_without_backticks.len());
14927        }
14928        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14929        in_code_block = !in_code_block;
14930        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14931            text_without_backticks.push_str("...");
14932            break;
14933        }
14934    }
14935
14936    (text_without_backticks.into(), code_ranges)
14937}
14938
14939fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14940    match severity {
14941        DiagnosticSeverity::ERROR => colors.error,
14942        DiagnosticSeverity::WARNING => colors.warning,
14943        DiagnosticSeverity::INFORMATION => colors.info,
14944        DiagnosticSeverity::HINT => colors.info,
14945        _ => colors.ignored,
14946    }
14947}
14948
14949pub fn styled_runs_for_code_label<'a>(
14950    label: &'a CodeLabel,
14951    syntax_theme: &'a theme::SyntaxTheme,
14952) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14953    let fade_out = HighlightStyle {
14954        fade_out: Some(0.35),
14955        ..Default::default()
14956    };
14957
14958    let mut prev_end = label.filter_range.end;
14959    label
14960        .runs
14961        .iter()
14962        .enumerate()
14963        .flat_map(move |(ix, (range, highlight_id))| {
14964            let style = if let Some(style) = highlight_id.style(syntax_theme) {
14965                style
14966            } else {
14967                return Default::default();
14968            };
14969            let mut muted_style = style;
14970            muted_style.highlight(fade_out);
14971
14972            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14973            if range.start >= label.filter_range.end {
14974                if range.start > prev_end {
14975                    runs.push((prev_end..range.start, fade_out));
14976                }
14977                runs.push((range.clone(), muted_style));
14978            } else if range.end <= label.filter_range.end {
14979                runs.push((range.clone(), style));
14980            } else {
14981                runs.push((range.start..label.filter_range.end, style));
14982                runs.push((label.filter_range.end..range.end, muted_style));
14983            }
14984            prev_end = cmp::max(prev_end, range.end);
14985
14986            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14987                runs.push((prev_end..label.text.len(), fade_out));
14988            }
14989
14990            runs
14991        })
14992}
14993
14994pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14995    let mut prev_index = 0;
14996    let mut prev_codepoint: Option<char> = None;
14997    text.char_indices()
14998        .chain([(text.len(), '\0')])
14999        .filter_map(move |(index, codepoint)| {
15000            let prev_codepoint = prev_codepoint.replace(codepoint)?;
15001            let is_boundary = index == text.len()
15002                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
15003                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
15004            if is_boundary {
15005                let chunk = &text[prev_index..index];
15006                prev_index = index;
15007                Some(chunk)
15008            } else {
15009                None
15010            }
15011        })
15012}
15013
15014pub trait RangeToAnchorExt: Sized {
15015    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
15016
15017    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
15018        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
15019        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
15020    }
15021}
15022
15023impl<T: ToOffset> RangeToAnchorExt for Range<T> {
15024    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
15025        let start_offset = self.start.to_offset(snapshot);
15026        let end_offset = self.end.to_offset(snapshot);
15027        if start_offset == end_offset {
15028            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
15029        } else {
15030            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
15031        }
15032    }
15033}
15034
15035pub trait RowExt {
15036    fn as_f32(&self) -> f32;
15037
15038    fn next_row(&self) -> Self;
15039
15040    fn previous_row(&self) -> Self;
15041
15042    fn minus(&self, other: Self) -> u32;
15043}
15044
15045impl RowExt for DisplayRow {
15046    fn as_f32(&self) -> f32 {
15047        self.0 as f32
15048    }
15049
15050    fn next_row(&self) -> Self {
15051        Self(self.0 + 1)
15052    }
15053
15054    fn previous_row(&self) -> Self {
15055        Self(self.0.saturating_sub(1))
15056    }
15057
15058    fn minus(&self, other: Self) -> u32 {
15059        self.0 - other.0
15060    }
15061}
15062
15063impl RowExt for MultiBufferRow {
15064    fn as_f32(&self) -> f32 {
15065        self.0 as f32
15066    }
15067
15068    fn next_row(&self) -> Self {
15069        Self(self.0 + 1)
15070    }
15071
15072    fn previous_row(&self) -> Self {
15073        Self(self.0.saturating_sub(1))
15074    }
15075
15076    fn minus(&self, other: Self) -> u32 {
15077        self.0 - other.0
15078    }
15079}
15080
15081trait RowRangeExt {
15082    type Row;
15083
15084    fn len(&self) -> usize;
15085
15086    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
15087}
15088
15089impl RowRangeExt for Range<MultiBufferRow> {
15090    type Row = MultiBufferRow;
15091
15092    fn len(&self) -> usize {
15093        (self.end.0 - self.start.0) as usize
15094    }
15095
15096    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
15097        (self.start.0..self.end.0).map(MultiBufferRow)
15098    }
15099}
15100
15101impl RowRangeExt for Range<DisplayRow> {
15102    type Row = DisplayRow;
15103
15104    fn len(&self) -> usize {
15105        (self.end.0 - self.start.0) as usize
15106    }
15107
15108    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
15109        (self.start.0..self.end.0).map(DisplayRow)
15110    }
15111}
15112
15113fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
15114    if hunk.diff_base_byte_range.is_empty() {
15115        DiffHunkStatus::Added
15116    } else if hunk.row_range.is_empty() {
15117        DiffHunkStatus::Removed
15118    } else {
15119        DiffHunkStatus::Modified
15120    }
15121}
15122
15123/// If select range has more than one line, we
15124/// just point the cursor to range.start.
15125fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
15126    if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
15127        range
15128    } else {
15129        range.start..range.start
15130    }
15131}
15132
15133pub struct KillRing(ClipboardItem);
15134impl Global for KillRing {}
15135
15136const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);