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(
 4146                                selection.start.saturating_sub(pair_start_len),
 4147                                &pair.start,
 4148                            ) {
 4149                                selection.start -= pair_start_len;
 4150                                selection.end += pair.end.len();
 4151
 4152                                return selection;
 4153                            }
 4154                        }
 4155                    }
 4156                }
 4157
 4158                selection
 4159            })
 4160            .collect();
 4161
 4162        drop(buffer);
 4163        self.change_selections(None, cx, |selections| selections.select(new_selections));
 4164    }
 4165
 4166    /// Iterate the given selections, and for each one, find the smallest surrounding
 4167    /// autoclose region. This uses the ordering of the selections and the autoclose
 4168    /// regions to avoid repeated comparisons.
 4169    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 4170        &'a self,
 4171        selections: impl IntoIterator<Item = Selection<D>>,
 4172        buffer: &'a MultiBufferSnapshot,
 4173    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 4174        let mut i = 0;
 4175        let mut regions = self.autoclose_regions.as_slice();
 4176        selections.into_iter().map(move |selection| {
 4177            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 4178
 4179            let mut enclosing = None;
 4180            while let Some(pair_state) = regions.get(i) {
 4181                if pair_state.range.end.to_offset(buffer) < range.start {
 4182                    regions = &regions[i + 1..];
 4183                    i = 0;
 4184                } else if pair_state.range.start.to_offset(buffer) > range.end {
 4185                    break;
 4186                } else {
 4187                    if pair_state.selection_id == selection.id {
 4188                        enclosing = Some(pair_state);
 4189                    }
 4190                    i += 1;
 4191                }
 4192            }
 4193
 4194            (selection, enclosing)
 4195        })
 4196    }
 4197
 4198    /// Remove any autoclose regions that no longer contain their selection.
 4199    fn invalidate_autoclose_regions(
 4200        &mut self,
 4201        mut selections: &[Selection<Anchor>],
 4202        buffer: &MultiBufferSnapshot,
 4203    ) {
 4204        self.autoclose_regions.retain(|state| {
 4205            let mut i = 0;
 4206            while let Some(selection) = selections.get(i) {
 4207                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 4208                    selections = &selections[1..];
 4209                    continue;
 4210                }
 4211                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 4212                    break;
 4213                }
 4214                if selection.id == state.selection_id {
 4215                    return true;
 4216                } else {
 4217                    i += 1;
 4218                }
 4219            }
 4220            false
 4221        });
 4222    }
 4223
 4224    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 4225        let offset = position.to_offset(buffer);
 4226        let (word_range, kind) = buffer.surrounding_word(offset, true);
 4227        if offset > word_range.start && kind == Some(CharKind::Word) {
 4228            Some(
 4229                buffer
 4230                    .text_for_range(word_range.start..offset)
 4231                    .collect::<String>(),
 4232            )
 4233        } else {
 4234            None
 4235        }
 4236    }
 4237
 4238    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 4239        self.refresh_inlay_hints(
 4240            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 4241            cx,
 4242        );
 4243    }
 4244
 4245    pub fn inlay_hints_enabled(&self) -> bool {
 4246        self.inlay_hint_cache.enabled
 4247    }
 4248
 4249    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 4250        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 4251            return;
 4252        }
 4253
 4254        let reason_description = reason.description();
 4255        let ignore_debounce = matches!(
 4256            reason,
 4257            InlayHintRefreshReason::SettingsChange(_)
 4258                | InlayHintRefreshReason::Toggle(_)
 4259                | InlayHintRefreshReason::ExcerptsRemoved(_)
 4260        );
 4261        let (invalidate_cache, required_languages) = match reason {
 4262            InlayHintRefreshReason::Toggle(enabled) => {
 4263                self.inlay_hint_cache.enabled = enabled;
 4264                if enabled {
 4265                    (InvalidationStrategy::RefreshRequested, None)
 4266                } else {
 4267                    self.inlay_hint_cache.clear();
 4268                    self.splice_inlays(
 4269                        self.visible_inlay_hints(cx)
 4270                            .iter()
 4271                            .map(|inlay| inlay.id)
 4272                            .collect(),
 4273                        Vec::new(),
 4274                        cx,
 4275                    );
 4276                    return;
 4277                }
 4278            }
 4279            InlayHintRefreshReason::SettingsChange(new_settings) => {
 4280                match self.inlay_hint_cache.update_settings(
 4281                    &self.buffer,
 4282                    new_settings,
 4283                    self.visible_inlay_hints(cx),
 4284                    cx,
 4285                ) {
 4286                    ControlFlow::Break(Some(InlaySplice {
 4287                        to_remove,
 4288                        to_insert,
 4289                    })) => {
 4290                        self.splice_inlays(to_remove, to_insert, cx);
 4291                        return;
 4292                    }
 4293                    ControlFlow::Break(None) => return,
 4294                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 4295                }
 4296            }
 4297            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 4298                if let Some(InlaySplice {
 4299                    to_remove,
 4300                    to_insert,
 4301                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 4302                {
 4303                    self.splice_inlays(to_remove, to_insert, cx);
 4304                }
 4305                return;
 4306            }
 4307            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 4308            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 4309                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 4310            }
 4311            InlayHintRefreshReason::RefreshRequested => {
 4312                (InvalidationStrategy::RefreshRequested, None)
 4313            }
 4314        };
 4315
 4316        if let Some(InlaySplice {
 4317            to_remove,
 4318            to_insert,
 4319        }) = self.inlay_hint_cache.spawn_hint_refresh(
 4320            reason_description,
 4321            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 4322            invalidate_cache,
 4323            ignore_debounce,
 4324            cx,
 4325        ) {
 4326            self.splice_inlays(to_remove, to_insert, cx);
 4327        }
 4328    }
 4329
 4330    fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
 4331        self.display_map
 4332            .read(cx)
 4333            .current_inlays()
 4334            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 4335            .cloned()
 4336            .collect()
 4337    }
 4338
 4339    pub fn excerpts_for_inlay_hints_query(
 4340        &self,
 4341        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 4342        cx: &mut ViewContext<Editor>,
 4343    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 4344        let Some(project) = self.project.as_ref() else {
 4345            return HashMap::default();
 4346        };
 4347        let project = project.read(cx);
 4348        let multi_buffer = self.buffer().read(cx);
 4349        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 4350        let multi_buffer_visible_start = self
 4351            .scroll_manager
 4352            .anchor()
 4353            .anchor
 4354            .to_point(&multi_buffer_snapshot);
 4355        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 4356            multi_buffer_visible_start
 4357                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 4358            Bias::Left,
 4359        );
 4360        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 4361        multi_buffer
 4362            .range_to_buffer_ranges(multi_buffer_visible_range, cx)
 4363            .into_iter()
 4364            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 4365            .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
 4366                let buffer = buffer_handle.read(cx);
 4367                let buffer_file = project::File::from_dyn(buffer.file())?;
 4368                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 4369                let worktree_entry = buffer_worktree
 4370                    .read(cx)
 4371                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 4372                if worktree_entry.is_ignored {
 4373                    return None;
 4374                }
 4375
 4376                let language = buffer.language()?;
 4377                if let Some(restrict_to_languages) = restrict_to_languages {
 4378                    if !restrict_to_languages.contains(language) {
 4379                        return None;
 4380                    }
 4381                }
 4382                Some((
 4383                    excerpt_id,
 4384                    (
 4385                        buffer_handle,
 4386                        buffer.version().clone(),
 4387                        excerpt_visible_range,
 4388                    ),
 4389                ))
 4390            })
 4391            .collect()
 4392    }
 4393
 4394    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 4395        TextLayoutDetails {
 4396            text_system: cx.text_system().clone(),
 4397            editor_style: self.style.clone().unwrap(),
 4398            rem_size: cx.rem_size(),
 4399            scroll_anchor: self.scroll_manager.anchor(),
 4400            visible_rows: self.visible_line_count(),
 4401            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 4402        }
 4403    }
 4404
 4405    fn splice_inlays(
 4406        &self,
 4407        to_remove: Vec<InlayId>,
 4408        to_insert: Vec<Inlay>,
 4409        cx: &mut ViewContext<Self>,
 4410    ) {
 4411        self.display_map.update(cx, |display_map, cx| {
 4412            display_map.splice_inlays(to_remove, to_insert, cx);
 4413        });
 4414        cx.notify();
 4415    }
 4416
 4417    fn trigger_on_type_formatting(
 4418        &self,
 4419        input: String,
 4420        cx: &mut ViewContext<Self>,
 4421    ) -> Option<Task<Result<()>>> {
 4422        if input.len() != 1 {
 4423            return None;
 4424        }
 4425
 4426        let project = self.project.as_ref()?;
 4427        let position = self.selections.newest_anchor().head();
 4428        let (buffer, buffer_position) = self
 4429            .buffer
 4430            .read(cx)
 4431            .text_anchor_for_position(position, cx)?;
 4432
 4433        let settings = language_settings::language_settings(
 4434            buffer
 4435                .read(cx)
 4436                .language_at(buffer_position)
 4437                .map(|l| l.name()),
 4438            buffer.read(cx).file(),
 4439            cx,
 4440        );
 4441        if !settings.use_on_type_format {
 4442            return None;
 4443        }
 4444
 4445        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 4446        // hence we do LSP request & edit on host side only — add formats to host's history.
 4447        let push_to_lsp_host_history = true;
 4448        // If this is not the host, append its history with new edits.
 4449        let push_to_client_history = project.read(cx).is_via_collab();
 4450
 4451        let on_type_formatting = project.update(cx, |project, cx| {
 4452            project.on_type_format(
 4453                buffer.clone(),
 4454                buffer_position,
 4455                input,
 4456                push_to_lsp_host_history,
 4457                cx,
 4458            )
 4459        });
 4460        Some(cx.spawn(|editor, mut cx| async move {
 4461            if let Some(transaction) = on_type_formatting.await? {
 4462                if push_to_client_history {
 4463                    buffer
 4464                        .update(&mut cx, |buffer, _| {
 4465                            buffer.push_transaction(transaction, Instant::now());
 4466                        })
 4467                        .ok();
 4468                }
 4469                editor.update(&mut cx, |editor, cx| {
 4470                    editor.refresh_document_highlights(cx);
 4471                })?;
 4472            }
 4473            Ok(())
 4474        }))
 4475    }
 4476
 4477    pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
 4478        if self.pending_rename.is_some() {
 4479            return;
 4480        }
 4481
 4482        let Some(provider) = self.completion_provider.as_ref() else {
 4483            return;
 4484        };
 4485
 4486        if !self.snippet_stack.is_empty() && self.context_menu.read().as_ref().is_some() {
 4487            return;
 4488        }
 4489
 4490        let position = self.selections.newest_anchor().head();
 4491        let (buffer, buffer_position) =
 4492            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4493                output
 4494            } else {
 4495                return;
 4496            };
 4497
 4498        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4499        let is_followup_invoke = {
 4500            let context_menu_state = self.context_menu.read();
 4501            matches!(
 4502                context_menu_state.deref(),
 4503                Some(ContextMenu::Completions(_))
 4504            )
 4505        };
 4506        let trigger_kind = match (&options.trigger, is_followup_invoke) {
 4507            (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
 4508            (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4509                CompletionTriggerKind::TRIGGER_CHARACTER
 4510            }
 4511
 4512            _ => CompletionTriggerKind::INVOKED,
 4513        };
 4514        let completion_context = CompletionContext {
 4515            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 4516                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4517                    Some(String::from(trigger))
 4518                } else {
 4519                    None
 4520                }
 4521            }),
 4522            trigger_kind,
 4523        };
 4524        let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
 4525        let sort_completions = provider.sort_completions();
 4526
 4527        let id = post_inc(&mut self.next_completion_id);
 4528        let task = cx.spawn(|this, mut cx| {
 4529            async move {
 4530                this.update(&mut cx, |this, _| {
 4531                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4532                })?;
 4533                let completions = completions.await.log_err();
 4534                let menu = if let Some(completions) = completions {
 4535                    let mut menu = CompletionsMenu::new(
 4536                        id,
 4537                        sort_completions,
 4538                        position,
 4539                        buffer.clone(),
 4540                        completions.into(),
 4541                    );
 4542                    menu.filter(query.as_deref(), cx.background_executor().clone())
 4543                        .await;
 4544
 4545                    if menu.matches.is_empty() {
 4546                        None
 4547                    } else {
 4548                        this.update(&mut cx, |editor, cx| {
 4549                            let completions = menu.completions.clone();
 4550                            let matches = menu.matches.clone();
 4551
 4552                            let delay_ms = EditorSettings::get_global(cx)
 4553                                .completion_documentation_secondary_query_debounce;
 4554                            let delay = Duration::from_millis(delay_ms);
 4555                            editor
 4556                                .completion_documentation_pre_resolve_debounce
 4557                                .fire_new(delay, cx, |editor, cx| {
 4558                                    CompletionsMenu::pre_resolve_completion_documentation(
 4559                                        buffer,
 4560                                        completions,
 4561                                        matches,
 4562                                        editor,
 4563                                        cx,
 4564                                    )
 4565                                });
 4566                        })
 4567                        .ok();
 4568                        Some(menu)
 4569                    }
 4570                } else {
 4571                    None
 4572                };
 4573
 4574                this.update(&mut cx, |this, cx| {
 4575                    let mut context_menu = this.context_menu.write();
 4576                    match context_menu.as_ref() {
 4577                        None => {}
 4578
 4579                        Some(ContextMenu::Completions(prev_menu)) => {
 4580                            if prev_menu.id > id {
 4581                                return;
 4582                            }
 4583                        }
 4584
 4585                        _ => return,
 4586                    }
 4587
 4588                    if this.focus_handle.is_focused(cx) && menu.is_some() {
 4589                        let menu = menu.unwrap();
 4590                        *context_menu = Some(ContextMenu::Completions(menu));
 4591                        drop(context_menu);
 4592                        this.discard_inline_completion(false, cx);
 4593                        cx.notify();
 4594                    } else if this.completion_tasks.len() <= 1 {
 4595                        // If there are no more completion tasks and the last menu was
 4596                        // empty, we should hide it. If it was already hidden, we should
 4597                        // also show the copilot completion when available.
 4598                        drop(context_menu);
 4599                        if this.hide_context_menu(cx).is_none() {
 4600                            this.update_visible_inline_completion(cx);
 4601                        }
 4602                    }
 4603                })?;
 4604
 4605                Ok::<_, anyhow::Error>(())
 4606            }
 4607            .log_err()
 4608        });
 4609
 4610        self.completion_tasks.push((id, task));
 4611    }
 4612
 4613    pub fn confirm_completion(
 4614        &mut self,
 4615        action: &ConfirmCompletion,
 4616        cx: &mut ViewContext<Self>,
 4617    ) -> Option<Task<Result<()>>> {
 4618        self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
 4619    }
 4620
 4621    pub fn compose_completion(
 4622        &mut self,
 4623        action: &ComposeCompletion,
 4624        cx: &mut ViewContext<Self>,
 4625    ) -> Option<Task<Result<()>>> {
 4626        self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
 4627    }
 4628
 4629    fn do_completion(
 4630        &mut self,
 4631        item_ix: Option<usize>,
 4632        intent: CompletionIntent,
 4633        cx: &mut ViewContext<Editor>,
 4634    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 4635        use language::ToOffset as _;
 4636
 4637        let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 4638            menu
 4639        } else {
 4640            return None;
 4641        };
 4642
 4643        let mat = completions_menu
 4644            .matches
 4645            .get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4646        let buffer_handle = completions_menu.buffer;
 4647        let completions = completions_menu.completions.read();
 4648        let completion = completions.get(mat.candidate_id)?;
 4649        cx.stop_propagation();
 4650
 4651        let snippet;
 4652        let text;
 4653
 4654        if completion.is_snippet() {
 4655            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4656            text = snippet.as_ref().unwrap().text.clone();
 4657        } else {
 4658            snippet = None;
 4659            text = completion.new_text.clone();
 4660        };
 4661        let selections = self.selections.all::<usize>(cx);
 4662        let buffer = buffer_handle.read(cx);
 4663        let old_range = completion.old_range.to_offset(buffer);
 4664        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4665
 4666        let newest_selection = self.selections.newest_anchor();
 4667        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4668            return None;
 4669        }
 4670
 4671        let lookbehind = newest_selection
 4672            .start
 4673            .text_anchor
 4674            .to_offset(buffer)
 4675            .saturating_sub(old_range.start);
 4676        let lookahead = old_range
 4677            .end
 4678            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4679        let mut common_prefix_len = old_text
 4680            .bytes()
 4681            .zip(text.bytes())
 4682            .take_while(|(a, b)| a == b)
 4683            .count();
 4684
 4685        let snapshot = self.buffer.read(cx).snapshot(cx);
 4686        let mut range_to_replace: Option<Range<isize>> = None;
 4687        let mut ranges = Vec::new();
 4688        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4689        for selection in &selections {
 4690            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4691                let start = selection.start.saturating_sub(lookbehind);
 4692                let end = selection.end + lookahead;
 4693                if selection.id == newest_selection.id {
 4694                    range_to_replace = Some(
 4695                        ((start + common_prefix_len) as isize - selection.start as isize)
 4696                            ..(end as isize - selection.start as isize),
 4697                    );
 4698                }
 4699                ranges.push(start + common_prefix_len..end);
 4700            } else {
 4701                common_prefix_len = 0;
 4702                ranges.clear();
 4703                ranges.extend(selections.iter().map(|s| {
 4704                    if s.id == newest_selection.id {
 4705                        range_to_replace = Some(
 4706                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4707                                - selection.start as isize
 4708                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4709                                    - selection.start as isize,
 4710                        );
 4711                        old_range.clone()
 4712                    } else {
 4713                        s.start..s.end
 4714                    }
 4715                }));
 4716                break;
 4717            }
 4718            if !self.linked_edit_ranges.is_empty() {
 4719                let start_anchor = snapshot.anchor_before(selection.head());
 4720                let end_anchor = snapshot.anchor_after(selection.tail());
 4721                if let Some(ranges) = self
 4722                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4723                {
 4724                    for (buffer, edits) in ranges {
 4725                        linked_edits.entry(buffer.clone()).or_default().extend(
 4726                            edits
 4727                                .into_iter()
 4728                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4729                        );
 4730                    }
 4731                }
 4732            }
 4733        }
 4734        let text = &text[common_prefix_len..];
 4735
 4736        cx.emit(EditorEvent::InputHandled {
 4737            utf16_range_to_replace: range_to_replace,
 4738            text: text.into(),
 4739        });
 4740
 4741        self.transact(cx, |this, cx| {
 4742            if let Some(mut snippet) = snippet {
 4743                snippet.text = text.to_string();
 4744                for tabstop in snippet
 4745                    .tabstops
 4746                    .iter_mut()
 4747                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4748                {
 4749                    tabstop.start -= common_prefix_len as isize;
 4750                    tabstop.end -= common_prefix_len as isize;
 4751                }
 4752
 4753                this.insert_snippet(&ranges, snippet, cx).log_err();
 4754            } else {
 4755                this.buffer.update(cx, |buffer, cx| {
 4756                    buffer.edit(
 4757                        ranges.iter().map(|range| (range.clone(), text)),
 4758                        this.autoindent_mode.clone(),
 4759                        cx,
 4760                    );
 4761                });
 4762            }
 4763            for (buffer, edits) in linked_edits {
 4764                buffer.update(cx, |buffer, cx| {
 4765                    let snapshot = buffer.snapshot();
 4766                    let edits = edits
 4767                        .into_iter()
 4768                        .map(|(range, text)| {
 4769                            use text::ToPoint as TP;
 4770                            let end_point = TP::to_point(&range.end, &snapshot);
 4771                            let start_point = TP::to_point(&range.start, &snapshot);
 4772                            (start_point..end_point, text)
 4773                        })
 4774                        .sorted_by_key(|(range, _)| range.start)
 4775                        .collect::<Vec<_>>();
 4776                    buffer.edit(edits, None, cx);
 4777                })
 4778            }
 4779
 4780            this.refresh_inline_completion(true, false, cx);
 4781        });
 4782
 4783        let show_new_completions_on_confirm = completion
 4784            .confirm
 4785            .as_ref()
 4786            .map_or(false, |confirm| confirm(intent, cx));
 4787        if show_new_completions_on_confirm {
 4788            self.show_completions(&ShowCompletions { trigger: None }, cx);
 4789        }
 4790
 4791        let provider = self.completion_provider.as_ref()?;
 4792        let apply_edits = provider.apply_additional_edits_for_completion(
 4793            buffer_handle,
 4794            completion.clone(),
 4795            true,
 4796            cx,
 4797        );
 4798
 4799        let editor_settings = EditorSettings::get_global(cx);
 4800        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4801            // After the code completion is finished, users often want to know what signatures are needed.
 4802            // so we should automatically call signature_help
 4803            self.show_signature_help(&ShowSignatureHelp, cx);
 4804        }
 4805
 4806        Some(cx.foreground_executor().spawn(async move {
 4807            apply_edits.await?;
 4808            Ok(())
 4809        }))
 4810    }
 4811
 4812    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 4813        let mut context_menu = self.context_menu.write();
 4814        if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4815            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4816                // Toggle if we're selecting the same one
 4817                *context_menu = None;
 4818                cx.notify();
 4819                return;
 4820            } else {
 4821                // Otherwise, clear it and start a new one
 4822                *context_menu = None;
 4823                cx.notify();
 4824            }
 4825        }
 4826        drop(context_menu);
 4827        let snapshot = self.snapshot(cx);
 4828        let deployed_from_indicator = action.deployed_from_indicator;
 4829        let mut task = self.code_actions_task.take();
 4830        let action = action.clone();
 4831        cx.spawn(|editor, mut cx| async move {
 4832            while let Some(prev_task) = task {
 4833                prev_task.await.log_err();
 4834                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4835            }
 4836
 4837            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 4838                if editor.focus_handle.is_focused(cx) {
 4839                    let multibuffer_point = action
 4840                        .deployed_from_indicator
 4841                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4842                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4843                    let (buffer, buffer_row) = snapshot
 4844                        .buffer_snapshot
 4845                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4846                        .and_then(|(buffer_snapshot, range)| {
 4847                            editor
 4848                                .buffer
 4849                                .read(cx)
 4850                                .buffer(buffer_snapshot.remote_id())
 4851                                .map(|buffer| (buffer, range.start.row))
 4852                        })?;
 4853                    let (_, code_actions) = editor
 4854                        .available_code_actions
 4855                        .clone()
 4856                        .and_then(|(location, code_actions)| {
 4857                            let snapshot = location.buffer.read(cx).snapshot();
 4858                            let point_range = location.range.to_point(&snapshot);
 4859                            let point_range = point_range.start.row..=point_range.end.row;
 4860                            if point_range.contains(&buffer_row) {
 4861                                Some((location, code_actions))
 4862                            } else {
 4863                                None
 4864                            }
 4865                        })
 4866                        .unzip();
 4867                    let buffer_id = buffer.read(cx).remote_id();
 4868                    let tasks = editor
 4869                        .tasks
 4870                        .get(&(buffer_id, buffer_row))
 4871                        .map(|t| Arc::new(t.to_owned()));
 4872                    if tasks.is_none() && code_actions.is_none() {
 4873                        return None;
 4874                    }
 4875
 4876                    editor.completion_tasks.clear();
 4877                    editor.discard_inline_completion(false, cx);
 4878                    let task_context =
 4879                        tasks
 4880                            .as_ref()
 4881                            .zip(editor.project.clone())
 4882                            .map(|(tasks, project)| {
 4883                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4884                            });
 4885
 4886                    Some(cx.spawn(|editor, mut cx| async move {
 4887                        let task_context = match task_context {
 4888                            Some(task_context) => task_context.await,
 4889                            None => None,
 4890                        };
 4891                        let resolved_tasks =
 4892                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4893                                Arc::new(ResolvedTasks {
 4894                                    templates: tasks.resolve(&task_context).collect(),
 4895                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4896                                        multibuffer_point.row,
 4897                                        tasks.column,
 4898                                    )),
 4899                                })
 4900                            });
 4901                        let spawn_straight_away = resolved_tasks
 4902                            .as_ref()
 4903                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4904                            && code_actions
 4905                                .as_ref()
 4906                                .map_or(true, |actions| actions.is_empty());
 4907                        if let Ok(task) = editor.update(&mut cx, |editor, cx| {
 4908                            *editor.context_menu.write() =
 4909                                Some(ContextMenu::CodeActions(CodeActionsMenu {
 4910                                    buffer,
 4911                                    actions: CodeActionContents {
 4912                                        tasks: resolved_tasks,
 4913                                        actions: code_actions,
 4914                                    },
 4915                                    selected_item: Default::default(),
 4916                                    scroll_handle: UniformListScrollHandle::default(),
 4917                                    deployed_from_indicator,
 4918                                }));
 4919                            if spawn_straight_away {
 4920                                if let Some(task) = editor.confirm_code_action(
 4921                                    &ConfirmCodeAction { item_ix: Some(0) },
 4922                                    cx,
 4923                                ) {
 4924                                    cx.notify();
 4925                                    return task;
 4926                                }
 4927                            }
 4928                            cx.notify();
 4929                            Task::ready(Ok(()))
 4930                        }) {
 4931                            task.await
 4932                        } else {
 4933                            Ok(())
 4934                        }
 4935                    }))
 4936                } else {
 4937                    Some(Task::ready(Ok(())))
 4938                }
 4939            })?;
 4940            if let Some(task) = spawned_test_task {
 4941                task.await?;
 4942            }
 4943
 4944            Ok::<_, anyhow::Error>(())
 4945        })
 4946        .detach_and_log_err(cx);
 4947    }
 4948
 4949    pub fn confirm_code_action(
 4950        &mut self,
 4951        action: &ConfirmCodeAction,
 4952        cx: &mut ViewContext<Self>,
 4953    ) -> Option<Task<Result<()>>> {
 4954        let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4955            menu
 4956        } else {
 4957            return None;
 4958        };
 4959        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4960        let action = actions_menu.actions.get(action_ix)?;
 4961        let title = action.label();
 4962        let buffer = actions_menu.buffer;
 4963        let workspace = self.workspace()?;
 4964
 4965        match action {
 4966            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4967                workspace.update(cx, |workspace, cx| {
 4968                    workspace::tasks::schedule_resolved_task(
 4969                        workspace,
 4970                        task_source_kind,
 4971                        resolved_task,
 4972                        false,
 4973                        cx,
 4974                    );
 4975
 4976                    Some(Task::ready(Ok(())))
 4977                })
 4978            }
 4979            CodeActionsItem::CodeAction {
 4980                excerpt_id,
 4981                action,
 4982                provider,
 4983            } => {
 4984                let apply_code_action =
 4985                    provider.apply_code_action(buffer, action, excerpt_id, true, cx);
 4986                let workspace = workspace.downgrade();
 4987                Some(cx.spawn(|editor, cx| async move {
 4988                    let project_transaction = apply_code_action.await?;
 4989                    Self::open_project_transaction(
 4990                        &editor,
 4991                        workspace,
 4992                        project_transaction,
 4993                        title,
 4994                        cx,
 4995                    )
 4996                    .await
 4997                }))
 4998            }
 4999        }
 5000    }
 5001
 5002    pub async fn open_project_transaction(
 5003        this: &WeakView<Editor>,
 5004        workspace: WeakView<Workspace>,
 5005        transaction: ProjectTransaction,
 5006        title: String,
 5007        mut cx: AsyncWindowContext,
 5008    ) -> Result<()> {
 5009        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 5010        cx.update(|cx| {
 5011            entries.sort_unstable_by_key(|(buffer, _)| {
 5012                buffer.read(cx).file().map(|f| f.path().clone())
 5013            });
 5014        })?;
 5015
 5016        // If the project transaction's edits are all contained within this editor, then
 5017        // avoid opening a new editor to display them.
 5018
 5019        if let Some((buffer, transaction)) = entries.first() {
 5020            if entries.len() == 1 {
 5021                let excerpt = this.update(&mut cx, |editor, cx| {
 5022                    editor
 5023                        .buffer()
 5024                        .read(cx)
 5025                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 5026                })?;
 5027                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 5028                    if excerpted_buffer == *buffer {
 5029                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 5030                            let excerpt_range = excerpt_range.to_offset(buffer);
 5031                            buffer
 5032                                .edited_ranges_for_transaction::<usize>(transaction)
 5033                                .all(|range| {
 5034                                    excerpt_range.start <= range.start
 5035                                        && excerpt_range.end >= range.end
 5036                                })
 5037                        })?;
 5038
 5039                        if all_edits_within_excerpt {
 5040                            return Ok(());
 5041                        }
 5042                    }
 5043                }
 5044            }
 5045        } else {
 5046            return Ok(());
 5047        }
 5048
 5049        let mut ranges_to_highlight = Vec::new();
 5050        let excerpt_buffer = cx.new_model(|cx| {
 5051            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 5052            for (buffer_handle, transaction) in &entries {
 5053                let buffer = buffer_handle.read(cx);
 5054                ranges_to_highlight.extend(
 5055                    multibuffer.push_excerpts_with_context_lines(
 5056                        buffer_handle.clone(),
 5057                        buffer
 5058                            .edited_ranges_for_transaction::<usize>(transaction)
 5059                            .collect(),
 5060                        DEFAULT_MULTIBUFFER_CONTEXT,
 5061                        cx,
 5062                    ),
 5063                );
 5064            }
 5065            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 5066            multibuffer
 5067        })?;
 5068
 5069        workspace.update(&mut cx, |workspace, cx| {
 5070            let project = workspace.project().clone();
 5071            let editor =
 5072                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 5073            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 5074            editor.update(cx, |editor, cx| {
 5075                editor.highlight_background::<Self>(
 5076                    &ranges_to_highlight,
 5077                    |theme| theme.editor_highlighted_line_background,
 5078                    cx,
 5079                );
 5080            });
 5081        })?;
 5082
 5083        Ok(())
 5084    }
 5085
 5086    pub fn clear_code_action_providers(&mut self) {
 5087        self.code_action_providers.clear();
 5088        self.available_code_actions.take();
 5089    }
 5090
 5091    pub fn push_code_action_provider(
 5092        &mut self,
 5093        provider: Arc<dyn CodeActionProvider>,
 5094        cx: &mut ViewContext<Self>,
 5095    ) {
 5096        self.code_action_providers.push(provider);
 5097        self.refresh_code_actions(cx);
 5098    }
 5099
 5100    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 5101        let buffer = self.buffer.read(cx);
 5102        let newest_selection = self.selections.newest_anchor().clone();
 5103        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 5104        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 5105        if start_buffer != end_buffer {
 5106            return None;
 5107        }
 5108
 5109        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 5110            cx.background_executor()
 5111                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 5112                .await;
 5113
 5114            let (providers, tasks) = this.update(&mut cx, |this, cx| {
 5115                let providers = this.code_action_providers.clone();
 5116                let tasks = this
 5117                    .code_action_providers
 5118                    .iter()
 5119                    .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
 5120                    .collect::<Vec<_>>();
 5121                (providers, tasks)
 5122            })?;
 5123
 5124            let mut actions = Vec::new();
 5125            for (provider, provider_actions) in
 5126                providers.into_iter().zip(future::join_all(tasks).await)
 5127            {
 5128                if let Some(provider_actions) = provider_actions.log_err() {
 5129                    actions.extend(provider_actions.into_iter().map(|action| {
 5130                        AvailableCodeAction {
 5131                            excerpt_id: newest_selection.start.excerpt_id,
 5132                            action,
 5133                            provider: provider.clone(),
 5134                        }
 5135                    }));
 5136                }
 5137            }
 5138
 5139            this.update(&mut cx, |this, cx| {
 5140                this.available_code_actions = if actions.is_empty() {
 5141                    None
 5142                } else {
 5143                    Some((
 5144                        Location {
 5145                            buffer: start_buffer,
 5146                            range: start..end,
 5147                        },
 5148                        actions.into(),
 5149                    ))
 5150                };
 5151                cx.notify();
 5152            })
 5153        }));
 5154        None
 5155    }
 5156
 5157    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 5158        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 5159            self.show_git_blame_inline = false;
 5160
 5161            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 5162                cx.background_executor().timer(delay).await;
 5163
 5164                this.update(&mut cx, |this, cx| {
 5165                    this.show_git_blame_inline = true;
 5166                    cx.notify();
 5167                })
 5168                .log_err();
 5169            }));
 5170        }
 5171    }
 5172
 5173    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 5174        if self.pending_rename.is_some() {
 5175            return None;
 5176        }
 5177
 5178        let provider = self.semantics_provider.clone()?;
 5179        let buffer = self.buffer.read(cx);
 5180        let newest_selection = self.selections.newest_anchor().clone();
 5181        let cursor_position = newest_selection.head();
 5182        let (cursor_buffer, cursor_buffer_position) =
 5183            buffer.text_anchor_for_position(cursor_position, cx)?;
 5184        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 5185        if cursor_buffer != tail_buffer {
 5186            return None;
 5187        }
 5188
 5189        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 5190            cx.background_executor()
 5191                .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
 5192                .await;
 5193
 5194            let highlights = if let Some(highlights) = cx
 5195                .update(|cx| {
 5196                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 5197                })
 5198                .ok()
 5199                .flatten()
 5200            {
 5201                highlights.await.log_err()
 5202            } else {
 5203                None
 5204            };
 5205
 5206            if let Some(highlights) = highlights {
 5207                this.update(&mut cx, |this, cx| {
 5208                    if this.pending_rename.is_some() {
 5209                        return;
 5210                    }
 5211
 5212                    let buffer_id = cursor_position.buffer_id;
 5213                    let buffer = this.buffer.read(cx);
 5214                    if !buffer
 5215                        .text_anchor_for_position(cursor_position, cx)
 5216                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 5217                    {
 5218                        return;
 5219                    }
 5220
 5221                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 5222                    let mut write_ranges = Vec::new();
 5223                    let mut read_ranges = Vec::new();
 5224                    for highlight in highlights {
 5225                        for (excerpt_id, excerpt_range) in
 5226                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 5227                        {
 5228                            let start = highlight
 5229                                .range
 5230                                .start
 5231                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 5232                            let end = highlight
 5233                                .range
 5234                                .end
 5235                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 5236                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 5237                                continue;
 5238                            }
 5239
 5240                            let range = Anchor {
 5241                                buffer_id,
 5242                                excerpt_id,
 5243                                text_anchor: start,
 5244                            }..Anchor {
 5245                                buffer_id,
 5246                                excerpt_id,
 5247                                text_anchor: end,
 5248                            };
 5249                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 5250                                write_ranges.push(range);
 5251                            } else {
 5252                                read_ranges.push(range);
 5253                            }
 5254                        }
 5255                    }
 5256
 5257                    this.highlight_background::<DocumentHighlightRead>(
 5258                        &read_ranges,
 5259                        |theme| theme.editor_document_highlight_read_background,
 5260                        cx,
 5261                    );
 5262                    this.highlight_background::<DocumentHighlightWrite>(
 5263                        &write_ranges,
 5264                        |theme| theme.editor_document_highlight_write_background,
 5265                        cx,
 5266                    );
 5267                    cx.notify();
 5268                })
 5269                .log_err();
 5270            }
 5271        }));
 5272        None
 5273    }
 5274
 5275    pub fn refresh_inline_completion(
 5276        &mut self,
 5277        debounce: bool,
 5278        user_requested: bool,
 5279        cx: &mut ViewContext<Self>,
 5280    ) -> Option<()> {
 5281        let provider = self.inline_completion_provider()?;
 5282        let cursor = self.selections.newest_anchor().head();
 5283        let (buffer, cursor_buffer_position) =
 5284            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5285
 5286        if !user_requested
 5287            && (!self.enable_inline_completions
 5288                || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx))
 5289        {
 5290            self.discard_inline_completion(false, cx);
 5291            return None;
 5292        }
 5293
 5294        self.update_visible_inline_completion(cx);
 5295        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 5296        Some(())
 5297    }
 5298
 5299    fn cycle_inline_completion(
 5300        &mut self,
 5301        direction: Direction,
 5302        cx: &mut ViewContext<Self>,
 5303    ) -> Option<()> {
 5304        let provider = self.inline_completion_provider()?;
 5305        let cursor = self.selections.newest_anchor().head();
 5306        let (buffer, cursor_buffer_position) =
 5307            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5308        if !self.enable_inline_completions
 5309            || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 5310        {
 5311            return None;
 5312        }
 5313
 5314        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5315        self.update_visible_inline_completion(cx);
 5316
 5317        Some(())
 5318    }
 5319
 5320    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 5321        if !self.has_active_inline_completion(cx) {
 5322            self.refresh_inline_completion(false, true, cx);
 5323            return;
 5324        }
 5325
 5326        self.update_visible_inline_completion(cx);
 5327    }
 5328
 5329    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 5330        self.show_cursor_names(cx);
 5331    }
 5332
 5333    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 5334        self.show_cursor_names = true;
 5335        cx.notify();
 5336        cx.spawn(|this, mut cx| async move {
 5337            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5338            this.update(&mut cx, |this, cx| {
 5339                this.show_cursor_names = false;
 5340                cx.notify()
 5341            })
 5342            .ok()
 5343        })
 5344        .detach();
 5345    }
 5346
 5347    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 5348        if self.has_active_inline_completion(cx) {
 5349            self.cycle_inline_completion(Direction::Next, cx);
 5350        } else {
 5351            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5352            if is_copilot_disabled {
 5353                cx.propagate();
 5354            }
 5355        }
 5356    }
 5357
 5358    pub fn previous_inline_completion(
 5359        &mut self,
 5360        _: &PreviousInlineCompletion,
 5361        cx: &mut ViewContext<Self>,
 5362    ) {
 5363        if self.has_active_inline_completion(cx) {
 5364            self.cycle_inline_completion(Direction::Prev, cx);
 5365        } else {
 5366            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5367            if is_copilot_disabled {
 5368                cx.propagate();
 5369            }
 5370        }
 5371    }
 5372
 5373    pub fn accept_inline_completion(
 5374        &mut self,
 5375        _: &AcceptInlineCompletion,
 5376        cx: &mut ViewContext<Self>,
 5377    ) {
 5378        let Some(completion) = self.take_active_inline_completion(cx) else {
 5379            return;
 5380        };
 5381        if let Some(provider) = self.inline_completion_provider() {
 5382            provider.accept(cx);
 5383        }
 5384
 5385        cx.emit(EditorEvent::InputHandled {
 5386            utf16_range_to_replace: None,
 5387            text: completion.text.to_string().into(),
 5388        });
 5389
 5390        if let Some(range) = completion.delete_range {
 5391            self.change_selections(None, cx, |s| s.select_ranges([range]))
 5392        }
 5393        self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
 5394        self.refresh_inline_completion(true, true, cx);
 5395        cx.notify();
 5396    }
 5397
 5398    pub fn accept_partial_inline_completion(
 5399        &mut self,
 5400        _: &AcceptPartialInlineCompletion,
 5401        cx: &mut ViewContext<Self>,
 5402    ) {
 5403        if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
 5404            if let Some(completion) = self.take_active_inline_completion(cx) {
 5405                let mut partial_completion = completion
 5406                    .text
 5407                    .chars()
 5408                    .by_ref()
 5409                    .take_while(|c| c.is_alphabetic())
 5410                    .collect::<String>();
 5411                if partial_completion.is_empty() {
 5412                    partial_completion = completion
 5413                        .text
 5414                        .chars()
 5415                        .by_ref()
 5416                        .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5417                        .collect::<String>();
 5418                }
 5419
 5420                cx.emit(EditorEvent::InputHandled {
 5421                    utf16_range_to_replace: None,
 5422                    text: partial_completion.clone().into(),
 5423                });
 5424
 5425                if let Some(range) = completion.delete_range {
 5426                    self.change_selections(None, cx, |s| s.select_ranges([range]))
 5427                }
 5428                self.insert_with_autoindent_mode(&partial_completion, None, cx);
 5429
 5430                self.refresh_inline_completion(true, true, cx);
 5431                cx.notify();
 5432            }
 5433        }
 5434    }
 5435
 5436    fn discard_inline_completion(
 5437        &mut self,
 5438        should_report_inline_completion_event: bool,
 5439        cx: &mut ViewContext<Self>,
 5440    ) -> bool {
 5441        if let Some(provider) = self.inline_completion_provider() {
 5442            provider.discard(should_report_inline_completion_event, cx);
 5443        }
 5444
 5445        self.take_active_inline_completion(cx).is_some()
 5446    }
 5447
 5448    pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
 5449        if let Some(completion) = self.active_inline_completion.as_ref() {
 5450            let buffer = self.buffer.read(cx).read(cx);
 5451            completion.position.is_valid(&buffer)
 5452        } else {
 5453            false
 5454        }
 5455    }
 5456
 5457    fn take_active_inline_completion(
 5458        &mut self,
 5459        cx: &mut ViewContext<Self>,
 5460    ) -> Option<CompletionState> {
 5461        let completion = self.active_inline_completion.take()?;
 5462        let render_inlay_ids = completion.render_inlay_ids.clone();
 5463        self.display_map.update(cx, |map, cx| {
 5464            map.splice_inlays(render_inlay_ids, Default::default(), cx);
 5465        });
 5466        let buffer = self.buffer.read(cx).read(cx);
 5467
 5468        if completion.position.is_valid(&buffer) {
 5469            Some(completion)
 5470        } else {
 5471            None
 5472        }
 5473    }
 5474
 5475    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
 5476        let selection = self.selections.newest_anchor();
 5477        let cursor = selection.head();
 5478
 5479        let excerpt_id = cursor.excerpt_id;
 5480
 5481        if self.context_menu.read().is_none()
 5482            && self.completion_tasks.is_empty()
 5483            && selection.start == selection.end
 5484        {
 5485            if let Some(provider) = self.inline_completion_provider() {
 5486                if let Some((buffer, cursor_buffer_position)) =
 5487                    self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5488                {
 5489                    if let Some(proposal) =
 5490                        provider.active_completion_text(&buffer, cursor_buffer_position, cx)
 5491                    {
 5492                        let mut to_remove = Vec::new();
 5493                        if let Some(completion) = self.active_inline_completion.take() {
 5494                            to_remove.extend(completion.render_inlay_ids.iter());
 5495                        }
 5496
 5497                        let to_add = proposal
 5498                            .inlays
 5499                            .iter()
 5500                            .filter_map(|inlay| {
 5501                                let snapshot = self.buffer.read(cx).snapshot(cx);
 5502                                let id = post_inc(&mut self.next_inlay_id);
 5503                                match inlay {
 5504                                    InlayProposal::Hint(position, hint) => {
 5505                                        let position =
 5506                                            snapshot.anchor_in_excerpt(excerpt_id, *position)?;
 5507                                        Some(Inlay::hint(id, position, hint))
 5508                                    }
 5509                                    InlayProposal::Suggestion(position, text) => {
 5510                                        let position =
 5511                                            snapshot.anchor_in_excerpt(excerpt_id, *position)?;
 5512                                        Some(Inlay::suggestion(id, position, text.clone()))
 5513                                    }
 5514                                }
 5515                            })
 5516                            .collect_vec();
 5517
 5518                        self.active_inline_completion = Some(CompletionState {
 5519                            position: cursor,
 5520                            text: proposal.text,
 5521                            delete_range: proposal.delete_range.and_then(|range| {
 5522                                let snapshot = self.buffer.read(cx).snapshot(cx);
 5523                                let start = snapshot.anchor_in_excerpt(excerpt_id, range.start);
 5524                                let end = snapshot.anchor_in_excerpt(excerpt_id, range.end);
 5525                                Some(start?..end?)
 5526                            }),
 5527                            render_inlay_ids: to_add.iter().map(|i| i.id).collect(),
 5528                        });
 5529
 5530                        self.display_map
 5531                            .update(cx, move |map, cx| map.splice_inlays(to_remove, to_add, cx));
 5532
 5533                        cx.notify();
 5534                        return;
 5535                    }
 5536                }
 5537            }
 5538        }
 5539
 5540        self.discard_inline_completion(false, cx);
 5541    }
 5542
 5543    fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5544        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 5545    }
 5546
 5547    fn render_code_actions_indicator(
 5548        &self,
 5549        _style: &EditorStyle,
 5550        row: DisplayRow,
 5551        is_active: bool,
 5552        cx: &mut ViewContext<Self>,
 5553    ) -> Option<IconButton> {
 5554        if self.available_code_actions.is_some() {
 5555            Some(
 5556                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5557                    .shape(ui::IconButtonShape::Square)
 5558                    .icon_size(IconSize::XSmall)
 5559                    .icon_color(Color::Muted)
 5560                    .selected(is_active)
 5561                    .tooltip({
 5562                        let focus_handle = self.focus_handle.clone();
 5563                        move |cx| {
 5564                            Tooltip::for_action_in(
 5565                                "Toggle Code Actions",
 5566                                &ToggleCodeActions {
 5567                                    deployed_from_indicator: None,
 5568                                },
 5569                                &focus_handle,
 5570                                cx,
 5571                            )
 5572                        }
 5573                    })
 5574                    .on_click(cx.listener(move |editor, _e, cx| {
 5575                        editor.focus(cx);
 5576                        editor.toggle_code_actions(
 5577                            &ToggleCodeActions {
 5578                                deployed_from_indicator: Some(row),
 5579                            },
 5580                            cx,
 5581                        );
 5582                    })),
 5583            )
 5584        } else {
 5585            None
 5586        }
 5587    }
 5588
 5589    fn clear_tasks(&mut self) {
 5590        self.tasks.clear()
 5591    }
 5592
 5593    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5594        if self.tasks.insert(key, value).is_some() {
 5595            // This case should hopefully be rare, but just in case...
 5596            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5597        }
 5598    }
 5599
 5600    fn build_tasks_context(
 5601        project: &Model<Project>,
 5602        buffer: &Model<Buffer>,
 5603        buffer_row: u32,
 5604        tasks: &Arc<RunnableTasks>,
 5605        cx: &mut ViewContext<Self>,
 5606    ) -> Task<Option<task::TaskContext>> {
 5607        let position = Point::new(buffer_row, tasks.column);
 5608        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5609        let location = Location {
 5610            buffer: buffer.clone(),
 5611            range: range_start..range_start,
 5612        };
 5613        // Fill in the environmental variables from the tree-sitter captures
 5614        let mut captured_task_variables = TaskVariables::default();
 5615        for (capture_name, value) in tasks.extra_variables.clone() {
 5616            captured_task_variables.insert(
 5617                task::VariableName::Custom(capture_name.into()),
 5618                value.clone(),
 5619            );
 5620        }
 5621        project.update(cx, |project, cx| {
 5622            project.task_store().update(cx, |task_store, cx| {
 5623                task_store.task_context_for_location(captured_task_variables, location, cx)
 5624            })
 5625        })
 5626    }
 5627
 5628    pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
 5629        let Some((workspace, _)) = self.workspace.clone() else {
 5630            return;
 5631        };
 5632        let Some(project) = self.project.clone() else {
 5633            return;
 5634        };
 5635
 5636        // Try to find a closest, enclosing node using tree-sitter that has a
 5637        // task
 5638        let Some((buffer, buffer_row, tasks)) = self
 5639            .find_enclosing_node_task(cx)
 5640            // Or find the task that's closest in row-distance.
 5641            .or_else(|| self.find_closest_task(cx))
 5642        else {
 5643            return;
 5644        };
 5645
 5646        let reveal_strategy = action.reveal;
 5647        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5648        cx.spawn(|_, mut cx| async move {
 5649            let context = task_context.await?;
 5650            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5651
 5652            let resolved = resolved_task.resolved.as_mut()?;
 5653            resolved.reveal = reveal_strategy;
 5654
 5655            workspace
 5656                .update(&mut cx, |workspace, cx| {
 5657                    workspace::tasks::schedule_resolved_task(
 5658                        workspace,
 5659                        task_source_kind,
 5660                        resolved_task,
 5661                        false,
 5662                        cx,
 5663                    );
 5664                })
 5665                .ok()
 5666        })
 5667        .detach();
 5668    }
 5669
 5670    fn find_closest_task(
 5671        &mut self,
 5672        cx: &mut ViewContext<Self>,
 5673    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5674        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5675
 5676        let ((buffer_id, row), tasks) = self
 5677            .tasks
 5678            .iter()
 5679            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5680
 5681        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5682        let tasks = Arc::new(tasks.to_owned());
 5683        Some((buffer, *row, tasks))
 5684    }
 5685
 5686    fn find_enclosing_node_task(
 5687        &mut self,
 5688        cx: &mut ViewContext<Self>,
 5689    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5690        let snapshot = self.buffer.read(cx).snapshot(cx);
 5691        let offset = self.selections.newest::<usize>(cx).head();
 5692        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5693        let buffer_id = excerpt.buffer().remote_id();
 5694
 5695        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5696        let mut cursor = layer.node().walk();
 5697
 5698        while cursor.goto_first_child_for_byte(offset).is_some() {
 5699            if cursor.node().end_byte() == offset {
 5700                cursor.goto_next_sibling();
 5701            }
 5702        }
 5703
 5704        // Ascend to the smallest ancestor that contains the range and has a task.
 5705        loop {
 5706            let node = cursor.node();
 5707            let node_range = node.byte_range();
 5708            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5709
 5710            // Check if this node contains our offset
 5711            if node_range.start <= offset && node_range.end >= offset {
 5712                // If it contains offset, check for task
 5713                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5714                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5715                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5716                }
 5717            }
 5718
 5719            if !cursor.goto_parent() {
 5720                break;
 5721            }
 5722        }
 5723        None
 5724    }
 5725
 5726    fn render_run_indicator(
 5727        &self,
 5728        _style: &EditorStyle,
 5729        is_active: bool,
 5730        row: DisplayRow,
 5731        cx: &mut ViewContext<Self>,
 5732    ) -> IconButton {
 5733        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5734            .shape(ui::IconButtonShape::Square)
 5735            .icon_size(IconSize::XSmall)
 5736            .icon_color(Color::Muted)
 5737            .selected(is_active)
 5738            .on_click(cx.listener(move |editor, _e, cx| {
 5739                editor.focus(cx);
 5740                editor.toggle_code_actions(
 5741                    &ToggleCodeActions {
 5742                        deployed_from_indicator: Some(row),
 5743                    },
 5744                    cx,
 5745                );
 5746            }))
 5747    }
 5748
 5749    pub fn context_menu_visible(&self) -> bool {
 5750        self.context_menu
 5751            .read()
 5752            .as_ref()
 5753            .map_or(false, |menu| menu.visible())
 5754    }
 5755
 5756    fn render_context_menu(
 5757        &self,
 5758        cursor_position: DisplayPoint,
 5759        style: &EditorStyle,
 5760        max_height: Pixels,
 5761        cx: &mut ViewContext<Editor>,
 5762    ) -> Option<(ContextMenuOrigin, AnyElement)> {
 5763        self.context_menu.read().as_ref().map(|menu| {
 5764            menu.render(
 5765                cursor_position,
 5766                style,
 5767                max_height,
 5768                self.workspace.as_ref().map(|(w, _)| w.clone()),
 5769                cx,
 5770            )
 5771        })
 5772    }
 5773
 5774    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
 5775        cx.notify();
 5776        self.completion_tasks.clear();
 5777        let context_menu = self.context_menu.write().take();
 5778        if context_menu.is_some() {
 5779            self.update_visible_inline_completion(cx);
 5780        }
 5781        context_menu
 5782    }
 5783
 5784    fn show_snippet_choices(
 5785        &mut self,
 5786        choices: &Vec<String>,
 5787        selection: Range<Anchor>,
 5788        cx: &mut ViewContext<Self>,
 5789    ) {
 5790        if selection.start.buffer_id.is_none() {
 5791            return;
 5792        }
 5793        let buffer_id = selection.start.buffer_id.unwrap();
 5794        let buffer = self.buffer().read(cx).buffer(buffer_id);
 5795        let id = post_inc(&mut self.next_completion_id);
 5796
 5797        if let Some(buffer) = buffer {
 5798            *self.context_menu.write() = Some(ContextMenu::Completions(
 5799                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer)
 5800                    .suppress_documentation_resolution(),
 5801            ));
 5802        }
 5803    }
 5804
 5805    pub fn insert_snippet(
 5806        &mut self,
 5807        insertion_ranges: &[Range<usize>],
 5808        snippet: Snippet,
 5809        cx: &mut ViewContext<Self>,
 5810    ) -> Result<()> {
 5811        struct Tabstop<T> {
 5812            is_end_tabstop: bool,
 5813            ranges: Vec<Range<T>>,
 5814            choices: Option<Vec<String>>,
 5815        }
 5816
 5817        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5818            let snippet_text: Arc<str> = snippet.text.clone().into();
 5819            buffer.edit(
 5820                insertion_ranges
 5821                    .iter()
 5822                    .cloned()
 5823                    .map(|range| (range, snippet_text.clone())),
 5824                Some(AutoindentMode::EachLine),
 5825                cx,
 5826            );
 5827
 5828            let snapshot = &*buffer.read(cx);
 5829            let snippet = &snippet;
 5830            snippet
 5831                .tabstops
 5832                .iter()
 5833                .map(|tabstop| {
 5834                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 5835                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5836                    });
 5837                    let mut tabstop_ranges = tabstop
 5838                        .ranges
 5839                        .iter()
 5840                        .flat_map(|tabstop_range| {
 5841                            let mut delta = 0_isize;
 5842                            insertion_ranges.iter().map(move |insertion_range| {
 5843                                let insertion_start = insertion_range.start as isize + delta;
 5844                                delta +=
 5845                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5846
 5847                                let start = ((insertion_start + tabstop_range.start) as usize)
 5848                                    .min(snapshot.len());
 5849                                let end = ((insertion_start + tabstop_range.end) as usize)
 5850                                    .min(snapshot.len());
 5851                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5852                            })
 5853                        })
 5854                        .collect::<Vec<_>>();
 5855                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5856
 5857                    Tabstop {
 5858                        is_end_tabstop,
 5859                        ranges: tabstop_ranges,
 5860                        choices: tabstop.choices.clone(),
 5861                    }
 5862                })
 5863                .collect::<Vec<_>>()
 5864        });
 5865        if let Some(tabstop) = tabstops.first() {
 5866            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5867                s.select_ranges(tabstop.ranges.iter().cloned());
 5868            });
 5869
 5870            if let Some(choices) = &tabstop.choices {
 5871                if let Some(selection) = tabstop.ranges.first() {
 5872                    self.show_snippet_choices(choices, selection.clone(), cx)
 5873                }
 5874            }
 5875
 5876            // If we're already at the last tabstop and it's at the end of the snippet,
 5877            // we're done, we don't need to keep the state around.
 5878            if !tabstop.is_end_tabstop {
 5879                let choices = tabstops
 5880                    .iter()
 5881                    .map(|tabstop| tabstop.choices.clone())
 5882                    .collect();
 5883
 5884                let ranges = tabstops
 5885                    .into_iter()
 5886                    .map(|tabstop| tabstop.ranges)
 5887                    .collect::<Vec<_>>();
 5888
 5889                self.snippet_stack.push(SnippetState {
 5890                    active_index: 0,
 5891                    ranges,
 5892                    choices,
 5893                });
 5894            }
 5895
 5896            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5897            if self.autoclose_regions.is_empty() {
 5898                let snapshot = self.buffer.read(cx).snapshot(cx);
 5899                for selection in &mut self.selections.all::<Point>(cx) {
 5900                    let selection_head = selection.head();
 5901                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5902                        continue;
 5903                    };
 5904
 5905                    let mut bracket_pair = None;
 5906                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5907                    let prev_chars = snapshot
 5908                        .reversed_chars_at(selection_head)
 5909                        .collect::<String>();
 5910                    for (pair, enabled) in scope.brackets() {
 5911                        if enabled
 5912                            && pair.close
 5913                            && prev_chars.starts_with(pair.start.as_str())
 5914                            && next_chars.starts_with(pair.end.as_str())
 5915                        {
 5916                            bracket_pair = Some(pair.clone());
 5917                            break;
 5918                        }
 5919                    }
 5920                    if let Some(pair) = bracket_pair {
 5921                        let start = snapshot.anchor_after(selection_head);
 5922                        let end = snapshot.anchor_after(selection_head);
 5923                        self.autoclose_regions.push(AutocloseRegion {
 5924                            selection_id: selection.id,
 5925                            range: start..end,
 5926                            pair,
 5927                        });
 5928                    }
 5929                }
 5930            }
 5931        }
 5932        Ok(())
 5933    }
 5934
 5935    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5936        self.move_to_snippet_tabstop(Bias::Right, cx)
 5937    }
 5938
 5939    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5940        self.move_to_snippet_tabstop(Bias::Left, cx)
 5941    }
 5942
 5943    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5944        if let Some(mut snippet) = self.snippet_stack.pop() {
 5945            match bias {
 5946                Bias::Left => {
 5947                    if snippet.active_index > 0 {
 5948                        snippet.active_index -= 1;
 5949                    } else {
 5950                        self.snippet_stack.push(snippet);
 5951                        return false;
 5952                    }
 5953                }
 5954                Bias::Right => {
 5955                    if snippet.active_index + 1 < snippet.ranges.len() {
 5956                        snippet.active_index += 1;
 5957                    } else {
 5958                        self.snippet_stack.push(snippet);
 5959                        return false;
 5960                    }
 5961                }
 5962            }
 5963            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5964                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5965                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5966                });
 5967
 5968                if let Some(choices) = &snippet.choices[snippet.active_index] {
 5969                    if let Some(selection) = current_ranges.first() {
 5970                        self.show_snippet_choices(&choices, selection.clone(), cx);
 5971                    }
 5972                }
 5973
 5974                // If snippet state is not at the last tabstop, push it back on the stack
 5975                if snippet.active_index + 1 < snippet.ranges.len() {
 5976                    self.snippet_stack.push(snippet);
 5977                }
 5978                return true;
 5979            }
 5980        }
 5981
 5982        false
 5983    }
 5984
 5985    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 5986        self.transact(cx, |this, cx| {
 5987            this.select_all(&SelectAll, cx);
 5988            this.insert("", cx);
 5989        });
 5990    }
 5991
 5992    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 5993        self.transact(cx, |this, cx| {
 5994            this.select_autoclose_pair(cx);
 5995            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5996            if !this.linked_edit_ranges.is_empty() {
 5997                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5998                let snapshot = this.buffer.read(cx).snapshot(cx);
 5999
 6000                for selection in selections.iter() {
 6001                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 6002                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 6003                    if selection_start.buffer_id != selection_end.buffer_id {
 6004                        continue;
 6005                    }
 6006                    if let Some(ranges) =
 6007                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 6008                    {
 6009                        for (buffer, entries) in ranges {
 6010                            linked_ranges.entry(buffer).or_default().extend(entries);
 6011                        }
 6012                    }
 6013                }
 6014            }
 6015
 6016            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 6017            if !this.selections.line_mode {
 6018                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 6019                for selection in &mut selections {
 6020                    if selection.is_empty() {
 6021                        let old_head = selection.head();
 6022                        let mut new_head =
 6023                            movement::left(&display_map, old_head.to_display_point(&display_map))
 6024                                .to_point(&display_map);
 6025                        if let Some((buffer, line_buffer_range)) = display_map
 6026                            .buffer_snapshot
 6027                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 6028                        {
 6029                            let indent_size =
 6030                                buffer.indent_size_for_line(line_buffer_range.start.row);
 6031                            let indent_len = match indent_size.kind {
 6032                                IndentKind::Space => {
 6033                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 6034                                }
 6035                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 6036                            };
 6037                            if old_head.column <= indent_size.len && old_head.column > 0 {
 6038                                let indent_len = indent_len.get();
 6039                                new_head = cmp::min(
 6040                                    new_head,
 6041                                    MultiBufferPoint::new(
 6042                                        old_head.row,
 6043                                        ((old_head.column - 1) / indent_len) * indent_len,
 6044                                    ),
 6045                                );
 6046                            }
 6047                        }
 6048
 6049                        selection.set_head(new_head, SelectionGoal::None);
 6050                    }
 6051                }
 6052            }
 6053
 6054            this.signature_help_state.set_backspace_pressed(true);
 6055            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6056            this.insert("", cx);
 6057            let empty_str: Arc<str> = Arc::from("");
 6058            for (buffer, edits) in linked_ranges {
 6059                let snapshot = buffer.read(cx).snapshot();
 6060                use text::ToPoint as TP;
 6061
 6062                let edits = edits
 6063                    .into_iter()
 6064                    .map(|range| {
 6065                        let end_point = TP::to_point(&range.end, &snapshot);
 6066                        let mut start_point = TP::to_point(&range.start, &snapshot);
 6067
 6068                        if end_point == start_point {
 6069                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 6070                                .saturating_sub(1);
 6071                            start_point = TP::to_point(&offset, &snapshot);
 6072                        };
 6073
 6074                        (start_point..end_point, empty_str.clone())
 6075                    })
 6076                    .sorted_by_key(|(range, _)| range.start)
 6077                    .collect::<Vec<_>>();
 6078                buffer.update(cx, |this, cx| {
 6079                    this.edit(edits, None, cx);
 6080                })
 6081            }
 6082            this.refresh_inline_completion(true, false, cx);
 6083            linked_editing_ranges::refresh_linked_ranges(this, cx);
 6084        });
 6085    }
 6086
 6087    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 6088        self.transact(cx, |this, cx| {
 6089            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6090                let line_mode = s.line_mode;
 6091                s.move_with(|map, selection| {
 6092                    if selection.is_empty() && !line_mode {
 6093                        let cursor = movement::right(map, selection.head());
 6094                        selection.end = cursor;
 6095                        selection.reversed = true;
 6096                        selection.goal = SelectionGoal::None;
 6097                    }
 6098                })
 6099            });
 6100            this.insert("", cx);
 6101            this.refresh_inline_completion(true, false, cx);
 6102        });
 6103    }
 6104
 6105    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 6106        if self.move_to_prev_snippet_tabstop(cx) {
 6107            return;
 6108        }
 6109
 6110        self.outdent(&Outdent, cx);
 6111    }
 6112
 6113    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 6114        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 6115            return;
 6116        }
 6117
 6118        let mut selections = self.selections.all_adjusted(cx);
 6119        let buffer = self.buffer.read(cx);
 6120        let snapshot = buffer.snapshot(cx);
 6121        let rows_iter = selections.iter().map(|s| s.head().row);
 6122        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 6123
 6124        let mut edits = Vec::new();
 6125        let mut prev_edited_row = 0;
 6126        let mut row_delta = 0;
 6127        for selection in &mut selections {
 6128            if selection.start.row != prev_edited_row {
 6129                row_delta = 0;
 6130            }
 6131            prev_edited_row = selection.end.row;
 6132
 6133            // If the selection is non-empty, then increase the indentation of the selected lines.
 6134            if !selection.is_empty() {
 6135                row_delta =
 6136                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6137                continue;
 6138            }
 6139
 6140            // If the selection is empty and the cursor is in the leading whitespace before the
 6141            // suggested indentation, then auto-indent the line.
 6142            let cursor = selection.head();
 6143            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 6144            if let Some(suggested_indent) =
 6145                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 6146            {
 6147                if cursor.column < suggested_indent.len
 6148                    && cursor.column <= current_indent.len
 6149                    && current_indent.len <= suggested_indent.len
 6150                {
 6151                    selection.start = Point::new(cursor.row, suggested_indent.len);
 6152                    selection.end = selection.start;
 6153                    if row_delta == 0 {
 6154                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 6155                            cursor.row,
 6156                            current_indent,
 6157                            suggested_indent,
 6158                        ));
 6159                        row_delta = suggested_indent.len - current_indent.len;
 6160                    }
 6161                    continue;
 6162                }
 6163            }
 6164
 6165            // Otherwise, insert a hard or soft tab.
 6166            let settings = buffer.settings_at(cursor, cx);
 6167            let tab_size = if settings.hard_tabs {
 6168                IndentSize::tab()
 6169            } else {
 6170                let tab_size = settings.tab_size.get();
 6171                let char_column = snapshot
 6172                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 6173                    .flat_map(str::chars)
 6174                    .count()
 6175                    + row_delta as usize;
 6176                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 6177                IndentSize::spaces(chars_to_next_tab_stop)
 6178            };
 6179            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 6180            selection.end = selection.start;
 6181            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 6182            row_delta += tab_size.len;
 6183        }
 6184
 6185        self.transact(cx, |this, cx| {
 6186            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6187            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6188            this.refresh_inline_completion(true, false, cx);
 6189        });
 6190    }
 6191
 6192    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 6193        if self.read_only(cx) {
 6194            return;
 6195        }
 6196        let mut selections = self.selections.all::<Point>(cx);
 6197        let mut prev_edited_row = 0;
 6198        let mut row_delta = 0;
 6199        let mut edits = Vec::new();
 6200        let buffer = self.buffer.read(cx);
 6201        let snapshot = buffer.snapshot(cx);
 6202        for selection in &mut selections {
 6203            if selection.start.row != prev_edited_row {
 6204                row_delta = 0;
 6205            }
 6206            prev_edited_row = selection.end.row;
 6207
 6208            row_delta =
 6209                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6210        }
 6211
 6212        self.transact(cx, |this, cx| {
 6213            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6214            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6215        });
 6216    }
 6217
 6218    fn indent_selection(
 6219        buffer: &MultiBuffer,
 6220        snapshot: &MultiBufferSnapshot,
 6221        selection: &mut Selection<Point>,
 6222        edits: &mut Vec<(Range<Point>, String)>,
 6223        delta_for_start_row: u32,
 6224        cx: &AppContext,
 6225    ) -> u32 {
 6226        let settings = buffer.settings_at(selection.start, cx);
 6227        let tab_size = settings.tab_size.get();
 6228        let indent_kind = if settings.hard_tabs {
 6229            IndentKind::Tab
 6230        } else {
 6231            IndentKind::Space
 6232        };
 6233        let mut start_row = selection.start.row;
 6234        let mut end_row = selection.end.row + 1;
 6235
 6236        // If a selection ends at the beginning of a line, don't indent
 6237        // that last line.
 6238        if selection.end.column == 0 && selection.end.row > selection.start.row {
 6239            end_row -= 1;
 6240        }
 6241
 6242        // Avoid re-indenting a row that has already been indented by a
 6243        // previous selection, but still update this selection's column
 6244        // to reflect that indentation.
 6245        if delta_for_start_row > 0 {
 6246            start_row += 1;
 6247            selection.start.column += delta_for_start_row;
 6248            if selection.end.row == selection.start.row {
 6249                selection.end.column += delta_for_start_row;
 6250            }
 6251        }
 6252
 6253        let mut delta_for_end_row = 0;
 6254        let has_multiple_rows = start_row + 1 != end_row;
 6255        for row in start_row..end_row {
 6256            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 6257            let indent_delta = match (current_indent.kind, indent_kind) {
 6258                (IndentKind::Space, IndentKind::Space) => {
 6259                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 6260                    IndentSize::spaces(columns_to_next_tab_stop)
 6261                }
 6262                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 6263                (_, IndentKind::Tab) => IndentSize::tab(),
 6264            };
 6265
 6266            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 6267                0
 6268            } else {
 6269                selection.start.column
 6270            };
 6271            let row_start = Point::new(row, start);
 6272            edits.push((
 6273                row_start..row_start,
 6274                indent_delta.chars().collect::<String>(),
 6275            ));
 6276
 6277            // Update this selection's endpoints to reflect the indentation.
 6278            if row == selection.start.row {
 6279                selection.start.column += indent_delta.len;
 6280            }
 6281            if row == selection.end.row {
 6282                selection.end.column += indent_delta.len;
 6283                delta_for_end_row = indent_delta.len;
 6284            }
 6285        }
 6286
 6287        if selection.start.row == selection.end.row {
 6288            delta_for_start_row + delta_for_end_row
 6289        } else {
 6290            delta_for_end_row
 6291        }
 6292    }
 6293
 6294    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 6295        if self.read_only(cx) {
 6296            return;
 6297        }
 6298        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6299        let selections = self.selections.all::<Point>(cx);
 6300        let mut deletion_ranges = Vec::new();
 6301        let mut last_outdent = None;
 6302        {
 6303            let buffer = self.buffer.read(cx);
 6304            let snapshot = buffer.snapshot(cx);
 6305            for selection in &selections {
 6306                let settings = buffer.settings_at(selection.start, cx);
 6307                let tab_size = settings.tab_size.get();
 6308                let mut rows = selection.spanned_rows(false, &display_map);
 6309
 6310                // Avoid re-outdenting a row that has already been outdented by a
 6311                // previous selection.
 6312                if let Some(last_row) = last_outdent {
 6313                    if last_row == rows.start {
 6314                        rows.start = rows.start.next_row();
 6315                    }
 6316                }
 6317                let has_multiple_rows = rows.len() > 1;
 6318                for row in rows.iter_rows() {
 6319                    let indent_size = snapshot.indent_size_for_line(row);
 6320                    if indent_size.len > 0 {
 6321                        let deletion_len = match indent_size.kind {
 6322                            IndentKind::Space => {
 6323                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 6324                                if columns_to_prev_tab_stop == 0 {
 6325                                    tab_size
 6326                                } else {
 6327                                    columns_to_prev_tab_stop
 6328                                }
 6329                            }
 6330                            IndentKind::Tab => 1,
 6331                        };
 6332                        let start = if has_multiple_rows
 6333                            || deletion_len > selection.start.column
 6334                            || indent_size.len < selection.start.column
 6335                        {
 6336                            0
 6337                        } else {
 6338                            selection.start.column - deletion_len
 6339                        };
 6340                        deletion_ranges.push(
 6341                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 6342                        );
 6343                        last_outdent = Some(row);
 6344                    }
 6345                }
 6346            }
 6347        }
 6348
 6349        self.transact(cx, |this, cx| {
 6350            this.buffer.update(cx, |buffer, cx| {
 6351                let empty_str: Arc<str> = Arc::default();
 6352                buffer.edit(
 6353                    deletion_ranges
 6354                        .into_iter()
 6355                        .map(|range| (range, empty_str.clone())),
 6356                    None,
 6357                    cx,
 6358                );
 6359            });
 6360            let selections = this.selections.all::<usize>(cx);
 6361            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6362        });
 6363    }
 6364
 6365    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 6366        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6367        let selections = self.selections.all::<Point>(cx);
 6368
 6369        let mut new_cursors = Vec::new();
 6370        let mut edit_ranges = Vec::new();
 6371        let mut selections = selections.iter().peekable();
 6372        while let Some(selection) = selections.next() {
 6373            let mut rows = selection.spanned_rows(false, &display_map);
 6374            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6375
 6376            // Accumulate contiguous regions of rows that we want to delete.
 6377            while let Some(next_selection) = selections.peek() {
 6378                let next_rows = next_selection.spanned_rows(false, &display_map);
 6379                if next_rows.start <= rows.end {
 6380                    rows.end = next_rows.end;
 6381                    selections.next().unwrap();
 6382                } else {
 6383                    break;
 6384                }
 6385            }
 6386
 6387            let buffer = &display_map.buffer_snapshot;
 6388            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6389            let edit_end;
 6390            let cursor_buffer_row;
 6391            if buffer.max_point().row >= rows.end.0 {
 6392                // If there's a line after the range, delete the \n from the end of the row range
 6393                // and position the cursor on the next line.
 6394                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6395                cursor_buffer_row = rows.end;
 6396            } else {
 6397                // If there isn't a line after the range, delete the \n from the line before the
 6398                // start of the row range and position the cursor there.
 6399                edit_start = edit_start.saturating_sub(1);
 6400                edit_end = buffer.len();
 6401                cursor_buffer_row = rows.start.previous_row();
 6402            }
 6403
 6404            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6405            *cursor.column_mut() =
 6406                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6407
 6408            new_cursors.push((
 6409                selection.id,
 6410                buffer.anchor_after(cursor.to_point(&display_map)),
 6411            ));
 6412            edit_ranges.push(edit_start..edit_end);
 6413        }
 6414
 6415        self.transact(cx, |this, cx| {
 6416            let buffer = this.buffer.update(cx, |buffer, cx| {
 6417                let empty_str: Arc<str> = Arc::default();
 6418                buffer.edit(
 6419                    edit_ranges
 6420                        .into_iter()
 6421                        .map(|range| (range, empty_str.clone())),
 6422                    None,
 6423                    cx,
 6424                );
 6425                buffer.snapshot(cx)
 6426            });
 6427            let new_selections = new_cursors
 6428                .into_iter()
 6429                .map(|(id, cursor)| {
 6430                    let cursor = cursor.to_point(&buffer);
 6431                    Selection {
 6432                        id,
 6433                        start: cursor,
 6434                        end: cursor,
 6435                        reversed: false,
 6436                        goal: SelectionGoal::None,
 6437                    }
 6438                })
 6439                .collect();
 6440
 6441            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6442                s.select(new_selections);
 6443            });
 6444        });
 6445    }
 6446
 6447    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 6448        if self.read_only(cx) {
 6449            return;
 6450        }
 6451        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6452        for selection in self.selections.all::<Point>(cx) {
 6453            let start = MultiBufferRow(selection.start.row);
 6454            // Treat single line selections as if they include the next line. Otherwise this action
 6455            // would do nothing for single line selections individual cursors.
 6456            let end = if selection.start.row == selection.end.row {
 6457                MultiBufferRow(selection.start.row + 1)
 6458            } else {
 6459                MultiBufferRow(selection.end.row)
 6460            };
 6461
 6462            if let Some(last_row_range) = row_ranges.last_mut() {
 6463                if start <= last_row_range.end {
 6464                    last_row_range.end = end;
 6465                    continue;
 6466                }
 6467            }
 6468            row_ranges.push(start..end);
 6469        }
 6470
 6471        let snapshot = self.buffer.read(cx).snapshot(cx);
 6472        let mut cursor_positions = Vec::new();
 6473        for row_range in &row_ranges {
 6474            let anchor = snapshot.anchor_before(Point::new(
 6475                row_range.end.previous_row().0,
 6476                snapshot.line_len(row_range.end.previous_row()),
 6477            ));
 6478            cursor_positions.push(anchor..anchor);
 6479        }
 6480
 6481        self.transact(cx, |this, cx| {
 6482            for row_range in row_ranges.into_iter().rev() {
 6483                for row in row_range.iter_rows().rev() {
 6484                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6485                    let next_line_row = row.next_row();
 6486                    let indent = snapshot.indent_size_for_line(next_line_row);
 6487                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 6488
 6489                    let replace = if snapshot.line_len(next_line_row) > indent.len {
 6490                        " "
 6491                    } else {
 6492                        ""
 6493                    };
 6494
 6495                    this.buffer.update(cx, |buffer, cx| {
 6496                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6497                    });
 6498                }
 6499            }
 6500
 6501            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6502                s.select_anchor_ranges(cursor_positions)
 6503            });
 6504        });
 6505    }
 6506
 6507    pub fn sort_lines_case_sensitive(
 6508        &mut self,
 6509        _: &SortLinesCaseSensitive,
 6510        cx: &mut ViewContext<Self>,
 6511    ) {
 6512        self.manipulate_lines(cx, |lines| lines.sort())
 6513    }
 6514
 6515    pub fn sort_lines_case_insensitive(
 6516        &mut self,
 6517        _: &SortLinesCaseInsensitive,
 6518        cx: &mut ViewContext<Self>,
 6519    ) {
 6520        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 6521    }
 6522
 6523    pub fn unique_lines_case_insensitive(
 6524        &mut self,
 6525        _: &UniqueLinesCaseInsensitive,
 6526        cx: &mut ViewContext<Self>,
 6527    ) {
 6528        self.manipulate_lines(cx, |lines| {
 6529            let mut seen = HashSet::default();
 6530            lines.retain(|line| seen.insert(line.to_lowercase()));
 6531        })
 6532    }
 6533
 6534    pub fn unique_lines_case_sensitive(
 6535        &mut self,
 6536        _: &UniqueLinesCaseSensitive,
 6537        cx: &mut ViewContext<Self>,
 6538    ) {
 6539        self.manipulate_lines(cx, |lines| {
 6540            let mut seen = HashSet::default();
 6541            lines.retain(|line| seen.insert(*line));
 6542        })
 6543    }
 6544
 6545    pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
 6546        let mut revert_changes = HashMap::default();
 6547        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 6548        for hunk in hunks_for_rows(
 6549            Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
 6550            &multi_buffer_snapshot,
 6551        ) {
 6552            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 6553        }
 6554        if !revert_changes.is_empty() {
 6555            self.transact(cx, |editor, cx| {
 6556                editor.revert(revert_changes, cx);
 6557            });
 6558        }
 6559    }
 6560
 6561    pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
 6562        let Some(project) = self.project.clone() else {
 6563            return;
 6564        };
 6565        self.reload(project, cx).detach_and_notify_err(cx);
 6566    }
 6567
 6568    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 6569        let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
 6570        if !revert_changes.is_empty() {
 6571            self.transact(cx, |editor, cx| {
 6572                editor.revert(revert_changes, cx);
 6573            });
 6574        }
 6575    }
 6576
 6577    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 6578        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6579            let project_path = buffer.read(cx).project_path(cx)?;
 6580            let project = self.project.as_ref()?.read(cx);
 6581            let entry = project.entry_for_path(&project_path, cx)?;
 6582            let parent = match &entry.canonical_path {
 6583                Some(canonical_path) => canonical_path.to_path_buf(),
 6584                None => project.absolute_path(&project_path, cx)?,
 6585            }
 6586            .parent()?
 6587            .to_path_buf();
 6588            Some(parent)
 6589        }) {
 6590            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 6591        }
 6592    }
 6593
 6594    fn gather_revert_changes(
 6595        &mut self,
 6596        selections: &[Selection<Anchor>],
 6597        cx: &mut ViewContext<'_, Editor>,
 6598    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 6599        let mut revert_changes = HashMap::default();
 6600        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 6601        for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
 6602            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 6603        }
 6604        revert_changes
 6605    }
 6606
 6607    pub fn prepare_revert_change(
 6608        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6609        multi_buffer: &Model<MultiBuffer>,
 6610        hunk: &MultiBufferDiffHunk,
 6611        cx: &AppContext,
 6612    ) -> Option<()> {
 6613        let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
 6614        let buffer = buffer.read(cx);
 6615        let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
 6616        let buffer_snapshot = buffer.snapshot();
 6617        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6618        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6619            probe
 6620                .0
 6621                .start
 6622                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6623                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6624        }) {
 6625            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6626            Some(())
 6627        } else {
 6628            None
 6629        }
 6630    }
 6631
 6632    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 6633        self.manipulate_lines(cx, |lines| lines.reverse())
 6634    }
 6635
 6636    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 6637        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 6638    }
 6639
 6640    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6641    where
 6642        Fn: FnMut(&mut Vec<&str>),
 6643    {
 6644        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6645        let buffer = self.buffer.read(cx).snapshot(cx);
 6646
 6647        let mut edits = Vec::new();
 6648
 6649        let selections = self.selections.all::<Point>(cx);
 6650        let mut selections = selections.iter().peekable();
 6651        let mut contiguous_row_selections = Vec::new();
 6652        let mut new_selections = Vec::new();
 6653        let mut added_lines = 0;
 6654        let mut removed_lines = 0;
 6655
 6656        while let Some(selection) = selections.next() {
 6657            let (start_row, end_row) = consume_contiguous_rows(
 6658                &mut contiguous_row_selections,
 6659                selection,
 6660                &display_map,
 6661                &mut selections,
 6662            );
 6663
 6664            let start_point = Point::new(start_row.0, 0);
 6665            let end_point = Point::new(
 6666                end_row.previous_row().0,
 6667                buffer.line_len(end_row.previous_row()),
 6668            );
 6669            let text = buffer
 6670                .text_for_range(start_point..end_point)
 6671                .collect::<String>();
 6672
 6673            let mut lines = text.split('\n').collect_vec();
 6674
 6675            let lines_before = lines.len();
 6676            callback(&mut lines);
 6677            let lines_after = lines.len();
 6678
 6679            edits.push((start_point..end_point, lines.join("\n")));
 6680
 6681            // Selections must change based on added and removed line count
 6682            let start_row =
 6683                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6684            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6685            new_selections.push(Selection {
 6686                id: selection.id,
 6687                start: start_row,
 6688                end: end_row,
 6689                goal: SelectionGoal::None,
 6690                reversed: selection.reversed,
 6691            });
 6692
 6693            if lines_after > lines_before {
 6694                added_lines += lines_after - lines_before;
 6695            } else if lines_before > lines_after {
 6696                removed_lines += lines_before - lines_after;
 6697            }
 6698        }
 6699
 6700        self.transact(cx, |this, cx| {
 6701            let buffer = this.buffer.update(cx, |buffer, cx| {
 6702                buffer.edit(edits, None, cx);
 6703                buffer.snapshot(cx)
 6704            });
 6705
 6706            // Recalculate offsets on newly edited buffer
 6707            let new_selections = new_selections
 6708                .iter()
 6709                .map(|s| {
 6710                    let start_point = Point::new(s.start.0, 0);
 6711                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6712                    Selection {
 6713                        id: s.id,
 6714                        start: buffer.point_to_offset(start_point),
 6715                        end: buffer.point_to_offset(end_point),
 6716                        goal: s.goal,
 6717                        reversed: s.reversed,
 6718                    }
 6719                })
 6720                .collect();
 6721
 6722            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6723                s.select(new_selections);
 6724            });
 6725
 6726            this.request_autoscroll(Autoscroll::fit(), cx);
 6727        });
 6728    }
 6729
 6730    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 6731        self.manipulate_text(cx, |text| text.to_uppercase())
 6732    }
 6733
 6734    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 6735        self.manipulate_text(cx, |text| text.to_lowercase())
 6736    }
 6737
 6738    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 6739        self.manipulate_text(cx, |text| {
 6740            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6741            // https://github.com/rutrum/convert-case/issues/16
 6742            text.split('\n')
 6743                .map(|line| line.to_case(Case::Title))
 6744                .join("\n")
 6745        })
 6746    }
 6747
 6748    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6749        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6750    }
 6751
 6752    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6753        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6754    }
 6755
 6756    pub fn convert_to_upper_camel_case(
 6757        &mut self,
 6758        _: &ConvertToUpperCamelCase,
 6759        cx: &mut ViewContext<Self>,
 6760    ) {
 6761        self.manipulate_text(cx, |text| {
 6762            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6763            // https://github.com/rutrum/convert-case/issues/16
 6764            text.split('\n')
 6765                .map(|line| line.to_case(Case::UpperCamel))
 6766                .join("\n")
 6767        })
 6768    }
 6769
 6770    pub fn convert_to_lower_camel_case(
 6771        &mut self,
 6772        _: &ConvertToLowerCamelCase,
 6773        cx: &mut ViewContext<Self>,
 6774    ) {
 6775        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6776    }
 6777
 6778    pub fn convert_to_opposite_case(
 6779        &mut self,
 6780        _: &ConvertToOppositeCase,
 6781        cx: &mut ViewContext<Self>,
 6782    ) {
 6783        self.manipulate_text(cx, |text| {
 6784            text.chars()
 6785                .fold(String::with_capacity(text.len()), |mut t, c| {
 6786                    if c.is_uppercase() {
 6787                        t.extend(c.to_lowercase());
 6788                    } else {
 6789                        t.extend(c.to_uppercase());
 6790                    }
 6791                    t
 6792                })
 6793        })
 6794    }
 6795
 6796    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6797    where
 6798        Fn: FnMut(&str) -> String,
 6799    {
 6800        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6801        let buffer = self.buffer.read(cx).snapshot(cx);
 6802
 6803        let mut new_selections = Vec::new();
 6804        let mut edits = Vec::new();
 6805        let mut selection_adjustment = 0i32;
 6806
 6807        for selection in self.selections.all::<usize>(cx) {
 6808            let selection_is_empty = selection.is_empty();
 6809
 6810            let (start, end) = if selection_is_empty {
 6811                let word_range = movement::surrounding_word(
 6812                    &display_map,
 6813                    selection.start.to_display_point(&display_map),
 6814                );
 6815                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6816                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6817                (start, end)
 6818            } else {
 6819                (selection.start, selection.end)
 6820            };
 6821
 6822            let text = buffer.text_for_range(start..end).collect::<String>();
 6823            let old_length = text.len() as i32;
 6824            let text = callback(&text);
 6825
 6826            new_selections.push(Selection {
 6827                start: (start as i32 - selection_adjustment) as usize,
 6828                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6829                goal: SelectionGoal::None,
 6830                ..selection
 6831            });
 6832
 6833            selection_adjustment += old_length - text.len() as i32;
 6834
 6835            edits.push((start..end, text));
 6836        }
 6837
 6838        self.transact(cx, |this, cx| {
 6839            this.buffer.update(cx, |buffer, cx| {
 6840                buffer.edit(edits, None, cx);
 6841            });
 6842
 6843            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6844                s.select(new_selections);
 6845            });
 6846
 6847            this.request_autoscroll(Autoscroll::fit(), cx);
 6848        });
 6849    }
 6850
 6851    pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
 6852        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6853        let buffer = &display_map.buffer_snapshot;
 6854        let selections = self.selections.all::<Point>(cx);
 6855
 6856        let mut edits = Vec::new();
 6857        let mut selections_iter = selections.iter().peekable();
 6858        while let Some(selection) = selections_iter.next() {
 6859            // Avoid duplicating the same lines twice.
 6860            let mut rows = selection.spanned_rows(false, &display_map);
 6861
 6862            while let Some(next_selection) = selections_iter.peek() {
 6863                let next_rows = next_selection.spanned_rows(false, &display_map);
 6864                if next_rows.start < rows.end {
 6865                    rows.end = next_rows.end;
 6866                    selections_iter.next().unwrap();
 6867                } else {
 6868                    break;
 6869                }
 6870            }
 6871
 6872            // Copy the text from the selected row region and splice it either at the start
 6873            // or end of the region.
 6874            let start = Point::new(rows.start.0, 0);
 6875            let end = Point::new(
 6876                rows.end.previous_row().0,
 6877                buffer.line_len(rows.end.previous_row()),
 6878            );
 6879            let text = buffer
 6880                .text_for_range(start..end)
 6881                .chain(Some("\n"))
 6882                .collect::<String>();
 6883            let insert_location = if upwards {
 6884                Point::new(rows.end.0, 0)
 6885            } else {
 6886                start
 6887            };
 6888            edits.push((insert_location..insert_location, text));
 6889        }
 6890
 6891        self.transact(cx, |this, cx| {
 6892            this.buffer.update(cx, |buffer, cx| {
 6893                buffer.edit(edits, None, cx);
 6894            });
 6895
 6896            this.request_autoscroll(Autoscroll::fit(), cx);
 6897        });
 6898    }
 6899
 6900    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6901        self.duplicate_line(true, cx);
 6902    }
 6903
 6904    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6905        self.duplicate_line(false, cx);
 6906    }
 6907
 6908    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6909        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6910        let buffer = self.buffer.read(cx).snapshot(cx);
 6911
 6912        let mut edits = Vec::new();
 6913        let mut unfold_ranges = Vec::new();
 6914        let mut refold_creases = Vec::new();
 6915
 6916        let selections = self.selections.all::<Point>(cx);
 6917        let mut selections = selections.iter().peekable();
 6918        let mut contiguous_row_selections = Vec::new();
 6919        let mut new_selections = Vec::new();
 6920
 6921        while let Some(selection) = selections.next() {
 6922            // Find all the selections that span a contiguous row range
 6923            let (start_row, end_row) = consume_contiguous_rows(
 6924                &mut contiguous_row_selections,
 6925                selection,
 6926                &display_map,
 6927                &mut selections,
 6928            );
 6929
 6930            // Move the text spanned by the row range to be before the line preceding the row range
 6931            if start_row.0 > 0 {
 6932                let range_to_move = Point::new(
 6933                    start_row.previous_row().0,
 6934                    buffer.line_len(start_row.previous_row()),
 6935                )
 6936                    ..Point::new(
 6937                        end_row.previous_row().0,
 6938                        buffer.line_len(end_row.previous_row()),
 6939                    );
 6940                let insertion_point = display_map
 6941                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6942                    .0;
 6943
 6944                // Don't move lines across excerpts
 6945                if buffer
 6946                    .excerpt_boundaries_in_range((
 6947                        Bound::Excluded(insertion_point),
 6948                        Bound::Included(range_to_move.end),
 6949                    ))
 6950                    .next()
 6951                    .is_none()
 6952                {
 6953                    let text = buffer
 6954                        .text_for_range(range_to_move.clone())
 6955                        .flat_map(|s| s.chars())
 6956                        .skip(1)
 6957                        .chain(['\n'])
 6958                        .collect::<String>();
 6959
 6960                    edits.push((
 6961                        buffer.anchor_after(range_to_move.start)
 6962                            ..buffer.anchor_before(range_to_move.end),
 6963                        String::new(),
 6964                    ));
 6965                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6966                    edits.push((insertion_anchor..insertion_anchor, text));
 6967
 6968                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6969
 6970                    // Move selections up
 6971                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6972                        |mut selection| {
 6973                            selection.start.row -= row_delta;
 6974                            selection.end.row -= row_delta;
 6975                            selection
 6976                        },
 6977                    ));
 6978
 6979                    // Move folds up
 6980                    unfold_ranges.push(range_to_move.clone());
 6981                    for fold in display_map.folds_in_range(
 6982                        buffer.anchor_before(range_to_move.start)
 6983                            ..buffer.anchor_after(range_to_move.end),
 6984                    ) {
 6985                        let mut start = fold.range.start.to_point(&buffer);
 6986                        let mut end = fold.range.end.to_point(&buffer);
 6987                        start.row -= row_delta;
 6988                        end.row -= row_delta;
 6989                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6990                    }
 6991                }
 6992            }
 6993
 6994            // If we didn't move line(s), preserve the existing selections
 6995            new_selections.append(&mut contiguous_row_selections);
 6996        }
 6997
 6998        self.transact(cx, |this, cx| {
 6999            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7000            this.buffer.update(cx, |buffer, cx| {
 7001                for (range, text) in edits {
 7002                    buffer.edit([(range, text)], None, cx);
 7003                }
 7004            });
 7005            this.fold_creases(refold_creases, true, cx);
 7006            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7007                s.select(new_selections);
 7008            })
 7009        });
 7010    }
 7011
 7012    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 7013        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7014        let buffer = self.buffer.read(cx).snapshot(cx);
 7015
 7016        let mut edits = Vec::new();
 7017        let mut unfold_ranges = Vec::new();
 7018        let mut refold_creases = Vec::new();
 7019
 7020        let selections = self.selections.all::<Point>(cx);
 7021        let mut selections = selections.iter().peekable();
 7022        let mut contiguous_row_selections = Vec::new();
 7023        let mut new_selections = Vec::new();
 7024
 7025        while let Some(selection) = selections.next() {
 7026            // Find all the selections that span a contiguous row range
 7027            let (start_row, end_row) = consume_contiguous_rows(
 7028                &mut contiguous_row_selections,
 7029                selection,
 7030                &display_map,
 7031                &mut selections,
 7032            );
 7033
 7034            // Move the text spanned by the row range to be after the last line of the row range
 7035            if end_row.0 <= buffer.max_point().row {
 7036                let range_to_move =
 7037                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 7038                let insertion_point = display_map
 7039                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 7040                    .0;
 7041
 7042                // Don't move lines across excerpt boundaries
 7043                if buffer
 7044                    .excerpt_boundaries_in_range((
 7045                        Bound::Excluded(range_to_move.start),
 7046                        Bound::Included(insertion_point),
 7047                    ))
 7048                    .next()
 7049                    .is_none()
 7050                {
 7051                    let mut text = String::from("\n");
 7052                    text.extend(buffer.text_for_range(range_to_move.clone()));
 7053                    text.pop(); // Drop trailing newline
 7054                    edits.push((
 7055                        buffer.anchor_after(range_to_move.start)
 7056                            ..buffer.anchor_before(range_to_move.end),
 7057                        String::new(),
 7058                    ));
 7059                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7060                    edits.push((insertion_anchor..insertion_anchor, text));
 7061
 7062                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 7063
 7064                    // Move selections down
 7065                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7066                        |mut selection| {
 7067                            selection.start.row += row_delta;
 7068                            selection.end.row += row_delta;
 7069                            selection
 7070                        },
 7071                    ));
 7072
 7073                    // Move folds down
 7074                    unfold_ranges.push(range_to_move.clone());
 7075                    for fold in display_map.folds_in_range(
 7076                        buffer.anchor_before(range_to_move.start)
 7077                            ..buffer.anchor_after(range_to_move.end),
 7078                    ) {
 7079                        let mut start = fold.range.start.to_point(&buffer);
 7080                        let mut end = fold.range.end.to_point(&buffer);
 7081                        start.row += row_delta;
 7082                        end.row += row_delta;
 7083                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7084                    }
 7085                }
 7086            }
 7087
 7088            // If we didn't move line(s), preserve the existing selections
 7089            new_selections.append(&mut contiguous_row_selections);
 7090        }
 7091
 7092        self.transact(cx, |this, cx| {
 7093            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7094            this.buffer.update(cx, |buffer, cx| {
 7095                for (range, text) in edits {
 7096                    buffer.edit([(range, text)], None, cx);
 7097                }
 7098            });
 7099            this.fold_creases(refold_creases, true, cx);
 7100            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 7101        });
 7102    }
 7103
 7104    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 7105        let text_layout_details = &self.text_layout_details(cx);
 7106        self.transact(cx, |this, cx| {
 7107            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7108                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 7109                let line_mode = s.line_mode;
 7110                s.move_with(|display_map, selection| {
 7111                    if !selection.is_empty() || line_mode {
 7112                        return;
 7113                    }
 7114
 7115                    let mut head = selection.head();
 7116                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 7117                    if head.column() == display_map.line_len(head.row()) {
 7118                        transpose_offset = display_map
 7119                            .buffer_snapshot
 7120                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7121                    }
 7122
 7123                    if transpose_offset == 0 {
 7124                        return;
 7125                    }
 7126
 7127                    *head.column_mut() += 1;
 7128                    head = display_map.clip_point(head, Bias::Right);
 7129                    let goal = SelectionGoal::HorizontalPosition(
 7130                        display_map
 7131                            .x_for_display_point(head, text_layout_details)
 7132                            .into(),
 7133                    );
 7134                    selection.collapse_to(head, goal);
 7135
 7136                    let transpose_start = display_map
 7137                        .buffer_snapshot
 7138                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7139                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 7140                        let transpose_end = display_map
 7141                            .buffer_snapshot
 7142                            .clip_offset(transpose_offset + 1, Bias::Right);
 7143                        if let Some(ch) =
 7144                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 7145                        {
 7146                            edits.push((transpose_start..transpose_offset, String::new()));
 7147                            edits.push((transpose_end..transpose_end, ch.to_string()));
 7148                        }
 7149                    }
 7150                });
 7151                edits
 7152            });
 7153            this.buffer
 7154                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7155            let selections = this.selections.all::<usize>(cx);
 7156            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7157                s.select(selections);
 7158            });
 7159        });
 7160    }
 7161
 7162    pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
 7163        self.rewrap_impl(IsVimMode::No, cx)
 7164    }
 7165
 7166    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
 7167        let buffer = self.buffer.read(cx).snapshot(cx);
 7168        let selections = self.selections.all::<Point>(cx);
 7169        let mut selections = selections.iter().peekable();
 7170
 7171        let mut edits = Vec::new();
 7172        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 7173
 7174        while let Some(selection) = selections.next() {
 7175            let mut start_row = selection.start.row;
 7176            let mut end_row = selection.end.row;
 7177
 7178            // Skip selections that overlap with a range that has already been rewrapped.
 7179            let selection_range = start_row..end_row;
 7180            if rewrapped_row_ranges
 7181                .iter()
 7182                .any(|range| range.overlaps(&selection_range))
 7183            {
 7184                continue;
 7185            }
 7186
 7187            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 7188
 7189            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 7190                match language_scope.language_name().0.as_ref() {
 7191                    "Markdown" | "Plain Text" => {
 7192                        should_rewrap = true;
 7193                    }
 7194                    _ => {}
 7195                }
 7196            }
 7197
 7198            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 7199
 7200            // Since not all lines in the selection may be at the same indent
 7201            // level, choose the indent size that is the most common between all
 7202            // of the lines.
 7203            //
 7204            // If there is a tie, we use the deepest indent.
 7205            let (indent_size, indent_end) = {
 7206                let mut indent_size_occurrences = HashMap::default();
 7207                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 7208
 7209                for row in start_row..=end_row {
 7210                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 7211                    rows_by_indent_size.entry(indent).or_default().push(row);
 7212                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 7213                }
 7214
 7215                let indent_size = indent_size_occurrences
 7216                    .into_iter()
 7217                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 7218                    .map(|(indent, _)| indent)
 7219                    .unwrap_or_default();
 7220                let row = rows_by_indent_size[&indent_size][0];
 7221                let indent_end = Point::new(row, indent_size.len);
 7222
 7223                (indent_size, indent_end)
 7224            };
 7225
 7226            let mut line_prefix = indent_size.chars().collect::<String>();
 7227
 7228            if let Some(comment_prefix) =
 7229                buffer
 7230                    .language_scope_at(selection.head())
 7231                    .and_then(|language| {
 7232                        language
 7233                            .line_comment_prefixes()
 7234                            .iter()
 7235                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 7236                            .cloned()
 7237                    })
 7238            {
 7239                line_prefix.push_str(&comment_prefix);
 7240                should_rewrap = true;
 7241            }
 7242
 7243            if !should_rewrap {
 7244                continue;
 7245            }
 7246
 7247            if selection.is_empty() {
 7248                'expand_upwards: while start_row > 0 {
 7249                    let prev_row = start_row - 1;
 7250                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 7251                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 7252                    {
 7253                        start_row = prev_row;
 7254                    } else {
 7255                        break 'expand_upwards;
 7256                    }
 7257                }
 7258
 7259                'expand_downwards: while end_row < buffer.max_point().row {
 7260                    let next_row = end_row + 1;
 7261                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 7262                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 7263                    {
 7264                        end_row = next_row;
 7265                    } else {
 7266                        break 'expand_downwards;
 7267                    }
 7268                }
 7269            }
 7270
 7271            let start = Point::new(start_row, 0);
 7272            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 7273            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 7274            let Some(lines_without_prefixes) = selection_text
 7275                .lines()
 7276                .map(|line| {
 7277                    line.strip_prefix(&line_prefix)
 7278                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 7279                        .ok_or_else(|| {
 7280                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 7281                        })
 7282                })
 7283                .collect::<Result<Vec<_>, _>>()
 7284                .log_err()
 7285            else {
 7286                continue;
 7287            };
 7288
 7289            let wrap_column = buffer
 7290                .settings_at(Point::new(start_row, 0), cx)
 7291                .preferred_line_length as usize;
 7292            let wrapped_text = wrap_with_prefix(
 7293                line_prefix,
 7294                lines_without_prefixes.join(" "),
 7295                wrap_column,
 7296                tab_size,
 7297            );
 7298
 7299            // TODO: should always use char-based diff while still supporting cursor behavior that
 7300            // matches vim.
 7301            let diff = match is_vim_mode {
 7302                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 7303                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 7304            };
 7305            let mut offset = start.to_offset(&buffer);
 7306            let mut moved_since_edit = true;
 7307
 7308            for change in diff.iter_all_changes() {
 7309                let value = change.value();
 7310                match change.tag() {
 7311                    ChangeTag::Equal => {
 7312                        offset += value.len();
 7313                        moved_since_edit = true;
 7314                    }
 7315                    ChangeTag::Delete => {
 7316                        let start = buffer.anchor_after(offset);
 7317                        let end = buffer.anchor_before(offset + value.len());
 7318
 7319                        if moved_since_edit {
 7320                            edits.push((start..end, String::new()));
 7321                        } else {
 7322                            edits.last_mut().unwrap().0.end = end;
 7323                        }
 7324
 7325                        offset += value.len();
 7326                        moved_since_edit = false;
 7327                    }
 7328                    ChangeTag::Insert => {
 7329                        if moved_since_edit {
 7330                            let anchor = buffer.anchor_after(offset);
 7331                            edits.push((anchor..anchor, value.to_string()));
 7332                        } else {
 7333                            edits.last_mut().unwrap().1.push_str(value);
 7334                        }
 7335
 7336                        moved_since_edit = false;
 7337                    }
 7338                }
 7339            }
 7340
 7341            rewrapped_row_ranges.push(start_row..=end_row);
 7342        }
 7343
 7344        self.buffer
 7345            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7346    }
 7347
 7348    pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
 7349        let mut text = String::new();
 7350        let buffer = self.buffer.read(cx).snapshot(cx);
 7351        let mut selections = self.selections.all::<Point>(cx);
 7352        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7353        {
 7354            let max_point = buffer.max_point();
 7355            let mut is_first = true;
 7356            for selection in &mut selections {
 7357                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7358                if is_entire_line {
 7359                    selection.start = Point::new(selection.start.row, 0);
 7360                    if !selection.is_empty() && selection.end.column == 0 {
 7361                        selection.end = cmp::min(max_point, selection.end);
 7362                    } else {
 7363                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7364                    }
 7365                    selection.goal = SelectionGoal::None;
 7366                }
 7367                if is_first {
 7368                    is_first = false;
 7369                } else {
 7370                    text += "\n";
 7371                }
 7372                let mut len = 0;
 7373                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7374                    text.push_str(chunk);
 7375                    len += chunk.len();
 7376                }
 7377                clipboard_selections.push(ClipboardSelection {
 7378                    len,
 7379                    is_entire_line,
 7380                    first_line_indent: buffer
 7381                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7382                        .len,
 7383                });
 7384            }
 7385        }
 7386
 7387        self.transact(cx, |this, cx| {
 7388            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7389                s.select(selections);
 7390            });
 7391            this.insert("", cx);
 7392        });
 7393        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 7394    }
 7395
 7396    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 7397        let item = self.cut_common(cx);
 7398        cx.write_to_clipboard(item);
 7399    }
 7400
 7401    pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
 7402        self.change_selections(None, cx, |s| {
 7403            s.move_with(|snapshot, sel| {
 7404                if sel.is_empty() {
 7405                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 7406                }
 7407            });
 7408        });
 7409        let item = self.cut_common(cx);
 7410        cx.set_global(KillRing(item))
 7411    }
 7412
 7413    pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
 7414        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 7415            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 7416                (kill_ring.text().to_string(), kill_ring.metadata_json())
 7417            } else {
 7418                return;
 7419            }
 7420        } else {
 7421            return;
 7422        };
 7423        self.do_paste(&text, metadata, false, cx);
 7424    }
 7425
 7426    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 7427        let selections = self.selections.all::<Point>(cx);
 7428        let buffer = self.buffer.read(cx).read(cx);
 7429        let mut text = String::new();
 7430
 7431        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7432        {
 7433            let max_point = buffer.max_point();
 7434            let mut is_first = true;
 7435            for selection in selections.iter() {
 7436                let mut start = selection.start;
 7437                let mut end = selection.end;
 7438                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7439                if is_entire_line {
 7440                    start = Point::new(start.row, 0);
 7441                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 7442                }
 7443                if is_first {
 7444                    is_first = false;
 7445                } else {
 7446                    text += "\n";
 7447                }
 7448                let mut len = 0;
 7449                for chunk in buffer.text_for_range(start..end) {
 7450                    text.push_str(chunk);
 7451                    len += chunk.len();
 7452                }
 7453                clipboard_selections.push(ClipboardSelection {
 7454                    len,
 7455                    is_entire_line,
 7456                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 7457                });
 7458            }
 7459        }
 7460
 7461        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7462            text,
 7463            clipboard_selections,
 7464        ));
 7465    }
 7466
 7467    pub fn do_paste(
 7468        &mut self,
 7469        text: &String,
 7470        clipboard_selections: Option<Vec<ClipboardSelection>>,
 7471        handle_entire_lines: bool,
 7472        cx: &mut ViewContext<Self>,
 7473    ) {
 7474        if self.read_only(cx) {
 7475            return;
 7476        }
 7477
 7478        let clipboard_text = Cow::Borrowed(text);
 7479
 7480        self.transact(cx, |this, cx| {
 7481            if let Some(mut clipboard_selections) = clipboard_selections {
 7482                let old_selections = this.selections.all::<usize>(cx);
 7483                let all_selections_were_entire_line =
 7484                    clipboard_selections.iter().all(|s| s.is_entire_line);
 7485                let first_selection_indent_column =
 7486                    clipboard_selections.first().map(|s| s.first_line_indent);
 7487                if clipboard_selections.len() != old_selections.len() {
 7488                    clipboard_selections.drain(..);
 7489                }
 7490                let cursor_offset = this.selections.last::<usize>(cx).head();
 7491                let mut auto_indent_on_paste = true;
 7492
 7493                this.buffer.update(cx, |buffer, cx| {
 7494                    let snapshot = buffer.read(cx);
 7495                    auto_indent_on_paste =
 7496                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 7497
 7498                    let mut start_offset = 0;
 7499                    let mut edits = Vec::new();
 7500                    let mut original_indent_columns = Vec::new();
 7501                    for (ix, selection) in old_selections.iter().enumerate() {
 7502                        let to_insert;
 7503                        let entire_line;
 7504                        let original_indent_column;
 7505                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 7506                            let end_offset = start_offset + clipboard_selection.len;
 7507                            to_insert = &clipboard_text[start_offset..end_offset];
 7508                            entire_line = clipboard_selection.is_entire_line;
 7509                            start_offset = end_offset + 1;
 7510                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7511                        } else {
 7512                            to_insert = clipboard_text.as_str();
 7513                            entire_line = all_selections_were_entire_line;
 7514                            original_indent_column = first_selection_indent_column
 7515                        }
 7516
 7517                        // If the corresponding selection was empty when this slice of the
 7518                        // clipboard text was written, then the entire line containing the
 7519                        // selection was copied. If this selection is also currently empty,
 7520                        // then paste the line before the current line of the buffer.
 7521                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7522                            let column = selection.start.to_point(&snapshot).column as usize;
 7523                            let line_start = selection.start - column;
 7524                            line_start..line_start
 7525                        } else {
 7526                            selection.range()
 7527                        };
 7528
 7529                        edits.push((range, to_insert));
 7530                        original_indent_columns.extend(original_indent_column);
 7531                    }
 7532                    drop(snapshot);
 7533
 7534                    buffer.edit(
 7535                        edits,
 7536                        if auto_indent_on_paste {
 7537                            Some(AutoindentMode::Block {
 7538                                original_indent_columns,
 7539                            })
 7540                        } else {
 7541                            None
 7542                        },
 7543                        cx,
 7544                    );
 7545                });
 7546
 7547                let selections = this.selections.all::<usize>(cx);
 7548                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 7549            } else {
 7550                this.insert(&clipboard_text, cx);
 7551            }
 7552        });
 7553    }
 7554
 7555    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 7556        if let Some(item) = cx.read_from_clipboard() {
 7557            let entries = item.entries();
 7558
 7559            match entries.first() {
 7560                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7561                // of all the pasted entries.
 7562                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7563                    .do_paste(
 7564                        clipboard_string.text(),
 7565                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7566                        true,
 7567                        cx,
 7568                    ),
 7569                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
 7570            }
 7571        }
 7572    }
 7573
 7574    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 7575        if self.read_only(cx) {
 7576            return;
 7577        }
 7578
 7579        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7580            if let Some((selections, _)) =
 7581                self.selection_history.transaction(transaction_id).cloned()
 7582            {
 7583                self.change_selections(None, cx, |s| {
 7584                    s.select_anchors(selections.to_vec());
 7585                });
 7586            }
 7587            self.request_autoscroll(Autoscroll::fit(), cx);
 7588            self.unmark_text(cx);
 7589            self.refresh_inline_completion(true, false, cx);
 7590            cx.emit(EditorEvent::Edited { transaction_id });
 7591            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7592        }
 7593    }
 7594
 7595    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 7596        if self.read_only(cx) {
 7597            return;
 7598        }
 7599
 7600        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7601            if let Some((_, Some(selections))) =
 7602                self.selection_history.transaction(transaction_id).cloned()
 7603            {
 7604                self.change_selections(None, cx, |s| {
 7605                    s.select_anchors(selections.to_vec());
 7606                });
 7607            }
 7608            self.request_autoscroll(Autoscroll::fit(), cx);
 7609            self.unmark_text(cx);
 7610            self.refresh_inline_completion(true, false, cx);
 7611            cx.emit(EditorEvent::Edited { transaction_id });
 7612        }
 7613    }
 7614
 7615    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 7616        self.buffer
 7617            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7618    }
 7619
 7620    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 7621        self.buffer
 7622            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7623    }
 7624
 7625    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 7626        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7627            let line_mode = s.line_mode;
 7628            s.move_with(|map, selection| {
 7629                let cursor = if selection.is_empty() && !line_mode {
 7630                    movement::left(map, selection.start)
 7631                } else {
 7632                    selection.start
 7633                };
 7634                selection.collapse_to(cursor, SelectionGoal::None);
 7635            });
 7636        })
 7637    }
 7638
 7639    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 7640        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7641            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7642        })
 7643    }
 7644
 7645    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 7646        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7647            let line_mode = s.line_mode;
 7648            s.move_with(|map, selection| {
 7649                let cursor = if selection.is_empty() && !line_mode {
 7650                    movement::right(map, selection.end)
 7651                } else {
 7652                    selection.end
 7653                };
 7654                selection.collapse_to(cursor, SelectionGoal::None)
 7655            });
 7656        })
 7657    }
 7658
 7659    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 7660        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7661            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7662        })
 7663    }
 7664
 7665    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 7666        if self.take_rename(true, cx).is_some() {
 7667            return;
 7668        }
 7669
 7670        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7671            cx.propagate();
 7672            return;
 7673        }
 7674
 7675        let text_layout_details = &self.text_layout_details(cx);
 7676        let selection_count = self.selections.count();
 7677        let first_selection = self.selections.first_anchor();
 7678
 7679        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7680            let line_mode = s.line_mode;
 7681            s.move_with(|map, selection| {
 7682                if !selection.is_empty() && !line_mode {
 7683                    selection.goal = SelectionGoal::None;
 7684                }
 7685                let (cursor, goal) = movement::up(
 7686                    map,
 7687                    selection.start,
 7688                    selection.goal,
 7689                    false,
 7690                    text_layout_details,
 7691                );
 7692                selection.collapse_to(cursor, goal);
 7693            });
 7694        });
 7695
 7696        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7697        {
 7698            cx.propagate();
 7699        }
 7700    }
 7701
 7702    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 7703        if self.take_rename(true, cx).is_some() {
 7704            return;
 7705        }
 7706
 7707        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7708            cx.propagate();
 7709            return;
 7710        }
 7711
 7712        let text_layout_details = &self.text_layout_details(cx);
 7713
 7714        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7715            let line_mode = s.line_mode;
 7716            s.move_with(|map, selection| {
 7717                if !selection.is_empty() && !line_mode {
 7718                    selection.goal = SelectionGoal::None;
 7719                }
 7720                let (cursor, goal) = movement::up_by_rows(
 7721                    map,
 7722                    selection.start,
 7723                    action.lines,
 7724                    selection.goal,
 7725                    false,
 7726                    text_layout_details,
 7727                );
 7728                selection.collapse_to(cursor, goal);
 7729            });
 7730        })
 7731    }
 7732
 7733    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 7734        if self.take_rename(true, cx).is_some() {
 7735            return;
 7736        }
 7737
 7738        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7739            cx.propagate();
 7740            return;
 7741        }
 7742
 7743        let text_layout_details = &self.text_layout_details(cx);
 7744
 7745        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7746            let line_mode = s.line_mode;
 7747            s.move_with(|map, selection| {
 7748                if !selection.is_empty() && !line_mode {
 7749                    selection.goal = SelectionGoal::None;
 7750                }
 7751                let (cursor, goal) = movement::down_by_rows(
 7752                    map,
 7753                    selection.start,
 7754                    action.lines,
 7755                    selection.goal,
 7756                    false,
 7757                    text_layout_details,
 7758                );
 7759                selection.collapse_to(cursor, goal);
 7760            });
 7761        })
 7762    }
 7763
 7764    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 7765        let text_layout_details = &self.text_layout_details(cx);
 7766        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7767            s.move_heads_with(|map, head, goal| {
 7768                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7769            })
 7770        })
 7771    }
 7772
 7773    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 7774        let text_layout_details = &self.text_layout_details(cx);
 7775        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7776            s.move_heads_with(|map, head, goal| {
 7777                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7778            })
 7779        })
 7780    }
 7781
 7782    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 7783        let Some(row_count) = self.visible_row_count() else {
 7784            return;
 7785        };
 7786
 7787        let text_layout_details = &self.text_layout_details(cx);
 7788
 7789        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7790            s.move_heads_with(|map, head, goal| {
 7791                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7792            })
 7793        })
 7794    }
 7795
 7796    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 7797        if self.take_rename(true, cx).is_some() {
 7798            return;
 7799        }
 7800
 7801        if self
 7802            .context_menu
 7803            .write()
 7804            .as_mut()
 7805            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 7806            .unwrap_or(false)
 7807        {
 7808            return;
 7809        }
 7810
 7811        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7812            cx.propagate();
 7813            return;
 7814        }
 7815
 7816        let Some(row_count) = self.visible_row_count() else {
 7817            return;
 7818        };
 7819
 7820        let autoscroll = if action.center_cursor {
 7821            Autoscroll::center()
 7822        } else {
 7823            Autoscroll::fit()
 7824        };
 7825
 7826        let text_layout_details = &self.text_layout_details(cx);
 7827
 7828        self.change_selections(Some(autoscroll), cx, |s| {
 7829            let line_mode = s.line_mode;
 7830            s.move_with(|map, selection| {
 7831                if !selection.is_empty() && !line_mode {
 7832                    selection.goal = SelectionGoal::None;
 7833                }
 7834                let (cursor, goal) = movement::up_by_rows(
 7835                    map,
 7836                    selection.end,
 7837                    row_count,
 7838                    selection.goal,
 7839                    false,
 7840                    text_layout_details,
 7841                );
 7842                selection.collapse_to(cursor, goal);
 7843            });
 7844        });
 7845    }
 7846
 7847    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 7848        let text_layout_details = &self.text_layout_details(cx);
 7849        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7850            s.move_heads_with(|map, head, goal| {
 7851                movement::up(map, head, goal, false, text_layout_details)
 7852            })
 7853        })
 7854    }
 7855
 7856    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 7857        self.take_rename(true, cx);
 7858
 7859        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7860            cx.propagate();
 7861            return;
 7862        }
 7863
 7864        let text_layout_details = &self.text_layout_details(cx);
 7865        let selection_count = self.selections.count();
 7866        let first_selection = self.selections.first_anchor();
 7867
 7868        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7869            let line_mode = s.line_mode;
 7870            s.move_with(|map, selection| {
 7871                if !selection.is_empty() && !line_mode {
 7872                    selection.goal = SelectionGoal::None;
 7873                }
 7874                let (cursor, goal) = movement::down(
 7875                    map,
 7876                    selection.end,
 7877                    selection.goal,
 7878                    false,
 7879                    text_layout_details,
 7880                );
 7881                selection.collapse_to(cursor, goal);
 7882            });
 7883        });
 7884
 7885        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7886        {
 7887            cx.propagate();
 7888        }
 7889    }
 7890
 7891    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 7892        let Some(row_count) = self.visible_row_count() else {
 7893            return;
 7894        };
 7895
 7896        let text_layout_details = &self.text_layout_details(cx);
 7897
 7898        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7899            s.move_heads_with(|map, head, goal| {
 7900                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 7901            })
 7902        })
 7903    }
 7904
 7905    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 7906        if self.take_rename(true, cx).is_some() {
 7907            return;
 7908        }
 7909
 7910        if self
 7911            .context_menu
 7912            .write()
 7913            .as_mut()
 7914            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 7915            .unwrap_or(false)
 7916        {
 7917            return;
 7918        }
 7919
 7920        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7921            cx.propagate();
 7922            return;
 7923        }
 7924
 7925        let Some(row_count) = self.visible_row_count() else {
 7926            return;
 7927        };
 7928
 7929        let autoscroll = if action.center_cursor {
 7930            Autoscroll::center()
 7931        } else {
 7932            Autoscroll::fit()
 7933        };
 7934
 7935        let text_layout_details = &self.text_layout_details(cx);
 7936        self.change_selections(Some(autoscroll), cx, |s| {
 7937            let line_mode = s.line_mode;
 7938            s.move_with(|map, selection| {
 7939                if !selection.is_empty() && !line_mode {
 7940                    selection.goal = SelectionGoal::None;
 7941                }
 7942                let (cursor, goal) = movement::down_by_rows(
 7943                    map,
 7944                    selection.end,
 7945                    row_count,
 7946                    selection.goal,
 7947                    false,
 7948                    text_layout_details,
 7949                );
 7950                selection.collapse_to(cursor, goal);
 7951            });
 7952        });
 7953    }
 7954
 7955    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 7956        let text_layout_details = &self.text_layout_details(cx);
 7957        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7958            s.move_heads_with(|map, head, goal| {
 7959                movement::down(map, head, goal, false, text_layout_details)
 7960            })
 7961        });
 7962    }
 7963
 7964    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 7965        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7966            context_menu.select_first(self.completion_provider.as_deref(), cx);
 7967        }
 7968    }
 7969
 7970    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 7971        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7972            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 7973        }
 7974    }
 7975
 7976    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7977        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7978            context_menu.select_next(self.completion_provider.as_deref(), cx);
 7979        }
 7980    }
 7981
 7982    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 7983        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7984            context_menu.select_last(self.completion_provider.as_deref(), cx);
 7985        }
 7986    }
 7987
 7988    pub fn move_to_previous_word_start(
 7989        &mut self,
 7990        _: &MoveToPreviousWordStart,
 7991        cx: &mut ViewContext<Self>,
 7992    ) {
 7993        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7994            s.move_cursors_with(|map, head, _| {
 7995                (
 7996                    movement::previous_word_start(map, head),
 7997                    SelectionGoal::None,
 7998                )
 7999            });
 8000        })
 8001    }
 8002
 8003    pub fn move_to_previous_subword_start(
 8004        &mut self,
 8005        _: &MoveToPreviousSubwordStart,
 8006        cx: &mut ViewContext<Self>,
 8007    ) {
 8008        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8009            s.move_cursors_with(|map, head, _| {
 8010                (
 8011                    movement::previous_subword_start(map, head),
 8012                    SelectionGoal::None,
 8013                )
 8014            });
 8015        })
 8016    }
 8017
 8018    pub fn select_to_previous_word_start(
 8019        &mut self,
 8020        _: &SelectToPreviousWordStart,
 8021        cx: &mut ViewContext<Self>,
 8022    ) {
 8023        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8024            s.move_heads_with(|map, head, _| {
 8025                (
 8026                    movement::previous_word_start(map, head),
 8027                    SelectionGoal::None,
 8028                )
 8029            });
 8030        })
 8031    }
 8032
 8033    pub fn select_to_previous_subword_start(
 8034        &mut self,
 8035        _: &SelectToPreviousSubwordStart,
 8036        cx: &mut ViewContext<Self>,
 8037    ) {
 8038        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8039            s.move_heads_with(|map, head, _| {
 8040                (
 8041                    movement::previous_subword_start(map, head),
 8042                    SelectionGoal::None,
 8043                )
 8044            });
 8045        })
 8046    }
 8047
 8048    pub fn delete_to_previous_word_start(
 8049        &mut self,
 8050        action: &DeleteToPreviousWordStart,
 8051        cx: &mut ViewContext<Self>,
 8052    ) {
 8053        self.transact(cx, |this, cx| {
 8054            this.select_autoclose_pair(cx);
 8055            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8056                let line_mode = s.line_mode;
 8057                s.move_with(|map, selection| {
 8058                    if selection.is_empty() && !line_mode {
 8059                        let cursor = if action.ignore_newlines {
 8060                            movement::previous_word_start(map, selection.head())
 8061                        } else {
 8062                            movement::previous_word_start_or_newline(map, selection.head())
 8063                        };
 8064                        selection.set_head(cursor, SelectionGoal::None);
 8065                    }
 8066                });
 8067            });
 8068            this.insert("", cx);
 8069        });
 8070    }
 8071
 8072    pub fn delete_to_previous_subword_start(
 8073        &mut self,
 8074        _: &DeleteToPreviousSubwordStart,
 8075        cx: &mut ViewContext<Self>,
 8076    ) {
 8077        self.transact(cx, |this, cx| {
 8078            this.select_autoclose_pair(cx);
 8079            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8080                let line_mode = s.line_mode;
 8081                s.move_with(|map, selection| {
 8082                    if selection.is_empty() && !line_mode {
 8083                        let cursor = movement::previous_subword_start(map, selection.head());
 8084                        selection.set_head(cursor, SelectionGoal::None);
 8085                    }
 8086                });
 8087            });
 8088            this.insert("", cx);
 8089        });
 8090    }
 8091
 8092    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 8093        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8094            s.move_cursors_with(|map, head, _| {
 8095                (movement::next_word_end(map, head), SelectionGoal::None)
 8096            });
 8097        })
 8098    }
 8099
 8100    pub fn move_to_next_subword_end(
 8101        &mut self,
 8102        _: &MoveToNextSubwordEnd,
 8103        cx: &mut ViewContext<Self>,
 8104    ) {
 8105        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8106            s.move_cursors_with(|map, head, _| {
 8107                (movement::next_subword_end(map, head), SelectionGoal::None)
 8108            });
 8109        })
 8110    }
 8111
 8112    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 8113        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8114            s.move_heads_with(|map, head, _| {
 8115                (movement::next_word_end(map, head), SelectionGoal::None)
 8116            });
 8117        })
 8118    }
 8119
 8120    pub fn select_to_next_subword_end(
 8121        &mut self,
 8122        _: &SelectToNextSubwordEnd,
 8123        cx: &mut ViewContext<Self>,
 8124    ) {
 8125        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8126            s.move_heads_with(|map, head, _| {
 8127                (movement::next_subword_end(map, head), SelectionGoal::None)
 8128            });
 8129        })
 8130    }
 8131
 8132    pub fn delete_to_next_word_end(
 8133        &mut self,
 8134        action: &DeleteToNextWordEnd,
 8135        cx: &mut ViewContext<Self>,
 8136    ) {
 8137        self.transact(cx, |this, cx| {
 8138            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8139                let line_mode = s.line_mode;
 8140                s.move_with(|map, selection| {
 8141                    if selection.is_empty() && !line_mode {
 8142                        let cursor = if action.ignore_newlines {
 8143                            movement::next_word_end(map, selection.head())
 8144                        } else {
 8145                            movement::next_word_end_or_newline(map, selection.head())
 8146                        };
 8147                        selection.set_head(cursor, SelectionGoal::None);
 8148                    }
 8149                });
 8150            });
 8151            this.insert("", cx);
 8152        });
 8153    }
 8154
 8155    pub fn delete_to_next_subword_end(
 8156        &mut self,
 8157        _: &DeleteToNextSubwordEnd,
 8158        cx: &mut ViewContext<Self>,
 8159    ) {
 8160        self.transact(cx, |this, cx| {
 8161            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8162                s.move_with(|map, selection| {
 8163                    if selection.is_empty() {
 8164                        let cursor = movement::next_subword_end(map, selection.head());
 8165                        selection.set_head(cursor, SelectionGoal::None);
 8166                    }
 8167                });
 8168            });
 8169            this.insert("", cx);
 8170        });
 8171    }
 8172
 8173    pub fn move_to_beginning_of_line(
 8174        &mut self,
 8175        action: &MoveToBeginningOfLine,
 8176        cx: &mut ViewContext<Self>,
 8177    ) {
 8178        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8179            s.move_cursors_with(|map, head, _| {
 8180                (
 8181                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8182                    SelectionGoal::None,
 8183                )
 8184            });
 8185        })
 8186    }
 8187
 8188    pub fn select_to_beginning_of_line(
 8189        &mut self,
 8190        action: &SelectToBeginningOfLine,
 8191        cx: &mut ViewContext<Self>,
 8192    ) {
 8193        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8194            s.move_heads_with(|map, head, _| {
 8195                (
 8196                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8197                    SelectionGoal::None,
 8198                )
 8199            });
 8200        });
 8201    }
 8202
 8203    pub fn delete_to_beginning_of_line(
 8204        &mut self,
 8205        _: &DeleteToBeginningOfLine,
 8206        cx: &mut ViewContext<Self>,
 8207    ) {
 8208        self.transact(cx, |this, cx| {
 8209            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8210                s.move_with(|_, selection| {
 8211                    selection.reversed = true;
 8212                });
 8213            });
 8214
 8215            this.select_to_beginning_of_line(
 8216                &SelectToBeginningOfLine {
 8217                    stop_at_soft_wraps: false,
 8218                },
 8219                cx,
 8220            );
 8221            this.backspace(&Backspace, cx);
 8222        });
 8223    }
 8224
 8225    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 8226        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8227            s.move_cursors_with(|map, head, _| {
 8228                (
 8229                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8230                    SelectionGoal::None,
 8231                )
 8232            });
 8233        })
 8234    }
 8235
 8236    pub fn select_to_end_of_line(
 8237        &mut self,
 8238        action: &SelectToEndOfLine,
 8239        cx: &mut ViewContext<Self>,
 8240    ) {
 8241        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8242            s.move_heads_with(|map, head, _| {
 8243                (
 8244                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8245                    SelectionGoal::None,
 8246                )
 8247            });
 8248        })
 8249    }
 8250
 8251    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 8252        self.transact(cx, |this, cx| {
 8253            this.select_to_end_of_line(
 8254                &SelectToEndOfLine {
 8255                    stop_at_soft_wraps: false,
 8256                },
 8257                cx,
 8258            );
 8259            this.delete(&Delete, cx);
 8260        });
 8261    }
 8262
 8263    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 8264        self.transact(cx, |this, cx| {
 8265            this.select_to_end_of_line(
 8266                &SelectToEndOfLine {
 8267                    stop_at_soft_wraps: false,
 8268                },
 8269                cx,
 8270            );
 8271            this.cut(&Cut, cx);
 8272        });
 8273    }
 8274
 8275    pub fn move_to_start_of_paragraph(
 8276        &mut self,
 8277        _: &MoveToStartOfParagraph,
 8278        cx: &mut ViewContext<Self>,
 8279    ) {
 8280        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8281            cx.propagate();
 8282            return;
 8283        }
 8284
 8285        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8286            s.move_with(|map, selection| {
 8287                selection.collapse_to(
 8288                    movement::start_of_paragraph(map, selection.head(), 1),
 8289                    SelectionGoal::None,
 8290                )
 8291            });
 8292        })
 8293    }
 8294
 8295    pub fn move_to_end_of_paragraph(
 8296        &mut self,
 8297        _: &MoveToEndOfParagraph,
 8298        cx: &mut ViewContext<Self>,
 8299    ) {
 8300        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8301            cx.propagate();
 8302            return;
 8303        }
 8304
 8305        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8306            s.move_with(|map, selection| {
 8307                selection.collapse_to(
 8308                    movement::end_of_paragraph(map, selection.head(), 1),
 8309                    SelectionGoal::None,
 8310                )
 8311            });
 8312        })
 8313    }
 8314
 8315    pub fn select_to_start_of_paragraph(
 8316        &mut self,
 8317        _: &SelectToStartOfParagraph,
 8318        cx: &mut ViewContext<Self>,
 8319    ) {
 8320        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8321            cx.propagate();
 8322            return;
 8323        }
 8324
 8325        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8326            s.move_heads_with(|map, head, _| {
 8327                (
 8328                    movement::start_of_paragraph(map, head, 1),
 8329                    SelectionGoal::None,
 8330                )
 8331            });
 8332        })
 8333    }
 8334
 8335    pub fn select_to_end_of_paragraph(
 8336        &mut self,
 8337        _: &SelectToEndOfParagraph,
 8338        cx: &mut ViewContext<Self>,
 8339    ) {
 8340        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8341            cx.propagate();
 8342            return;
 8343        }
 8344
 8345        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8346            s.move_heads_with(|map, head, _| {
 8347                (
 8348                    movement::end_of_paragraph(map, head, 1),
 8349                    SelectionGoal::None,
 8350                )
 8351            });
 8352        })
 8353    }
 8354
 8355    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 8356        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8357            cx.propagate();
 8358            return;
 8359        }
 8360
 8361        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8362            s.select_ranges(vec![0..0]);
 8363        });
 8364    }
 8365
 8366    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 8367        let mut selection = self.selections.last::<Point>(cx);
 8368        selection.set_head(Point::zero(), SelectionGoal::None);
 8369
 8370        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8371            s.select(vec![selection]);
 8372        });
 8373    }
 8374
 8375    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 8376        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8377            cx.propagate();
 8378            return;
 8379        }
 8380
 8381        let cursor = self.buffer.read(cx).read(cx).len();
 8382        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8383            s.select_ranges(vec![cursor..cursor])
 8384        });
 8385    }
 8386
 8387    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 8388        self.nav_history = nav_history;
 8389    }
 8390
 8391    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 8392        self.nav_history.as_ref()
 8393    }
 8394
 8395    fn push_to_nav_history(
 8396        &mut self,
 8397        cursor_anchor: Anchor,
 8398        new_position: Option<Point>,
 8399        cx: &mut ViewContext<Self>,
 8400    ) {
 8401        if let Some(nav_history) = self.nav_history.as_mut() {
 8402            let buffer = self.buffer.read(cx).read(cx);
 8403            let cursor_position = cursor_anchor.to_point(&buffer);
 8404            let scroll_state = self.scroll_manager.anchor();
 8405            let scroll_top_row = scroll_state.top_row(&buffer);
 8406            drop(buffer);
 8407
 8408            if let Some(new_position) = new_position {
 8409                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 8410                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 8411                    return;
 8412                }
 8413            }
 8414
 8415            nav_history.push(
 8416                Some(NavigationData {
 8417                    cursor_anchor,
 8418                    cursor_position,
 8419                    scroll_anchor: scroll_state,
 8420                    scroll_top_row,
 8421                }),
 8422                cx,
 8423            );
 8424        }
 8425    }
 8426
 8427    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 8428        let buffer = self.buffer.read(cx).snapshot(cx);
 8429        let mut selection = self.selections.first::<usize>(cx);
 8430        selection.set_head(buffer.len(), SelectionGoal::None);
 8431        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8432            s.select(vec![selection]);
 8433        });
 8434    }
 8435
 8436    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 8437        let end = self.buffer.read(cx).read(cx).len();
 8438        self.change_selections(None, cx, |s| {
 8439            s.select_ranges(vec![0..end]);
 8440        });
 8441    }
 8442
 8443    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 8444        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8445        let mut selections = self.selections.all::<Point>(cx);
 8446        let max_point = display_map.buffer_snapshot.max_point();
 8447        for selection in &mut selections {
 8448            let rows = selection.spanned_rows(true, &display_map);
 8449            selection.start = Point::new(rows.start.0, 0);
 8450            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 8451            selection.reversed = false;
 8452        }
 8453        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8454            s.select(selections);
 8455        });
 8456    }
 8457
 8458    pub fn split_selection_into_lines(
 8459        &mut self,
 8460        _: &SplitSelectionIntoLines,
 8461        cx: &mut ViewContext<Self>,
 8462    ) {
 8463        let mut to_unfold = Vec::new();
 8464        let mut new_selection_ranges = Vec::new();
 8465        {
 8466            let selections = self.selections.all::<Point>(cx);
 8467            let buffer = self.buffer.read(cx).read(cx);
 8468            for selection in selections {
 8469                for row in selection.start.row..selection.end.row {
 8470                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 8471                    new_selection_ranges.push(cursor..cursor);
 8472                }
 8473                new_selection_ranges.push(selection.end..selection.end);
 8474                to_unfold.push(selection.start..selection.end);
 8475            }
 8476        }
 8477        self.unfold_ranges(&to_unfold, true, true, cx);
 8478        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8479            s.select_ranges(new_selection_ranges);
 8480        });
 8481    }
 8482
 8483    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 8484        self.add_selection(true, cx);
 8485    }
 8486
 8487    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 8488        self.add_selection(false, cx);
 8489    }
 8490
 8491    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 8492        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8493        let mut selections = self.selections.all::<Point>(cx);
 8494        let text_layout_details = self.text_layout_details(cx);
 8495        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 8496            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 8497            let range = oldest_selection.display_range(&display_map).sorted();
 8498
 8499            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 8500            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 8501            let positions = start_x.min(end_x)..start_x.max(end_x);
 8502
 8503            selections.clear();
 8504            let mut stack = Vec::new();
 8505            for row in range.start.row().0..=range.end.row().0 {
 8506                if let Some(selection) = self.selections.build_columnar_selection(
 8507                    &display_map,
 8508                    DisplayRow(row),
 8509                    &positions,
 8510                    oldest_selection.reversed,
 8511                    &text_layout_details,
 8512                ) {
 8513                    stack.push(selection.id);
 8514                    selections.push(selection);
 8515                }
 8516            }
 8517
 8518            if above {
 8519                stack.reverse();
 8520            }
 8521
 8522            AddSelectionsState { above, stack }
 8523        });
 8524
 8525        let last_added_selection = *state.stack.last().unwrap();
 8526        let mut new_selections = Vec::new();
 8527        if above == state.above {
 8528            let end_row = if above {
 8529                DisplayRow(0)
 8530            } else {
 8531                display_map.max_point().row()
 8532            };
 8533
 8534            'outer: for selection in selections {
 8535                if selection.id == last_added_selection {
 8536                    let range = selection.display_range(&display_map).sorted();
 8537                    debug_assert_eq!(range.start.row(), range.end.row());
 8538                    let mut row = range.start.row();
 8539                    let positions =
 8540                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 8541                            px(start)..px(end)
 8542                        } else {
 8543                            let start_x =
 8544                                display_map.x_for_display_point(range.start, &text_layout_details);
 8545                            let end_x =
 8546                                display_map.x_for_display_point(range.end, &text_layout_details);
 8547                            start_x.min(end_x)..start_x.max(end_x)
 8548                        };
 8549
 8550                    while row != end_row {
 8551                        if above {
 8552                            row.0 -= 1;
 8553                        } else {
 8554                            row.0 += 1;
 8555                        }
 8556
 8557                        if let Some(new_selection) = self.selections.build_columnar_selection(
 8558                            &display_map,
 8559                            row,
 8560                            &positions,
 8561                            selection.reversed,
 8562                            &text_layout_details,
 8563                        ) {
 8564                            state.stack.push(new_selection.id);
 8565                            if above {
 8566                                new_selections.push(new_selection);
 8567                                new_selections.push(selection);
 8568                            } else {
 8569                                new_selections.push(selection);
 8570                                new_selections.push(new_selection);
 8571                            }
 8572
 8573                            continue 'outer;
 8574                        }
 8575                    }
 8576                }
 8577
 8578                new_selections.push(selection);
 8579            }
 8580        } else {
 8581            new_selections = selections;
 8582            new_selections.retain(|s| s.id != last_added_selection);
 8583            state.stack.pop();
 8584        }
 8585
 8586        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8587            s.select(new_selections);
 8588        });
 8589        if state.stack.len() > 1 {
 8590            self.add_selections_state = Some(state);
 8591        }
 8592    }
 8593
 8594    pub fn select_next_match_internal(
 8595        &mut self,
 8596        display_map: &DisplaySnapshot,
 8597        replace_newest: bool,
 8598        autoscroll: Option<Autoscroll>,
 8599        cx: &mut ViewContext<Self>,
 8600    ) -> Result<()> {
 8601        fn select_next_match_ranges(
 8602            this: &mut Editor,
 8603            range: Range<usize>,
 8604            replace_newest: bool,
 8605            auto_scroll: Option<Autoscroll>,
 8606            cx: &mut ViewContext<Editor>,
 8607        ) {
 8608            this.unfold_ranges(&[range.clone()], false, true, cx);
 8609            this.change_selections(auto_scroll, cx, |s| {
 8610                if replace_newest {
 8611                    s.delete(s.newest_anchor().id);
 8612                }
 8613                s.insert_range(range.clone());
 8614            });
 8615        }
 8616
 8617        let buffer = &display_map.buffer_snapshot;
 8618        let mut selections = self.selections.all::<usize>(cx);
 8619        if let Some(mut select_next_state) = self.select_next_state.take() {
 8620            let query = &select_next_state.query;
 8621            if !select_next_state.done {
 8622                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8623                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8624                let mut next_selected_range = None;
 8625
 8626                let bytes_after_last_selection =
 8627                    buffer.bytes_in_range(last_selection.end..buffer.len());
 8628                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 8629                let query_matches = query
 8630                    .stream_find_iter(bytes_after_last_selection)
 8631                    .map(|result| (last_selection.end, result))
 8632                    .chain(
 8633                        query
 8634                            .stream_find_iter(bytes_before_first_selection)
 8635                            .map(|result| (0, result)),
 8636                    );
 8637
 8638                for (start_offset, query_match) in query_matches {
 8639                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8640                    let offset_range =
 8641                        start_offset + query_match.start()..start_offset + query_match.end();
 8642                    let display_range = offset_range.start.to_display_point(display_map)
 8643                        ..offset_range.end.to_display_point(display_map);
 8644
 8645                    if !select_next_state.wordwise
 8646                        || (!movement::is_inside_word(display_map, display_range.start)
 8647                            && !movement::is_inside_word(display_map, display_range.end))
 8648                    {
 8649                        // TODO: This is n^2, because we might check all the selections
 8650                        if !selections
 8651                            .iter()
 8652                            .any(|selection| selection.range().overlaps(&offset_range))
 8653                        {
 8654                            next_selected_range = Some(offset_range);
 8655                            break;
 8656                        }
 8657                    }
 8658                }
 8659
 8660                if let Some(next_selected_range) = next_selected_range {
 8661                    select_next_match_ranges(
 8662                        self,
 8663                        next_selected_range,
 8664                        replace_newest,
 8665                        autoscroll,
 8666                        cx,
 8667                    );
 8668                } else {
 8669                    select_next_state.done = true;
 8670                }
 8671            }
 8672
 8673            self.select_next_state = Some(select_next_state);
 8674        } else {
 8675            let mut only_carets = true;
 8676            let mut same_text_selected = true;
 8677            let mut selected_text = None;
 8678
 8679            let mut selections_iter = selections.iter().peekable();
 8680            while let Some(selection) = selections_iter.next() {
 8681                if selection.start != selection.end {
 8682                    only_carets = false;
 8683                }
 8684
 8685                if same_text_selected {
 8686                    if selected_text.is_none() {
 8687                        selected_text =
 8688                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8689                    }
 8690
 8691                    if let Some(next_selection) = selections_iter.peek() {
 8692                        if next_selection.range().len() == selection.range().len() {
 8693                            let next_selected_text = buffer
 8694                                .text_for_range(next_selection.range())
 8695                                .collect::<String>();
 8696                            if Some(next_selected_text) != selected_text {
 8697                                same_text_selected = false;
 8698                                selected_text = None;
 8699                            }
 8700                        } else {
 8701                            same_text_selected = false;
 8702                            selected_text = None;
 8703                        }
 8704                    }
 8705                }
 8706            }
 8707
 8708            if only_carets {
 8709                for selection in &mut selections {
 8710                    let word_range = movement::surrounding_word(
 8711                        display_map,
 8712                        selection.start.to_display_point(display_map),
 8713                    );
 8714                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 8715                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 8716                    selection.goal = SelectionGoal::None;
 8717                    selection.reversed = false;
 8718                    select_next_match_ranges(
 8719                        self,
 8720                        selection.start..selection.end,
 8721                        replace_newest,
 8722                        autoscroll,
 8723                        cx,
 8724                    );
 8725                }
 8726
 8727                if selections.len() == 1 {
 8728                    let selection = selections
 8729                        .last()
 8730                        .expect("ensured that there's only one selection");
 8731                    let query = buffer
 8732                        .text_for_range(selection.start..selection.end)
 8733                        .collect::<String>();
 8734                    let is_empty = query.is_empty();
 8735                    let select_state = SelectNextState {
 8736                        query: AhoCorasick::new(&[query])?,
 8737                        wordwise: true,
 8738                        done: is_empty,
 8739                    };
 8740                    self.select_next_state = Some(select_state);
 8741                } else {
 8742                    self.select_next_state = None;
 8743                }
 8744            } else if let Some(selected_text) = selected_text {
 8745                self.select_next_state = Some(SelectNextState {
 8746                    query: AhoCorasick::new(&[selected_text])?,
 8747                    wordwise: false,
 8748                    done: false,
 8749                });
 8750                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 8751            }
 8752        }
 8753        Ok(())
 8754    }
 8755
 8756    pub fn select_all_matches(
 8757        &mut self,
 8758        _action: &SelectAllMatches,
 8759        cx: &mut ViewContext<Self>,
 8760    ) -> Result<()> {
 8761        self.push_to_selection_history();
 8762        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8763
 8764        self.select_next_match_internal(&display_map, false, None, cx)?;
 8765        let Some(select_next_state) = self.select_next_state.as_mut() else {
 8766            return Ok(());
 8767        };
 8768        if select_next_state.done {
 8769            return Ok(());
 8770        }
 8771
 8772        let mut new_selections = self.selections.all::<usize>(cx);
 8773
 8774        let buffer = &display_map.buffer_snapshot;
 8775        let query_matches = select_next_state
 8776            .query
 8777            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 8778
 8779        for query_match in query_matches {
 8780            let query_match = query_match.unwrap(); // can only fail due to I/O
 8781            let offset_range = query_match.start()..query_match.end();
 8782            let display_range = offset_range.start.to_display_point(&display_map)
 8783                ..offset_range.end.to_display_point(&display_map);
 8784
 8785            if !select_next_state.wordwise
 8786                || (!movement::is_inside_word(&display_map, display_range.start)
 8787                    && !movement::is_inside_word(&display_map, display_range.end))
 8788            {
 8789                self.selections.change_with(cx, |selections| {
 8790                    new_selections.push(Selection {
 8791                        id: selections.new_selection_id(),
 8792                        start: offset_range.start,
 8793                        end: offset_range.end,
 8794                        reversed: false,
 8795                        goal: SelectionGoal::None,
 8796                    });
 8797                });
 8798            }
 8799        }
 8800
 8801        new_selections.sort_by_key(|selection| selection.start);
 8802        let mut ix = 0;
 8803        while ix + 1 < new_selections.len() {
 8804            let current_selection = &new_selections[ix];
 8805            let next_selection = &new_selections[ix + 1];
 8806            if current_selection.range().overlaps(&next_selection.range()) {
 8807                if current_selection.id < next_selection.id {
 8808                    new_selections.remove(ix + 1);
 8809                } else {
 8810                    new_selections.remove(ix);
 8811                }
 8812            } else {
 8813                ix += 1;
 8814            }
 8815        }
 8816
 8817        select_next_state.done = true;
 8818        self.unfold_ranges(
 8819            &new_selections
 8820                .iter()
 8821                .map(|selection| selection.range())
 8822                .collect::<Vec<_>>(),
 8823            false,
 8824            false,
 8825            cx,
 8826        );
 8827        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 8828            selections.select(new_selections)
 8829        });
 8830
 8831        Ok(())
 8832    }
 8833
 8834    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 8835        self.push_to_selection_history();
 8836        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8837        self.select_next_match_internal(
 8838            &display_map,
 8839            action.replace_newest,
 8840            Some(Autoscroll::newest()),
 8841            cx,
 8842        )?;
 8843        Ok(())
 8844    }
 8845
 8846    pub fn select_previous(
 8847        &mut self,
 8848        action: &SelectPrevious,
 8849        cx: &mut ViewContext<Self>,
 8850    ) -> Result<()> {
 8851        self.push_to_selection_history();
 8852        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8853        let buffer = &display_map.buffer_snapshot;
 8854        let mut selections = self.selections.all::<usize>(cx);
 8855        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8856            let query = &select_prev_state.query;
 8857            if !select_prev_state.done {
 8858                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8859                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8860                let mut next_selected_range = None;
 8861                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8862                let bytes_before_last_selection =
 8863                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8864                let bytes_after_first_selection =
 8865                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8866                let query_matches = query
 8867                    .stream_find_iter(bytes_before_last_selection)
 8868                    .map(|result| (last_selection.start, result))
 8869                    .chain(
 8870                        query
 8871                            .stream_find_iter(bytes_after_first_selection)
 8872                            .map(|result| (buffer.len(), result)),
 8873                    );
 8874                for (end_offset, query_match) in query_matches {
 8875                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8876                    let offset_range =
 8877                        end_offset - query_match.end()..end_offset - query_match.start();
 8878                    let display_range = offset_range.start.to_display_point(&display_map)
 8879                        ..offset_range.end.to_display_point(&display_map);
 8880
 8881                    if !select_prev_state.wordwise
 8882                        || (!movement::is_inside_word(&display_map, display_range.start)
 8883                            && !movement::is_inside_word(&display_map, display_range.end))
 8884                    {
 8885                        next_selected_range = Some(offset_range);
 8886                        break;
 8887                    }
 8888                }
 8889
 8890                if let Some(next_selected_range) = next_selected_range {
 8891                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 8892                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8893                        if action.replace_newest {
 8894                            s.delete(s.newest_anchor().id);
 8895                        }
 8896                        s.insert_range(next_selected_range);
 8897                    });
 8898                } else {
 8899                    select_prev_state.done = true;
 8900                }
 8901            }
 8902
 8903            self.select_prev_state = Some(select_prev_state);
 8904        } else {
 8905            let mut only_carets = true;
 8906            let mut same_text_selected = true;
 8907            let mut selected_text = None;
 8908
 8909            let mut selections_iter = selections.iter().peekable();
 8910            while let Some(selection) = selections_iter.next() {
 8911                if selection.start != selection.end {
 8912                    only_carets = false;
 8913                }
 8914
 8915                if same_text_selected {
 8916                    if selected_text.is_none() {
 8917                        selected_text =
 8918                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8919                    }
 8920
 8921                    if let Some(next_selection) = selections_iter.peek() {
 8922                        if next_selection.range().len() == selection.range().len() {
 8923                            let next_selected_text = buffer
 8924                                .text_for_range(next_selection.range())
 8925                                .collect::<String>();
 8926                            if Some(next_selected_text) != selected_text {
 8927                                same_text_selected = false;
 8928                                selected_text = None;
 8929                            }
 8930                        } else {
 8931                            same_text_selected = false;
 8932                            selected_text = None;
 8933                        }
 8934                    }
 8935                }
 8936            }
 8937
 8938            if only_carets {
 8939                for selection in &mut selections {
 8940                    let word_range = movement::surrounding_word(
 8941                        &display_map,
 8942                        selection.start.to_display_point(&display_map),
 8943                    );
 8944                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8945                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8946                    selection.goal = SelectionGoal::None;
 8947                    selection.reversed = false;
 8948                }
 8949                if selections.len() == 1 {
 8950                    let selection = selections
 8951                        .last()
 8952                        .expect("ensured that there's only one selection");
 8953                    let query = buffer
 8954                        .text_for_range(selection.start..selection.end)
 8955                        .collect::<String>();
 8956                    let is_empty = query.is_empty();
 8957                    let select_state = SelectNextState {
 8958                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8959                        wordwise: true,
 8960                        done: is_empty,
 8961                    };
 8962                    self.select_prev_state = Some(select_state);
 8963                } else {
 8964                    self.select_prev_state = None;
 8965                }
 8966
 8967                self.unfold_ranges(
 8968                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8969                    false,
 8970                    true,
 8971                    cx,
 8972                );
 8973                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8974                    s.select(selections);
 8975                });
 8976            } else if let Some(selected_text) = selected_text {
 8977                self.select_prev_state = Some(SelectNextState {
 8978                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8979                    wordwise: false,
 8980                    done: false,
 8981                });
 8982                self.select_previous(action, cx)?;
 8983            }
 8984        }
 8985        Ok(())
 8986    }
 8987
 8988    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 8989        if self.read_only(cx) {
 8990            return;
 8991        }
 8992        let text_layout_details = &self.text_layout_details(cx);
 8993        self.transact(cx, |this, cx| {
 8994            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8995            let mut edits = Vec::new();
 8996            let mut selection_edit_ranges = Vec::new();
 8997            let mut last_toggled_row = None;
 8998            let snapshot = this.buffer.read(cx).read(cx);
 8999            let empty_str: Arc<str> = Arc::default();
 9000            let mut suffixes_inserted = Vec::new();
 9001            let ignore_indent = action.ignore_indent;
 9002
 9003            fn comment_prefix_range(
 9004                snapshot: &MultiBufferSnapshot,
 9005                row: MultiBufferRow,
 9006                comment_prefix: &str,
 9007                comment_prefix_whitespace: &str,
 9008                ignore_indent: bool,
 9009            ) -> Range<Point> {
 9010                let indent_size = if ignore_indent {
 9011                    0
 9012                } else {
 9013                    snapshot.indent_size_for_line(row).len
 9014                };
 9015
 9016                let start = Point::new(row.0, indent_size);
 9017
 9018                let mut line_bytes = snapshot
 9019                    .bytes_in_range(start..snapshot.max_point())
 9020                    .flatten()
 9021                    .copied();
 9022
 9023                // If this line currently begins with the line comment prefix, then record
 9024                // the range containing the prefix.
 9025                if line_bytes
 9026                    .by_ref()
 9027                    .take(comment_prefix.len())
 9028                    .eq(comment_prefix.bytes())
 9029                {
 9030                    // Include any whitespace that matches the comment prefix.
 9031                    let matching_whitespace_len = line_bytes
 9032                        .zip(comment_prefix_whitespace.bytes())
 9033                        .take_while(|(a, b)| a == b)
 9034                        .count() as u32;
 9035                    let end = Point::new(
 9036                        start.row,
 9037                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 9038                    );
 9039                    start..end
 9040                } else {
 9041                    start..start
 9042                }
 9043            }
 9044
 9045            fn comment_suffix_range(
 9046                snapshot: &MultiBufferSnapshot,
 9047                row: MultiBufferRow,
 9048                comment_suffix: &str,
 9049                comment_suffix_has_leading_space: bool,
 9050            ) -> Range<Point> {
 9051                let end = Point::new(row.0, snapshot.line_len(row));
 9052                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 9053
 9054                let mut line_end_bytes = snapshot
 9055                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 9056                    .flatten()
 9057                    .copied();
 9058
 9059                let leading_space_len = if suffix_start_column > 0
 9060                    && line_end_bytes.next() == Some(b' ')
 9061                    && comment_suffix_has_leading_space
 9062                {
 9063                    1
 9064                } else {
 9065                    0
 9066                };
 9067
 9068                // If this line currently begins with the line comment prefix, then record
 9069                // the range containing the prefix.
 9070                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 9071                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 9072                    start..end
 9073                } else {
 9074                    end..end
 9075                }
 9076            }
 9077
 9078            // TODO: Handle selections that cross excerpts
 9079            for selection in &mut selections {
 9080                let start_column = snapshot
 9081                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 9082                    .len;
 9083                let language = if let Some(language) =
 9084                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 9085                {
 9086                    language
 9087                } else {
 9088                    continue;
 9089                };
 9090
 9091                selection_edit_ranges.clear();
 9092
 9093                // If multiple selections contain a given row, avoid processing that
 9094                // row more than once.
 9095                let mut start_row = MultiBufferRow(selection.start.row);
 9096                if last_toggled_row == Some(start_row) {
 9097                    start_row = start_row.next_row();
 9098                }
 9099                let end_row =
 9100                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 9101                        MultiBufferRow(selection.end.row - 1)
 9102                    } else {
 9103                        MultiBufferRow(selection.end.row)
 9104                    };
 9105                last_toggled_row = Some(end_row);
 9106
 9107                if start_row > end_row {
 9108                    continue;
 9109                }
 9110
 9111                // If the language has line comments, toggle those.
 9112                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 9113
 9114                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 9115                if ignore_indent {
 9116                    full_comment_prefixes = full_comment_prefixes
 9117                        .into_iter()
 9118                        .map(|s| Arc::from(s.trim_end()))
 9119                        .collect();
 9120                }
 9121
 9122                if !full_comment_prefixes.is_empty() {
 9123                    let first_prefix = full_comment_prefixes
 9124                        .first()
 9125                        .expect("prefixes is non-empty");
 9126                    let prefix_trimmed_lengths = full_comment_prefixes
 9127                        .iter()
 9128                        .map(|p| p.trim_end_matches(' ').len())
 9129                        .collect::<SmallVec<[usize; 4]>>();
 9130
 9131                    let mut all_selection_lines_are_comments = true;
 9132
 9133                    for row in start_row.0..=end_row.0 {
 9134                        let row = MultiBufferRow(row);
 9135                        if start_row < end_row && snapshot.is_line_blank(row) {
 9136                            continue;
 9137                        }
 9138
 9139                        let prefix_range = full_comment_prefixes
 9140                            .iter()
 9141                            .zip(prefix_trimmed_lengths.iter().copied())
 9142                            .map(|(prefix, trimmed_prefix_len)| {
 9143                                comment_prefix_range(
 9144                                    snapshot.deref(),
 9145                                    row,
 9146                                    &prefix[..trimmed_prefix_len],
 9147                                    &prefix[trimmed_prefix_len..],
 9148                                    ignore_indent,
 9149                                )
 9150                            })
 9151                            .max_by_key(|range| range.end.column - range.start.column)
 9152                            .expect("prefixes is non-empty");
 9153
 9154                        if prefix_range.is_empty() {
 9155                            all_selection_lines_are_comments = false;
 9156                        }
 9157
 9158                        selection_edit_ranges.push(prefix_range);
 9159                    }
 9160
 9161                    if all_selection_lines_are_comments {
 9162                        edits.extend(
 9163                            selection_edit_ranges
 9164                                .iter()
 9165                                .cloned()
 9166                                .map(|range| (range, empty_str.clone())),
 9167                        );
 9168                    } else {
 9169                        let min_column = selection_edit_ranges
 9170                            .iter()
 9171                            .map(|range| range.start.column)
 9172                            .min()
 9173                            .unwrap_or(0);
 9174                        edits.extend(selection_edit_ranges.iter().map(|range| {
 9175                            let position = Point::new(range.start.row, min_column);
 9176                            (position..position, first_prefix.clone())
 9177                        }));
 9178                    }
 9179                } else if let Some((full_comment_prefix, comment_suffix)) =
 9180                    language.block_comment_delimiters()
 9181                {
 9182                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 9183                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 9184                    let prefix_range = comment_prefix_range(
 9185                        snapshot.deref(),
 9186                        start_row,
 9187                        comment_prefix,
 9188                        comment_prefix_whitespace,
 9189                        ignore_indent,
 9190                    );
 9191                    let suffix_range = comment_suffix_range(
 9192                        snapshot.deref(),
 9193                        end_row,
 9194                        comment_suffix.trim_start_matches(' '),
 9195                        comment_suffix.starts_with(' '),
 9196                    );
 9197
 9198                    if prefix_range.is_empty() || suffix_range.is_empty() {
 9199                        edits.push((
 9200                            prefix_range.start..prefix_range.start,
 9201                            full_comment_prefix.clone(),
 9202                        ));
 9203                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 9204                        suffixes_inserted.push((end_row, comment_suffix.len()));
 9205                    } else {
 9206                        edits.push((prefix_range, empty_str.clone()));
 9207                        edits.push((suffix_range, empty_str.clone()));
 9208                    }
 9209                } else {
 9210                    continue;
 9211                }
 9212            }
 9213
 9214            drop(snapshot);
 9215            this.buffer.update(cx, |buffer, cx| {
 9216                buffer.edit(edits, None, cx);
 9217            });
 9218
 9219            // Adjust selections so that they end before any comment suffixes that
 9220            // were inserted.
 9221            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 9222            let mut selections = this.selections.all::<Point>(cx);
 9223            let snapshot = this.buffer.read(cx).read(cx);
 9224            for selection in &mut selections {
 9225                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 9226                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 9227                        Ordering::Less => {
 9228                            suffixes_inserted.next();
 9229                            continue;
 9230                        }
 9231                        Ordering::Greater => break,
 9232                        Ordering::Equal => {
 9233                            if selection.end.column == snapshot.line_len(row) {
 9234                                if selection.is_empty() {
 9235                                    selection.start.column -= suffix_len as u32;
 9236                                }
 9237                                selection.end.column -= suffix_len as u32;
 9238                            }
 9239                            break;
 9240                        }
 9241                    }
 9242                }
 9243            }
 9244
 9245            drop(snapshot);
 9246            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 9247
 9248            let selections = this.selections.all::<Point>(cx);
 9249            let selections_on_single_row = selections.windows(2).all(|selections| {
 9250                selections[0].start.row == selections[1].start.row
 9251                    && selections[0].end.row == selections[1].end.row
 9252                    && selections[0].start.row == selections[0].end.row
 9253            });
 9254            let selections_selecting = selections
 9255                .iter()
 9256                .any(|selection| selection.start != selection.end);
 9257            let advance_downwards = action.advance_downwards
 9258                && selections_on_single_row
 9259                && !selections_selecting
 9260                && !matches!(this.mode, EditorMode::SingleLine { .. });
 9261
 9262            if advance_downwards {
 9263                let snapshot = this.buffer.read(cx).snapshot(cx);
 9264
 9265                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9266                    s.move_cursors_with(|display_snapshot, display_point, _| {
 9267                        let mut point = display_point.to_point(display_snapshot);
 9268                        point.row += 1;
 9269                        point = snapshot.clip_point(point, Bias::Left);
 9270                        let display_point = point.to_display_point(display_snapshot);
 9271                        let goal = SelectionGoal::HorizontalPosition(
 9272                            display_snapshot
 9273                                .x_for_display_point(display_point, text_layout_details)
 9274                                .into(),
 9275                        );
 9276                        (display_point, goal)
 9277                    })
 9278                });
 9279            }
 9280        });
 9281    }
 9282
 9283    pub fn select_enclosing_symbol(
 9284        &mut self,
 9285        _: &SelectEnclosingSymbol,
 9286        cx: &mut ViewContext<Self>,
 9287    ) {
 9288        let buffer = self.buffer.read(cx).snapshot(cx);
 9289        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9290
 9291        fn update_selection(
 9292            selection: &Selection<usize>,
 9293            buffer_snap: &MultiBufferSnapshot,
 9294        ) -> Option<Selection<usize>> {
 9295            let cursor = selection.head();
 9296            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 9297            for symbol in symbols.iter().rev() {
 9298                let start = symbol.range.start.to_offset(buffer_snap);
 9299                let end = symbol.range.end.to_offset(buffer_snap);
 9300                let new_range = start..end;
 9301                if start < selection.start || end > selection.end {
 9302                    return Some(Selection {
 9303                        id: selection.id,
 9304                        start: new_range.start,
 9305                        end: new_range.end,
 9306                        goal: SelectionGoal::None,
 9307                        reversed: selection.reversed,
 9308                    });
 9309                }
 9310            }
 9311            None
 9312        }
 9313
 9314        let mut selected_larger_symbol = false;
 9315        let new_selections = old_selections
 9316            .iter()
 9317            .map(|selection| match update_selection(selection, &buffer) {
 9318                Some(new_selection) => {
 9319                    if new_selection.range() != selection.range() {
 9320                        selected_larger_symbol = true;
 9321                    }
 9322                    new_selection
 9323                }
 9324                None => selection.clone(),
 9325            })
 9326            .collect::<Vec<_>>();
 9327
 9328        if selected_larger_symbol {
 9329            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9330                s.select(new_selections);
 9331            });
 9332        }
 9333    }
 9334
 9335    pub fn select_larger_syntax_node(
 9336        &mut self,
 9337        _: &SelectLargerSyntaxNode,
 9338        cx: &mut ViewContext<Self>,
 9339    ) {
 9340        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9341        let buffer = self.buffer.read(cx).snapshot(cx);
 9342        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9343
 9344        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9345        let mut selected_larger_node = false;
 9346        let new_selections = old_selections
 9347            .iter()
 9348            .map(|selection| {
 9349                let old_range = selection.start..selection.end;
 9350                let mut new_range = old_range.clone();
 9351                while let Some(containing_range) =
 9352                    buffer.range_for_syntax_ancestor(new_range.clone())
 9353                {
 9354                    new_range = containing_range;
 9355                    if !display_map.intersects_fold(new_range.start)
 9356                        && !display_map.intersects_fold(new_range.end)
 9357                    {
 9358                        break;
 9359                    }
 9360                }
 9361
 9362                selected_larger_node |= new_range != old_range;
 9363                Selection {
 9364                    id: selection.id,
 9365                    start: new_range.start,
 9366                    end: new_range.end,
 9367                    goal: SelectionGoal::None,
 9368                    reversed: selection.reversed,
 9369                }
 9370            })
 9371            .collect::<Vec<_>>();
 9372
 9373        if selected_larger_node {
 9374            stack.push(old_selections);
 9375            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9376                s.select(new_selections);
 9377            });
 9378        }
 9379        self.select_larger_syntax_node_stack = stack;
 9380    }
 9381
 9382    pub fn select_smaller_syntax_node(
 9383        &mut self,
 9384        _: &SelectSmallerSyntaxNode,
 9385        cx: &mut ViewContext<Self>,
 9386    ) {
 9387        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9388        if let Some(selections) = stack.pop() {
 9389            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9390                s.select(selections.to_vec());
 9391            });
 9392        }
 9393        self.select_larger_syntax_node_stack = stack;
 9394    }
 9395
 9396    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 9397        if !EditorSettings::get_global(cx).gutter.runnables {
 9398            self.clear_tasks();
 9399            return Task::ready(());
 9400        }
 9401        let project = self.project.as_ref().map(Model::downgrade);
 9402        cx.spawn(|this, mut cx| async move {
 9403            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
 9404            let Some(project) = project.and_then(|p| p.upgrade()) else {
 9405                return;
 9406            };
 9407            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 9408                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 9409            }) else {
 9410                return;
 9411            };
 9412
 9413            let hide_runnables = project
 9414                .update(&mut cx, |project, cx| {
 9415                    // Do not display any test indicators in non-dev server remote projects.
 9416                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 9417                })
 9418                .unwrap_or(true);
 9419            if hide_runnables {
 9420                return;
 9421            }
 9422            let new_rows =
 9423                cx.background_executor()
 9424                    .spawn({
 9425                        let snapshot = display_snapshot.clone();
 9426                        async move {
 9427                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 9428                        }
 9429                    })
 9430                    .await;
 9431            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 9432
 9433            this.update(&mut cx, |this, _| {
 9434                this.clear_tasks();
 9435                for (key, value) in rows {
 9436                    this.insert_tasks(key, value);
 9437                }
 9438            })
 9439            .ok();
 9440        })
 9441    }
 9442    fn fetch_runnable_ranges(
 9443        snapshot: &DisplaySnapshot,
 9444        range: Range<Anchor>,
 9445    ) -> Vec<language::RunnableRange> {
 9446        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 9447    }
 9448
 9449    fn runnable_rows(
 9450        project: Model<Project>,
 9451        snapshot: DisplaySnapshot,
 9452        runnable_ranges: Vec<RunnableRange>,
 9453        mut cx: AsyncWindowContext,
 9454    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 9455        runnable_ranges
 9456            .into_iter()
 9457            .filter_map(|mut runnable| {
 9458                let tasks = cx
 9459                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 9460                    .ok()?;
 9461                if tasks.is_empty() {
 9462                    return None;
 9463                }
 9464
 9465                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 9466
 9467                let row = snapshot
 9468                    .buffer_snapshot
 9469                    .buffer_line_for_row(MultiBufferRow(point.row))?
 9470                    .1
 9471                    .start
 9472                    .row;
 9473
 9474                let context_range =
 9475                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 9476                Some((
 9477                    (runnable.buffer_id, row),
 9478                    RunnableTasks {
 9479                        templates: tasks,
 9480                        offset: MultiBufferOffset(runnable.run_range.start),
 9481                        context_range,
 9482                        column: point.column,
 9483                        extra_variables: runnable.extra_captures,
 9484                    },
 9485                ))
 9486            })
 9487            .collect()
 9488    }
 9489
 9490    fn templates_with_tags(
 9491        project: &Model<Project>,
 9492        runnable: &mut Runnable,
 9493        cx: &WindowContext<'_>,
 9494    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 9495        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 9496            let (worktree_id, file) = project
 9497                .buffer_for_id(runnable.buffer, cx)
 9498                .and_then(|buffer| buffer.read(cx).file())
 9499                .map(|file| (file.worktree_id(cx), file.clone()))
 9500                .unzip();
 9501
 9502            (
 9503                project.task_store().read(cx).task_inventory().cloned(),
 9504                worktree_id,
 9505                file,
 9506            )
 9507        });
 9508
 9509        let tags = mem::take(&mut runnable.tags);
 9510        let mut tags: Vec<_> = tags
 9511            .into_iter()
 9512            .flat_map(|tag| {
 9513                let tag = tag.0.clone();
 9514                inventory
 9515                    .as_ref()
 9516                    .into_iter()
 9517                    .flat_map(|inventory| {
 9518                        inventory.read(cx).list_tasks(
 9519                            file.clone(),
 9520                            Some(runnable.language.clone()),
 9521                            worktree_id,
 9522                            cx,
 9523                        )
 9524                    })
 9525                    .filter(move |(_, template)| {
 9526                        template.tags.iter().any(|source_tag| source_tag == &tag)
 9527                    })
 9528            })
 9529            .sorted_by_key(|(kind, _)| kind.to_owned())
 9530            .collect();
 9531        if let Some((leading_tag_source, _)) = tags.first() {
 9532            // Strongest source wins; if we have worktree tag binding, prefer that to
 9533            // global and language bindings;
 9534            // if we have a global binding, prefer that to language binding.
 9535            let first_mismatch = tags
 9536                .iter()
 9537                .position(|(tag_source, _)| tag_source != leading_tag_source);
 9538            if let Some(index) = first_mismatch {
 9539                tags.truncate(index);
 9540            }
 9541        }
 9542
 9543        tags
 9544    }
 9545
 9546    pub fn move_to_enclosing_bracket(
 9547        &mut self,
 9548        _: &MoveToEnclosingBracket,
 9549        cx: &mut ViewContext<Self>,
 9550    ) {
 9551        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9552            s.move_offsets_with(|snapshot, selection| {
 9553                let Some(enclosing_bracket_ranges) =
 9554                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 9555                else {
 9556                    return;
 9557                };
 9558
 9559                let mut best_length = usize::MAX;
 9560                let mut best_inside = false;
 9561                let mut best_in_bracket_range = false;
 9562                let mut best_destination = None;
 9563                for (open, close) in enclosing_bracket_ranges {
 9564                    let close = close.to_inclusive();
 9565                    let length = close.end() - open.start;
 9566                    let inside = selection.start >= open.end && selection.end <= *close.start();
 9567                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 9568                        || close.contains(&selection.head());
 9569
 9570                    // If best is next to a bracket and current isn't, skip
 9571                    if !in_bracket_range && best_in_bracket_range {
 9572                        continue;
 9573                    }
 9574
 9575                    // Prefer smaller lengths unless best is inside and current isn't
 9576                    if length > best_length && (best_inside || !inside) {
 9577                        continue;
 9578                    }
 9579
 9580                    best_length = length;
 9581                    best_inside = inside;
 9582                    best_in_bracket_range = in_bracket_range;
 9583                    best_destination = Some(
 9584                        if close.contains(&selection.start) && close.contains(&selection.end) {
 9585                            if inside {
 9586                                open.end
 9587                            } else {
 9588                                open.start
 9589                            }
 9590                        } else if inside {
 9591                            *close.start()
 9592                        } else {
 9593                            *close.end()
 9594                        },
 9595                    );
 9596                }
 9597
 9598                if let Some(destination) = best_destination {
 9599                    selection.collapse_to(destination, SelectionGoal::None);
 9600                }
 9601            })
 9602        });
 9603    }
 9604
 9605    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 9606        self.end_selection(cx);
 9607        self.selection_history.mode = SelectionHistoryMode::Undoing;
 9608        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 9609            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9610            self.select_next_state = entry.select_next_state;
 9611            self.select_prev_state = entry.select_prev_state;
 9612            self.add_selections_state = entry.add_selections_state;
 9613            self.request_autoscroll(Autoscroll::newest(), cx);
 9614        }
 9615        self.selection_history.mode = SelectionHistoryMode::Normal;
 9616    }
 9617
 9618    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 9619        self.end_selection(cx);
 9620        self.selection_history.mode = SelectionHistoryMode::Redoing;
 9621        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 9622            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9623            self.select_next_state = entry.select_next_state;
 9624            self.select_prev_state = entry.select_prev_state;
 9625            self.add_selections_state = entry.add_selections_state;
 9626            self.request_autoscroll(Autoscroll::newest(), cx);
 9627        }
 9628        self.selection_history.mode = SelectionHistoryMode::Normal;
 9629    }
 9630
 9631    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 9632        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 9633    }
 9634
 9635    pub fn expand_excerpts_down(
 9636        &mut self,
 9637        action: &ExpandExcerptsDown,
 9638        cx: &mut ViewContext<Self>,
 9639    ) {
 9640        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 9641    }
 9642
 9643    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 9644        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 9645    }
 9646
 9647    pub fn expand_excerpts_for_direction(
 9648        &mut self,
 9649        lines: u32,
 9650        direction: ExpandExcerptDirection,
 9651        cx: &mut ViewContext<Self>,
 9652    ) {
 9653        let selections = self.selections.disjoint_anchors();
 9654
 9655        let lines = if lines == 0 {
 9656            EditorSettings::get_global(cx).expand_excerpt_lines
 9657        } else {
 9658            lines
 9659        };
 9660
 9661        self.buffer.update(cx, |buffer, cx| {
 9662            buffer.expand_excerpts(
 9663                selections
 9664                    .iter()
 9665                    .map(|selection| selection.head().excerpt_id)
 9666                    .dedup(),
 9667                lines,
 9668                direction,
 9669                cx,
 9670            )
 9671        })
 9672    }
 9673
 9674    pub fn expand_excerpt(
 9675        &mut self,
 9676        excerpt: ExcerptId,
 9677        direction: ExpandExcerptDirection,
 9678        cx: &mut ViewContext<Self>,
 9679    ) {
 9680        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 9681        self.buffer.update(cx, |buffer, cx| {
 9682            buffer.expand_excerpts([excerpt], lines, direction, cx)
 9683        })
 9684    }
 9685
 9686    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 9687        self.go_to_diagnostic_impl(Direction::Next, cx)
 9688    }
 9689
 9690    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 9691        self.go_to_diagnostic_impl(Direction::Prev, cx)
 9692    }
 9693
 9694    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 9695        let buffer = self.buffer.read(cx).snapshot(cx);
 9696        let selection = self.selections.newest::<usize>(cx);
 9697
 9698        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 9699        if direction == Direction::Next {
 9700            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 9701                let (group_id, jump_to) = popover.activation_info();
 9702                if self.activate_diagnostics(group_id, cx) {
 9703                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9704                        let mut new_selection = s.newest_anchor().clone();
 9705                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 9706                        s.select_anchors(vec![new_selection.clone()]);
 9707                    });
 9708                }
 9709                return;
 9710            }
 9711        }
 9712
 9713        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 9714            active_diagnostics
 9715                .primary_range
 9716                .to_offset(&buffer)
 9717                .to_inclusive()
 9718        });
 9719        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 9720            if active_primary_range.contains(&selection.head()) {
 9721                *active_primary_range.start()
 9722            } else {
 9723                selection.head()
 9724            }
 9725        } else {
 9726            selection.head()
 9727        };
 9728        let snapshot = self.snapshot(cx);
 9729        loop {
 9730            let diagnostics = if direction == Direction::Prev {
 9731                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 9732            } else {
 9733                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 9734            }
 9735            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 9736            let group = diagnostics
 9737                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 9738                // be sorted in a stable way
 9739                // skip until we are at current active diagnostic, if it exists
 9740                .skip_while(|entry| {
 9741                    (match direction {
 9742                        Direction::Prev => entry.range.start >= search_start,
 9743                        Direction::Next => entry.range.start <= search_start,
 9744                    }) && self
 9745                        .active_diagnostics
 9746                        .as_ref()
 9747                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 9748                })
 9749                .find_map(|entry| {
 9750                    if entry.diagnostic.is_primary
 9751                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 9752                        && !entry.range.is_empty()
 9753                        // if we match with the active diagnostic, skip it
 9754                        && Some(entry.diagnostic.group_id)
 9755                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 9756                    {
 9757                        Some((entry.range, entry.diagnostic.group_id))
 9758                    } else {
 9759                        None
 9760                    }
 9761                });
 9762
 9763            if let Some((primary_range, group_id)) = group {
 9764                if self.activate_diagnostics(group_id, cx) {
 9765                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9766                        s.select(vec![Selection {
 9767                            id: selection.id,
 9768                            start: primary_range.start,
 9769                            end: primary_range.start,
 9770                            reversed: false,
 9771                            goal: SelectionGoal::None,
 9772                        }]);
 9773                    });
 9774                }
 9775                break;
 9776            } else {
 9777                // Cycle around to the start of the buffer, potentially moving back to the start of
 9778                // the currently active diagnostic.
 9779                active_primary_range.take();
 9780                if direction == Direction::Prev {
 9781                    if search_start == buffer.len() {
 9782                        break;
 9783                    } else {
 9784                        search_start = buffer.len();
 9785                    }
 9786                } else if search_start == 0 {
 9787                    break;
 9788                } else {
 9789                    search_start = 0;
 9790                }
 9791            }
 9792        }
 9793    }
 9794
 9795    fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 9796        let snapshot = self
 9797            .display_map
 9798            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9799        let selection = self.selections.newest::<Point>(cx);
 9800        self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
 9801    }
 9802
 9803    fn go_to_hunk_after_position(
 9804        &mut self,
 9805        snapshot: &DisplaySnapshot,
 9806        position: Point,
 9807        cx: &mut ViewContext<'_, Editor>,
 9808    ) -> Option<MultiBufferDiffHunk> {
 9809        if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9810            snapshot,
 9811            position,
 9812            false,
 9813            snapshot
 9814                .buffer_snapshot
 9815                .git_diff_hunks_in_range(MultiBufferRow(position.row + 1)..MultiBufferRow::MAX),
 9816            cx,
 9817        ) {
 9818            return Some(hunk);
 9819        }
 9820
 9821        let wrapped_point = Point::zero();
 9822        self.go_to_next_hunk_in_direction(
 9823            snapshot,
 9824            wrapped_point,
 9825            true,
 9826            snapshot.buffer_snapshot.git_diff_hunks_in_range(
 9827                MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
 9828            ),
 9829            cx,
 9830        )
 9831    }
 9832
 9833    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 9834        let snapshot = self
 9835            .display_map
 9836            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9837        let selection = self.selections.newest::<Point>(cx);
 9838
 9839        self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
 9840    }
 9841
 9842    fn go_to_hunk_before_position(
 9843        &mut self,
 9844        snapshot: &DisplaySnapshot,
 9845        position: Point,
 9846        cx: &mut ViewContext<'_, Editor>,
 9847    ) -> Option<MultiBufferDiffHunk> {
 9848        if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9849            snapshot,
 9850            position,
 9851            false,
 9852            snapshot
 9853                .buffer_snapshot
 9854                .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(position.row)),
 9855            cx,
 9856        ) {
 9857            return Some(hunk);
 9858        }
 9859
 9860        let wrapped_point = snapshot.buffer_snapshot.max_point();
 9861        self.go_to_next_hunk_in_direction(
 9862            snapshot,
 9863            wrapped_point,
 9864            true,
 9865            snapshot
 9866                .buffer_snapshot
 9867                .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(wrapped_point.row)),
 9868            cx,
 9869        )
 9870    }
 9871
 9872    fn go_to_next_hunk_in_direction(
 9873        &mut self,
 9874        snapshot: &DisplaySnapshot,
 9875        initial_point: Point,
 9876        is_wrapped: bool,
 9877        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
 9878        cx: &mut ViewContext<Editor>,
 9879    ) -> Option<MultiBufferDiffHunk> {
 9880        let display_point = initial_point.to_display_point(snapshot);
 9881        let mut hunks = hunks
 9882            .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
 9883            .filter(|(display_hunk, _)| {
 9884                is_wrapped || !display_hunk.contains_display_row(display_point.row())
 9885            })
 9886            .dedup();
 9887
 9888        if let Some((display_hunk, hunk)) = hunks.next() {
 9889            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9890                let row = display_hunk.start_display_row();
 9891                let point = DisplayPoint::new(row, 0);
 9892                s.select_display_ranges([point..point]);
 9893            });
 9894
 9895            Some(hunk)
 9896        } else {
 9897            None
 9898        }
 9899    }
 9900
 9901    pub fn go_to_definition(
 9902        &mut self,
 9903        _: &GoToDefinition,
 9904        cx: &mut ViewContext<Self>,
 9905    ) -> Task<Result<Navigated>> {
 9906        let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
 9907        cx.spawn(|editor, mut cx| async move {
 9908            if definition.await? == Navigated::Yes {
 9909                return Ok(Navigated::Yes);
 9910            }
 9911            match editor.update(&mut cx, |editor, cx| {
 9912                editor.find_all_references(&FindAllReferences, cx)
 9913            })? {
 9914                Some(references) => references.await,
 9915                None => Ok(Navigated::No),
 9916            }
 9917        })
 9918    }
 9919
 9920    pub fn go_to_declaration(
 9921        &mut self,
 9922        _: &GoToDeclaration,
 9923        cx: &mut ViewContext<Self>,
 9924    ) -> Task<Result<Navigated>> {
 9925        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
 9926    }
 9927
 9928    pub fn go_to_declaration_split(
 9929        &mut self,
 9930        _: &GoToDeclaration,
 9931        cx: &mut ViewContext<Self>,
 9932    ) -> Task<Result<Navigated>> {
 9933        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
 9934    }
 9935
 9936    pub fn go_to_implementation(
 9937        &mut self,
 9938        _: &GoToImplementation,
 9939        cx: &mut ViewContext<Self>,
 9940    ) -> Task<Result<Navigated>> {
 9941        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 9942    }
 9943
 9944    pub fn go_to_implementation_split(
 9945        &mut self,
 9946        _: &GoToImplementationSplit,
 9947        cx: &mut ViewContext<Self>,
 9948    ) -> Task<Result<Navigated>> {
 9949        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 9950    }
 9951
 9952    pub fn go_to_type_definition(
 9953        &mut self,
 9954        _: &GoToTypeDefinition,
 9955        cx: &mut ViewContext<Self>,
 9956    ) -> Task<Result<Navigated>> {
 9957        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 9958    }
 9959
 9960    pub fn go_to_definition_split(
 9961        &mut self,
 9962        _: &GoToDefinitionSplit,
 9963        cx: &mut ViewContext<Self>,
 9964    ) -> Task<Result<Navigated>> {
 9965        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 9966    }
 9967
 9968    pub fn go_to_type_definition_split(
 9969        &mut self,
 9970        _: &GoToTypeDefinitionSplit,
 9971        cx: &mut ViewContext<Self>,
 9972    ) -> Task<Result<Navigated>> {
 9973        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 9974    }
 9975
 9976    fn go_to_definition_of_kind(
 9977        &mut self,
 9978        kind: GotoDefinitionKind,
 9979        split: bool,
 9980        cx: &mut ViewContext<Self>,
 9981    ) -> Task<Result<Navigated>> {
 9982        let Some(provider) = self.semantics_provider.clone() else {
 9983            return Task::ready(Ok(Navigated::No));
 9984        };
 9985        let head = self.selections.newest::<usize>(cx).head();
 9986        let buffer = self.buffer.read(cx);
 9987        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 9988            text_anchor
 9989        } else {
 9990            return Task::ready(Ok(Navigated::No));
 9991        };
 9992
 9993        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
 9994            return Task::ready(Ok(Navigated::No));
 9995        };
 9996
 9997        cx.spawn(|editor, mut cx| async move {
 9998            let definitions = definitions.await?;
 9999            let navigated = editor
10000                .update(&mut cx, |editor, cx| {
10001                    editor.navigate_to_hover_links(
10002                        Some(kind),
10003                        definitions
10004                            .into_iter()
10005                            .filter(|location| {
10006                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10007                            })
10008                            .map(HoverLink::Text)
10009                            .collect::<Vec<_>>(),
10010                        split,
10011                        cx,
10012                    )
10013                })?
10014                .await?;
10015            anyhow::Ok(navigated)
10016        })
10017    }
10018
10019    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
10020        let position = self.selections.newest_anchor().head();
10021        let Some((buffer, buffer_position)) =
10022            self.buffer.read(cx).text_anchor_for_position(position, cx)
10023        else {
10024            return;
10025        };
10026
10027        cx.spawn(|editor, mut cx| async move {
10028            if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
10029                editor.update(&mut cx, |_, cx| {
10030                    cx.open_url(&url);
10031                })
10032            } else {
10033                Ok(())
10034            }
10035        })
10036        .detach();
10037    }
10038
10039    pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
10040        let Some(workspace) = self.workspace() else {
10041            return;
10042        };
10043
10044        let position = self.selections.newest_anchor().head();
10045
10046        let Some((buffer, buffer_position)) =
10047            self.buffer.read(cx).text_anchor_for_position(position, cx)
10048        else {
10049            return;
10050        };
10051
10052        let project = self.project.clone();
10053
10054        cx.spawn(|_, mut cx| async move {
10055            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10056
10057            if let Some((_, path)) = result {
10058                workspace
10059                    .update(&mut cx, |workspace, cx| {
10060                        workspace.open_resolved_path(path, cx)
10061                    })?
10062                    .await?;
10063            }
10064            anyhow::Ok(())
10065        })
10066        .detach();
10067    }
10068
10069    pub(crate) fn navigate_to_hover_links(
10070        &mut self,
10071        kind: Option<GotoDefinitionKind>,
10072        mut definitions: Vec<HoverLink>,
10073        split: bool,
10074        cx: &mut ViewContext<Editor>,
10075    ) -> Task<Result<Navigated>> {
10076        // If there is one definition, just open it directly
10077        if definitions.len() == 1 {
10078            let definition = definitions.pop().unwrap();
10079
10080            enum TargetTaskResult {
10081                Location(Option<Location>),
10082                AlreadyNavigated,
10083            }
10084
10085            let target_task = match definition {
10086                HoverLink::Text(link) => {
10087                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10088                }
10089                HoverLink::InlayHint(lsp_location, server_id) => {
10090                    let computation = self.compute_target_location(lsp_location, server_id, cx);
10091                    cx.background_executor().spawn(async move {
10092                        let location = computation.await?;
10093                        Ok(TargetTaskResult::Location(location))
10094                    })
10095                }
10096                HoverLink::Url(url) => {
10097                    cx.open_url(&url);
10098                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10099                }
10100                HoverLink::File(path) => {
10101                    if let Some(workspace) = self.workspace() {
10102                        cx.spawn(|_, mut cx| async move {
10103                            workspace
10104                                .update(&mut cx, |workspace, cx| {
10105                                    workspace.open_resolved_path(path, cx)
10106                                })?
10107                                .await
10108                                .map(|_| TargetTaskResult::AlreadyNavigated)
10109                        })
10110                    } else {
10111                        Task::ready(Ok(TargetTaskResult::Location(None)))
10112                    }
10113                }
10114            };
10115            cx.spawn(|editor, mut cx| async move {
10116                let target = match target_task.await.context("target resolution task")? {
10117                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10118                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
10119                    TargetTaskResult::Location(Some(target)) => target,
10120                };
10121
10122                editor.update(&mut cx, |editor, cx| {
10123                    let Some(workspace) = editor.workspace() else {
10124                        return Navigated::No;
10125                    };
10126                    let pane = workspace.read(cx).active_pane().clone();
10127
10128                    let range = target.range.to_offset(target.buffer.read(cx));
10129                    let range = editor.range_for_match(&range);
10130
10131                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10132                        let buffer = target.buffer.read(cx);
10133                        let range = check_multiline_range(buffer, range);
10134                        editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10135                            s.select_ranges([range]);
10136                        });
10137                    } else {
10138                        cx.window_context().defer(move |cx| {
10139                            let target_editor: View<Self> =
10140                                workspace.update(cx, |workspace, cx| {
10141                                    let pane = if split {
10142                                        workspace.adjacent_pane(cx)
10143                                    } else {
10144                                        workspace.active_pane().clone()
10145                                    };
10146
10147                                    workspace.open_project_item(
10148                                        pane,
10149                                        target.buffer.clone(),
10150                                        true,
10151                                        true,
10152                                        cx,
10153                                    )
10154                                });
10155                            target_editor.update(cx, |target_editor, cx| {
10156                                // When selecting a definition in a different buffer, disable the nav history
10157                                // to avoid creating a history entry at the previous cursor location.
10158                                pane.update(cx, |pane, _| pane.disable_history());
10159                                let buffer = target.buffer.read(cx);
10160                                let range = check_multiline_range(buffer, range);
10161                                target_editor.change_selections(
10162                                    Some(Autoscroll::focused()),
10163                                    cx,
10164                                    |s| {
10165                                        s.select_ranges([range]);
10166                                    },
10167                                );
10168                                pane.update(cx, |pane, _| pane.enable_history());
10169                            });
10170                        });
10171                    }
10172                    Navigated::Yes
10173                })
10174            })
10175        } else if !definitions.is_empty() {
10176            cx.spawn(|editor, mut cx| async move {
10177                let (title, location_tasks, workspace) = editor
10178                    .update(&mut cx, |editor, cx| {
10179                        let tab_kind = match kind {
10180                            Some(GotoDefinitionKind::Implementation) => "Implementations",
10181                            _ => "Definitions",
10182                        };
10183                        let title = definitions
10184                            .iter()
10185                            .find_map(|definition| match definition {
10186                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10187                                    let buffer = origin.buffer.read(cx);
10188                                    format!(
10189                                        "{} for {}",
10190                                        tab_kind,
10191                                        buffer
10192                                            .text_for_range(origin.range.clone())
10193                                            .collect::<String>()
10194                                    )
10195                                }),
10196                                HoverLink::InlayHint(_, _) => None,
10197                                HoverLink::Url(_) => None,
10198                                HoverLink::File(_) => None,
10199                            })
10200                            .unwrap_or(tab_kind.to_string());
10201                        let location_tasks = definitions
10202                            .into_iter()
10203                            .map(|definition| match definition {
10204                                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
10205                                HoverLink::InlayHint(lsp_location, server_id) => {
10206                                    editor.compute_target_location(lsp_location, server_id, cx)
10207                                }
10208                                HoverLink::Url(_) => Task::ready(Ok(None)),
10209                                HoverLink::File(_) => Task::ready(Ok(None)),
10210                            })
10211                            .collect::<Vec<_>>();
10212                        (title, location_tasks, editor.workspace().clone())
10213                    })
10214                    .context("location tasks preparation")?;
10215
10216                let locations = future::join_all(location_tasks)
10217                    .await
10218                    .into_iter()
10219                    .filter_map(|location| location.transpose())
10220                    .collect::<Result<_>>()
10221                    .context("location tasks")?;
10222
10223                let Some(workspace) = workspace else {
10224                    return Ok(Navigated::No);
10225                };
10226                let opened = workspace
10227                    .update(&mut cx, |workspace, cx| {
10228                        Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
10229                    })
10230                    .ok();
10231
10232                anyhow::Ok(Navigated::from_bool(opened.is_some()))
10233            })
10234        } else {
10235            Task::ready(Ok(Navigated::No))
10236        }
10237    }
10238
10239    fn compute_target_location(
10240        &self,
10241        lsp_location: lsp::Location,
10242        server_id: LanguageServerId,
10243        cx: &mut ViewContext<Self>,
10244    ) -> Task<anyhow::Result<Option<Location>>> {
10245        let Some(project) = self.project.clone() else {
10246            return Task::Ready(Some(Ok(None)));
10247        };
10248
10249        cx.spawn(move |editor, mut cx| async move {
10250            let location_task = editor.update(&mut cx, |_, cx| {
10251                project.update(cx, |project, cx| {
10252                    let language_server_name = project
10253                        .language_server_statuses(cx)
10254                        .find(|(id, _)| server_id == *id)
10255                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10256                    language_server_name.map(|language_server_name| {
10257                        project.open_local_buffer_via_lsp(
10258                            lsp_location.uri.clone(),
10259                            server_id,
10260                            language_server_name,
10261                            cx,
10262                        )
10263                    })
10264                })
10265            })?;
10266            let location = match location_task {
10267                Some(task) => Some({
10268                    let target_buffer_handle = task.await.context("open local buffer")?;
10269                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10270                        let target_start = target_buffer
10271                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10272                        let target_end = target_buffer
10273                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10274                        target_buffer.anchor_after(target_start)
10275                            ..target_buffer.anchor_before(target_end)
10276                    })?;
10277                    Location {
10278                        buffer: target_buffer_handle,
10279                        range,
10280                    }
10281                }),
10282                None => None,
10283            };
10284            Ok(location)
10285        })
10286    }
10287
10288    pub fn find_all_references(
10289        &mut self,
10290        _: &FindAllReferences,
10291        cx: &mut ViewContext<Self>,
10292    ) -> Option<Task<Result<Navigated>>> {
10293        let selection = self.selections.newest::<usize>(cx);
10294        let multi_buffer = self.buffer.read(cx);
10295        let head = selection.head();
10296
10297        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10298        let head_anchor = multi_buffer_snapshot.anchor_at(
10299            head,
10300            if head < selection.tail() {
10301                Bias::Right
10302            } else {
10303                Bias::Left
10304            },
10305        );
10306
10307        match self
10308            .find_all_references_task_sources
10309            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10310        {
10311            Ok(_) => {
10312                log::info!(
10313                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
10314                );
10315                return None;
10316            }
10317            Err(i) => {
10318                self.find_all_references_task_sources.insert(i, head_anchor);
10319            }
10320        }
10321
10322        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10323        let workspace = self.workspace()?;
10324        let project = workspace.read(cx).project().clone();
10325        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10326        Some(cx.spawn(|editor, mut cx| async move {
10327            let _cleanup = defer({
10328                let mut cx = cx.clone();
10329                move || {
10330                    let _ = editor.update(&mut cx, |editor, _| {
10331                        if let Ok(i) =
10332                            editor
10333                                .find_all_references_task_sources
10334                                .binary_search_by(|anchor| {
10335                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10336                                })
10337                        {
10338                            editor.find_all_references_task_sources.remove(i);
10339                        }
10340                    });
10341                }
10342            });
10343
10344            let locations = references.await?;
10345            if locations.is_empty() {
10346                return anyhow::Ok(Navigated::No);
10347            }
10348
10349            workspace.update(&mut cx, |workspace, cx| {
10350                let title = locations
10351                    .first()
10352                    .as_ref()
10353                    .map(|location| {
10354                        let buffer = location.buffer.read(cx);
10355                        format!(
10356                            "References to `{}`",
10357                            buffer
10358                                .text_for_range(location.range.clone())
10359                                .collect::<String>()
10360                        )
10361                    })
10362                    .unwrap();
10363                Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
10364                Navigated::Yes
10365            })
10366        }))
10367    }
10368
10369    /// Opens a multibuffer with the given project locations in it
10370    pub fn open_locations_in_multibuffer(
10371        workspace: &mut Workspace,
10372        mut locations: Vec<Location>,
10373        title: String,
10374        split: bool,
10375        cx: &mut ViewContext<Workspace>,
10376    ) {
10377        // If there are multiple definitions, open them in a multibuffer
10378        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10379        let mut locations = locations.into_iter().peekable();
10380        let mut ranges_to_highlight = Vec::new();
10381        let capability = workspace.project().read(cx).capability();
10382
10383        let excerpt_buffer = cx.new_model(|cx| {
10384            let mut multibuffer = MultiBuffer::new(capability);
10385            while let Some(location) = locations.next() {
10386                let buffer = location.buffer.read(cx);
10387                let mut ranges_for_buffer = Vec::new();
10388                let range = location.range.to_offset(buffer);
10389                ranges_for_buffer.push(range.clone());
10390
10391                while let Some(next_location) = locations.peek() {
10392                    if next_location.buffer == location.buffer {
10393                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
10394                        locations.next();
10395                    } else {
10396                        break;
10397                    }
10398                }
10399
10400                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10401                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
10402                    location.buffer.clone(),
10403                    ranges_for_buffer,
10404                    DEFAULT_MULTIBUFFER_CONTEXT,
10405                    cx,
10406                ))
10407            }
10408
10409            multibuffer.with_title(title)
10410        });
10411
10412        let editor = cx.new_view(|cx| {
10413            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
10414        });
10415        editor.update(cx, |editor, cx| {
10416            if let Some(first_range) = ranges_to_highlight.first() {
10417                editor.change_selections(None, cx, |selections| {
10418                    selections.clear_disjoint();
10419                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10420                });
10421            }
10422            editor.highlight_background::<Self>(
10423                &ranges_to_highlight,
10424                |theme| theme.editor_highlighted_line_background,
10425                cx,
10426            );
10427        });
10428
10429        let item = Box::new(editor);
10430        let item_id = item.item_id();
10431
10432        if split {
10433            workspace.split_item(SplitDirection::Right, item.clone(), cx);
10434        } else {
10435            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10436                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10437                    pane.close_current_preview_item(cx)
10438                } else {
10439                    None
10440                }
10441            });
10442            workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
10443        }
10444        workspace.active_pane().update(cx, |pane, cx| {
10445            pane.set_preview_item_id(Some(item_id), cx);
10446        });
10447    }
10448
10449    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10450        use language::ToOffset as _;
10451
10452        let provider = self.semantics_provider.clone()?;
10453        let selection = self.selections.newest_anchor().clone();
10454        let (cursor_buffer, cursor_buffer_position) = self
10455            .buffer
10456            .read(cx)
10457            .text_anchor_for_position(selection.head(), cx)?;
10458        let (tail_buffer, cursor_buffer_position_end) = self
10459            .buffer
10460            .read(cx)
10461            .text_anchor_for_position(selection.tail(), cx)?;
10462        if tail_buffer != cursor_buffer {
10463            return None;
10464        }
10465
10466        let snapshot = cursor_buffer.read(cx).snapshot();
10467        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10468        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10469        let prepare_rename = provider
10470            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10471            .unwrap_or_else(|| Task::ready(Ok(None)));
10472        drop(snapshot);
10473
10474        Some(cx.spawn(|this, mut cx| async move {
10475            let rename_range = if let Some(range) = prepare_rename.await? {
10476                Some(range)
10477            } else {
10478                this.update(&mut cx, |this, cx| {
10479                    let buffer = this.buffer.read(cx).snapshot(cx);
10480                    let mut buffer_highlights = this
10481                        .document_highlights_for_position(selection.head(), &buffer)
10482                        .filter(|highlight| {
10483                            highlight.start.excerpt_id == selection.head().excerpt_id
10484                                && highlight.end.excerpt_id == selection.head().excerpt_id
10485                        });
10486                    buffer_highlights
10487                        .next()
10488                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10489                })?
10490            };
10491            if let Some(rename_range) = rename_range {
10492                this.update(&mut cx, |this, cx| {
10493                    let snapshot = cursor_buffer.read(cx).snapshot();
10494                    let rename_buffer_range = rename_range.to_offset(&snapshot);
10495                    let cursor_offset_in_rename_range =
10496                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10497                    let cursor_offset_in_rename_range_end =
10498                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10499
10500                    this.take_rename(false, cx);
10501                    let buffer = this.buffer.read(cx).read(cx);
10502                    let cursor_offset = selection.head().to_offset(&buffer);
10503                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10504                    let rename_end = rename_start + rename_buffer_range.len();
10505                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10506                    let mut old_highlight_id = None;
10507                    let old_name: Arc<str> = buffer
10508                        .chunks(rename_start..rename_end, true)
10509                        .map(|chunk| {
10510                            if old_highlight_id.is_none() {
10511                                old_highlight_id = chunk.syntax_highlight_id;
10512                            }
10513                            chunk.text
10514                        })
10515                        .collect::<String>()
10516                        .into();
10517
10518                    drop(buffer);
10519
10520                    // Position the selection in the rename editor so that it matches the current selection.
10521                    this.show_local_selections = false;
10522                    let rename_editor = cx.new_view(|cx| {
10523                        let mut editor = Editor::single_line(cx);
10524                        editor.buffer.update(cx, |buffer, cx| {
10525                            buffer.edit([(0..0, old_name.clone())], None, cx)
10526                        });
10527                        let rename_selection_range = match cursor_offset_in_rename_range
10528                            .cmp(&cursor_offset_in_rename_range_end)
10529                        {
10530                            Ordering::Equal => {
10531                                editor.select_all(&SelectAll, cx);
10532                                return editor;
10533                            }
10534                            Ordering::Less => {
10535                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10536                            }
10537                            Ordering::Greater => {
10538                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10539                            }
10540                        };
10541                        if rename_selection_range.end > old_name.len() {
10542                            editor.select_all(&SelectAll, cx);
10543                        } else {
10544                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10545                                s.select_ranges([rename_selection_range]);
10546                            });
10547                        }
10548                        editor
10549                    });
10550                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10551                        if e == &EditorEvent::Focused {
10552                            cx.emit(EditorEvent::FocusedIn)
10553                        }
10554                    })
10555                    .detach();
10556
10557                    let write_highlights =
10558                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10559                    let read_highlights =
10560                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
10561                    let ranges = write_highlights
10562                        .iter()
10563                        .flat_map(|(_, ranges)| ranges.iter())
10564                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10565                        .cloned()
10566                        .collect();
10567
10568                    this.highlight_text::<Rename>(
10569                        ranges,
10570                        HighlightStyle {
10571                            fade_out: Some(0.6),
10572                            ..Default::default()
10573                        },
10574                        cx,
10575                    );
10576                    let rename_focus_handle = rename_editor.focus_handle(cx);
10577                    cx.focus(&rename_focus_handle);
10578                    let block_id = this.insert_blocks(
10579                        [BlockProperties {
10580                            style: BlockStyle::Flex,
10581                            placement: BlockPlacement::Below(range.start),
10582                            height: 1,
10583                            render: Arc::new({
10584                                let rename_editor = rename_editor.clone();
10585                                move |cx: &mut BlockContext| {
10586                                    let mut text_style = cx.editor_style.text.clone();
10587                                    if let Some(highlight_style) = old_highlight_id
10588                                        .and_then(|h| h.style(&cx.editor_style.syntax))
10589                                    {
10590                                        text_style = text_style.highlight(highlight_style);
10591                                    }
10592                                    div()
10593                                        .block_mouse_down()
10594                                        .pl(cx.anchor_x)
10595                                        .child(EditorElement::new(
10596                                            &rename_editor,
10597                                            EditorStyle {
10598                                                background: cx.theme().system().transparent,
10599                                                local_player: cx.editor_style.local_player,
10600                                                text: text_style,
10601                                                scrollbar_width: cx.editor_style.scrollbar_width,
10602                                                syntax: cx.editor_style.syntax.clone(),
10603                                                status: cx.editor_style.status.clone(),
10604                                                inlay_hints_style: HighlightStyle {
10605                                                    font_weight: Some(FontWeight::BOLD),
10606                                                    ..make_inlay_hints_style(cx)
10607                                                },
10608                                                suggestions_style: HighlightStyle {
10609                                                    color: Some(cx.theme().status().predictive),
10610                                                    ..HighlightStyle::default()
10611                                                },
10612                                                ..EditorStyle::default()
10613                                            },
10614                                        ))
10615                                        .into_any_element()
10616                                }
10617                            }),
10618                            priority: 0,
10619                        }],
10620                        Some(Autoscroll::fit()),
10621                        cx,
10622                    )[0];
10623                    this.pending_rename = Some(RenameState {
10624                        range,
10625                        old_name,
10626                        editor: rename_editor,
10627                        block_id,
10628                    });
10629                })?;
10630            }
10631
10632            Ok(())
10633        }))
10634    }
10635
10636    pub fn confirm_rename(
10637        &mut self,
10638        _: &ConfirmRename,
10639        cx: &mut ViewContext<Self>,
10640    ) -> Option<Task<Result<()>>> {
10641        let rename = self.take_rename(false, cx)?;
10642        let workspace = self.workspace()?.downgrade();
10643        let (buffer, start) = self
10644            .buffer
10645            .read(cx)
10646            .text_anchor_for_position(rename.range.start, cx)?;
10647        let (end_buffer, _) = self
10648            .buffer
10649            .read(cx)
10650            .text_anchor_for_position(rename.range.end, cx)?;
10651        if buffer != end_buffer {
10652            return None;
10653        }
10654
10655        let old_name = rename.old_name;
10656        let new_name = rename.editor.read(cx).text(cx);
10657
10658        let rename = self.semantics_provider.as_ref()?.perform_rename(
10659            &buffer,
10660            start,
10661            new_name.clone(),
10662            cx,
10663        )?;
10664
10665        Some(cx.spawn(|editor, mut cx| async move {
10666            let project_transaction = rename.await?;
10667            Self::open_project_transaction(
10668                &editor,
10669                workspace,
10670                project_transaction,
10671                format!("Rename: {}{}", old_name, new_name),
10672                cx.clone(),
10673            )
10674            .await?;
10675
10676            editor.update(&mut cx, |editor, cx| {
10677                editor.refresh_document_highlights(cx);
10678            })?;
10679            Ok(())
10680        }))
10681    }
10682
10683    fn take_rename(
10684        &mut self,
10685        moving_cursor: bool,
10686        cx: &mut ViewContext<Self>,
10687    ) -> Option<RenameState> {
10688        let rename = self.pending_rename.take()?;
10689        if rename.editor.focus_handle(cx).is_focused(cx) {
10690            cx.focus(&self.focus_handle);
10691        }
10692
10693        self.remove_blocks(
10694            [rename.block_id].into_iter().collect(),
10695            Some(Autoscroll::fit()),
10696            cx,
10697        );
10698        self.clear_highlights::<Rename>(cx);
10699        self.show_local_selections = true;
10700
10701        if moving_cursor {
10702            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10703                editor.selections.newest::<usize>(cx).head()
10704            });
10705
10706            // Update the selection to match the position of the selection inside
10707            // the rename editor.
10708            let snapshot = self.buffer.read(cx).read(cx);
10709            let rename_range = rename.range.to_offset(&snapshot);
10710            let cursor_in_editor = snapshot
10711                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10712                .min(rename_range.end);
10713            drop(snapshot);
10714
10715            self.change_selections(None, cx, |s| {
10716                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10717            });
10718        } else {
10719            self.refresh_document_highlights(cx);
10720        }
10721
10722        Some(rename)
10723    }
10724
10725    pub fn pending_rename(&self) -> Option<&RenameState> {
10726        self.pending_rename.as_ref()
10727    }
10728
10729    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10730        let project = match &self.project {
10731            Some(project) => project.clone(),
10732            None => return None,
10733        };
10734
10735        Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10736    }
10737
10738    fn format_selections(
10739        &mut self,
10740        _: &FormatSelections,
10741        cx: &mut ViewContext<Self>,
10742    ) -> Option<Task<Result<()>>> {
10743        let project = match &self.project {
10744            Some(project) => project.clone(),
10745            None => return None,
10746        };
10747
10748        let selections = self
10749            .selections
10750            .all_adjusted(cx)
10751            .into_iter()
10752            .filter(|s| !s.is_empty())
10753            .collect_vec();
10754
10755        Some(self.perform_format(
10756            project,
10757            FormatTrigger::Manual,
10758            FormatTarget::Ranges(selections),
10759            cx,
10760        ))
10761    }
10762
10763    fn perform_format(
10764        &mut self,
10765        project: Model<Project>,
10766        trigger: FormatTrigger,
10767        target: FormatTarget,
10768        cx: &mut ViewContext<Self>,
10769    ) -> Task<Result<()>> {
10770        let buffer = self.buffer().clone();
10771        let mut buffers = buffer.read(cx).all_buffers();
10772        if trigger == FormatTrigger::Save {
10773            buffers.retain(|buffer| buffer.read(cx).is_dirty());
10774        }
10775
10776        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10777        let format = project.update(cx, |project, cx| {
10778            project.format(buffers, true, trigger, target, cx)
10779        });
10780
10781        cx.spawn(|_, mut cx| async move {
10782            let transaction = futures::select_biased! {
10783                () = timeout => {
10784                    log::warn!("timed out waiting for formatting");
10785                    None
10786                }
10787                transaction = format.log_err().fuse() => transaction,
10788            };
10789
10790            buffer
10791                .update(&mut cx, |buffer, cx| {
10792                    if let Some(transaction) = transaction {
10793                        if !buffer.is_singleton() {
10794                            buffer.push_transaction(&transaction.0, cx);
10795                        }
10796                    }
10797
10798                    cx.notify();
10799                })
10800                .ok();
10801
10802            Ok(())
10803        })
10804    }
10805
10806    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10807        if let Some(project) = self.project.clone() {
10808            self.buffer.update(cx, |multi_buffer, cx| {
10809                project.update(cx, |project, cx| {
10810                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10811                });
10812            })
10813        }
10814    }
10815
10816    fn cancel_language_server_work(
10817        &mut self,
10818        _: &actions::CancelLanguageServerWork,
10819        cx: &mut ViewContext<Self>,
10820    ) {
10821        if let Some(project) = self.project.clone() {
10822            self.buffer.update(cx, |multi_buffer, cx| {
10823                project.update(cx, |project, cx| {
10824                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10825                });
10826            })
10827        }
10828    }
10829
10830    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10831        cx.show_character_palette();
10832    }
10833
10834    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10835        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10836            let buffer = self.buffer.read(cx).snapshot(cx);
10837            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10838            let is_valid = buffer
10839                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10840                .any(|entry| {
10841                    entry.diagnostic.is_primary
10842                        && !entry.range.is_empty()
10843                        && entry.range.start == primary_range_start
10844                        && entry.diagnostic.message == active_diagnostics.primary_message
10845                });
10846
10847            if is_valid != active_diagnostics.is_valid {
10848                active_diagnostics.is_valid = is_valid;
10849                let mut new_styles = HashMap::default();
10850                for (block_id, diagnostic) in &active_diagnostics.blocks {
10851                    new_styles.insert(
10852                        *block_id,
10853                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10854                    );
10855                }
10856                self.display_map.update(cx, |display_map, _cx| {
10857                    display_map.replace_blocks(new_styles)
10858                });
10859            }
10860        }
10861    }
10862
10863    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10864        self.dismiss_diagnostics(cx);
10865        let snapshot = self.snapshot(cx);
10866        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10867            let buffer = self.buffer.read(cx).snapshot(cx);
10868
10869            let mut primary_range = None;
10870            let mut primary_message = None;
10871            let mut group_end = Point::zero();
10872            let diagnostic_group = buffer
10873                .diagnostic_group::<MultiBufferPoint>(group_id)
10874                .filter_map(|entry| {
10875                    if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10876                        && (entry.range.start.row == entry.range.end.row
10877                            || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10878                    {
10879                        return None;
10880                    }
10881                    if entry.range.end > group_end {
10882                        group_end = entry.range.end;
10883                    }
10884                    if entry.diagnostic.is_primary {
10885                        primary_range = Some(entry.range.clone());
10886                        primary_message = Some(entry.diagnostic.message.clone());
10887                    }
10888                    Some(entry)
10889                })
10890                .collect::<Vec<_>>();
10891            let primary_range = primary_range?;
10892            let primary_message = primary_message?;
10893            let primary_range =
10894                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10895
10896            let blocks = display_map
10897                .insert_blocks(
10898                    diagnostic_group.iter().map(|entry| {
10899                        let diagnostic = entry.diagnostic.clone();
10900                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10901                        BlockProperties {
10902                            style: BlockStyle::Fixed,
10903                            placement: BlockPlacement::Below(
10904                                buffer.anchor_after(entry.range.start),
10905                            ),
10906                            height: message_height,
10907                            render: diagnostic_block_renderer(diagnostic, None, true, true),
10908                            priority: 0,
10909                        }
10910                    }),
10911                    cx,
10912                )
10913                .into_iter()
10914                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10915                .collect();
10916
10917            Some(ActiveDiagnosticGroup {
10918                primary_range,
10919                primary_message,
10920                group_id,
10921                blocks,
10922                is_valid: true,
10923            })
10924        });
10925        self.active_diagnostics.is_some()
10926    }
10927
10928    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10929        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10930            self.display_map.update(cx, |display_map, cx| {
10931                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10932            });
10933            cx.notify();
10934        }
10935    }
10936
10937    pub fn set_selections_from_remote(
10938        &mut self,
10939        selections: Vec<Selection<Anchor>>,
10940        pending_selection: Option<Selection<Anchor>>,
10941        cx: &mut ViewContext<Self>,
10942    ) {
10943        let old_cursor_position = self.selections.newest_anchor().head();
10944        self.selections.change_with(cx, |s| {
10945            s.select_anchors(selections);
10946            if let Some(pending_selection) = pending_selection {
10947                s.set_pending(pending_selection, SelectMode::Character);
10948            } else {
10949                s.clear_pending();
10950            }
10951        });
10952        self.selections_did_change(false, &old_cursor_position, true, cx);
10953    }
10954
10955    fn push_to_selection_history(&mut self) {
10956        self.selection_history.push(SelectionHistoryEntry {
10957            selections: self.selections.disjoint_anchors(),
10958            select_next_state: self.select_next_state.clone(),
10959            select_prev_state: self.select_prev_state.clone(),
10960            add_selections_state: self.add_selections_state.clone(),
10961        });
10962    }
10963
10964    pub fn transact(
10965        &mut self,
10966        cx: &mut ViewContext<Self>,
10967        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10968    ) -> Option<TransactionId> {
10969        self.start_transaction_at(Instant::now(), cx);
10970        update(self, cx);
10971        self.end_transaction_at(Instant::now(), cx)
10972    }
10973
10974    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10975        self.end_selection(cx);
10976        if let Some(tx_id) = self
10977            .buffer
10978            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10979        {
10980            self.selection_history
10981                .insert_transaction(tx_id, self.selections.disjoint_anchors());
10982            cx.emit(EditorEvent::TransactionBegun {
10983                transaction_id: tx_id,
10984            })
10985        }
10986    }
10987
10988    fn end_transaction_at(
10989        &mut self,
10990        now: Instant,
10991        cx: &mut ViewContext<Self>,
10992    ) -> Option<TransactionId> {
10993        if let Some(transaction_id) = self
10994            .buffer
10995            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10996        {
10997            if let Some((_, end_selections)) =
10998                self.selection_history.transaction_mut(transaction_id)
10999            {
11000                *end_selections = Some(self.selections.disjoint_anchors());
11001            } else {
11002                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11003            }
11004
11005            cx.emit(EditorEvent::Edited { transaction_id });
11006            Some(transaction_id)
11007        } else {
11008            None
11009        }
11010    }
11011
11012    pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
11013        let selection = self.selections.newest::<Point>(cx);
11014
11015        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11016        let range = if selection.is_empty() {
11017            let point = selection.head().to_display_point(&display_map);
11018            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11019            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11020                .to_point(&display_map);
11021            start..end
11022        } else {
11023            selection.range()
11024        };
11025        if display_map.folds_in_range(range).next().is_some() {
11026            self.unfold_lines(&Default::default(), cx)
11027        } else {
11028            self.fold(&Default::default(), cx)
11029        }
11030    }
11031
11032    pub fn toggle_fold_recursive(
11033        &mut self,
11034        _: &actions::ToggleFoldRecursive,
11035        cx: &mut ViewContext<Self>,
11036    ) {
11037        let selection = self.selections.newest::<Point>(cx);
11038
11039        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11040        let range = if selection.is_empty() {
11041            let point = selection.head().to_display_point(&display_map);
11042            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11043            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11044                .to_point(&display_map);
11045            start..end
11046        } else {
11047            selection.range()
11048        };
11049        if display_map.folds_in_range(range).next().is_some() {
11050            self.unfold_recursive(&Default::default(), cx)
11051        } else {
11052            self.fold_recursive(&Default::default(), cx)
11053        }
11054    }
11055
11056    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
11057        let mut to_fold = Vec::new();
11058        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11059        let selections = self.selections.all_adjusted(cx);
11060
11061        for selection in selections {
11062            let range = selection.range().sorted();
11063            let buffer_start_row = range.start.row;
11064
11065            if range.start.row != range.end.row {
11066                let mut found = false;
11067                let mut row = range.start.row;
11068                while row <= range.end.row {
11069                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11070                        found = true;
11071                        row = crease.range().end.row + 1;
11072                        to_fold.push(crease);
11073                    } else {
11074                        row += 1
11075                    }
11076                }
11077                if found {
11078                    continue;
11079                }
11080            }
11081
11082            for row in (0..=range.start.row).rev() {
11083                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11084                    if crease.range().end.row >= buffer_start_row {
11085                        to_fold.push(crease);
11086                        if row <= range.start.row {
11087                            break;
11088                        }
11089                    }
11090                }
11091            }
11092        }
11093
11094        self.fold_creases(to_fold, true, cx);
11095    }
11096
11097    fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
11098        let fold_at_level = fold_at.level;
11099        let snapshot = self.buffer.read(cx).snapshot(cx);
11100        let mut to_fold = Vec::new();
11101        let mut stack = vec![(0, snapshot.max_buffer_row().0, 1)];
11102
11103        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
11104            while start_row < end_row {
11105                match self
11106                    .snapshot(cx)
11107                    .crease_for_buffer_row(MultiBufferRow(start_row))
11108                {
11109                    Some(crease) => {
11110                        let nested_start_row = crease.range().start.row + 1;
11111                        let nested_end_row = crease.range().end.row;
11112
11113                        if current_level < fold_at_level {
11114                            stack.push((nested_start_row, nested_end_row, current_level + 1));
11115                        } else if current_level == fold_at_level {
11116                            to_fold.push(crease);
11117                        }
11118
11119                        start_row = nested_end_row + 1;
11120                    }
11121                    None => start_row += 1,
11122                }
11123            }
11124        }
11125
11126        self.fold_creases(to_fold, true, cx);
11127    }
11128
11129    pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
11130        let mut fold_ranges = Vec::new();
11131        let snapshot = self.buffer.read(cx).snapshot(cx);
11132
11133        for row in 0..snapshot.max_buffer_row().0 {
11134            if let Some(foldable_range) =
11135                self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
11136            {
11137                fold_ranges.push(foldable_range);
11138            }
11139        }
11140
11141        self.fold_creases(fold_ranges, true, cx);
11142    }
11143
11144    pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
11145        let mut to_fold = Vec::new();
11146        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11147        let selections = self.selections.all_adjusted(cx);
11148
11149        for selection in selections {
11150            let range = selection.range().sorted();
11151            let buffer_start_row = range.start.row;
11152
11153            if range.start.row != range.end.row {
11154                let mut found = false;
11155                for row in range.start.row..=range.end.row {
11156                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11157                        found = true;
11158                        to_fold.push(crease);
11159                    }
11160                }
11161                if found {
11162                    continue;
11163                }
11164            }
11165
11166            for row in (0..=range.start.row).rev() {
11167                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11168                    if crease.range().end.row >= buffer_start_row {
11169                        to_fold.push(crease);
11170                    } else {
11171                        break;
11172                    }
11173                }
11174            }
11175        }
11176
11177        self.fold_creases(to_fold, true, cx);
11178    }
11179
11180    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
11181        let buffer_row = fold_at.buffer_row;
11182        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11183
11184        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
11185            let autoscroll = self
11186                .selections
11187                .all::<Point>(cx)
11188                .iter()
11189                .any(|selection| crease.range().overlaps(&selection.range()));
11190
11191            self.fold_creases(vec![crease], autoscroll, cx);
11192        }
11193    }
11194
11195    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
11196        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11197        let buffer = &display_map.buffer_snapshot;
11198        let selections = self.selections.all::<Point>(cx);
11199        let ranges = selections
11200            .iter()
11201            .map(|s| {
11202                let range = s.display_range(&display_map).sorted();
11203                let mut start = range.start.to_point(&display_map);
11204                let mut end = range.end.to_point(&display_map);
11205                start.column = 0;
11206                end.column = buffer.line_len(MultiBufferRow(end.row));
11207                start..end
11208            })
11209            .collect::<Vec<_>>();
11210
11211        self.unfold_ranges(&ranges, true, true, cx);
11212    }
11213
11214    pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
11215        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11216        let selections = self.selections.all::<Point>(cx);
11217        let ranges = selections
11218            .iter()
11219            .map(|s| {
11220                let mut range = s.display_range(&display_map).sorted();
11221                *range.start.column_mut() = 0;
11222                *range.end.column_mut() = display_map.line_len(range.end.row());
11223                let start = range.start.to_point(&display_map);
11224                let end = range.end.to_point(&display_map);
11225                start..end
11226            })
11227            .collect::<Vec<_>>();
11228
11229        self.unfold_ranges(&ranges, true, true, cx);
11230    }
11231
11232    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
11233        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11234
11235        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
11236            ..Point::new(
11237                unfold_at.buffer_row.0,
11238                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
11239            );
11240
11241        let autoscroll = self
11242            .selections
11243            .all::<Point>(cx)
11244            .iter()
11245            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
11246
11247        self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
11248    }
11249
11250    pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
11251        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11252        self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
11253    }
11254
11255    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
11256        let selections = self.selections.all::<Point>(cx);
11257        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11258        let line_mode = self.selections.line_mode;
11259        let ranges = selections
11260            .into_iter()
11261            .map(|s| {
11262                if line_mode {
11263                    let start = Point::new(s.start.row, 0);
11264                    let end = Point::new(
11265                        s.end.row,
11266                        display_map
11267                            .buffer_snapshot
11268                            .line_len(MultiBufferRow(s.end.row)),
11269                    );
11270                    Crease::simple(start..end, display_map.fold_placeholder.clone())
11271                } else {
11272                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
11273                }
11274            })
11275            .collect::<Vec<_>>();
11276        self.fold_creases(ranges, true, cx);
11277    }
11278
11279    pub fn fold_creases<T: ToOffset + Clone>(
11280        &mut self,
11281        creases: Vec<Crease<T>>,
11282        auto_scroll: bool,
11283        cx: &mut ViewContext<Self>,
11284    ) {
11285        if creases.is_empty() {
11286            return;
11287        }
11288
11289        let mut buffers_affected = HashMap::default();
11290        let multi_buffer = self.buffer().read(cx);
11291        for crease in &creases {
11292            if let Some((_, buffer, _)) =
11293                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
11294            {
11295                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
11296            };
11297        }
11298
11299        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
11300
11301        if auto_scroll {
11302            self.request_autoscroll(Autoscroll::fit(), cx);
11303        }
11304
11305        for buffer in buffers_affected.into_values() {
11306            self.sync_expanded_diff_hunks(buffer, cx);
11307        }
11308
11309        cx.notify();
11310
11311        if let Some(active_diagnostics) = self.active_diagnostics.take() {
11312            // Clear diagnostics block when folding a range that contains it.
11313            let snapshot = self.snapshot(cx);
11314            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
11315                drop(snapshot);
11316                self.active_diagnostics = Some(active_diagnostics);
11317                self.dismiss_diagnostics(cx);
11318            } else {
11319                self.active_diagnostics = Some(active_diagnostics);
11320            }
11321        }
11322
11323        self.scrollbar_marker_state.dirty = true;
11324    }
11325
11326    /// Removes any folds whose ranges intersect any of the given ranges.
11327    pub fn unfold_ranges<T: ToOffset + Clone>(
11328        &mut self,
11329        ranges: &[Range<T>],
11330        inclusive: bool,
11331        auto_scroll: bool,
11332        cx: &mut ViewContext<Self>,
11333    ) {
11334        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11335            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
11336        });
11337    }
11338
11339    /// Removes any folds with the given ranges.
11340    pub fn remove_folds_with_type<T: ToOffset + Clone>(
11341        &mut self,
11342        ranges: &[Range<T>],
11343        type_id: TypeId,
11344        auto_scroll: bool,
11345        cx: &mut ViewContext<Self>,
11346    ) {
11347        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11348            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
11349        });
11350    }
11351
11352    fn remove_folds_with<T: ToOffset + Clone>(
11353        &mut self,
11354        ranges: &[Range<T>],
11355        auto_scroll: bool,
11356        cx: &mut ViewContext<Self>,
11357        update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
11358    ) {
11359        if ranges.is_empty() {
11360            return;
11361        }
11362
11363        let mut buffers_affected = HashMap::default();
11364        let multi_buffer = self.buffer().read(cx);
11365        for range in ranges {
11366            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11367                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
11368            };
11369        }
11370
11371        self.display_map.update(cx, update);
11372
11373        if auto_scroll {
11374            self.request_autoscroll(Autoscroll::fit(), cx);
11375        }
11376
11377        for buffer in buffers_affected.into_values() {
11378            self.sync_expanded_diff_hunks(buffer, cx);
11379        }
11380
11381        cx.notify();
11382        self.scrollbar_marker_state.dirty = true;
11383        self.active_indent_guides_state.dirty = true;
11384    }
11385
11386    pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
11387        self.display_map.read(cx).fold_placeholder.clone()
11388    }
11389
11390    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11391        if hovered != self.gutter_hovered {
11392            self.gutter_hovered = hovered;
11393            cx.notify();
11394        }
11395    }
11396
11397    pub fn insert_blocks(
11398        &mut self,
11399        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11400        autoscroll: Option<Autoscroll>,
11401        cx: &mut ViewContext<Self>,
11402    ) -> Vec<CustomBlockId> {
11403        let blocks = self
11404            .display_map
11405            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11406        if let Some(autoscroll) = autoscroll {
11407            self.request_autoscroll(autoscroll, cx);
11408        }
11409        cx.notify();
11410        blocks
11411    }
11412
11413    pub fn resize_blocks(
11414        &mut self,
11415        heights: HashMap<CustomBlockId, u32>,
11416        autoscroll: Option<Autoscroll>,
11417        cx: &mut ViewContext<Self>,
11418    ) {
11419        self.display_map
11420            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11421        if let Some(autoscroll) = autoscroll {
11422            self.request_autoscroll(autoscroll, cx);
11423        }
11424        cx.notify();
11425    }
11426
11427    pub fn replace_blocks(
11428        &mut self,
11429        renderers: HashMap<CustomBlockId, RenderBlock>,
11430        autoscroll: Option<Autoscroll>,
11431        cx: &mut ViewContext<Self>,
11432    ) {
11433        self.display_map
11434            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11435        if let Some(autoscroll) = autoscroll {
11436            self.request_autoscroll(autoscroll, cx);
11437        }
11438        cx.notify();
11439    }
11440
11441    pub fn remove_blocks(
11442        &mut self,
11443        block_ids: HashSet<CustomBlockId>,
11444        autoscroll: Option<Autoscroll>,
11445        cx: &mut ViewContext<Self>,
11446    ) {
11447        self.display_map.update(cx, |display_map, cx| {
11448            display_map.remove_blocks(block_ids, cx)
11449        });
11450        if let Some(autoscroll) = autoscroll {
11451            self.request_autoscroll(autoscroll, cx);
11452        }
11453        cx.notify();
11454    }
11455
11456    pub fn row_for_block(
11457        &self,
11458        block_id: CustomBlockId,
11459        cx: &mut ViewContext<Self>,
11460    ) -> Option<DisplayRow> {
11461        self.display_map
11462            .update(cx, |map, cx| map.row_for_block(block_id, cx))
11463    }
11464
11465    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11466        self.focused_block = Some(focused_block);
11467    }
11468
11469    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11470        self.focused_block.take()
11471    }
11472
11473    pub fn insert_creases(
11474        &mut self,
11475        creases: impl IntoIterator<Item = Crease<Anchor>>,
11476        cx: &mut ViewContext<Self>,
11477    ) -> Vec<CreaseId> {
11478        self.display_map
11479            .update(cx, |map, cx| map.insert_creases(creases, cx))
11480    }
11481
11482    pub fn remove_creases(
11483        &mut self,
11484        ids: impl IntoIterator<Item = CreaseId>,
11485        cx: &mut ViewContext<Self>,
11486    ) {
11487        self.display_map
11488            .update(cx, |map, cx| map.remove_creases(ids, cx));
11489    }
11490
11491    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11492        self.display_map
11493            .update(cx, |map, cx| map.snapshot(cx))
11494            .longest_row()
11495    }
11496
11497    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11498        self.display_map
11499            .update(cx, |map, cx| map.snapshot(cx))
11500            .max_point()
11501    }
11502
11503    pub fn text(&self, cx: &AppContext) -> String {
11504        self.buffer.read(cx).read(cx).text()
11505    }
11506
11507    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11508        let text = self.text(cx);
11509        let text = text.trim();
11510
11511        if text.is_empty() {
11512            return None;
11513        }
11514
11515        Some(text.to_string())
11516    }
11517
11518    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11519        self.transact(cx, |this, cx| {
11520            this.buffer
11521                .read(cx)
11522                .as_singleton()
11523                .expect("you can only call set_text on editors for singleton buffers")
11524                .update(cx, |buffer, cx| buffer.set_text(text, cx));
11525        });
11526    }
11527
11528    pub fn display_text(&self, cx: &mut AppContext) -> String {
11529        self.display_map
11530            .update(cx, |map, cx| map.snapshot(cx))
11531            .text()
11532    }
11533
11534    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11535        let mut wrap_guides = smallvec::smallvec![];
11536
11537        if self.show_wrap_guides == Some(false) {
11538            return wrap_guides;
11539        }
11540
11541        let settings = self.buffer.read(cx).settings_at(0, cx);
11542        if settings.show_wrap_guides {
11543            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11544                wrap_guides.push((soft_wrap as usize, true));
11545            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11546                wrap_guides.push((soft_wrap as usize, true));
11547            }
11548            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11549        }
11550
11551        wrap_guides
11552    }
11553
11554    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11555        let settings = self.buffer.read(cx).settings_at(0, cx);
11556        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11557        match mode {
11558            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11559                SoftWrap::None
11560            }
11561            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11562            language_settings::SoftWrap::PreferredLineLength => {
11563                SoftWrap::Column(settings.preferred_line_length)
11564            }
11565            language_settings::SoftWrap::Bounded => {
11566                SoftWrap::Bounded(settings.preferred_line_length)
11567            }
11568        }
11569    }
11570
11571    pub fn set_soft_wrap_mode(
11572        &mut self,
11573        mode: language_settings::SoftWrap,
11574        cx: &mut ViewContext<Self>,
11575    ) {
11576        self.soft_wrap_mode_override = Some(mode);
11577        cx.notify();
11578    }
11579
11580    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11581        self.text_style_refinement = Some(style);
11582    }
11583
11584    /// called by the Element so we know what style we were most recently rendered with.
11585    pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11586        let rem_size = cx.rem_size();
11587        self.display_map.update(cx, |map, cx| {
11588            map.set_font(
11589                style.text.font(),
11590                style.text.font_size.to_pixels(rem_size),
11591                cx,
11592            )
11593        });
11594        self.style = Some(style);
11595    }
11596
11597    pub fn style(&self) -> Option<&EditorStyle> {
11598        self.style.as_ref()
11599    }
11600
11601    // Called by the element. This method is not designed to be called outside of the editor
11602    // element's layout code because it does not notify when rewrapping is computed synchronously.
11603    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11604        self.display_map
11605            .update(cx, |map, cx| map.set_wrap_width(width, cx))
11606    }
11607
11608    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11609        if self.soft_wrap_mode_override.is_some() {
11610            self.soft_wrap_mode_override.take();
11611        } else {
11612            let soft_wrap = match self.soft_wrap_mode(cx) {
11613                SoftWrap::GitDiff => return,
11614                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11615                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11616                    language_settings::SoftWrap::None
11617                }
11618            };
11619            self.soft_wrap_mode_override = Some(soft_wrap);
11620        }
11621        cx.notify();
11622    }
11623
11624    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11625        let Some(workspace) = self.workspace() else {
11626            return;
11627        };
11628        let fs = workspace.read(cx).app_state().fs.clone();
11629        let current_show = TabBarSettings::get_global(cx).show;
11630        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11631            setting.show = Some(!current_show);
11632        });
11633    }
11634
11635    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11636        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11637            self.buffer
11638                .read(cx)
11639                .settings_at(0, cx)
11640                .indent_guides
11641                .enabled
11642        });
11643        self.show_indent_guides = Some(!currently_enabled);
11644        cx.notify();
11645    }
11646
11647    fn should_show_indent_guides(&self) -> Option<bool> {
11648        self.show_indent_guides
11649    }
11650
11651    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11652        let mut editor_settings = EditorSettings::get_global(cx).clone();
11653        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11654        EditorSettings::override_global(editor_settings, cx);
11655    }
11656
11657    pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11658        self.use_relative_line_numbers
11659            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11660    }
11661
11662    pub fn toggle_relative_line_numbers(
11663        &mut self,
11664        _: &ToggleRelativeLineNumbers,
11665        cx: &mut ViewContext<Self>,
11666    ) {
11667        let is_relative = self.should_use_relative_line_numbers(cx);
11668        self.set_relative_line_number(Some(!is_relative), cx)
11669    }
11670
11671    pub fn set_relative_line_number(
11672        &mut self,
11673        is_relative: Option<bool>,
11674        cx: &mut ViewContext<Self>,
11675    ) {
11676        self.use_relative_line_numbers = is_relative;
11677        cx.notify();
11678    }
11679
11680    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11681        self.show_gutter = show_gutter;
11682        cx.notify();
11683    }
11684
11685    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11686        self.show_line_numbers = Some(show_line_numbers);
11687        cx.notify();
11688    }
11689
11690    pub fn set_show_git_diff_gutter(
11691        &mut self,
11692        show_git_diff_gutter: bool,
11693        cx: &mut ViewContext<Self>,
11694    ) {
11695        self.show_git_diff_gutter = Some(show_git_diff_gutter);
11696        cx.notify();
11697    }
11698
11699    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11700        self.show_code_actions = Some(show_code_actions);
11701        cx.notify();
11702    }
11703
11704    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11705        self.show_runnables = Some(show_runnables);
11706        cx.notify();
11707    }
11708
11709    pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11710        if self.display_map.read(cx).masked != masked {
11711            self.display_map.update(cx, |map, _| map.masked = masked);
11712        }
11713        cx.notify()
11714    }
11715
11716    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11717        self.show_wrap_guides = Some(show_wrap_guides);
11718        cx.notify();
11719    }
11720
11721    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11722        self.show_indent_guides = Some(show_indent_guides);
11723        cx.notify();
11724    }
11725
11726    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11727        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11728            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11729                if let Some(dir) = file.abs_path(cx).parent() {
11730                    return Some(dir.to_owned());
11731                }
11732            }
11733
11734            if let Some(project_path) = buffer.read(cx).project_path(cx) {
11735                return Some(project_path.path.to_path_buf());
11736            }
11737        }
11738
11739        None
11740    }
11741
11742    fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11743        self.active_excerpt(cx)?
11744            .1
11745            .read(cx)
11746            .file()
11747            .and_then(|f| f.as_local())
11748    }
11749
11750    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11751        if let Some(target) = self.target_file(cx) {
11752            cx.reveal_path(&target.abs_path(cx));
11753        }
11754    }
11755
11756    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11757        if let Some(file) = self.target_file(cx) {
11758            if let Some(path) = file.abs_path(cx).to_str() {
11759                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11760            }
11761        }
11762    }
11763
11764    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11765        if let Some(file) = self.target_file(cx) {
11766            if let Some(path) = file.path().to_str() {
11767                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11768            }
11769        }
11770    }
11771
11772    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11773        self.show_git_blame_gutter = !self.show_git_blame_gutter;
11774
11775        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11776            self.start_git_blame(true, cx);
11777        }
11778
11779        cx.notify();
11780    }
11781
11782    pub fn toggle_git_blame_inline(
11783        &mut self,
11784        _: &ToggleGitBlameInline,
11785        cx: &mut ViewContext<Self>,
11786    ) {
11787        self.toggle_git_blame_inline_internal(true, cx);
11788        cx.notify();
11789    }
11790
11791    pub fn git_blame_inline_enabled(&self) -> bool {
11792        self.git_blame_inline_enabled
11793    }
11794
11795    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11796        self.show_selection_menu = self
11797            .show_selection_menu
11798            .map(|show_selections_menu| !show_selections_menu)
11799            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11800
11801        cx.notify();
11802    }
11803
11804    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11805        self.show_selection_menu
11806            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11807    }
11808
11809    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11810        if let Some(project) = self.project.as_ref() {
11811            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11812                return;
11813            };
11814
11815            if buffer.read(cx).file().is_none() {
11816                return;
11817            }
11818
11819            let focused = self.focus_handle(cx).contains_focused(cx);
11820
11821            let project = project.clone();
11822            let blame =
11823                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11824            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11825            self.blame = Some(blame);
11826        }
11827    }
11828
11829    fn toggle_git_blame_inline_internal(
11830        &mut self,
11831        user_triggered: bool,
11832        cx: &mut ViewContext<Self>,
11833    ) {
11834        if self.git_blame_inline_enabled {
11835            self.git_blame_inline_enabled = false;
11836            self.show_git_blame_inline = false;
11837            self.show_git_blame_inline_delay_task.take();
11838        } else {
11839            self.git_blame_inline_enabled = true;
11840            self.start_git_blame_inline(user_triggered, cx);
11841        }
11842
11843        cx.notify();
11844    }
11845
11846    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11847        self.start_git_blame(user_triggered, cx);
11848
11849        if ProjectSettings::get_global(cx)
11850            .git
11851            .inline_blame_delay()
11852            .is_some()
11853        {
11854            self.start_inline_blame_timer(cx);
11855        } else {
11856            self.show_git_blame_inline = true
11857        }
11858    }
11859
11860    pub fn blame(&self) -> Option<&Model<GitBlame>> {
11861        self.blame.as_ref()
11862    }
11863
11864    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11865        self.show_git_blame_gutter && self.has_blame_entries(cx)
11866    }
11867
11868    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11869        self.show_git_blame_inline
11870            && self.focus_handle.is_focused(cx)
11871            && !self.newest_selection_head_on_empty_line(cx)
11872            && self.has_blame_entries(cx)
11873    }
11874
11875    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11876        self.blame()
11877            .map_or(false, |blame| blame.read(cx).has_generated_entries())
11878    }
11879
11880    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11881        let cursor_anchor = self.selections.newest_anchor().head();
11882
11883        let snapshot = self.buffer.read(cx).snapshot(cx);
11884        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11885
11886        snapshot.line_len(buffer_row) == 0
11887    }
11888
11889    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11890        let buffer_and_selection = maybe!({
11891            let selection = self.selections.newest::<Point>(cx);
11892            let selection_range = selection.range();
11893
11894            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11895                (buffer, selection_range.start.row..selection_range.end.row)
11896            } else {
11897                let buffer_ranges = self
11898                    .buffer()
11899                    .read(cx)
11900                    .range_to_buffer_ranges(selection_range, cx);
11901
11902                let (buffer, range, _) = if selection.reversed {
11903                    buffer_ranges.first()
11904                } else {
11905                    buffer_ranges.last()
11906                }?;
11907
11908                let snapshot = buffer.read(cx).snapshot();
11909                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11910                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
11911                (buffer.clone(), selection)
11912            };
11913
11914            Some((buffer, selection))
11915        });
11916
11917        let Some((buffer, selection)) = buffer_and_selection else {
11918            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11919        };
11920
11921        let Some(project) = self.project.as_ref() else {
11922            return Task::ready(Err(anyhow!("editor does not have project")));
11923        };
11924
11925        project.update(cx, |project, cx| {
11926            project.get_permalink_to_line(&buffer, selection, cx)
11927        })
11928    }
11929
11930    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11931        let permalink_task = self.get_permalink_to_line(cx);
11932        let workspace = self.workspace();
11933
11934        cx.spawn(|_, mut cx| async move {
11935            match permalink_task.await {
11936                Ok(permalink) => {
11937                    cx.update(|cx| {
11938                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11939                    })
11940                    .ok();
11941                }
11942                Err(err) => {
11943                    let message = format!("Failed to copy permalink: {err}");
11944
11945                    Err::<(), anyhow::Error>(err).log_err();
11946
11947                    if let Some(workspace) = workspace {
11948                        workspace
11949                            .update(&mut cx, |workspace, cx| {
11950                                struct CopyPermalinkToLine;
11951
11952                                workspace.show_toast(
11953                                    Toast::new(
11954                                        NotificationId::unique::<CopyPermalinkToLine>(),
11955                                        message,
11956                                    ),
11957                                    cx,
11958                                )
11959                            })
11960                            .ok();
11961                    }
11962                }
11963            }
11964        })
11965        .detach();
11966    }
11967
11968    pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11969        let selection = self.selections.newest::<Point>(cx).start.row + 1;
11970        if let Some(file) = self.target_file(cx) {
11971            if let Some(path) = file.path().to_str() {
11972                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11973            }
11974        }
11975    }
11976
11977    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11978        let permalink_task = self.get_permalink_to_line(cx);
11979        let workspace = self.workspace();
11980
11981        cx.spawn(|_, mut cx| async move {
11982            match permalink_task.await {
11983                Ok(permalink) => {
11984                    cx.update(|cx| {
11985                        cx.open_url(permalink.as_ref());
11986                    })
11987                    .ok();
11988                }
11989                Err(err) => {
11990                    let message = format!("Failed to open permalink: {err}");
11991
11992                    Err::<(), anyhow::Error>(err).log_err();
11993
11994                    if let Some(workspace) = workspace {
11995                        workspace
11996                            .update(&mut cx, |workspace, cx| {
11997                                struct OpenPermalinkToLine;
11998
11999                                workspace.show_toast(
12000                                    Toast::new(
12001                                        NotificationId::unique::<OpenPermalinkToLine>(),
12002                                        message,
12003                                    ),
12004                                    cx,
12005                                )
12006                            })
12007                            .ok();
12008                    }
12009                }
12010            }
12011        })
12012        .detach();
12013    }
12014
12015    /// Adds a row highlight for the given range. If a row has multiple highlights, the
12016    /// last highlight added will be used.
12017    ///
12018    /// If the range ends at the beginning of a line, then that line will not be highlighted.
12019    pub fn highlight_rows<T: 'static>(
12020        &mut self,
12021        range: Range<Anchor>,
12022        color: Hsla,
12023        should_autoscroll: bool,
12024        cx: &mut ViewContext<Self>,
12025    ) {
12026        let snapshot = self.buffer().read(cx).snapshot(cx);
12027        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
12028        let ix = row_highlights.binary_search_by(|highlight| {
12029            Ordering::Equal
12030                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
12031                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
12032        });
12033
12034        if let Err(mut ix) = ix {
12035            let index = post_inc(&mut self.highlight_order);
12036
12037            // If this range intersects with the preceding highlight, then merge it with
12038            // the preceding highlight. Otherwise insert a new highlight.
12039            let mut merged = false;
12040            if ix > 0 {
12041                let prev_highlight = &mut row_highlights[ix - 1];
12042                if prev_highlight
12043                    .range
12044                    .end
12045                    .cmp(&range.start, &snapshot)
12046                    .is_ge()
12047                {
12048                    ix -= 1;
12049                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
12050                        prev_highlight.range.end = range.end;
12051                    }
12052                    merged = true;
12053                    prev_highlight.index = index;
12054                    prev_highlight.color = color;
12055                    prev_highlight.should_autoscroll = should_autoscroll;
12056                }
12057            }
12058
12059            if !merged {
12060                row_highlights.insert(
12061                    ix,
12062                    RowHighlight {
12063                        range: range.clone(),
12064                        index,
12065                        color,
12066                        should_autoscroll,
12067                    },
12068                );
12069            }
12070
12071            // If any of the following highlights intersect with this one, merge them.
12072            while let Some(next_highlight) = row_highlights.get(ix + 1) {
12073                let highlight = &row_highlights[ix];
12074                if next_highlight
12075                    .range
12076                    .start
12077                    .cmp(&highlight.range.end, &snapshot)
12078                    .is_le()
12079                {
12080                    if next_highlight
12081                        .range
12082                        .end
12083                        .cmp(&highlight.range.end, &snapshot)
12084                        .is_gt()
12085                    {
12086                        row_highlights[ix].range.end = next_highlight.range.end;
12087                    }
12088                    row_highlights.remove(ix + 1);
12089                } else {
12090                    break;
12091                }
12092            }
12093        }
12094    }
12095
12096    /// Remove any highlighted row ranges of the given type that intersect the
12097    /// given ranges.
12098    pub fn remove_highlighted_rows<T: 'static>(
12099        &mut self,
12100        ranges_to_remove: Vec<Range<Anchor>>,
12101        cx: &mut ViewContext<Self>,
12102    ) {
12103        let snapshot = self.buffer().read(cx).snapshot(cx);
12104        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
12105        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
12106        row_highlights.retain(|highlight| {
12107            while let Some(range_to_remove) = ranges_to_remove.peek() {
12108                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
12109                    Ordering::Less | Ordering::Equal => {
12110                        ranges_to_remove.next();
12111                    }
12112                    Ordering::Greater => {
12113                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
12114                            Ordering::Less | Ordering::Equal => {
12115                                return false;
12116                            }
12117                            Ordering::Greater => break,
12118                        }
12119                    }
12120                }
12121            }
12122
12123            true
12124        })
12125    }
12126
12127    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
12128    pub fn clear_row_highlights<T: 'static>(&mut self) {
12129        self.highlighted_rows.remove(&TypeId::of::<T>());
12130    }
12131
12132    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
12133    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
12134        self.highlighted_rows
12135            .get(&TypeId::of::<T>())
12136            .map_or(&[] as &[_], |vec| vec.as_slice())
12137            .iter()
12138            .map(|highlight| (highlight.range.clone(), highlight.color))
12139    }
12140
12141    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
12142    /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
12143    /// Allows to ignore certain kinds of highlights.
12144    pub fn highlighted_display_rows(
12145        &mut self,
12146        cx: &mut WindowContext,
12147    ) -> BTreeMap<DisplayRow, Hsla> {
12148        let snapshot = self.snapshot(cx);
12149        let mut used_highlight_orders = HashMap::default();
12150        self.highlighted_rows
12151            .iter()
12152            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
12153            .fold(
12154                BTreeMap::<DisplayRow, Hsla>::new(),
12155                |mut unique_rows, highlight| {
12156                    let start = highlight.range.start.to_display_point(&snapshot);
12157                    let end = highlight.range.end.to_display_point(&snapshot);
12158                    let start_row = start.row().0;
12159                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
12160                        && end.column() == 0
12161                    {
12162                        end.row().0.saturating_sub(1)
12163                    } else {
12164                        end.row().0
12165                    };
12166                    for row in start_row..=end_row {
12167                        let used_index =
12168                            used_highlight_orders.entry(row).or_insert(highlight.index);
12169                        if highlight.index >= *used_index {
12170                            *used_index = highlight.index;
12171                            unique_rows.insert(DisplayRow(row), highlight.color);
12172                        }
12173                    }
12174                    unique_rows
12175                },
12176            )
12177    }
12178
12179    pub fn highlighted_display_row_for_autoscroll(
12180        &self,
12181        snapshot: &DisplaySnapshot,
12182    ) -> Option<DisplayRow> {
12183        self.highlighted_rows
12184            .values()
12185            .flat_map(|highlighted_rows| highlighted_rows.iter())
12186            .filter_map(|highlight| {
12187                if highlight.should_autoscroll {
12188                    Some(highlight.range.start.to_display_point(snapshot).row())
12189                } else {
12190                    None
12191                }
12192            })
12193            .min()
12194    }
12195
12196    pub fn set_search_within_ranges(
12197        &mut self,
12198        ranges: &[Range<Anchor>],
12199        cx: &mut ViewContext<Self>,
12200    ) {
12201        self.highlight_background::<SearchWithinRange>(
12202            ranges,
12203            |colors| colors.editor_document_highlight_read_background,
12204            cx,
12205        )
12206    }
12207
12208    pub fn set_breadcrumb_header(&mut self, new_header: String) {
12209        self.breadcrumb_header = Some(new_header);
12210    }
12211
12212    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
12213        self.clear_background_highlights::<SearchWithinRange>(cx);
12214    }
12215
12216    pub fn highlight_background<T: 'static>(
12217        &mut self,
12218        ranges: &[Range<Anchor>],
12219        color_fetcher: fn(&ThemeColors) -> Hsla,
12220        cx: &mut ViewContext<Self>,
12221    ) {
12222        self.background_highlights
12223            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12224        self.scrollbar_marker_state.dirty = true;
12225        cx.notify();
12226    }
12227
12228    pub fn clear_background_highlights<T: 'static>(
12229        &mut self,
12230        cx: &mut ViewContext<Self>,
12231    ) -> Option<BackgroundHighlight> {
12232        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
12233        if !text_highlights.1.is_empty() {
12234            self.scrollbar_marker_state.dirty = true;
12235            cx.notify();
12236        }
12237        Some(text_highlights)
12238    }
12239
12240    pub fn highlight_gutter<T: 'static>(
12241        &mut self,
12242        ranges: &[Range<Anchor>],
12243        color_fetcher: fn(&AppContext) -> Hsla,
12244        cx: &mut ViewContext<Self>,
12245    ) {
12246        self.gutter_highlights
12247            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12248        cx.notify();
12249    }
12250
12251    pub fn clear_gutter_highlights<T: 'static>(
12252        &mut self,
12253        cx: &mut ViewContext<Self>,
12254    ) -> Option<GutterHighlight> {
12255        cx.notify();
12256        self.gutter_highlights.remove(&TypeId::of::<T>())
12257    }
12258
12259    #[cfg(feature = "test-support")]
12260    pub fn all_text_background_highlights(
12261        &mut self,
12262        cx: &mut ViewContext<Self>,
12263    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12264        let snapshot = self.snapshot(cx);
12265        let buffer = &snapshot.buffer_snapshot;
12266        let start = buffer.anchor_before(0);
12267        let end = buffer.anchor_after(buffer.len());
12268        let theme = cx.theme().colors();
12269        self.background_highlights_in_range(start..end, &snapshot, theme)
12270    }
12271
12272    #[cfg(feature = "test-support")]
12273    pub fn search_background_highlights(
12274        &mut self,
12275        cx: &mut ViewContext<Self>,
12276    ) -> Vec<Range<Point>> {
12277        let snapshot = self.buffer().read(cx).snapshot(cx);
12278
12279        let highlights = self
12280            .background_highlights
12281            .get(&TypeId::of::<items::BufferSearchHighlights>());
12282
12283        if let Some((_color, ranges)) = highlights {
12284            ranges
12285                .iter()
12286                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
12287                .collect_vec()
12288        } else {
12289            vec![]
12290        }
12291    }
12292
12293    fn document_highlights_for_position<'a>(
12294        &'a self,
12295        position: Anchor,
12296        buffer: &'a MultiBufferSnapshot,
12297    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
12298        let read_highlights = self
12299            .background_highlights
12300            .get(&TypeId::of::<DocumentHighlightRead>())
12301            .map(|h| &h.1);
12302        let write_highlights = self
12303            .background_highlights
12304            .get(&TypeId::of::<DocumentHighlightWrite>())
12305            .map(|h| &h.1);
12306        let left_position = position.bias_left(buffer);
12307        let right_position = position.bias_right(buffer);
12308        read_highlights
12309            .into_iter()
12310            .chain(write_highlights)
12311            .flat_map(move |ranges| {
12312                let start_ix = match ranges.binary_search_by(|probe| {
12313                    let cmp = probe.end.cmp(&left_position, buffer);
12314                    if cmp.is_ge() {
12315                        Ordering::Greater
12316                    } else {
12317                        Ordering::Less
12318                    }
12319                }) {
12320                    Ok(i) | Err(i) => i,
12321                };
12322
12323                ranges[start_ix..]
12324                    .iter()
12325                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
12326            })
12327    }
12328
12329    pub fn has_background_highlights<T: 'static>(&self) -> bool {
12330        self.background_highlights
12331            .get(&TypeId::of::<T>())
12332            .map_or(false, |(_, highlights)| !highlights.is_empty())
12333    }
12334
12335    pub fn background_highlights_in_range(
12336        &self,
12337        search_range: Range<Anchor>,
12338        display_snapshot: &DisplaySnapshot,
12339        theme: &ThemeColors,
12340    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12341        let mut results = Vec::new();
12342        for (color_fetcher, ranges) in self.background_highlights.values() {
12343            let color = color_fetcher(theme);
12344            let start_ix = match ranges.binary_search_by(|probe| {
12345                let cmp = probe
12346                    .end
12347                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12348                if cmp.is_gt() {
12349                    Ordering::Greater
12350                } else {
12351                    Ordering::Less
12352                }
12353            }) {
12354                Ok(i) | Err(i) => i,
12355            };
12356            for range in &ranges[start_ix..] {
12357                if range
12358                    .start
12359                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12360                    .is_ge()
12361                {
12362                    break;
12363                }
12364
12365                let start = range.start.to_display_point(display_snapshot);
12366                let end = range.end.to_display_point(display_snapshot);
12367                results.push((start..end, color))
12368            }
12369        }
12370        results
12371    }
12372
12373    pub fn background_highlight_row_ranges<T: 'static>(
12374        &self,
12375        search_range: Range<Anchor>,
12376        display_snapshot: &DisplaySnapshot,
12377        count: usize,
12378    ) -> Vec<RangeInclusive<DisplayPoint>> {
12379        let mut results = Vec::new();
12380        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12381            return vec![];
12382        };
12383
12384        let start_ix = match ranges.binary_search_by(|probe| {
12385            let cmp = probe
12386                .end
12387                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12388            if cmp.is_gt() {
12389                Ordering::Greater
12390            } else {
12391                Ordering::Less
12392            }
12393        }) {
12394            Ok(i) | Err(i) => i,
12395        };
12396        let mut push_region = |start: Option<Point>, end: Option<Point>| {
12397            if let (Some(start_display), Some(end_display)) = (start, end) {
12398                results.push(
12399                    start_display.to_display_point(display_snapshot)
12400                        ..=end_display.to_display_point(display_snapshot),
12401                );
12402            }
12403        };
12404        let mut start_row: Option<Point> = None;
12405        let mut end_row: Option<Point> = None;
12406        if ranges.len() > count {
12407            return Vec::new();
12408        }
12409        for range in &ranges[start_ix..] {
12410            if range
12411                .start
12412                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12413                .is_ge()
12414            {
12415                break;
12416            }
12417            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12418            if let Some(current_row) = &end_row {
12419                if end.row == current_row.row {
12420                    continue;
12421                }
12422            }
12423            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12424            if start_row.is_none() {
12425                assert_eq!(end_row, None);
12426                start_row = Some(start);
12427                end_row = Some(end);
12428                continue;
12429            }
12430            if let Some(current_end) = end_row.as_mut() {
12431                if start.row > current_end.row + 1 {
12432                    push_region(start_row, end_row);
12433                    start_row = Some(start);
12434                    end_row = Some(end);
12435                } else {
12436                    // Merge two hunks.
12437                    *current_end = end;
12438                }
12439            } else {
12440                unreachable!();
12441            }
12442        }
12443        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12444        push_region(start_row, end_row);
12445        results
12446    }
12447
12448    pub fn gutter_highlights_in_range(
12449        &self,
12450        search_range: Range<Anchor>,
12451        display_snapshot: &DisplaySnapshot,
12452        cx: &AppContext,
12453    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12454        let mut results = Vec::new();
12455        for (color_fetcher, ranges) in self.gutter_highlights.values() {
12456            let color = color_fetcher(cx);
12457            let start_ix = match ranges.binary_search_by(|probe| {
12458                let cmp = probe
12459                    .end
12460                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12461                if cmp.is_gt() {
12462                    Ordering::Greater
12463                } else {
12464                    Ordering::Less
12465                }
12466            }) {
12467                Ok(i) | Err(i) => i,
12468            };
12469            for range in &ranges[start_ix..] {
12470                if range
12471                    .start
12472                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12473                    .is_ge()
12474                {
12475                    break;
12476                }
12477
12478                let start = range.start.to_display_point(display_snapshot);
12479                let end = range.end.to_display_point(display_snapshot);
12480                results.push((start..end, color))
12481            }
12482        }
12483        results
12484    }
12485
12486    /// Get the text ranges corresponding to the redaction query
12487    pub fn redacted_ranges(
12488        &self,
12489        search_range: Range<Anchor>,
12490        display_snapshot: &DisplaySnapshot,
12491        cx: &WindowContext,
12492    ) -> Vec<Range<DisplayPoint>> {
12493        display_snapshot
12494            .buffer_snapshot
12495            .redacted_ranges(search_range, |file| {
12496                if let Some(file) = file {
12497                    file.is_private()
12498                        && EditorSettings::get(
12499                            Some(SettingsLocation {
12500                                worktree_id: file.worktree_id(cx),
12501                                path: file.path().as_ref(),
12502                            }),
12503                            cx,
12504                        )
12505                        .redact_private_values
12506                } else {
12507                    false
12508                }
12509            })
12510            .map(|range| {
12511                range.start.to_display_point(display_snapshot)
12512                    ..range.end.to_display_point(display_snapshot)
12513            })
12514            .collect()
12515    }
12516
12517    pub fn highlight_text<T: 'static>(
12518        &mut self,
12519        ranges: Vec<Range<Anchor>>,
12520        style: HighlightStyle,
12521        cx: &mut ViewContext<Self>,
12522    ) {
12523        self.display_map.update(cx, |map, _| {
12524            map.highlight_text(TypeId::of::<T>(), ranges, style)
12525        });
12526        cx.notify();
12527    }
12528
12529    pub(crate) fn highlight_inlays<T: 'static>(
12530        &mut self,
12531        highlights: Vec<InlayHighlight>,
12532        style: HighlightStyle,
12533        cx: &mut ViewContext<Self>,
12534    ) {
12535        self.display_map.update(cx, |map, _| {
12536            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12537        });
12538        cx.notify();
12539    }
12540
12541    pub fn text_highlights<'a, T: 'static>(
12542        &'a self,
12543        cx: &'a AppContext,
12544    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12545        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12546    }
12547
12548    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12549        let cleared = self
12550            .display_map
12551            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12552        if cleared {
12553            cx.notify();
12554        }
12555    }
12556
12557    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12558        (self.read_only(cx) || self.blink_manager.read(cx).visible())
12559            && self.focus_handle.is_focused(cx)
12560    }
12561
12562    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12563        self.show_cursor_when_unfocused = is_enabled;
12564        cx.notify();
12565    }
12566
12567    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12568        cx.notify();
12569    }
12570
12571    fn on_buffer_event(
12572        &mut self,
12573        multibuffer: Model<MultiBuffer>,
12574        event: &multi_buffer::Event,
12575        cx: &mut ViewContext<Self>,
12576    ) {
12577        match event {
12578            multi_buffer::Event::Edited {
12579                singleton_buffer_edited,
12580            } => {
12581                self.scrollbar_marker_state.dirty = true;
12582                self.active_indent_guides_state.dirty = true;
12583                self.refresh_active_diagnostics(cx);
12584                self.refresh_code_actions(cx);
12585                if self.has_active_inline_completion(cx) {
12586                    self.update_visible_inline_completion(cx);
12587                }
12588                cx.emit(EditorEvent::BufferEdited);
12589                cx.emit(SearchEvent::MatchesInvalidated);
12590                if *singleton_buffer_edited {
12591                    if let Some(project) = &self.project {
12592                        let project = project.read(cx);
12593                        #[allow(clippy::mutable_key_type)]
12594                        let languages_affected = multibuffer
12595                            .read(cx)
12596                            .all_buffers()
12597                            .into_iter()
12598                            .filter_map(|buffer| {
12599                                let buffer = buffer.read(cx);
12600                                let language = buffer.language()?;
12601                                if project.is_local()
12602                                    && project.language_servers_for_buffer(buffer, cx).count() == 0
12603                                {
12604                                    None
12605                                } else {
12606                                    Some(language)
12607                                }
12608                            })
12609                            .cloned()
12610                            .collect::<HashSet<_>>();
12611                        if !languages_affected.is_empty() {
12612                            self.refresh_inlay_hints(
12613                                InlayHintRefreshReason::BufferEdited(languages_affected),
12614                                cx,
12615                            );
12616                        }
12617                    }
12618                }
12619
12620                let Some(project) = &self.project else { return };
12621                let (telemetry, is_via_ssh) = {
12622                    let project = project.read(cx);
12623                    let telemetry = project.client().telemetry().clone();
12624                    let is_via_ssh = project.is_via_ssh();
12625                    (telemetry, is_via_ssh)
12626                };
12627                refresh_linked_ranges(self, cx);
12628                telemetry.log_edit_event("editor", is_via_ssh);
12629            }
12630            multi_buffer::Event::ExcerptsAdded {
12631                buffer,
12632                predecessor,
12633                excerpts,
12634            } => {
12635                self.tasks_update_task = Some(self.refresh_runnables(cx));
12636                cx.emit(EditorEvent::ExcerptsAdded {
12637                    buffer: buffer.clone(),
12638                    predecessor: *predecessor,
12639                    excerpts: excerpts.clone(),
12640                });
12641                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12642            }
12643            multi_buffer::Event::ExcerptsRemoved { ids } => {
12644                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12645                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12646            }
12647            multi_buffer::Event::ExcerptsEdited { ids } => {
12648                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12649            }
12650            multi_buffer::Event::ExcerptsExpanded { ids } => {
12651                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12652            }
12653            multi_buffer::Event::Reparsed(buffer_id) => {
12654                self.tasks_update_task = Some(self.refresh_runnables(cx));
12655
12656                cx.emit(EditorEvent::Reparsed(*buffer_id));
12657            }
12658            multi_buffer::Event::LanguageChanged(buffer_id) => {
12659                linked_editing_ranges::refresh_linked_ranges(self, cx);
12660                cx.emit(EditorEvent::Reparsed(*buffer_id));
12661                cx.notify();
12662            }
12663            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12664            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12665            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12666                cx.emit(EditorEvent::TitleChanged)
12667            }
12668            multi_buffer::Event::DiffBaseChanged => {
12669                self.scrollbar_marker_state.dirty = true;
12670                cx.emit(EditorEvent::DiffBaseChanged);
12671                cx.notify();
12672            }
12673            multi_buffer::Event::DiffUpdated { buffer } => {
12674                self.sync_expanded_diff_hunks(buffer.clone(), cx);
12675                cx.notify();
12676            }
12677            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12678            multi_buffer::Event::DiagnosticsUpdated => {
12679                self.refresh_active_diagnostics(cx);
12680                self.scrollbar_marker_state.dirty = true;
12681                cx.notify();
12682            }
12683            _ => {}
12684        };
12685    }
12686
12687    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12688        cx.notify();
12689    }
12690
12691    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12692        self.tasks_update_task = Some(self.refresh_runnables(cx));
12693        self.refresh_inline_completion(true, false, cx);
12694        self.refresh_inlay_hints(
12695            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12696                self.selections.newest_anchor().head(),
12697                &self.buffer.read(cx).snapshot(cx),
12698                cx,
12699            )),
12700            cx,
12701        );
12702
12703        let old_cursor_shape = self.cursor_shape;
12704
12705        {
12706            let editor_settings = EditorSettings::get_global(cx);
12707            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12708            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12709            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12710        }
12711
12712        if old_cursor_shape != self.cursor_shape {
12713            cx.emit(EditorEvent::CursorShapeChanged);
12714        }
12715
12716        let project_settings = ProjectSettings::get_global(cx);
12717        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12718
12719        if self.mode == EditorMode::Full {
12720            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12721            if self.git_blame_inline_enabled != inline_blame_enabled {
12722                self.toggle_git_blame_inline_internal(false, cx);
12723            }
12724        }
12725
12726        cx.notify();
12727    }
12728
12729    pub fn set_searchable(&mut self, searchable: bool) {
12730        self.searchable = searchable;
12731    }
12732
12733    pub fn searchable(&self) -> bool {
12734        self.searchable
12735    }
12736
12737    fn open_proposed_changes_editor(
12738        &mut self,
12739        _: &OpenProposedChangesEditor,
12740        cx: &mut ViewContext<Self>,
12741    ) {
12742        let Some(workspace) = self.workspace() else {
12743            cx.propagate();
12744            return;
12745        };
12746
12747        let selections = self.selections.all::<usize>(cx);
12748        let buffer = self.buffer.read(cx);
12749        let mut new_selections_by_buffer = HashMap::default();
12750        for selection in selections {
12751            for (buffer, range, _) in
12752                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12753            {
12754                let mut range = range.to_point(buffer.read(cx));
12755                range.start.column = 0;
12756                range.end.column = buffer.read(cx).line_len(range.end.row);
12757                new_selections_by_buffer
12758                    .entry(buffer)
12759                    .or_insert(Vec::new())
12760                    .push(range)
12761            }
12762        }
12763
12764        let proposed_changes_buffers = new_selections_by_buffer
12765            .into_iter()
12766            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12767            .collect::<Vec<_>>();
12768        let proposed_changes_editor = cx.new_view(|cx| {
12769            ProposedChangesEditor::new(
12770                "Proposed changes",
12771                proposed_changes_buffers,
12772                self.project.clone(),
12773                cx,
12774            )
12775        });
12776
12777        cx.window_context().defer(move |cx| {
12778            workspace.update(cx, |workspace, cx| {
12779                workspace.active_pane().update(cx, |pane, cx| {
12780                    pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12781                });
12782            });
12783        });
12784    }
12785
12786    pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12787        self.open_excerpts_common(None, true, cx)
12788    }
12789
12790    pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12791        self.open_excerpts_common(None, false, cx)
12792    }
12793
12794    fn open_excerpts_common(
12795        &mut self,
12796        jump_data: Option<JumpData>,
12797        split: bool,
12798        cx: &mut ViewContext<Self>,
12799    ) {
12800        let Some(workspace) = self.workspace() else {
12801            cx.propagate();
12802            return;
12803        };
12804
12805        if self.buffer.read(cx).is_singleton() {
12806            cx.propagate();
12807            return;
12808        }
12809
12810        let mut new_selections_by_buffer = HashMap::default();
12811        match &jump_data {
12812            Some(jump_data) => {
12813                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12814                if let Some(buffer) = multi_buffer_snapshot
12815                    .buffer_id_for_excerpt(jump_data.excerpt_id)
12816                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12817                {
12818                    let buffer_snapshot = buffer.read(cx).snapshot();
12819                    let jump_to_point = if buffer_snapshot.can_resolve(&jump_data.anchor) {
12820                        language::ToPoint::to_point(&jump_data.anchor, &buffer_snapshot)
12821                    } else {
12822                        buffer_snapshot.clip_point(jump_data.position, Bias::Left)
12823                    };
12824                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12825                    new_selections_by_buffer.insert(
12826                        buffer,
12827                        (
12828                            vec![jump_to_offset..jump_to_offset],
12829                            Some(jump_data.line_offset_from_top),
12830                        ),
12831                    );
12832                }
12833            }
12834            None => {
12835                let selections = self.selections.all::<usize>(cx);
12836                let buffer = self.buffer.read(cx);
12837                for selection in selections {
12838                    for (mut buffer_handle, mut range, _) in
12839                        buffer.range_to_buffer_ranges(selection.range(), cx)
12840                    {
12841                        // When editing branch buffers, jump to the corresponding location
12842                        // in their base buffer.
12843                        let buffer = buffer_handle.read(cx);
12844                        if let Some(base_buffer) = buffer.diff_base_buffer() {
12845                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12846                            buffer_handle = base_buffer;
12847                        }
12848
12849                        if selection.reversed {
12850                            mem::swap(&mut range.start, &mut range.end);
12851                        }
12852                        new_selections_by_buffer
12853                            .entry(buffer_handle)
12854                            .or_insert((Vec::new(), None))
12855                            .0
12856                            .push(range)
12857                    }
12858                }
12859            }
12860        }
12861
12862        if new_selections_by_buffer.is_empty() {
12863            return;
12864        }
12865
12866        // We defer the pane interaction because we ourselves are a workspace item
12867        // and activating a new item causes the pane to call a method on us reentrantly,
12868        // which panics if we're on the stack.
12869        cx.window_context().defer(move |cx| {
12870            workspace.update(cx, |workspace, cx| {
12871                let pane = if split {
12872                    workspace.adjacent_pane(cx)
12873                } else {
12874                    workspace.active_pane().clone()
12875                };
12876
12877                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12878                    let editor = buffer
12879                        .read(cx)
12880                        .file()
12881                        .is_none()
12882                        .then(|| {
12883                            // Handle file-less buffers separately: those are not really the project items, so won't have a paroject path or entity id,
12884                            // so `workspace.open_project_item` will never find them, always opening a new editor.
12885                            // Instead, we try to activate the existing editor in the pane first.
12886                            let (editor, pane_item_index) =
12887                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
12888                                    let editor = item.downcast::<Editor>()?;
12889                                    let singleton_buffer =
12890                                        editor.read(cx).buffer().read(cx).as_singleton()?;
12891                                    if singleton_buffer == buffer {
12892                                        Some((editor, i))
12893                                    } else {
12894                                        None
12895                                    }
12896                                })?;
12897                            pane.update(cx, |pane, cx| {
12898                                pane.activate_item(pane_item_index, true, true, cx)
12899                            });
12900                            Some(editor)
12901                        })
12902                        .flatten()
12903                        .unwrap_or_else(|| {
12904                            workspace.open_project_item::<Self>(
12905                                pane.clone(),
12906                                buffer,
12907                                true,
12908                                true,
12909                                cx,
12910                            )
12911                        });
12912
12913                    editor.update(cx, |editor, cx| {
12914                        let autoscroll = match scroll_offset {
12915                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12916                            None => Autoscroll::newest(),
12917                        };
12918                        let nav_history = editor.nav_history.take();
12919                        editor.change_selections(Some(autoscroll), cx, |s| {
12920                            s.select_ranges(ranges);
12921                        });
12922                        editor.nav_history = nav_history;
12923                    });
12924                }
12925            })
12926        });
12927    }
12928
12929    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12930        let snapshot = self.buffer.read(cx).read(cx);
12931        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12932        Some(
12933            ranges
12934                .iter()
12935                .map(move |range| {
12936                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12937                })
12938                .collect(),
12939        )
12940    }
12941
12942    fn selection_replacement_ranges(
12943        &self,
12944        range: Range<OffsetUtf16>,
12945        cx: &mut AppContext,
12946    ) -> Vec<Range<OffsetUtf16>> {
12947        let selections = self.selections.all::<OffsetUtf16>(cx);
12948        let newest_selection = selections
12949            .iter()
12950            .max_by_key(|selection| selection.id)
12951            .unwrap();
12952        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12953        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12954        let snapshot = self.buffer.read(cx).read(cx);
12955        selections
12956            .into_iter()
12957            .map(|mut selection| {
12958                selection.start.0 =
12959                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
12960                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12961                snapshot.clip_offset_utf16(selection.start, Bias::Left)
12962                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12963            })
12964            .collect()
12965    }
12966
12967    fn report_editor_event(
12968        &self,
12969        operation: &'static str,
12970        file_extension: Option<String>,
12971        cx: &AppContext,
12972    ) {
12973        if cfg!(any(test, feature = "test-support")) {
12974            return;
12975        }
12976
12977        let Some(project) = &self.project else { return };
12978
12979        // If None, we are in a file without an extension
12980        let file = self
12981            .buffer
12982            .read(cx)
12983            .as_singleton()
12984            .and_then(|b| b.read(cx).file());
12985        let file_extension = file_extension.or(file
12986            .as_ref()
12987            .and_then(|file| Path::new(file.file_name(cx)).extension())
12988            .and_then(|e| e.to_str())
12989            .map(|a| a.to_string()));
12990
12991        let vim_mode = cx
12992            .global::<SettingsStore>()
12993            .raw_user_settings()
12994            .get("vim_mode")
12995            == Some(&serde_json::Value::Bool(true));
12996
12997        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12998            == language::language_settings::InlineCompletionProvider::Copilot;
12999        let copilot_enabled_for_language = self
13000            .buffer
13001            .read(cx)
13002            .settings_at(0, cx)
13003            .show_inline_completions;
13004
13005        let project = project.read(cx);
13006        let telemetry = project.client().telemetry().clone();
13007        telemetry.report_editor_event(
13008            file_extension,
13009            vim_mode,
13010            operation,
13011            copilot_enabled,
13012            copilot_enabled_for_language,
13013            project.is_via_ssh(),
13014        )
13015    }
13016
13017    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
13018    /// with each line being an array of {text, highlight} objects.
13019    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
13020        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
13021            return;
13022        };
13023
13024        #[derive(Serialize)]
13025        struct Chunk<'a> {
13026            text: String,
13027            highlight: Option<&'a str>,
13028        }
13029
13030        let snapshot = buffer.read(cx).snapshot();
13031        let range = self
13032            .selected_text_range(false, cx)
13033            .and_then(|selection| {
13034                if selection.range.is_empty() {
13035                    None
13036                } else {
13037                    Some(selection.range)
13038                }
13039            })
13040            .unwrap_or_else(|| 0..snapshot.len());
13041
13042        let chunks = snapshot.chunks(range, true);
13043        let mut lines = Vec::new();
13044        let mut line: VecDeque<Chunk> = VecDeque::new();
13045
13046        let Some(style) = self.style.as_ref() else {
13047            return;
13048        };
13049
13050        for chunk in chunks {
13051            let highlight = chunk
13052                .syntax_highlight_id
13053                .and_then(|id| id.name(&style.syntax));
13054            let mut chunk_lines = chunk.text.split('\n').peekable();
13055            while let Some(text) = chunk_lines.next() {
13056                let mut merged_with_last_token = false;
13057                if let Some(last_token) = line.back_mut() {
13058                    if last_token.highlight == highlight {
13059                        last_token.text.push_str(text);
13060                        merged_with_last_token = true;
13061                    }
13062                }
13063
13064                if !merged_with_last_token {
13065                    line.push_back(Chunk {
13066                        text: text.into(),
13067                        highlight,
13068                    });
13069                }
13070
13071                if chunk_lines.peek().is_some() {
13072                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
13073                        line.pop_front();
13074                    }
13075                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
13076                        line.pop_back();
13077                    }
13078
13079                    lines.push(mem::take(&mut line));
13080                }
13081            }
13082        }
13083
13084        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
13085            return;
13086        };
13087        cx.write_to_clipboard(ClipboardItem::new_string(lines));
13088    }
13089
13090    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
13091        &self.inlay_hint_cache
13092    }
13093
13094    pub fn replay_insert_event(
13095        &mut self,
13096        text: &str,
13097        relative_utf16_range: Option<Range<isize>>,
13098        cx: &mut ViewContext<Self>,
13099    ) {
13100        if !self.input_enabled {
13101            cx.emit(EditorEvent::InputIgnored { text: text.into() });
13102            return;
13103        }
13104        if let Some(relative_utf16_range) = relative_utf16_range {
13105            let selections = self.selections.all::<OffsetUtf16>(cx);
13106            self.change_selections(None, cx, |s| {
13107                let new_ranges = selections.into_iter().map(|range| {
13108                    let start = OffsetUtf16(
13109                        range
13110                            .head()
13111                            .0
13112                            .saturating_add_signed(relative_utf16_range.start),
13113                    );
13114                    let end = OffsetUtf16(
13115                        range
13116                            .head()
13117                            .0
13118                            .saturating_add_signed(relative_utf16_range.end),
13119                    );
13120                    start..end
13121                });
13122                s.select_ranges(new_ranges);
13123            });
13124        }
13125
13126        self.handle_input(text, cx);
13127    }
13128
13129    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
13130        let Some(provider) = self.semantics_provider.as_ref() else {
13131            return false;
13132        };
13133
13134        let mut supports = false;
13135        self.buffer().read(cx).for_each_buffer(|buffer| {
13136            supports |= provider.supports_inlay_hints(buffer, cx);
13137        });
13138        supports
13139    }
13140
13141    pub fn focus(&self, cx: &mut WindowContext) {
13142        cx.focus(&self.focus_handle)
13143    }
13144
13145    pub fn is_focused(&self, cx: &WindowContext) -> bool {
13146        self.focus_handle.is_focused(cx)
13147    }
13148
13149    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
13150        cx.emit(EditorEvent::Focused);
13151
13152        if let Some(descendant) = self
13153            .last_focused_descendant
13154            .take()
13155            .and_then(|descendant| descendant.upgrade())
13156        {
13157            cx.focus(&descendant);
13158        } else {
13159            if let Some(blame) = self.blame.as_ref() {
13160                blame.update(cx, GitBlame::focus)
13161            }
13162
13163            self.blink_manager.update(cx, BlinkManager::enable);
13164            self.show_cursor_names(cx);
13165            self.buffer.update(cx, |buffer, cx| {
13166                buffer.finalize_last_transaction(cx);
13167                if self.leader_peer_id.is_none() {
13168                    buffer.set_active_selections(
13169                        &self.selections.disjoint_anchors(),
13170                        self.selections.line_mode,
13171                        self.cursor_shape,
13172                        cx,
13173                    );
13174                }
13175            });
13176        }
13177    }
13178
13179    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
13180        cx.emit(EditorEvent::FocusedIn)
13181    }
13182
13183    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
13184        if event.blurred != self.focus_handle {
13185            self.last_focused_descendant = Some(event.blurred);
13186        }
13187    }
13188
13189    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
13190        self.blink_manager.update(cx, BlinkManager::disable);
13191        self.buffer
13192            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
13193
13194        if let Some(blame) = self.blame.as_ref() {
13195            blame.update(cx, GitBlame::blur)
13196        }
13197        if !self.hover_state.focused(cx) {
13198            hide_hover(self, cx);
13199        }
13200
13201        self.hide_context_menu(cx);
13202        cx.emit(EditorEvent::Blurred);
13203        cx.notify();
13204    }
13205
13206    pub fn register_action<A: Action>(
13207        &mut self,
13208        listener: impl Fn(&A, &mut WindowContext) + 'static,
13209    ) -> Subscription {
13210        let id = self.next_editor_action_id.post_inc();
13211        let listener = Arc::new(listener);
13212        self.editor_actions.borrow_mut().insert(
13213            id,
13214            Box::new(move |cx| {
13215                let cx = cx.window_context();
13216                let listener = listener.clone();
13217                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
13218                    let action = action.downcast_ref().unwrap();
13219                    if phase == DispatchPhase::Bubble {
13220                        listener(action, cx)
13221                    }
13222                })
13223            }),
13224        );
13225
13226        let editor_actions = self.editor_actions.clone();
13227        Subscription::new(move || {
13228            editor_actions.borrow_mut().remove(&id);
13229        })
13230    }
13231
13232    pub fn file_header_size(&self) -> u32 {
13233        FILE_HEADER_HEIGHT
13234    }
13235
13236    pub fn revert(
13237        &mut self,
13238        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
13239        cx: &mut ViewContext<Self>,
13240    ) {
13241        self.buffer().update(cx, |multi_buffer, cx| {
13242            for (buffer_id, changes) in revert_changes {
13243                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13244                    buffer.update(cx, |buffer, cx| {
13245                        buffer.edit(
13246                            changes.into_iter().map(|(range, text)| {
13247                                (range, text.to_string().map(Arc::<str>::from))
13248                            }),
13249                            None,
13250                            cx,
13251                        );
13252                    });
13253                }
13254            }
13255        });
13256        self.change_selections(None, cx, |selections| selections.refresh());
13257    }
13258
13259    pub fn to_pixel_point(
13260        &mut self,
13261        source: multi_buffer::Anchor,
13262        editor_snapshot: &EditorSnapshot,
13263        cx: &mut ViewContext<Self>,
13264    ) -> Option<gpui::Point<Pixels>> {
13265        let source_point = source.to_display_point(editor_snapshot);
13266        self.display_to_pixel_point(source_point, editor_snapshot, cx)
13267    }
13268
13269    pub fn display_to_pixel_point(
13270        &mut self,
13271        source: DisplayPoint,
13272        editor_snapshot: &EditorSnapshot,
13273        cx: &mut ViewContext<Self>,
13274    ) -> Option<gpui::Point<Pixels>> {
13275        let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
13276        let text_layout_details = self.text_layout_details(cx);
13277        let scroll_top = text_layout_details
13278            .scroll_anchor
13279            .scroll_position(editor_snapshot)
13280            .y;
13281
13282        if source.row().as_f32() < scroll_top.floor() {
13283            return None;
13284        }
13285        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
13286        let source_y = line_height * (source.row().as_f32() - scroll_top);
13287        Some(gpui::Point::new(source_x, source_y))
13288    }
13289
13290    pub fn has_active_completions_menu(&self) -> bool {
13291        self.context_menu.read().as_ref().map_or(false, |menu| {
13292            menu.visible() && matches!(menu, ContextMenu::Completions(_))
13293        })
13294    }
13295
13296    pub fn register_addon<T: Addon>(&mut self, instance: T) {
13297        self.addons
13298            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
13299    }
13300
13301    pub fn unregister_addon<T: Addon>(&mut self) {
13302        self.addons.remove(&std::any::TypeId::of::<T>());
13303    }
13304
13305    pub fn addon<T: Addon>(&self) -> Option<&T> {
13306        let type_id = std::any::TypeId::of::<T>();
13307        self.addons
13308            .get(&type_id)
13309            .and_then(|item| item.to_any().downcast_ref::<T>())
13310    }
13311}
13312
13313fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13314    let tab_size = tab_size.get() as usize;
13315    let mut width = offset;
13316
13317    for ch in text.chars() {
13318        width += if ch == '\t' {
13319            tab_size - (width % tab_size)
13320        } else {
13321            1
13322        };
13323    }
13324
13325    width - offset
13326}
13327
13328#[cfg(test)]
13329mod tests {
13330    use super::*;
13331
13332    #[test]
13333    fn test_string_size_with_expanded_tabs() {
13334        let nz = |val| NonZeroU32::new(val).unwrap();
13335        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13336        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13337        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13338        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13339        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13340        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13341        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13342        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13343    }
13344}
13345
13346/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13347struct WordBreakingTokenizer<'a> {
13348    input: &'a str,
13349}
13350
13351impl<'a> WordBreakingTokenizer<'a> {
13352    fn new(input: &'a str) -> Self {
13353        Self { input }
13354    }
13355}
13356
13357fn is_char_ideographic(ch: char) -> bool {
13358    use unicode_script::Script::*;
13359    use unicode_script::UnicodeScript;
13360    matches!(ch.script(), Han | Tangut | Yi)
13361}
13362
13363fn is_grapheme_ideographic(text: &str) -> bool {
13364    text.chars().any(is_char_ideographic)
13365}
13366
13367fn is_grapheme_whitespace(text: &str) -> bool {
13368    text.chars().any(|x| x.is_whitespace())
13369}
13370
13371fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13372    text.chars().next().map_or(false, |ch| {
13373        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13374    })
13375}
13376
13377#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13378struct WordBreakToken<'a> {
13379    token: &'a str,
13380    grapheme_len: usize,
13381    is_whitespace: bool,
13382}
13383
13384impl<'a> Iterator for WordBreakingTokenizer<'a> {
13385    /// Yields a span, the count of graphemes in the token, and whether it was
13386    /// whitespace. Note that it also breaks at word boundaries.
13387    type Item = WordBreakToken<'a>;
13388
13389    fn next(&mut self) -> Option<Self::Item> {
13390        use unicode_segmentation::UnicodeSegmentation;
13391        if self.input.is_empty() {
13392            return None;
13393        }
13394
13395        let mut iter = self.input.graphemes(true).peekable();
13396        let mut offset = 0;
13397        let mut graphemes = 0;
13398        if let Some(first_grapheme) = iter.next() {
13399            let is_whitespace = is_grapheme_whitespace(first_grapheme);
13400            offset += first_grapheme.len();
13401            graphemes += 1;
13402            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13403                if let Some(grapheme) = iter.peek().copied() {
13404                    if should_stay_with_preceding_ideograph(grapheme) {
13405                        offset += grapheme.len();
13406                        graphemes += 1;
13407                    }
13408                }
13409            } else {
13410                let mut words = self.input[offset..].split_word_bound_indices().peekable();
13411                let mut next_word_bound = words.peek().copied();
13412                if next_word_bound.map_or(false, |(i, _)| i == 0) {
13413                    next_word_bound = words.next();
13414                }
13415                while let Some(grapheme) = iter.peek().copied() {
13416                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
13417                        break;
13418                    };
13419                    if is_grapheme_whitespace(grapheme) != is_whitespace {
13420                        break;
13421                    };
13422                    offset += grapheme.len();
13423                    graphemes += 1;
13424                    iter.next();
13425                }
13426            }
13427            let token = &self.input[..offset];
13428            self.input = &self.input[offset..];
13429            if is_whitespace {
13430                Some(WordBreakToken {
13431                    token: " ",
13432                    grapheme_len: 1,
13433                    is_whitespace: true,
13434                })
13435            } else {
13436                Some(WordBreakToken {
13437                    token,
13438                    grapheme_len: graphemes,
13439                    is_whitespace: false,
13440                })
13441            }
13442        } else {
13443            None
13444        }
13445    }
13446}
13447
13448#[test]
13449fn test_word_breaking_tokenizer() {
13450    let tests: &[(&str, &[(&str, usize, bool)])] = &[
13451        ("", &[]),
13452        ("  ", &[(" ", 1, true)]),
13453        ("Ʒ", &[("Ʒ", 1, false)]),
13454        ("Ǽ", &[("Ǽ", 1, false)]),
13455        ("", &[("", 1, false)]),
13456        ("⋑⋑", &[("⋑⋑", 2, false)]),
13457        (
13458            "原理,进而",
13459            &[
13460                ("", 1, false),
13461                ("理,", 2, false),
13462                ("", 1, false),
13463                ("", 1, false),
13464            ],
13465        ),
13466        (
13467            "hello world",
13468            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13469        ),
13470        (
13471            "hello, world",
13472            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13473        ),
13474        (
13475            "  hello world",
13476            &[
13477                (" ", 1, true),
13478                ("hello", 5, false),
13479                (" ", 1, true),
13480                ("world", 5, false),
13481            ],
13482        ),
13483        (
13484            "这是什么 \n 钢笔",
13485            &[
13486                ("", 1, false),
13487                ("", 1, false),
13488                ("", 1, false),
13489                ("", 1, false),
13490                (" ", 1, true),
13491                ("", 1, false),
13492                ("", 1, false),
13493            ],
13494        ),
13495        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13496    ];
13497
13498    for (input, result) in tests {
13499        assert_eq!(
13500            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13501            result
13502                .iter()
13503                .copied()
13504                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13505                    token,
13506                    grapheme_len,
13507                    is_whitespace,
13508                })
13509                .collect::<Vec<_>>()
13510        );
13511    }
13512}
13513
13514fn wrap_with_prefix(
13515    line_prefix: String,
13516    unwrapped_text: String,
13517    wrap_column: usize,
13518    tab_size: NonZeroU32,
13519) -> String {
13520    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13521    let mut wrapped_text = String::new();
13522    let mut current_line = line_prefix.clone();
13523
13524    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13525    let mut current_line_len = line_prefix_len;
13526    for WordBreakToken {
13527        token,
13528        grapheme_len,
13529        is_whitespace,
13530    } in tokenizer
13531    {
13532        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13533            wrapped_text.push_str(current_line.trim_end());
13534            wrapped_text.push('\n');
13535            current_line.truncate(line_prefix.len());
13536            current_line_len = line_prefix_len;
13537            if !is_whitespace {
13538                current_line.push_str(token);
13539                current_line_len += grapheme_len;
13540            }
13541        } else if !is_whitespace {
13542            current_line.push_str(token);
13543            current_line_len += grapheme_len;
13544        } else if current_line_len != line_prefix_len {
13545            current_line.push(' ');
13546            current_line_len += 1;
13547        }
13548    }
13549
13550    if !current_line.is_empty() {
13551        wrapped_text.push_str(&current_line);
13552    }
13553    wrapped_text
13554}
13555
13556#[test]
13557fn test_wrap_with_prefix() {
13558    assert_eq!(
13559        wrap_with_prefix(
13560            "# ".to_string(),
13561            "abcdefg".to_string(),
13562            4,
13563            NonZeroU32::new(4).unwrap()
13564        ),
13565        "# abcdefg"
13566    );
13567    assert_eq!(
13568        wrap_with_prefix(
13569            "".to_string(),
13570            "\thello world".to_string(),
13571            8,
13572            NonZeroU32::new(4).unwrap()
13573        ),
13574        "hello\nworld"
13575    );
13576    assert_eq!(
13577        wrap_with_prefix(
13578            "// ".to_string(),
13579            "xx \nyy zz aa bb cc".to_string(),
13580            12,
13581            NonZeroU32::new(4).unwrap()
13582        ),
13583        "// xx yy zz\n// aa bb cc"
13584    );
13585    assert_eq!(
13586        wrap_with_prefix(
13587            String::new(),
13588            "这是什么 \n 钢笔".to_string(),
13589            3,
13590            NonZeroU32::new(4).unwrap()
13591        ),
13592        "这是什\n么 钢\n"
13593    );
13594}
13595
13596fn hunks_for_selections(
13597    multi_buffer_snapshot: &MultiBufferSnapshot,
13598    selections: &[Selection<Anchor>],
13599) -> Vec<MultiBufferDiffHunk> {
13600    let buffer_rows_for_selections = selections.iter().map(|selection| {
13601        let head = selection.head();
13602        let tail = selection.tail();
13603        let start = MultiBufferRow(tail.to_point(multi_buffer_snapshot).row);
13604        let end = MultiBufferRow(head.to_point(multi_buffer_snapshot).row);
13605        if start > end {
13606            end..start
13607        } else {
13608            start..end
13609        }
13610    });
13611
13612    hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
13613}
13614
13615pub fn hunks_for_rows(
13616    rows: impl Iterator<Item = Range<MultiBufferRow>>,
13617    multi_buffer_snapshot: &MultiBufferSnapshot,
13618) -> Vec<MultiBufferDiffHunk> {
13619    let mut hunks = Vec::new();
13620    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13621        HashMap::default();
13622    for selected_multi_buffer_rows in rows {
13623        let query_rows =
13624            selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
13625        for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
13626            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13627            // when the caret is just above or just below the deleted hunk.
13628            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13629            let related_to_selection = if allow_adjacent {
13630                hunk.row_range.overlaps(&query_rows)
13631                    || hunk.row_range.start == query_rows.end
13632                    || hunk.row_range.end == query_rows.start
13633            } else {
13634                // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
13635                // `hunk.row_range` is exclusive (e.g. [2..3] means 2nd row is selected)
13636                hunk.row_range.overlaps(&selected_multi_buffer_rows)
13637                    || selected_multi_buffer_rows.end == hunk.row_range.start
13638            };
13639            if related_to_selection {
13640                if !processed_buffer_rows
13641                    .entry(hunk.buffer_id)
13642                    .or_default()
13643                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13644                {
13645                    continue;
13646                }
13647                hunks.push(hunk);
13648            }
13649        }
13650    }
13651
13652    hunks
13653}
13654
13655pub trait CollaborationHub {
13656    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13657    fn user_participant_indices<'a>(
13658        &self,
13659        cx: &'a AppContext,
13660    ) -> &'a HashMap<u64, ParticipantIndex>;
13661    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13662}
13663
13664impl CollaborationHub for Model<Project> {
13665    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13666        self.read(cx).collaborators()
13667    }
13668
13669    fn user_participant_indices<'a>(
13670        &self,
13671        cx: &'a AppContext,
13672    ) -> &'a HashMap<u64, ParticipantIndex> {
13673        self.read(cx).user_store().read(cx).participant_indices()
13674    }
13675
13676    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13677        let this = self.read(cx);
13678        let user_ids = this.collaborators().values().map(|c| c.user_id);
13679        this.user_store().read_with(cx, |user_store, cx| {
13680            user_store.participant_names(user_ids, cx)
13681        })
13682    }
13683}
13684
13685pub trait SemanticsProvider {
13686    fn hover(
13687        &self,
13688        buffer: &Model<Buffer>,
13689        position: text::Anchor,
13690        cx: &mut AppContext,
13691    ) -> Option<Task<Vec<project::Hover>>>;
13692
13693    fn inlay_hints(
13694        &self,
13695        buffer_handle: Model<Buffer>,
13696        range: Range<text::Anchor>,
13697        cx: &mut AppContext,
13698    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13699
13700    fn resolve_inlay_hint(
13701        &self,
13702        hint: InlayHint,
13703        buffer_handle: Model<Buffer>,
13704        server_id: LanguageServerId,
13705        cx: &mut AppContext,
13706    ) -> Option<Task<anyhow::Result<InlayHint>>>;
13707
13708    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13709
13710    fn document_highlights(
13711        &self,
13712        buffer: &Model<Buffer>,
13713        position: text::Anchor,
13714        cx: &mut AppContext,
13715    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13716
13717    fn definitions(
13718        &self,
13719        buffer: &Model<Buffer>,
13720        position: text::Anchor,
13721        kind: GotoDefinitionKind,
13722        cx: &mut AppContext,
13723    ) -> Option<Task<Result<Vec<LocationLink>>>>;
13724
13725    fn range_for_rename(
13726        &self,
13727        buffer: &Model<Buffer>,
13728        position: text::Anchor,
13729        cx: &mut AppContext,
13730    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13731
13732    fn perform_rename(
13733        &self,
13734        buffer: &Model<Buffer>,
13735        position: text::Anchor,
13736        new_name: String,
13737        cx: &mut AppContext,
13738    ) -> Option<Task<Result<ProjectTransaction>>>;
13739}
13740
13741pub trait CompletionProvider {
13742    fn completions(
13743        &self,
13744        buffer: &Model<Buffer>,
13745        buffer_position: text::Anchor,
13746        trigger: CompletionContext,
13747        cx: &mut ViewContext<Editor>,
13748    ) -> Task<Result<Vec<Completion>>>;
13749
13750    fn resolve_completions(
13751        &self,
13752        buffer: Model<Buffer>,
13753        completion_indices: Vec<usize>,
13754        completions: Arc<RwLock<Box<[Completion]>>>,
13755        cx: &mut ViewContext<Editor>,
13756    ) -> Task<Result<bool>>;
13757
13758    fn apply_additional_edits_for_completion(
13759        &self,
13760        buffer: Model<Buffer>,
13761        completion: Completion,
13762        push_to_history: bool,
13763        cx: &mut ViewContext<Editor>,
13764    ) -> Task<Result<Option<language::Transaction>>>;
13765
13766    fn is_completion_trigger(
13767        &self,
13768        buffer: &Model<Buffer>,
13769        position: language::Anchor,
13770        text: &str,
13771        trigger_in_words: bool,
13772        cx: &mut ViewContext<Editor>,
13773    ) -> bool;
13774
13775    fn sort_completions(&self) -> bool {
13776        true
13777    }
13778}
13779
13780pub trait CodeActionProvider {
13781    fn code_actions(
13782        &self,
13783        buffer: &Model<Buffer>,
13784        range: Range<text::Anchor>,
13785        cx: &mut WindowContext,
13786    ) -> Task<Result<Vec<CodeAction>>>;
13787
13788    fn apply_code_action(
13789        &self,
13790        buffer_handle: Model<Buffer>,
13791        action: CodeAction,
13792        excerpt_id: ExcerptId,
13793        push_to_history: bool,
13794        cx: &mut WindowContext,
13795    ) -> Task<Result<ProjectTransaction>>;
13796}
13797
13798impl CodeActionProvider for Model<Project> {
13799    fn code_actions(
13800        &self,
13801        buffer: &Model<Buffer>,
13802        range: Range<text::Anchor>,
13803        cx: &mut WindowContext,
13804    ) -> Task<Result<Vec<CodeAction>>> {
13805        self.update(cx, |project, cx| {
13806            project.code_actions(buffer, range, None, cx)
13807        })
13808    }
13809
13810    fn apply_code_action(
13811        &self,
13812        buffer_handle: Model<Buffer>,
13813        action: CodeAction,
13814        _excerpt_id: ExcerptId,
13815        push_to_history: bool,
13816        cx: &mut WindowContext,
13817    ) -> Task<Result<ProjectTransaction>> {
13818        self.update(cx, |project, cx| {
13819            project.apply_code_action(buffer_handle, action, push_to_history, cx)
13820        })
13821    }
13822}
13823
13824fn snippet_completions(
13825    project: &Project,
13826    buffer: &Model<Buffer>,
13827    buffer_position: text::Anchor,
13828    cx: &mut AppContext,
13829) -> Vec<Completion> {
13830    let language = buffer.read(cx).language_at(buffer_position);
13831    let language_name = language.as_ref().map(|language| language.lsp_id());
13832    let snippet_store = project.snippets().read(cx);
13833    let snippets = snippet_store.snippets_for(language_name, cx);
13834
13835    if snippets.is_empty() {
13836        return vec![];
13837    }
13838    let snapshot = buffer.read(cx).text_snapshot();
13839    let chars = snapshot.reversed_chars_for_range(text::Anchor::MIN..buffer_position);
13840
13841    let scope = language.map(|language| language.default_scope());
13842    let classifier = CharClassifier::new(scope).for_completion(true);
13843    let mut last_word = chars
13844        .take_while(|c| classifier.is_word(*c))
13845        .collect::<String>();
13846    last_word = last_word.chars().rev().collect();
13847    let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13848    let to_lsp = |point: &text::Anchor| {
13849        let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13850        point_to_lsp(end)
13851    };
13852    let lsp_end = to_lsp(&buffer_position);
13853    snippets
13854        .into_iter()
13855        .filter_map(|snippet| {
13856            let matching_prefix = snippet
13857                .prefix
13858                .iter()
13859                .find(|prefix| prefix.starts_with(&last_word))?;
13860            let start = as_offset - last_word.len();
13861            let start = snapshot.anchor_before(start);
13862            let range = start..buffer_position;
13863            let lsp_start = to_lsp(&start);
13864            let lsp_range = lsp::Range {
13865                start: lsp_start,
13866                end: lsp_end,
13867            };
13868            Some(Completion {
13869                old_range: range,
13870                new_text: snippet.body.clone(),
13871                label: CodeLabel {
13872                    text: matching_prefix.clone(),
13873                    runs: vec![],
13874                    filter_range: 0..matching_prefix.len(),
13875                },
13876                server_id: LanguageServerId(usize::MAX),
13877                documentation: snippet.description.clone().map(Documentation::SingleLine),
13878                lsp_completion: lsp::CompletionItem {
13879                    label: snippet.prefix.first().unwrap().clone(),
13880                    kind: Some(CompletionItemKind::SNIPPET),
13881                    label_details: snippet.description.as_ref().map(|description| {
13882                        lsp::CompletionItemLabelDetails {
13883                            detail: Some(description.clone()),
13884                            description: None,
13885                        }
13886                    }),
13887                    insert_text_format: Some(InsertTextFormat::SNIPPET),
13888                    text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13889                        lsp::InsertReplaceEdit {
13890                            new_text: snippet.body.clone(),
13891                            insert: lsp_range,
13892                            replace: lsp_range,
13893                        },
13894                    )),
13895                    filter_text: Some(snippet.body.clone()),
13896                    sort_text: Some(char::MAX.to_string()),
13897                    ..Default::default()
13898                },
13899                confirm: None,
13900            })
13901        })
13902        .collect()
13903}
13904
13905impl CompletionProvider for Model<Project> {
13906    fn completions(
13907        &self,
13908        buffer: &Model<Buffer>,
13909        buffer_position: text::Anchor,
13910        options: CompletionContext,
13911        cx: &mut ViewContext<Editor>,
13912    ) -> Task<Result<Vec<Completion>>> {
13913        self.update(cx, |project, cx| {
13914            let snippets = snippet_completions(project, buffer, buffer_position, cx);
13915            let project_completions = project.completions(buffer, buffer_position, options, cx);
13916            cx.background_executor().spawn(async move {
13917                let mut completions = project_completions.await?;
13918                //let snippets = snippets.into_iter().;
13919                completions.extend(snippets);
13920                Ok(completions)
13921            })
13922        })
13923    }
13924
13925    fn resolve_completions(
13926        &self,
13927        buffer: Model<Buffer>,
13928        completion_indices: Vec<usize>,
13929        completions: Arc<RwLock<Box<[Completion]>>>,
13930        cx: &mut ViewContext<Editor>,
13931    ) -> Task<Result<bool>> {
13932        self.update(cx, |project, cx| {
13933            project.resolve_completions(buffer, completion_indices, completions, cx)
13934        })
13935    }
13936
13937    fn apply_additional_edits_for_completion(
13938        &self,
13939        buffer: Model<Buffer>,
13940        completion: Completion,
13941        push_to_history: bool,
13942        cx: &mut ViewContext<Editor>,
13943    ) -> Task<Result<Option<language::Transaction>>> {
13944        self.update(cx, |project, cx| {
13945            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13946        })
13947    }
13948
13949    fn is_completion_trigger(
13950        &self,
13951        buffer: &Model<Buffer>,
13952        position: language::Anchor,
13953        text: &str,
13954        trigger_in_words: bool,
13955        cx: &mut ViewContext<Editor>,
13956    ) -> bool {
13957        if !EditorSettings::get_global(cx).show_completions_on_input {
13958            return false;
13959        }
13960
13961        let mut chars = text.chars();
13962        let char = if let Some(char) = chars.next() {
13963            char
13964        } else {
13965            return false;
13966        };
13967        if chars.next().is_some() {
13968            return false;
13969        }
13970
13971        let buffer = buffer.read(cx);
13972        let classifier = buffer
13973            .snapshot()
13974            .char_classifier_at(position)
13975            .for_completion(true);
13976        if trigger_in_words && classifier.is_word(char) {
13977            return true;
13978        }
13979
13980        buffer.completion_triggers().contains(text)
13981    }
13982}
13983
13984impl SemanticsProvider for Model<Project> {
13985    fn hover(
13986        &self,
13987        buffer: &Model<Buffer>,
13988        position: text::Anchor,
13989        cx: &mut AppContext,
13990    ) -> Option<Task<Vec<project::Hover>>> {
13991        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13992    }
13993
13994    fn document_highlights(
13995        &self,
13996        buffer: &Model<Buffer>,
13997        position: text::Anchor,
13998        cx: &mut AppContext,
13999    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
14000        Some(self.update(cx, |project, cx| {
14001            project.document_highlights(buffer, position, cx)
14002        }))
14003    }
14004
14005    fn definitions(
14006        &self,
14007        buffer: &Model<Buffer>,
14008        position: text::Anchor,
14009        kind: GotoDefinitionKind,
14010        cx: &mut AppContext,
14011    ) -> Option<Task<Result<Vec<LocationLink>>>> {
14012        Some(self.update(cx, |project, cx| match kind {
14013            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
14014            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
14015            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
14016            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
14017        }))
14018    }
14019
14020    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
14021        // TODO: make this work for remote projects
14022        self.read(cx)
14023            .language_servers_for_buffer(buffer.read(cx), cx)
14024            .any(
14025                |(_, server)| match server.capabilities().inlay_hint_provider {
14026                    Some(lsp::OneOf::Left(enabled)) => enabled,
14027                    Some(lsp::OneOf::Right(_)) => true,
14028                    None => false,
14029                },
14030            )
14031    }
14032
14033    fn inlay_hints(
14034        &self,
14035        buffer_handle: Model<Buffer>,
14036        range: Range<text::Anchor>,
14037        cx: &mut AppContext,
14038    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
14039        Some(self.update(cx, |project, cx| {
14040            project.inlay_hints(buffer_handle, range, cx)
14041        }))
14042    }
14043
14044    fn resolve_inlay_hint(
14045        &self,
14046        hint: InlayHint,
14047        buffer_handle: Model<Buffer>,
14048        server_id: LanguageServerId,
14049        cx: &mut AppContext,
14050    ) -> Option<Task<anyhow::Result<InlayHint>>> {
14051        Some(self.update(cx, |project, cx| {
14052            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
14053        }))
14054    }
14055
14056    fn range_for_rename(
14057        &self,
14058        buffer: &Model<Buffer>,
14059        position: text::Anchor,
14060        cx: &mut AppContext,
14061    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
14062        Some(self.update(cx, |project, cx| {
14063            project.prepare_rename(buffer.clone(), position, cx)
14064        }))
14065    }
14066
14067    fn perform_rename(
14068        &self,
14069        buffer: &Model<Buffer>,
14070        position: text::Anchor,
14071        new_name: String,
14072        cx: &mut AppContext,
14073    ) -> Option<Task<Result<ProjectTransaction>>> {
14074        Some(self.update(cx, |project, cx| {
14075            project.perform_rename(buffer.clone(), position, new_name, cx)
14076        }))
14077    }
14078}
14079
14080fn inlay_hint_settings(
14081    location: Anchor,
14082    snapshot: &MultiBufferSnapshot,
14083    cx: &mut ViewContext<'_, Editor>,
14084) -> InlayHintSettings {
14085    let file = snapshot.file_at(location);
14086    let language = snapshot.language_at(location).map(|l| l.name());
14087    language_settings(language, file, cx).inlay_hints
14088}
14089
14090fn consume_contiguous_rows(
14091    contiguous_row_selections: &mut Vec<Selection<Point>>,
14092    selection: &Selection<Point>,
14093    display_map: &DisplaySnapshot,
14094    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
14095) -> (MultiBufferRow, MultiBufferRow) {
14096    contiguous_row_selections.push(selection.clone());
14097    let start_row = MultiBufferRow(selection.start.row);
14098    let mut end_row = ending_row(selection, display_map);
14099
14100    while let Some(next_selection) = selections.peek() {
14101        if next_selection.start.row <= end_row.0 {
14102            end_row = ending_row(next_selection, display_map);
14103            contiguous_row_selections.push(selections.next().unwrap().clone());
14104        } else {
14105            break;
14106        }
14107    }
14108    (start_row, end_row)
14109}
14110
14111fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
14112    if next_selection.end.column > 0 || next_selection.is_empty() {
14113        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
14114    } else {
14115        MultiBufferRow(next_selection.end.row)
14116    }
14117}
14118
14119impl EditorSnapshot {
14120    pub fn remote_selections_in_range<'a>(
14121        &'a self,
14122        range: &'a Range<Anchor>,
14123        collaboration_hub: &dyn CollaborationHub,
14124        cx: &'a AppContext,
14125    ) -> impl 'a + Iterator<Item = RemoteSelection> {
14126        let participant_names = collaboration_hub.user_names(cx);
14127        let participant_indices = collaboration_hub.user_participant_indices(cx);
14128        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
14129        let collaborators_by_replica_id = collaborators_by_peer_id
14130            .iter()
14131            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
14132            .collect::<HashMap<_, _>>();
14133        self.buffer_snapshot
14134            .selections_in_range(range, false)
14135            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
14136                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
14137                let participant_index = participant_indices.get(&collaborator.user_id).copied();
14138                let user_name = participant_names.get(&collaborator.user_id).cloned();
14139                Some(RemoteSelection {
14140                    replica_id,
14141                    selection,
14142                    cursor_shape,
14143                    line_mode,
14144                    participant_index,
14145                    peer_id: collaborator.peer_id,
14146                    user_name,
14147                })
14148            })
14149    }
14150
14151    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
14152        self.display_snapshot.buffer_snapshot.language_at(position)
14153    }
14154
14155    pub fn is_focused(&self) -> bool {
14156        self.is_focused
14157    }
14158
14159    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
14160        self.placeholder_text.as_ref()
14161    }
14162
14163    pub fn scroll_position(&self) -> gpui::Point<f32> {
14164        self.scroll_anchor.scroll_position(&self.display_snapshot)
14165    }
14166
14167    fn gutter_dimensions(
14168        &self,
14169        font_id: FontId,
14170        font_size: Pixels,
14171        em_width: Pixels,
14172        em_advance: Pixels,
14173        max_line_number_width: Pixels,
14174        cx: &AppContext,
14175    ) -> GutterDimensions {
14176        if !self.show_gutter {
14177            return GutterDimensions::default();
14178        }
14179        let descent = cx.text_system().descent(font_id, font_size);
14180
14181        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
14182            matches!(
14183                ProjectSettings::get_global(cx).git.git_gutter,
14184                Some(GitGutterSetting::TrackedFiles)
14185            )
14186        });
14187        let gutter_settings = EditorSettings::get_global(cx).gutter;
14188        let show_line_numbers = self
14189            .show_line_numbers
14190            .unwrap_or(gutter_settings.line_numbers);
14191        let line_gutter_width = if show_line_numbers {
14192            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
14193            let min_width_for_number_on_gutter = em_advance * 4.0;
14194            max_line_number_width.max(min_width_for_number_on_gutter)
14195        } else {
14196            0.0.into()
14197        };
14198
14199        let show_code_actions = self
14200            .show_code_actions
14201            .unwrap_or(gutter_settings.code_actions);
14202
14203        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
14204
14205        let git_blame_entries_width =
14206            self.git_blame_gutter_max_author_length
14207                .map(|max_author_length| {
14208                    // Length of the author name, but also space for the commit hash,
14209                    // the spacing and the timestamp.
14210                    let max_char_count = max_author_length
14211                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
14212                        + 7 // length of commit sha
14213                        + 14 // length of max relative timestamp ("60 minutes ago")
14214                        + 4; // gaps and margins
14215
14216                    em_advance * max_char_count
14217                });
14218
14219        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
14220        left_padding += if show_code_actions || show_runnables {
14221            em_width * 3.0
14222        } else if show_git_gutter && show_line_numbers {
14223            em_width * 2.0
14224        } else if show_git_gutter || show_line_numbers {
14225            em_width
14226        } else {
14227            px(0.)
14228        };
14229
14230        let right_padding = if gutter_settings.folds && show_line_numbers {
14231            em_width * 4.0
14232        } else if gutter_settings.folds {
14233            em_width * 3.0
14234        } else if show_line_numbers {
14235            em_width
14236        } else {
14237            px(0.)
14238        };
14239
14240        GutterDimensions {
14241            left_padding,
14242            right_padding,
14243            width: line_gutter_width + left_padding + right_padding,
14244            margin: -descent,
14245            git_blame_entries_width,
14246        }
14247    }
14248
14249    pub fn render_crease_toggle(
14250        &self,
14251        buffer_row: MultiBufferRow,
14252        row_contains_cursor: bool,
14253        editor: View<Editor>,
14254        cx: &mut WindowContext,
14255    ) -> Option<AnyElement> {
14256        let folded = self.is_line_folded(buffer_row);
14257        let mut is_foldable = false;
14258
14259        if let Some(crease) = self
14260            .crease_snapshot
14261            .query_row(buffer_row, &self.buffer_snapshot)
14262        {
14263            is_foldable = true;
14264            match crease {
14265                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
14266                    if let Some(render_toggle) = render_toggle {
14267                        let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14268                            if folded {
14269                                editor.update(cx, |editor, cx| {
14270                                    editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14271                                });
14272                            } else {
14273                                editor.update(cx, |editor, cx| {
14274                                    editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14275                                });
14276                            }
14277                        });
14278                        return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
14279                    }
14280                }
14281            }
14282        }
14283
14284        is_foldable |= self.starts_indent(buffer_row);
14285
14286        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
14287            Some(
14288                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
14289                    .selected(folded)
14290                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14291                        if folded {
14292                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
14293                        } else {
14294                            this.fold_at(&FoldAt { buffer_row }, cx);
14295                        }
14296                    }))
14297                    .into_any_element(),
14298            )
14299        } else {
14300            None
14301        }
14302    }
14303
14304    pub fn render_crease_trailer(
14305        &self,
14306        buffer_row: MultiBufferRow,
14307        cx: &mut WindowContext,
14308    ) -> Option<AnyElement> {
14309        let folded = self.is_line_folded(buffer_row);
14310        if let Crease::Inline { render_trailer, .. } = self
14311            .crease_snapshot
14312            .query_row(buffer_row, &self.buffer_snapshot)?
14313        {
14314            let render_trailer = render_trailer.as_ref()?;
14315            Some(render_trailer(buffer_row, folded, cx))
14316        } else {
14317            None
14318        }
14319    }
14320}
14321
14322impl Deref for EditorSnapshot {
14323    type Target = DisplaySnapshot;
14324
14325    fn deref(&self) -> &Self::Target {
14326        &self.display_snapshot
14327    }
14328}
14329
14330#[derive(Clone, Debug, PartialEq, Eq)]
14331pub enum EditorEvent {
14332    InputIgnored {
14333        text: Arc<str>,
14334    },
14335    InputHandled {
14336        utf16_range_to_replace: Option<Range<isize>>,
14337        text: Arc<str>,
14338    },
14339    ExcerptsAdded {
14340        buffer: Model<Buffer>,
14341        predecessor: ExcerptId,
14342        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14343    },
14344    ExcerptsRemoved {
14345        ids: Vec<ExcerptId>,
14346    },
14347    ExcerptsEdited {
14348        ids: Vec<ExcerptId>,
14349    },
14350    ExcerptsExpanded {
14351        ids: Vec<ExcerptId>,
14352    },
14353    BufferEdited,
14354    Edited {
14355        transaction_id: clock::Lamport,
14356    },
14357    Reparsed(BufferId),
14358    Focused,
14359    FocusedIn,
14360    Blurred,
14361    DirtyChanged,
14362    Saved,
14363    TitleChanged,
14364    DiffBaseChanged,
14365    SelectionsChanged {
14366        local: bool,
14367    },
14368    ScrollPositionChanged {
14369        local: bool,
14370        autoscroll: bool,
14371    },
14372    Closed,
14373    TransactionUndone {
14374        transaction_id: clock::Lamport,
14375    },
14376    TransactionBegun {
14377        transaction_id: clock::Lamport,
14378    },
14379    Reloaded,
14380    CursorShapeChanged,
14381}
14382
14383impl EventEmitter<EditorEvent> for Editor {}
14384
14385impl FocusableView for Editor {
14386    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14387        self.focus_handle.clone()
14388    }
14389}
14390
14391impl Render for Editor {
14392    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14393        let settings = ThemeSettings::get_global(cx);
14394
14395        let mut text_style = match self.mode {
14396            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14397                color: cx.theme().colors().editor_foreground,
14398                font_family: settings.ui_font.family.clone(),
14399                font_features: settings.ui_font.features.clone(),
14400                font_fallbacks: settings.ui_font.fallbacks.clone(),
14401                font_size: rems(0.875).into(),
14402                font_weight: settings.ui_font.weight,
14403                line_height: relative(settings.buffer_line_height.value()),
14404                ..Default::default()
14405            },
14406            EditorMode::Full => TextStyle {
14407                color: cx.theme().colors().editor_foreground,
14408                font_family: settings.buffer_font.family.clone(),
14409                font_features: settings.buffer_font.features.clone(),
14410                font_fallbacks: settings.buffer_font.fallbacks.clone(),
14411                font_size: settings.buffer_font_size(cx).into(),
14412                font_weight: settings.buffer_font.weight,
14413                line_height: relative(settings.buffer_line_height.value()),
14414                ..Default::default()
14415            },
14416        };
14417        if let Some(text_style_refinement) = &self.text_style_refinement {
14418            text_style.refine(text_style_refinement)
14419        }
14420
14421        let background = match self.mode {
14422            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14423            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14424            EditorMode::Full => cx.theme().colors().editor_background,
14425        };
14426
14427        EditorElement::new(
14428            cx.view(),
14429            EditorStyle {
14430                background,
14431                local_player: cx.theme().players().local(),
14432                text: text_style,
14433                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14434                syntax: cx.theme().syntax().clone(),
14435                status: cx.theme().status().clone(),
14436                inlay_hints_style: make_inlay_hints_style(cx),
14437                suggestions_style: HighlightStyle {
14438                    color: Some(cx.theme().status().predictive),
14439                    ..HighlightStyle::default()
14440                },
14441                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14442            },
14443        )
14444    }
14445}
14446
14447impl ViewInputHandler for Editor {
14448    fn text_for_range(
14449        &mut self,
14450        range_utf16: Range<usize>,
14451        adjusted_range: &mut Option<Range<usize>>,
14452        cx: &mut ViewContext<Self>,
14453    ) -> Option<String> {
14454        let snapshot = self.buffer.read(cx).read(cx);
14455        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
14456        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
14457        if (start.0..end.0) != range_utf16 {
14458            adjusted_range.replace(start.0..end.0);
14459        }
14460        Some(snapshot.text_for_range(start..end).collect())
14461    }
14462
14463    fn selected_text_range(
14464        &mut self,
14465        ignore_disabled_input: bool,
14466        cx: &mut ViewContext<Self>,
14467    ) -> Option<UTF16Selection> {
14468        // Prevent the IME menu from appearing when holding down an alphabetic key
14469        // while input is disabled.
14470        if !ignore_disabled_input && !self.input_enabled {
14471            return None;
14472        }
14473
14474        let selection = self.selections.newest::<OffsetUtf16>(cx);
14475        let range = selection.range();
14476
14477        Some(UTF16Selection {
14478            range: range.start.0..range.end.0,
14479            reversed: selection.reversed,
14480        })
14481    }
14482
14483    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14484        let snapshot = self.buffer.read(cx).read(cx);
14485        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14486        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14487    }
14488
14489    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14490        self.clear_highlights::<InputComposition>(cx);
14491        self.ime_transaction.take();
14492    }
14493
14494    fn replace_text_in_range(
14495        &mut self,
14496        range_utf16: Option<Range<usize>>,
14497        text: &str,
14498        cx: &mut ViewContext<Self>,
14499    ) {
14500        if !self.input_enabled {
14501            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14502            return;
14503        }
14504
14505        self.transact(cx, |this, cx| {
14506            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14507                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14508                Some(this.selection_replacement_ranges(range_utf16, cx))
14509            } else {
14510                this.marked_text_ranges(cx)
14511            };
14512
14513            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14514                let newest_selection_id = this.selections.newest_anchor().id;
14515                this.selections
14516                    .all::<OffsetUtf16>(cx)
14517                    .iter()
14518                    .zip(ranges_to_replace.iter())
14519                    .find_map(|(selection, range)| {
14520                        if selection.id == newest_selection_id {
14521                            Some(
14522                                (range.start.0 as isize - selection.head().0 as isize)
14523                                    ..(range.end.0 as isize - selection.head().0 as isize),
14524                            )
14525                        } else {
14526                            None
14527                        }
14528                    })
14529            });
14530
14531            cx.emit(EditorEvent::InputHandled {
14532                utf16_range_to_replace: range_to_replace,
14533                text: text.into(),
14534            });
14535
14536            if let Some(new_selected_ranges) = new_selected_ranges {
14537                this.change_selections(None, cx, |selections| {
14538                    selections.select_ranges(new_selected_ranges)
14539                });
14540                this.backspace(&Default::default(), cx);
14541            }
14542
14543            this.handle_input(text, cx);
14544        });
14545
14546        if let Some(transaction) = self.ime_transaction {
14547            self.buffer.update(cx, |buffer, cx| {
14548                buffer.group_until_transaction(transaction, cx);
14549            });
14550        }
14551
14552        self.unmark_text(cx);
14553    }
14554
14555    fn replace_and_mark_text_in_range(
14556        &mut self,
14557        range_utf16: Option<Range<usize>>,
14558        text: &str,
14559        new_selected_range_utf16: Option<Range<usize>>,
14560        cx: &mut ViewContext<Self>,
14561    ) {
14562        if !self.input_enabled {
14563            return;
14564        }
14565
14566        let transaction = self.transact(cx, |this, cx| {
14567            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14568                let snapshot = this.buffer.read(cx).read(cx);
14569                if let Some(relative_range_utf16) = range_utf16.as_ref() {
14570                    for marked_range in &mut marked_ranges {
14571                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14572                        marked_range.start.0 += relative_range_utf16.start;
14573                        marked_range.start =
14574                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14575                        marked_range.end =
14576                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14577                    }
14578                }
14579                Some(marked_ranges)
14580            } else if let Some(range_utf16) = range_utf16 {
14581                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14582                Some(this.selection_replacement_ranges(range_utf16, cx))
14583            } else {
14584                None
14585            };
14586
14587            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14588                let newest_selection_id = this.selections.newest_anchor().id;
14589                this.selections
14590                    .all::<OffsetUtf16>(cx)
14591                    .iter()
14592                    .zip(ranges_to_replace.iter())
14593                    .find_map(|(selection, range)| {
14594                        if selection.id == newest_selection_id {
14595                            Some(
14596                                (range.start.0 as isize - selection.head().0 as isize)
14597                                    ..(range.end.0 as isize - selection.head().0 as isize),
14598                            )
14599                        } else {
14600                            None
14601                        }
14602                    })
14603            });
14604
14605            cx.emit(EditorEvent::InputHandled {
14606                utf16_range_to_replace: range_to_replace,
14607                text: text.into(),
14608            });
14609
14610            if let Some(ranges) = ranges_to_replace {
14611                this.change_selections(None, cx, |s| s.select_ranges(ranges));
14612            }
14613
14614            let marked_ranges = {
14615                let snapshot = this.buffer.read(cx).read(cx);
14616                this.selections
14617                    .disjoint_anchors()
14618                    .iter()
14619                    .map(|selection| {
14620                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14621                    })
14622                    .collect::<Vec<_>>()
14623            };
14624
14625            if text.is_empty() {
14626                this.unmark_text(cx);
14627            } else {
14628                this.highlight_text::<InputComposition>(
14629                    marked_ranges.clone(),
14630                    HighlightStyle {
14631                        underline: Some(UnderlineStyle {
14632                            thickness: px(1.),
14633                            color: None,
14634                            wavy: false,
14635                        }),
14636                        ..Default::default()
14637                    },
14638                    cx,
14639                );
14640            }
14641
14642            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14643            let use_autoclose = this.use_autoclose;
14644            let use_auto_surround = this.use_auto_surround;
14645            this.set_use_autoclose(false);
14646            this.set_use_auto_surround(false);
14647            this.handle_input(text, cx);
14648            this.set_use_autoclose(use_autoclose);
14649            this.set_use_auto_surround(use_auto_surround);
14650
14651            if let Some(new_selected_range) = new_selected_range_utf16 {
14652                let snapshot = this.buffer.read(cx).read(cx);
14653                let new_selected_ranges = marked_ranges
14654                    .into_iter()
14655                    .map(|marked_range| {
14656                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14657                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14658                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14659                        snapshot.clip_offset_utf16(new_start, Bias::Left)
14660                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14661                    })
14662                    .collect::<Vec<_>>();
14663
14664                drop(snapshot);
14665                this.change_selections(None, cx, |selections| {
14666                    selections.select_ranges(new_selected_ranges)
14667                });
14668            }
14669        });
14670
14671        self.ime_transaction = self.ime_transaction.or(transaction);
14672        if let Some(transaction) = self.ime_transaction {
14673            self.buffer.update(cx, |buffer, cx| {
14674                buffer.group_until_transaction(transaction, cx);
14675            });
14676        }
14677
14678        if self.text_highlights::<InputComposition>(cx).is_none() {
14679            self.ime_transaction.take();
14680        }
14681    }
14682
14683    fn bounds_for_range(
14684        &mut self,
14685        range_utf16: Range<usize>,
14686        element_bounds: gpui::Bounds<Pixels>,
14687        cx: &mut ViewContext<Self>,
14688    ) -> Option<gpui::Bounds<Pixels>> {
14689        let text_layout_details = self.text_layout_details(cx);
14690        let style = &text_layout_details.editor_style;
14691        let font_id = cx.text_system().resolve_font(&style.text.font());
14692        let font_size = style.text.font_size.to_pixels(cx.rem_size());
14693        let line_height = style.text.line_height_in_pixels(cx.rem_size());
14694
14695        let em_width = cx
14696            .text_system()
14697            .typographic_bounds(font_id, font_size, 'm')
14698            .unwrap()
14699            .size
14700            .width;
14701
14702        let snapshot = self.snapshot(cx);
14703        let scroll_position = snapshot.scroll_position();
14704        let scroll_left = scroll_position.x * em_width;
14705
14706        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14707        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14708            + self.gutter_dimensions.width
14709            + self.gutter_dimensions.margin;
14710        let y = line_height * (start.row().as_f32() - scroll_position.y);
14711
14712        Some(Bounds {
14713            origin: element_bounds.origin + point(x, y),
14714            size: size(em_width, line_height),
14715        })
14716    }
14717}
14718
14719trait SelectionExt {
14720    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14721    fn spanned_rows(
14722        &self,
14723        include_end_if_at_line_start: bool,
14724        map: &DisplaySnapshot,
14725    ) -> Range<MultiBufferRow>;
14726}
14727
14728impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14729    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14730        let start = self
14731            .start
14732            .to_point(&map.buffer_snapshot)
14733            .to_display_point(map);
14734        let end = self
14735            .end
14736            .to_point(&map.buffer_snapshot)
14737            .to_display_point(map);
14738        if self.reversed {
14739            end..start
14740        } else {
14741            start..end
14742        }
14743    }
14744
14745    fn spanned_rows(
14746        &self,
14747        include_end_if_at_line_start: bool,
14748        map: &DisplaySnapshot,
14749    ) -> Range<MultiBufferRow> {
14750        let start = self.start.to_point(&map.buffer_snapshot);
14751        let mut end = self.end.to_point(&map.buffer_snapshot);
14752        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14753            end.row -= 1;
14754        }
14755
14756        let buffer_start = map.prev_line_boundary(start).0;
14757        let buffer_end = map.next_line_boundary(end).0;
14758        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14759    }
14760}
14761
14762impl<T: InvalidationRegion> InvalidationStack<T> {
14763    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14764    where
14765        S: Clone + ToOffset,
14766    {
14767        while let Some(region) = self.last() {
14768            let all_selections_inside_invalidation_ranges =
14769                if selections.len() == region.ranges().len() {
14770                    selections
14771                        .iter()
14772                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14773                        .all(|(selection, invalidation_range)| {
14774                            let head = selection.head().to_offset(buffer);
14775                            invalidation_range.start <= head && invalidation_range.end >= head
14776                        })
14777                } else {
14778                    false
14779                };
14780
14781            if all_selections_inside_invalidation_ranges {
14782                break;
14783            } else {
14784                self.pop();
14785            }
14786        }
14787    }
14788}
14789
14790impl<T> Default for InvalidationStack<T> {
14791    fn default() -> Self {
14792        Self(Default::default())
14793    }
14794}
14795
14796impl<T> Deref for InvalidationStack<T> {
14797    type Target = Vec<T>;
14798
14799    fn deref(&self) -> &Self::Target {
14800        &self.0
14801    }
14802}
14803
14804impl<T> DerefMut for InvalidationStack<T> {
14805    fn deref_mut(&mut self) -> &mut Self::Target {
14806        &mut self.0
14807    }
14808}
14809
14810impl InvalidationRegion for SnippetState {
14811    fn ranges(&self) -> &[Range<Anchor>] {
14812        &self.ranges[self.active_index]
14813    }
14814}
14815
14816pub fn diagnostic_block_renderer(
14817    diagnostic: Diagnostic,
14818    max_message_rows: Option<u8>,
14819    allow_closing: bool,
14820    _is_valid: bool,
14821) -> RenderBlock {
14822    let (text_without_backticks, code_ranges) =
14823        highlight_diagnostic_message(&diagnostic, max_message_rows);
14824
14825    Arc::new(move |cx: &mut BlockContext| {
14826        let group_id: SharedString = cx.block_id.to_string().into();
14827
14828        let mut text_style = cx.text_style().clone();
14829        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14830        let theme_settings = ThemeSettings::get_global(cx);
14831        text_style.font_family = theme_settings.buffer_font.family.clone();
14832        text_style.font_style = theme_settings.buffer_font.style;
14833        text_style.font_features = theme_settings.buffer_font.features.clone();
14834        text_style.font_weight = theme_settings.buffer_font.weight;
14835
14836        let multi_line_diagnostic = diagnostic.message.contains('\n');
14837
14838        let buttons = |diagnostic: &Diagnostic| {
14839            if multi_line_diagnostic {
14840                v_flex()
14841            } else {
14842                h_flex()
14843            }
14844            .when(allow_closing, |div| {
14845                div.children(diagnostic.is_primary.then(|| {
14846                    IconButton::new("close-block", IconName::XCircle)
14847                        .icon_color(Color::Muted)
14848                        .size(ButtonSize::Compact)
14849                        .style(ButtonStyle::Transparent)
14850                        .visible_on_hover(group_id.clone())
14851                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14852                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14853                }))
14854            })
14855            .child(
14856                IconButton::new("copy-block", IconName::Copy)
14857                    .icon_color(Color::Muted)
14858                    .size(ButtonSize::Compact)
14859                    .style(ButtonStyle::Transparent)
14860                    .visible_on_hover(group_id.clone())
14861                    .on_click({
14862                        let message = diagnostic.message.clone();
14863                        move |_click, cx| {
14864                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14865                        }
14866                    })
14867                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14868            )
14869        };
14870
14871        let icon_size = buttons(&diagnostic)
14872            .into_any_element()
14873            .layout_as_root(AvailableSpace::min_size(), cx);
14874
14875        h_flex()
14876            .id(cx.block_id)
14877            .group(group_id.clone())
14878            .relative()
14879            .size_full()
14880            .block_mouse_down()
14881            .pl(cx.gutter_dimensions.width)
14882            .w(cx.max_width - cx.gutter_dimensions.full_width())
14883            .child(
14884                div()
14885                    .flex()
14886                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14887                    .flex_shrink(),
14888            )
14889            .child(buttons(&diagnostic))
14890            .child(div().flex().flex_shrink_0().child(
14891                StyledText::new(text_without_backticks.clone()).with_highlights(
14892                    &text_style,
14893                    code_ranges.iter().map(|range| {
14894                        (
14895                            range.clone(),
14896                            HighlightStyle {
14897                                font_weight: Some(FontWeight::BOLD),
14898                                ..Default::default()
14899                            },
14900                        )
14901                    }),
14902                ),
14903            ))
14904            .into_any_element()
14905    })
14906}
14907
14908pub fn highlight_diagnostic_message(
14909    diagnostic: &Diagnostic,
14910    mut max_message_rows: Option<u8>,
14911) -> (SharedString, Vec<Range<usize>>) {
14912    let mut text_without_backticks = String::new();
14913    let mut code_ranges = Vec::new();
14914
14915    if let Some(source) = &diagnostic.source {
14916        text_without_backticks.push_str(source);
14917        code_ranges.push(0..source.len());
14918        text_without_backticks.push_str(": ");
14919    }
14920
14921    let mut prev_offset = 0;
14922    let mut in_code_block = false;
14923    let has_row_limit = max_message_rows.is_some();
14924    let mut newline_indices = diagnostic
14925        .message
14926        .match_indices('\n')
14927        .filter(|_| has_row_limit)
14928        .map(|(ix, _)| ix)
14929        .fuse()
14930        .peekable();
14931
14932    for (quote_ix, _) in diagnostic
14933        .message
14934        .match_indices('`')
14935        .chain([(diagnostic.message.len(), "")])
14936    {
14937        let mut first_newline_ix = None;
14938        let mut last_newline_ix = None;
14939        while let Some(newline_ix) = newline_indices.peek() {
14940            if *newline_ix < quote_ix {
14941                if first_newline_ix.is_none() {
14942                    first_newline_ix = Some(*newline_ix);
14943                }
14944                last_newline_ix = Some(*newline_ix);
14945
14946                if let Some(rows_left) = &mut max_message_rows {
14947                    if *rows_left == 0 {
14948                        break;
14949                    } else {
14950                        *rows_left -= 1;
14951                    }
14952                }
14953                let _ = newline_indices.next();
14954            } else {
14955                break;
14956            }
14957        }
14958        let prev_len = text_without_backticks.len();
14959        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14960        text_without_backticks.push_str(new_text);
14961        if in_code_block {
14962            code_ranges.push(prev_len..text_without_backticks.len());
14963        }
14964        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14965        in_code_block = !in_code_block;
14966        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14967            text_without_backticks.push_str("...");
14968            break;
14969        }
14970    }
14971
14972    (text_without_backticks.into(), code_ranges)
14973}
14974
14975fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14976    match severity {
14977        DiagnosticSeverity::ERROR => colors.error,
14978        DiagnosticSeverity::WARNING => colors.warning,
14979        DiagnosticSeverity::INFORMATION => colors.info,
14980        DiagnosticSeverity::HINT => colors.info,
14981        _ => colors.ignored,
14982    }
14983}
14984
14985pub fn styled_runs_for_code_label<'a>(
14986    label: &'a CodeLabel,
14987    syntax_theme: &'a theme::SyntaxTheme,
14988) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14989    let fade_out = HighlightStyle {
14990        fade_out: Some(0.35),
14991        ..Default::default()
14992    };
14993
14994    let mut prev_end = label.filter_range.end;
14995    label
14996        .runs
14997        .iter()
14998        .enumerate()
14999        .flat_map(move |(ix, (range, highlight_id))| {
15000            let style = if let Some(style) = highlight_id.style(syntax_theme) {
15001                style
15002            } else {
15003                return Default::default();
15004            };
15005            let mut muted_style = style;
15006            muted_style.highlight(fade_out);
15007
15008            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
15009            if range.start >= label.filter_range.end {
15010                if range.start > prev_end {
15011                    runs.push((prev_end..range.start, fade_out));
15012                }
15013                runs.push((range.clone(), muted_style));
15014            } else if range.end <= label.filter_range.end {
15015                runs.push((range.clone(), style));
15016            } else {
15017                runs.push((range.start..label.filter_range.end, style));
15018                runs.push((label.filter_range.end..range.end, muted_style));
15019            }
15020            prev_end = cmp::max(prev_end, range.end);
15021
15022            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
15023                runs.push((prev_end..label.text.len(), fade_out));
15024            }
15025
15026            runs
15027        })
15028}
15029
15030pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
15031    let mut prev_index = 0;
15032    let mut prev_codepoint: Option<char> = None;
15033    text.char_indices()
15034        .chain([(text.len(), '\0')])
15035        .filter_map(move |(index, codepoint)| {
15036            let prev_codepoint = prev_codepoint.replace(codepoint)?;
15037            let is_boundary = index == text.len()
15038                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
15039                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
15040            if is_boundary {
15041                let chunk = &text[prev_index..index];
15042                prev_index = index;
15043                Some(chunk)
15044            } else {
15045                None
15046            }
15047        })
15048}
15049
15050pub trait RangeToAnchorExt: Sized {
15051    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
15052
15053    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
15054        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
15055        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
15056    }
15057}
15058
15059impl<T: ToOffset> RangeToAnchorExt for Range<T> {
15060    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
15061        let start_offset = self.start.to_offset(snapshot);
15062        let end_offset = self.end.to_offset(snapshot);
15063        if start_offset == end_offset {
15064            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
15065        } else {
15066            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
15067        }
15068    }
15069}
15070
15071pub trait RowExt {
15072    fn as_f32(&self) -> f32;
15073
15074    fn next_row(&self) -> Self;
15075
15076    fn previous_row(&self) -> Self;
15077
15078    fn minus(&self, other: Self) -> u32;
15079}
15080
15081impl RowExt for DisplayRow {
15082    fn as_f32(&self) -> f32 {
15083        self.0 as f32
15084    }
15085
15086    fn next_row(&self) -> Self {
15087        Self(self.0 + 1)
15088    }
15089
15090    fn previous_row(&self) -> Self {
15091        Self(self.0.saturating_sub(1))
15092    }
15093
15094    fn minus(&self, other: Self) -> u32 {
15095        self.0 - other.0
15096    }
15097}
15098
15099impl RowExt for MultiBufferRow {
15100    fn as_f32(&self) -> f32 {
15101        self.0 as f32
15102    }
15103
15104    fn next_row(&self) -> Self {
15105        Self(self.0 + 1)
15106    }
15107
15108    fn previous_row(&self) -> Self {
15109        Self(self.0.saturating_sub(1))
15110    }
15111
15112    fn minus(&self, other: Self) -> u32 {
15113        self.0 - other.0
15114    }
15115}
15116
15117trait RowRangeExt {
15118    type Row;
15119
15120    fn len(&self) -> usize;
15121
15122    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
15123}
15124
15125impl RowRangeExt for Range<MultiBufferRow> {
15126    type Row = MultiBufferRow;
15127
15128    fn len(&self) -> usize {
15129        (self.end.0 - self.start.0) as usize
15130    }
15131
15132    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
15133        (self.start.0..self.end.0).map(MultiBufferRow)
15134    }
15135}
15136
15137impl RowRangeExt for Range<DisplayRow> {
15138    type Row = DisplayRow;
15139
15140    fn len(&self) -> usize {
15141        (self.end.0 - self.start.0) as usize
15142    }
15143
15144    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
15145        (self.start.0..self.end.0).map(DisplayRow)
15146    }
15147}
15148
15149fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
15150    if hunk.diff_base_byte_range.is_empty() {
15151        DiffHunkStatus::Added
15152    } else if hunk.row_range.is_empty() {
15153        DiffHunkStatus::Removed
15154    } else {
15155        DiffHunkStatus::Modified
15156    }
15157}
15158
15159/// If select range has more than one line, we
15160/// just point the cursor to range.start.
15161fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
15162    if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
15163        range
15164    } else {
15165        range.start..range.start
15166    }
15167}
15168
15169pub struct KillRing(ClipboardItem);
15170impl Global for KillRing {}
15171
15172const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);