editor.rs

    1#![allow(rustdoc::private_intra_doc_links)]
    2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
    3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
    4//! It comes in different flavors: single line, multiline and a fixed height one.
    5//!
    6//! Editor contains of multiple large submodules:
    7//! * [`element`] — the place where all rendering happens
    8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
    9//!   Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
   10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
   11//!
   12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
   13//!
   14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
   15pub mod actions;
   16mod blame_entry_tooltip;
   17mod blink_manager;
   18mod clangd_ext;
   19mod debounced_delay;
   20pub mod display_map;
   21mod editor_settings;
   22mod editor_settings_controls;
   23mod element;
   24mod git;
   25mod highlight_matching_bracket;
   26mod hover_links;
   27mod hover_popover;
   28mod hunk_diff;
   29mod indent_guides;
   30mod inlay_hint_cache;
   31mod inline_completion_provider;
   32pub mod items;
   33mod linked_editing_ranges;
   34mod lsp_ext;
   35mod mouse_context_menu;
   36pub mod movement;
   37mod persistence;
   38mod proposed_changes_editor;
   39mod rust_analyzer_ext;
   40pub mod scroll;
   41mod selections_collection;
   42pub mod tasks;
   43
   44#[cfg(test)]
   45mod editor_tests;
   46mod signature_help;
   47#[cfg(any(test, feature = "test-support"))]
   48pub mod test;
   49
   50use ::git::diff::DiffHunkStatus;
   51pub(crate) use actions::*;
   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, 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_provider::*;
   90pub use items::MAX_TAB_TITLE_LEN;
   91use itertools::Itertools;
   92use language::{
   93    language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
   94    markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
   95    CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
   96    Point, Selection, SelectionGoal, TransactionId,
   97};
   98use language::{
   99    point_to_lsp, BufferRow, CharClassifier, LanguageServerName, Runnable, RunnableRange,
  100};
  101use linked_editing_ranges::refresh_linked_ranges;
  102pub use proposed_changes_editor::{
  103    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  104};
  105use similar::{ChangeTag, TextDiff};
  106use std::iter::Peekable;
  107use task::{ResolvedTask, TaskTemplate, TaskVariables};
  108
  109use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  110pub use lsp::CompletionContext;
  111use lsp::{
  112    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  113    LanguageServerId,
  114};
  115use mouse_context_menu::MouseContextMenu;
  116use movement::TextLayoutDetails;
  117pub use multi_buffer::{
  118    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
  119    ToPoint,
  120};
  121use multi_buffer::{
  122    ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
  123};
  124use ordered_float::OrderedFloat;
  125use parking_lot::{Mutex, RwLock};
  126use project::{
  127    lsp_store::{FormatTarget, FormatTrigger},
  128    project_settings::{GitGutterSetting, ProjectSettings},
  129    CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Item, Location,
  130    LocationLink, Project, ProjectPath, ProjectTransaction, TaskSourceKind,
  131};
  132use rand::prelude::*;
  133use rpc::{proto::*, ErrorExt};
  134use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  135use selections_collection::{
  136    resolve_selections, MutableSelectionsCollection, SelectionsCollection,
  137};
  138use serde::{Deserialize, Serialize};
  139use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  140use smallvec::SmallVec;
  141use snippet::Snippet;
  142use std::{
  143    any::TypeId,
  144    borrow::Cow,
  145    cell::RefCell,
  146    cmp::{self, Ordering, Reverse},
  147    mem,
  148    num::NonZeroU32,
  149    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  150    path::{Path, PathBuf},
  151    rc::Rc,
  152    sync::Arc,
  153    time::{Duration, Instant},
  154};
  155pub use sum_tree::Bias;
  156use sum_tree::TreeMap;
  157use text::{BufferId, OffsetUtf16, Rope};
  158use theme::{
  159    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  160    ThemeColors, ThemeSettings,
  161};
  162use ui::{
  163    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
  164    ListItem, Popover, PopoverMenuHandle, Tooltip,
  165};
  166use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  167use workspace::item::{ItemHandle, PreviewTabsSettings};
  168use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
  169use workspace::{
  170    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  171};
  172use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  173
  174use crate::hover_links::find_url;
  175use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  176
  177pub const FILE_HEADER_HEIGHT: u32 = 2;
  178pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  179pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  180pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  181const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  182const MAX_LINE_LEN: usize = 1024;
  183const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  184const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  185pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  186#[doc(hidden)]
  187pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  188#[doc(hidden)]
  189pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
  190
  191pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  192pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  193
  194pub fn render_parsed_markdown(
  195    element_id: impl Into<ElementId>,
  196    parsed: &language::ParsedMarkdown,
  197    editor_style: &EditorStyle,
  198    workspace: Option<WeakView<Workspace>>,
  199    cx: &mut WindowContext,
  200) -> InteractiveText {
  201    let code_span_background_color = cx
  202        .theme()
  203        .colors()
  204        .editor_document_highlight_read_background;
  205
  206    let highlights = gpui::combine_highlights(
  207        parsed.highlights.iter().filter_map(|(range, highlight)| {
  208            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  209            Some((range.clone(), highlight))
  210        }),
  211        parsed
  212            .regions
  213            .iter()
  214            .zip(&parsed.region_ranges)
  215            .filter_map(|(region, range)| {
  216                if region.code {
  217                    Some((
  218                        range.clone(),
  219                        HighlightStyle {
  220                            background_color: Some(code_span_background_color),
  221                            ..Default::default()
  222                        },
  223                    ))
  224                } else {
  225                    None
  226                }
  227            }),
  228    );
  229
  230    let mut links = Vec::new();
  231    let mut link_ranges = Vec::new();
  232    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  233        if let Some(link) = region.link.clone() {
  234            links.push(link);
  235            link_ranges.push(range.clone());
  236        }
  237    }
  238
  239    InteractiveText::new(
  240        element_id,
  241        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  242    )
  243    .on_click(link_ranges, move |clicked_range_ix, cx| {
  244        match &links[clicked_range_ix] {
  245            markdown::Link::Web { url } => cx.open_url(url),
  246            markdown::Link::Path { path } => {
  247                if let Some(workspace) = &workspace {
  248                    _ = workspace.update(cx, |workspace, cx| {
  249                        workspace.open_abs_path(path.clone(), false, cx).detach();
  250                    });
  251                }
  252            }
  253        }
  254    })
  255}
  256
  257#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  258pub(crate) enum InlayId {
  259    Suggestion(usize),
  260    Hint(usize),
  261}
  262
  263impl InlayId {
  264    fn id(&self) -> usize {
  265        match self {
  266            Self::Suggestion(id) => *id,
  267            Self::Hint(id) => *id,
  268        }
  269    }
  270}
  271
  272enum DiffRowHighlight {}
  273enum DocumentHighlightRead {}
  274enum DocumentHighlightWrite {}
  275enum InputComposition {}
  276
  277#[derive(Copy, Clone, PartialEq, Eq)]
  278pub enum Direction {
  279    Prev,
  280    Next,
  281}
  282
  283#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  284pub enum Navigated {
  285    Yes,
  286    No,
  287}
  288
  289impl Navigated {
  290    pub fn from_bool(yes: bool) -> Navigated {
  291        if yes {
  292            Navigated::Yes
  293        } else {
  294            Navigated::No
  295        }
  296    }
  297}
  298
  299pub fn init_settings(cx: &mut AppContext) {
  300    EditorSettings::register(cx);
  301}
  302
  303pub fn init(cx: &mut AppContext) {
  304    init_settings(cx);
  305
  306    workspace::register_project_item::<Editor>(cx);
  307    workspace::FollowableViewRegistry::register::<Editor>(cx);
  308    workspace::register_serializable_item::<Editor>(cx);
  309
  310    cx.observe_new_views(
  311        |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
  312            workspace.register_action(Editor::new_file);
  313            workspace.register_action(Editor::new_file_vertical);
  314            workspace.register_action(Editor::new_file_horizontal);
  315        },
  316    )
  317    .detach();
  318
  319    cx.on_action(move |_: &workspace::NewFile, cx| {
  320        let app_state = workspace::AppState::global(cx);
  321        if let Some(app_state) = app_state.upgrade() {
  322            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  323                Editor::new_file(workspace, &Default::default(), cx)
  324            })
  325            .detach();
  326        }
  327    });
  328    cx.on_action(move |_: &workspace::NewWindow, cx| {
  329        let app_state = workspace::AppState::global(cx);
  330        if let Some(app_state) = app_state.upgrade() {
  331            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  332                Editor::new_file(workspace, &Default::default(), cx)
  333            })
  334            .detach();
  335        }
  336    });
  337}
  338
  339pub struct SearchWithinRange;
  340
  341trait InvalidationRegion {
  342    fn ranges(&self) -> &[Range<Anchor>];
  343}
  344
  345#[derive(Clone, Debug, PartialEq)]
  346pub enum SelectPhase {
  347    Begin {
  348        position: DisplayPoint,
  349        add: bool,
  350        click_count: usize,
  351    },
  352    BeginColumnar {
  353        position: DisplayPoint,
  354        reset: bool,
  355        goal_column: u32,
  356    },
  357    Extend {
  358        position: DisplayPoint,
  359        click_count: usize,
  360    },
  361    Update {
  362        position: DisplayPoint,
  363        goal_column: u32,
  364        scroll_delta: gpui::Point<f32>,
  365    },
  366    End,
  367}
  368
  369#[derive(Clone, Debug)]
  370pub enum SelectMode {
  371    Character,
  372    Word(Range<Anchor>),
  373    Line(Range<Anchor>),
  374    All,
  375}
  376
  377#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  378pub enum EditorMode {
  379    SingleLine { auto_width: bool },
  380    AutoHeight { max_lines: usize },
  381    Full,
  382}
  383
  384#[derive(Copy, Clone, Debug)]
  385pub enum SoftWrap {
  386    /// Prefer not to wrap at all.
  387    ///
  388    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  389    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  390    GitDiff,
  391    /// Prefer a single line generally, unless an overly long line is encountered.
  392    None,
  393    /// Soft wrap lines that exceed the editor width.
  394    EditorWidth,
  395    /// Soft wrap lines at the preferred line length.
  396    Column(u32),
  397    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  398    Bounded(u32),
  399}
  400
  401#[derive(Clone)]
  402pub struct EditorStyle {
  403    pub background: Hsla,
  404    pub local_player: PlayerColor,
  405    pub text: TextStyle,
  406    pub scrollbar_width: Pixels,
  407    pub syntax: Arc<SyntaxTheme>,
  408    pub status: StatusColors,
  409    pub inlay_hints_style: HighlightStyle,
  410    pub suggestions_style: HighlightStyle,
  411    pub unnecessary_code_fade: f32,
  412}
  413
  414impl Default for EditorStyle {
  415    fn default() -> Self {
  416        Self {
  417            background: Hsla::default(),
  418            local_player: PlayerColor::default(),
  419            text: TextStyle::default(),
  420            scrollbar_width: Pixels::default(),
  421            syntax: Default::default(),
  422            // HACK: Status colors don't have a real default.
  423            // We should look into removing the status colors from the editor
  424            // style and retrieve them directly from the theme.
  425            status: StatusColors::dark(),
  426            inlay_hints_style: HighlightStyle::default(),
  427            suggestions_style: HighlightStyle::default(),
  428            unnecessary_code_fade: Default::default(),
  429        }
  430    }
  431}
  432
  433pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
  434    let show_background = language_settings::language_settings(None, None, cx)
  435        .inlay_hints
  436        .show_background;
  437
  438    HighlightStyle {
  439        color: Some(cx.theme().status().hint),
  440        background_color: show_background.then(|| cx.theme().status().hint_background),
  441        ..HighlightStyle::default()
  442    }
  443}
  444
  445type CompletionId = usize;
  446
  447#[derive(Clone, Debug)]
  448struct CompletionState {
  449    // render_inlay_ids represents the inlay hints that are inserted
  450    // for rendering the inline completions. They may be discontinuous
  451    // in the event that the completion provider returns some intersection
  452    // with the existing content.
  453    render_inlay_ids: Vec<InlayId>,
  454    // text is the resulting rope that is inserted when the user accepts a completion.
  455    text: Rope,
  456    // position is the position of the cursor when the completion was triggered.
  457    position: multi_buffer::Anchor,
  458    // delete_range is the range of text that this completion state covers.
  459    // if the completion is accepted, this range should be deleted.
  460    delete_range: Option<Range<multi_buffer::Anchor>>,
  461}
  462
  463#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  464struct EditorActionId(usize);
  465
  466impl EditorActionId {
  467    pub fn post_inc(&mut self) -> Self {
  468        let answer = self.0;
  469
  470        *self = Self(answer + 1);
  471
  472        Self(answer)
  473    }
  474}
  475
  476// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  477// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  478
  479type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  480type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
  481
  482#[derive(Default)]
  483struct ScrollbarMarkerState {
  484    scrollbar_size: Size<Pixels>,
  485    dirty: bool,
  486    markers: Arc<[PaintQuad]>,
  487    pending_refresh: Option<Task<Result<()>>>,
  488}
  489
  490impl ScrollbarMarkerState {
  491    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  492        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  493    }
  494}
  495
  496#[derive(Clone, Debug)]
  497struct RunnableTasks {
  498    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  499    offset: MultiBufferOffset,
  500    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  501    column: u32,
  502    // Values of all named captures, including those starting with '_'
  503    extra_variables: HashMap<String, String>,
  504    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  505    context_range: Range<BufferOffset>,
  506}
  507
  508impl RunnableTasks {
  509    fn resolve<'a>(
  510        &'a self,
  511        cx: &'a task::TaskContext,
  512    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  513        self.templates.iter().filter_map(|(kind, template)| {
  514            template
  515                .resolve_task(&kind.to_id_base(), cx)
  516                .map(|task| (kind.clone(), task))
  517        })
  518    }
  519}
  520
  521#[derive(Clone)]
  522struct ResolvedTasks {
  523    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  524    position: Anchor,
  525}
  526#[derive(Copy, Clone, Debug)]
  527struct MultiBufferOffset(usize);
  528#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  529struct BufferOffset(usize);
  530
  531// Addons allow storing per-editor state in other crates (e.g. Vim)
  532pub trait Addon: 'static {
  533    fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
  534
  535    fn to_any(&self) -> &dyn std::any::Any;
  536}
  537
  538/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
  539///
  540/// See the [module level documentation](self) for more information.
  541pub struct Editor {
  542    focus_handle: FocusHandle,
  543    last_focused_descendant: Option<WeakFocusHandle>,
  544    /// The text buffer being edited
  545    buffer: Model<MultiBuffer>,
  546    /// Map of how text in the buffer should be displayed.
  547    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  548    pub display_map: Model<DisplayMap>,
  549    pub selections: SelectionsCollection,
  550    pub scroll_manager: ScrollManager,
  551    /// When inline assist editors are linked, they all render cursors because
  552    /// typing enters text into each of them, even the ones that aren't focused.
  553    pub(crate) show_cursor_when_unfocused: bool,
  554    columnar_selection_tail: Option<Anchor>,
  555    add_selections_state: Option<AddSelectionsState>,
  556    select_next_state: Option<SelectNextState>,
  557    select_prev_state: Option<SelectNextState>,
  558    selection_history: SelectionHistory,
  559    autoclose_regions: Vec<AutocloseRegion>,
  560    snippet_stack: InvalidationStack<SnippetState>,
  561    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  562    ime_transaction: Option<TransactionId>,
  563    active_diagnostics: Option<ActiveDiagnosticGroup>,
  564    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  565
  566    project: Option<Model<Project>>,
  567    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  568    completion_provider: Option<Box<dyn CompletionProvider>>,
  569    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  570    blink_manager: Model<BlinkManager>,
  571    show_cursor_names: bool,
  572    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  573    pub show_local_selections: bool,
  574    mode: EditorMode,
  575    show_breadcrumbs: bool,
  576    show_gutter: bool,
  577    show_line_numbers: Option<bool>,
  578    use_relative_line_numbers: Option<bool>,
  579    show_git_diff_gutter: Option<bool>,
  580    show_code_actions: Option<bool>,
  581    show_runnables: Option<bool>,
  582    show_wrap_guides: Option<bool>,
  583    show_indent_guides: Option<bool>,
  584    placeholder_text: Option<Arc<str>>,
  585    highlight_order: usize,
  586    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  587    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  588    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  589    scrollbar_marker_state: ScrollbarMarkerState,
  590    active_indent_guides_state: ActiveIndentGuidesState,
  591    nav_history: Option<ItemNavHistory>,
  592    context_menu: RwLock<Option<ContextMenu>>,
  593    mouse_context_menu: Option<MouseContextMenu>,
  594    hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
  595    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  596    signature_help_state: SignatureHelpState,
  597    auto_signature_help: Option<bool>,
  598    find_all_references_task_sources: Vec<Anchor>,
  599    next_completion_id: CompletionId,
  600    completion_documentation_pre_resolve_debounce: DebouncedDelay,
  601    available_code_actions: Option<(Location, Arc<[AvailableCodeAction]>)>,
  602    code_actions_task: Option<Task<Result<()>>>,
  603    document_highlights_task: Option<Task<()>>,
  604    linked_editing_range_task: Option<Task<Option<()>>>,
  605    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  606    pending_rename: Option<RenameState>,
  607    searchable: bool,
  608    cursor_shape: CursorShape,
  609    current_line_highlight: Option<CurrentLineHighlight>,
  610    collapse_matches: bool,
  611    autoindent_mode: Option<AutoindentMode>,
  612    workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
  613    input_enabled: bool,
  614    use_modal_editing: bool,
  615    read_only: bool,
  616    leader_peer_id: Option<PeerId>,
  617    remote_id: Option<ViewId>,
  618    hover_state: HoverState,
  619    gutter_hovered: bool,
  620    hovered_link_state: Option<HoveredLinkState>,
  621    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  622    code_action_providers: Vec<Arc<dyn CodeActionProvider>>,
  623    active_inline_completion: Option<CompletionState>,
  624    // enable_inline_completions is a switch that Vim can use to disable
  625    // inline completions based on its mode.
  626    enable_inline_completions: bool,
  627    show_inline_completions_override: Option<bool>,
  628    inlay_hint_cache: InlayHintCache,
  629    expanded_hunks: ExpandedHunks,
  630    next_inlay_id: usize,
  631    _subscriptions: Vec<Subscription>,
  632    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  633    gutter_dimensions: GutterDimensions,
  634    style: Option<EditorStyle>,
  635    text_style_refinement: Option<TextStyleRefinement>,
  636    next_editor_action_id: EditorActionId,
  637    editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
  638    use_autoclose: bool,
  639    use_auto_surround: bool,
  640    auto_replace_emoji_shortcode: bool,
  641    show_git_blame_gutter: bool,
  642    show_git_blame_inline: bool,
  643    show_git_blame_inline_delay_task: Option<Task<()>>,
  644    git_blame_inline_enabled: bool,
  645    serialize_dirty_buffers: bool,
  646    show_selection_menu: Option<bool>,
  647    blame: Option<Model<GitBlame>>,
  648    blame_subscription: Option<Subscription>,
  649    custom_context_menu: Option<
  650        Box<
  651            dyn 'static
  652                + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
  653        >,
  654    >,
  655    last_bounds: Option<Bounds<Pixels>>,
  656    expect_bounds_change: Option<Bounds<Pixels>>,
  657    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  658    tasks_update_task: Option<Task<()>>,
  659    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  660    breadcrumb_header: Option<String>,
  661    focused_block: Option<FocusedBlock>,
  662    next_scroll_position: NextScrollCursorCenterTopBottom,
  663    addons: HashMap<TypeId, Box<dyn Addon>>,
  664    _scroll_cursor_center_top_bottom_task: Task<()>,
  665}
  666
  667#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  668enum NextScrollCursorCenterTopBottom {
  669    #[default]
  670    Center,
  671    Top,
  672    Bottom,
  673}
  674
  675impl NextScrollCursorCenterTopBottom {
  676    fn next(&self) -> Self {
  677        match self {
  678            Self::Center => Self::Top,
  679            Self::Top => Self::Bottom,
  680            Self::Bottom => Self::Center,
  681        }
  682    }
  683}
  684
  685#[derive(Clone)]
  686pub struct EditorSnapshot {
  687    pub mode: EditorMode,
  688    show_gutter: bool,
  689    show_line_numbers: Option<bool>,
  690    show_git_diff_gutter: Option<bool>,
  691    show_code_actions: Option<bool>,
  692    show_runnables: Option<bool>,
  693    git_blame_gutter_max_author_length: Option<usize>,
  694    pub display_snapshot: DisplaySnapshot,
  695    pub placeholder_text: Option<Arc<str>>,
  696    is_focused: bool,
  697    scroll_anchor: ScrollAnchor,
  698    ongoing_scroll: OngoingScroll,
  699    current_line_highlight: CurrentLineHighlight,
  700    gutter_hovered: bool,
  701}
  702
  703const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  704
  705#[derive(Default, Debug, Clone, Copy)]
  706pub struct GutterDimensions {
  707    pub left_padding: Pixels,
  708    pub right_padding: Pixels,
  709    pub width: Pixels,
  710    pub margin: Pixels,
  711    pub git_blame_entries_width: Option<Pixels>,
  712}
  713
  714impl GutterDimensions {
  715    /// The full width of the space taken up by the gutter.
  716    pub fn full_width(&self) -> Pixels {
  717        self.margin + self.width
  718    }
  719
  720    /// The width of the space reserved for the fold indicators,
  721    /// use alongside 'justify_end' and `gutter_width` to
  722    /// right align content with the line numbers
  723    pub fn fold_area_width(&self) -> Pixels {
  724        self.margin + self.right_padding
  725    }
  726}
  727
  728#[derive(Debug)]
  729pub struct RemoteSelection {
  730    pub replica_id: ReplicaId,
  731    pub selection: Selection<Anchor>,
  732    pub cursor_shape: CursorShape,
  733    pub peer_id: PeerId,
  734    pub line_mode: bool,
  735    pub participant_index: Option<ParticipantIndex>,
  736    pub user_name: Option<SharedString>,
  737}
  738
  739#[derive(Clone, Debug)]
  740struct SelectionHistoryEntry {
  741    selections: Arc<[Selection<Anchor>]>,
  742    select_next_state: Option<SelectNextState>,
  743    select_prev_state: Option<SelectNextState>,
  744    add_selections_state: Option<AddSelectionsState>,
  745}
  746
  747enum SelectionHistoryMode {
  748    Normal,
  749    Undoing,
  750    Redoing,
  751}
  752
  753#[derive(Clone, PartialEq, Eq, Hash)]
  754struct HoveredCursor {
  755    replica_id: u16,
  756    selection_id: usize,
  757}
  758
  759impl Default for SelectionHistoryMode {
  760    fn default() -> Self {
  761        Self::Normal
  762    }
  763}
  764
  765#[derive(Default)]
  766struct SelectionHistory {
  767    #[allow(clippy::type_complexity)]
  768    selections_by_transaction:
  769        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  770    mode: SelectionHistoryMode,
  771    undo_stack: VecDeque<SelectionHistoryEntry>,
  772    redo_stack: VecDeque<SelectionHistoryEntry>,
  773}
  774
  775impl SelectionHistory {
  776    fn insert_transaction(
  777        &mut self,
  778        transaction_id: TransactionId,
  779        selections: Arc<[Selection<Anchor>]>,
  780    ) {
  781        self.selections_by_transaction
  782            .insert(transaction_id, (selections, None));
  783    }
  784
  785    #[allow(clippy::type_complexity)]
  786    fn transaction(
  787        &self,
  788        transaction_id: TransactionId,
  789    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  790        self.selections_by_transaction.get(&transaction_id)
  791    }
  792
  793    #[allow(clippy::type_complexity)]
  794    fn transaction_mut(
  795        &mut self,
  796        transaction_id: TransactionId,
  797    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  798        self.selections_by_transaction.get_mut(&transaction_id)
  799    }
  800
  801    fn push(&mut self, entry: SelectionHistoryEntry) {
  802        if !entry.selections.is_empty() {
  803            match self.mode {
  804                SelectionHistoryMode::Normal => {
  805                    self.push_undo(entry);
  806                    self.redo_stack.clear();
  807                }
  808                SelectionHistoryMode::Undoing => self.push_redo(entry),
  809                SelectionHistoryMode::Redoing => self.push_undo(entry),
  810            }
  811        }
  812    }
  813
  814    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  815        if self
  816            .undo_stack
  817            .back()
  818            .map_or(true, |e| e.selections != entry.selections)
  819        {
  820            self.undo_stack.push_back(entry);
  821            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  822                self.undo_stack.pop_front();
  823            }
  824        }
  825    }
  826
  827    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  828        if self
  829            .redo_stack
  830            .back()
  831            .map_or(true, |e| e.selections != entry.selections)
  832        {
  833            self.redo_stack.push_back(entry);
  834            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  835                self.redo_stack.pop_front();
  836            }
  837        }
  838    }
  839}
  840
  841struct RowHighlight {
  842    index: usize,
  843    range: Range<Anchor>,
  844    color: Hsla,
  845    should_autoscroll: bool,
  846}
  847
  848#[derive(Clone, Debug)]
  849struct AddSelectionsState {
  850    above: bool,
  851    stack: Vec<usize>,
  852}
  853
  854#[derive(Clone)]
  855struct SelectNextState {
  856    query: AhoCorasick,
  857    wordwise: bool,
  858    done: bool,
  859}
  860
  861impl std::fmt::Debug for SelectNextState {
  862    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  863        f.debug_struct(std::any::type_name::<Self>())
  864            .field("wordwise", &self.wordwise)
  865            .field("done", &self.done)
  866            .finish()
  867    }
  868}
  869
  870#[derive(Debug)]
  871struct AutocloseRegion {
  872    selection_id: usize,
  873    range: Range<Anchor>,
  874    pair: BracketPair,
  875}
  876
  877#[derive(Debug)]
  878struct SnippetState {
  879    ranges: Vec<Vec<Range<Anchor>>>,
  880    active_index: usize,
  881}
  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)]
  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: Arc<Mutex<DebouncedDelay>>,
 1010}
 1011
 1012impl CompletionsMenu {
 1013    fn select_first(
 1014        &mut self,
 1015        provider: Option<&dyn CompletionProvider>,
 1016        cx: &mut ViewContext<Editor>,
 1017    ) {
 1018        self.selected_item = 0;
 1019        self.scroll_handle
 1020            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1021        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1022        cx.notify();
 1023    }
 1024
 1025    fn select_prev(
 1026        &mut self,
 1027        provider: Option<&dyn CompletionProvider>,
 1028        cx: &mut ViewContext<Editor>,
 1029    ) {
 1030        if self.selected_item > 0 {
 1031            self.selected_item -= 1;
 1032        } else {
 1033            self.selected_item = self.matches.len() - 1;
 1034        }
 1035        self.scroll_handle
 1036            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1037        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1038        cx.notify();
 1039    }
 1040
 1041    fn select_next(
 1042        &mut self,
 1043        provider: Option<&dyn CompletionProvider>,
 1044        cx: &mut ViewContext<Editor>,
 1045    ) {
 1046        if self.selected_item + 1 < self.matches.len() {
 1047            self.selected_item += 1;
 1048        } else {
 1049            self.selected_item = 0;
 1050        }
 1051        self.scroll_handle
 1052            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1053        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1054        cx.notify();
 1055    }
 1056
 1057    fn select_last(
 1058        &mut self,
 1059        provider: Option<&dyn CompletionProvider>,
 1060        cx: &mut ViewContext<Editor>,
 1061    ) {
 1062        self.selected_item = self.matches.len() - 1;
 1063        self.scroll_handle
 1064            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1065        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1066        cx.notify();
 1067    }
 1068
 1069    fn pre_resolve_completion_documentation(
 1070        buffer: Model<Buffer>,
 1071        completions: Arc<RwLock<Box<[Completion]>>>,
 1072        matches: Arc<[StringMatch]>,
 1073        editor: &Editor,
 1074        cx: &mut ViewContext<Editor>,
 1075    ) -> Task<()> {
 1076        let settings = EditorSettings::get_global(cx);
 1077        if !settings.show_completion_documentation {
 1078            return Task::ready(());
 1079        }
 1080
 1081        let Some(provider) = editor.completion_provider.as_ref() else {
 1082            return Task::ready(());
 1083        };
 1084
 1085        let resolve_task = provider.resolve_completions(
 1086            buffer,
 1087            matches.iter().map(|m| m.candidate_id).collect(),
 1088            completions.clone(),
 1089            cx,
 1090        );
 1091
 1092        cx.spawn(move |this, mut cx| async move {
 1093            if let Some(true) = resolve_task.await.log_err() {
 1094                this.update(&mut cx, |_, cx| cx.notify()).ok();
 1095            }
 1096        })
 1097    }
 1098
 1099    fn attempt_resolve_selected_completion_documentation(
 1100        &mut self,
 1101        provider: Option<&dyn CompletionProvider>,
 1102        cx: &mut ViewContext<Editor>,
 1103    ) {
 1104        let settings = EditorSettings::get_global(cx);
 1105        if !settings.show_completion_documentation {
 1106            return;
 1107        }
 1108
 1109        let completion_index = self.matches[self.selected_item].candidate_id;
 1110        let Some(provider) = provider else {
 1111            return;
 1112        };
 1113
 1114        let resolve_task = provider.resolve_completions(
 1115            self.buffer.clone(),
 1116            vec![completion_index],
 1117            self.completions.clone(),
 1118            cx,
 1119        );
 1120
 1121        let delay_ms =
 1122            EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
 1123        let delay = Duration::from_millis(delay_ms);
 1124
 1125        self.selected_completion_documentation_resolve_debounce
 1126            .lock()
 1127            .fire_new(delay, cx, |_, cx| {
 1128                cx.spawn(move |this, mut cx| async move {
 1129                    if let Some(true) = resolve_task.await.log_err() {
 1130                        this.update(&mut cx, |_, cx| cx.notify()).ok();
 1131                    }
 1132                })
 1133            });
 1134    }
 1135
 1136    fn visible(&self) -> bool {
 1137        !self.matches.is_empty()
 1138    }
 1139
 1140    fn render(
 1141        &self,
 1142        style: &EditorStyle,
 1143        max_height: Pixels,
 1144        workspace: Option<WeakView<Workspace>>,
 1145        cx: &mut ViewContext<Editor>,
 1146    ) -> AnyElement {
 1147        let settings = EditorSettings::get_global(cx);
 1148        let show_completion_documentation = settings.show_completion_documentation;
 1149
 1150        let widest_completion_ix = self
 1151            .matches
 1152            .iter()
 1153            .enumerate()
 1154            .max_by_key(|(_, mat)| {
 1155                let completions = self.completions.read();
 1156                let completion = &completions[mat.candidate_id];
 1157                let documentation = &completion.documentation;
 1158
 1159                let mut len = completion.label.text.chars().count();
 1160                if let Some(Documentation::SingleLine(text)) = documentation {
 1161                    if show_completion_documentation {
 1162                        len += text.chars().count();
 1163                    }
 1164                }
 1165
 1166                len
 1167            })
 1168            .map(|(ix, _)| ix);
 1169
 1170        let completions = self.completions.clone();
 1171        let matches = self.matches.clone();
 1172        let selected_item = self.selected_item;
 1173        let style = style.clone();
 1174
 1175        let multiline_docs = if show_completion_documentation {
 1176            let mat = &self.matches[selected_item];
 1177            let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
 1178                Some(Documentation::MultiLinePlainText(text)) => {
 1179                    Some(div().child(SharedString::from(text.clone())))
 1180                }
 1181                Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
 1182                    Some(div().child(render_parsed_markdown(
 1183                        "completions_markdown",
 1184                        parsed,
 1185                        &style,
 1186                        workspace,
 1187                        cx,
 1188                    )))
 1189                }
 1190                _ => None,
 1191            };
 1192            multiline_docs.map(|div| {
 1193                div.id("multiline_docs")
 1194                    .max_h(max_height)
 1195                    .flex_1()
 1196                    .px_1p5()
 1197                    .py_1()
 1198                    .min_w(px(260.))
 1199                    .max_w(px(640.))
 1200                    .w(px(500.))
 1201                    .overflow_y_scroll()
 1202                    .occlude()
 1203            })
 1204        } else {
 1205            None
 1206        };
 1207
 1208        let list = uniform_list(
 1209            cx.view().clone(),
 1210            "completions",
 1211            matches.len(),
 1212            move |_editor, range, cx| {
 1213                let start_ix = range.start;
 1214                let completions_guard = completions.read();
 1215
 1216                matches[range]
 1217                    .iter()
 1218                    .enumerate()
 1219                    .map(|(ix, mat)| {
 1220                        let item_ix = start_ix + ix;
 1221                        let candidate_id = mat.candidate_id;
 1222                        let completion = &completions_guard[candidate_id];
 1223
 1224                        let documentation = if show_completion_documentation {
 1225                            &completion.documentation
 1226                        } else {
 1227                            &None
 1228                        };
 1229
 1230                        let highlights = gpui::combine_highlights(
 1231                            mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
 1232                            styled_runs_for_code_label(&completion.label, &style.syntax).map(
 1233                                |(range, mut highlight)| {
 1234                                    // Ignore font weight for syntax highlighting, as we'll use it
 1235                                    // for fuzzy matches.
 1236                                    highlight.font_weight = None;
 1237
 1238                                    if completion.lsp_completion.deprecated.unwrap_or(false) {
 1239                                        highlight.strikethrough = Some(StrikethroughStyle {
 1240                                            thickness: 1.0.into(),
 1241                                            ..Default::default()
 1242                                        });
 1243                                        highlight.color = Some(cx.theme().colors().text_muted);
 1244                                    }
 1245
 1246                                    (range, highlight)
 1247                                },
 1248                            ),
 1249                        );
 1250                        let completion_label = StyledText::new(completion.label.text.clone())
 1251                            .with_highlights(&style.text, highlights);
 1252                        let documentation_label =
 1253                            if let Some(Documentation::SingleLine(text)) = documentation {
 1254                                if text.trim().is_empty() {
 1255                                    None
 1256                                } else {
 1257                                    Some(
 1258                                        Label::new(text.clone())
 1259                                            .ml_4()
 1260                                            .size(LabelSize::Small)
 1261                                            .color(Color::Muted),
 1262                                    )
 1263                                }
 1264                            } else {
 1265                                None
 1266                            };
 1267
 1268                        let color_swatch = completion
 1269                            .color()
 1270                            .map(|color| div().size_4().bg(color).rounded_sm());
 1271
 1272                        div().min_w(px(220.)).max_w(px(540.)).child(
 1273                            ListItem::new(mat.candidate_id)
 1274                                .inset(true)
 1275                                .selected(item_ix == selected_item)
 1276                                .on_click(cx.listener(move |editor, _event, cx| {
 1277                                    cx.stop_propagation();
 1278                                    if let Some(task) = editor.confirm_completion(
 1279                                        &ConfirmCompletion {
 1280                                            item_ix: Some(item_ix),
 1281                                        },
 1282                                        cx,
 1283                                    ) {
 1284                                        task.detach_and_log_err(cx)
 1285                                    }
 1286                                }))
 1287                                .start_slot::<Div>(color_swatch)
 1288                                .child(h_flex().overflow_hidden().child(completion_label))
 1289                                .end_slot::<Label>(documentation_label),
 1290                        )
 1291                    })
 1292                    .collect()
 1293            },
 1294        )
 1295        .occlude()
 1296        .max_h(max_height)
 1297        .track_scroll(self.scroll_handle.clone())
 1298        .with_width_from_item(widest_completion_ix)
 1299        .with_sizing_behavior(ListSizingBehavior::Infer);
 1300
 1301        Popover::new()
 1302            .child(list)
 1303            .when_some(multiline_docs, |popover, multiline_docs| {
 1304                popover.aside(multiline_docs)
 1305            })
 1306            .into_any_element()
 1307    }
 1308
 1309    pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
 1310        let mut matches = if let Some(query) = query {
 1311            fuzzy::match_strings(
 1312                &self.match_candidates,
 1313                query,
 1314                query.chars().any(|c| c.is_uppercase()),
 1315                100,
 1316                &Default::default(),
 1317                executor,
 1318            )
 1319            .await
 1320        } else {
 1321            self.match_candidates
 1322                .iter()
 1323                .enumerate()
 1324                .map(|(candidate_id, candidate)| StringMatch {
 1325                    candidate_id,
 1326                    score: Default::default(),
 1327                    positions: Default::default(),
 1328                    string: candidate.string.clone(),
 1329                })
 1330                .collect()
 1331        };
 1332
 1333        // Remove all candidates where the query's start does not match the start of any word in the candidate
 1334        if let Some(query) = query {
 1335            if let Some(query_start) = query.chars().next() {
 1336                matches.retain(|string_match| {
 1337                    split_words(&string_match.string).any(|word| {
 1338                        // Check that the first codepoint of the word as lowercase matches the first
 1339                        // codepoint of the query as lowercase
 1340                        word.chars()
 1341                            .flat_map(|codepoint| codepoint.to_lowercase())
 1342                            .zip(query_start.to_lowercase())
 1343                            .all(|(word_cp, query_cp)| word_cp == query_cp)
 1344                    })
 1345                });
 1346            }
 1347        }
 1348
 1349        let completions = self.completions.read();
 1350        if self.sort_completions {
 1351            matches.sort_unstable_by_key(|mat| {
 1352                // We do want to strike a balance here between what the language server tells us
 1353                // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
 1354                // `Creat` and there is a local variable called `CreateComponent`).
 1355                // So what we do is: we bucket all matches into two buckets
 1356                // - Strong matches
 1357                // - Weak matches
 1358                // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
 1359                // and the Weak matches are the rest.
 1360                //
 1361                // For the strong matches, we sort by our fuzzy-finder score first and for the weak
 1362                // matches, we prefer language-server sort_text first.
 1363                //
 1364                // The thinking behind that: we want to show strong matches first in order of relevance(fuzzy score).
 1365                // Rest of the matches(weak) can be sorted as language-server expects.
 1366
 1367                #[derive(PartialEq, Eq, PartialOrd, Ord)]
 1368                enum MatchScore<'a> {
 1369                    Strong {
 1370                        score: Reverse<OrderedFloat<f64>>,
 1371                        sort_text: Option<&'a str>,
 1372                        sort_key: (usize, &'a str),
 1373                    },
 1374                    Weak {
 1375                        sort_text: Option<&'a str>,
 1376                        score: Reverse<OrderedFloat<f64>>,
 1377                        sort_key: (usize, &'a str),
 1378                    },
 1379                }
 1380
 1381                let completion = &completions[mat.candidate_id];
 1382                let sort_key = completion.sort_key();
 1383                let sort_text = completion.lsp_completion.sort_text.as_deref();
 1384                let score = Reverse(OrderedFloat(mat.score));
 1385
 1386                if mat.score >= 0.2 {
 1387                    MatchScore::Strong {
 1388                        score,
 1389                        sort_text,
 1390                        sort_key,
 1391                    }
 1392                } else {
 1393                    MatchScore::Weak {
 1394                        sort_text,
 1395                        score,
 1396                        sort_key,
 1397                    }
 1398                }
 1399            });
 1400        }
 1401
 1402        for mat in &mut matches {
 1403            let completion = &completions[mat.candidate_id];
 1404            mat.string.clone_from(&completion.label.text);
 1405            for position in &mut mat.positions {
 1406                *position += completion.label.filter_range.start;
 1407            }
 1408        }
 1409        drop(completions);
 1410
 1411        self.matches = matches.into();
 1412        self.selected_item = 0;
 1413    }
 1414}
 1415
 1416struct AvailableCodeAction {
 1417    excerpt_id: ExcerptId,
 1418    action: CodeAction,
 1419    provider: Arc<dyn CodeActionProvider>,
 1420}
 1421
 1422#[derive(Clone)]
 1423struct CodeActionContents {
 1424    tasks: Option<Arc<ResolvedTasks>>,
 1425    actions: Option<Arc<[AvailableCodeAction]>>,
 1426}
 1427
 1428impl CodeActionContents {
 1429    fn len(&self) -> usize {
 1430        match (&self.tasks, &self.actions) {
 1431            (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
 1432            (Some(tasks), None) => tasks.templates.len(),
 1433            (None, Some(actions)) => actions.len(),
 1434            (None, None) => 0,
 1435        }
 1436    }
 1437
 1438    fn is_empty(&self) -> bool {
 1439        match (&self.tasks, &self.actions) {
 1440            (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
 1441            (Some(tasks), None) => tasks.templates.is_empty(),
 1442            (None, Some(actions)) => actions.is_empty(),
 1443            (None, None) => true,
 1444        }
 1445    }
 1446
 1447    fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
 1448        self.tasks
 1449            .iter()
 1450            .flat_map(|tasks| {
 1451                tasks
 1452                    .templates
 1453                    .iter()
 1454                    .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
 1455            })
 1456            .chain(self.actions.iter().flat_map(|actions| {
 1457                actions.iter().map(|available| CodeActionsItem::CodeAction {
 1458                    excerpt_id: available.excerpt_id,
 1459                    action: available.action.clone(),
 1460                    provider: available.provider.clone(),
 1461                })
 1462            }))
 1463    }
 1464    fn get(&self, index: usize) -> Option<CodeActionsItem> {
 1465        match (&self.tasks, &self.actions) {
 1466            (Some(tasks), Some(actions)) => {
 1467                if index < tasks.templates.len() {
 1468                    tasks
 1469                        .templates
 1470                        .get(index)
 1471                        .cloned()
 1472                        .map(|(kind, task)| CodeActionsItem::Task(kind, task))
 1473                } else {
 1474                    actions.get(index - tasks.templates.len()).map(|available| {
 1475                        CodeActionsItem::CodeAction {
 1476                            excerpt_id: available.excerpt_id,
 1477                            action: available.action.clone(),
 1478                            provider: available.provider.clone(),
 1479                        }
 1480                    })
 1481                }
 1482            }
 1483            (Some(tasks), None) => tasks
 1484                .templates
 1485                .get(index)
 1486                .cloned()
 1487                .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
 1488            (None, Some(actions)) => {
 1489                actions
 1490                    .get(index)
 1491                    .map(|available| CodeActionsItem::CodeAction {
 1492                        excerpt_id: available.excerpt_id,
 1493                        action: available.action.clone(),
 1494                        provider: available.provider.clone(),
 1495                    })
 1496            }
 1497            (None, None) => None,
 1498        }
 1499    }
 1500}
 1501
 1502#[allow(clippy::large_enum_variant)]
 1503#[derive(Clone)]
 1504enum CodeActionsItem {
 1505    Task(TaskSourceKind, ResolvedTask),
 1506    CodeAction {
 1507        excerpt_id: ExcerptId,
 1508        action: CodeAction,
 1509        provider: Arc<dyn CodeActionProvider>,
 1510    },
 1511}
 1512
 1513impl CodeActionsItem {
 1514    fn as_task(&self) -> Option<&ResolvedTask> {
 1515        let Self::Task(_, task) = self else {
 1516            return None;
 1517        };
 1518        Some(task)
 1519    }
 1520    fn as_code_action(&self) -> Option<&CodeAction> {
 1521        let Self::CodeAction { action, .. } = self else {
 1522            return None;
 1523        };
 1524        Some(action)
 1525    }
 1526    fn label(&self) -> String {
 1527        match self {
 1528            Self::CodeAction { action, .. } => action.lsp_action.title.clone(),
 1529            Self::Task(_, task) => task.resolved_label.clone(),
 1530        }
 1531    }
 1532}
 1533
 1534struct CodeActionsMenu {
 1535    actions: CodeActionContents,
 1536    buffer: Model<Buffer>,
 1537    selected_item: usize,
 1538    scroll_handle: UniformListScrollHandle,
 1539    deployed_from_indicator: Option<DisplayRow>,
 1540}
 1541
 1542impl CodeActionsMenu {
 1543    fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
 1544        self.selected_item = 0;
 1545        self.scroll_handle
 1546            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1547        cx.notify()
 1548    }
 1549
 1550    fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
 1551        if self.selected_item > 0 {
 1552            self.selected_item -= 1;
 1553        } else {
 1554            self.selected_item = self.actions.len() - 1;
 1555        }
 1556        self.scroll_handle
 1557            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1558        cx.notify();
 1559    }
 1560
 1561    fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
 1562        if self.selected_item + 1 < self.actions.len() {
 1563            self.selected_item += 1;
 1564        } else {
 1565            self.selected_item = 0;
 1566        }
 1567        self.scroll_handle
 1568            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1569        cx.notify();
 1570    }
 1571
 1572    fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
 1573        self.selected_item = self.actions.len() - 1;
 1574        self.scroll_handle
 1575            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1576        cx.notify()
 1577    }
 1578
 1579    fn visible(&self) -> bool {
 1580        !self.actions.is_empty()
 1581    }
 1582
 1583    fn render(
 1584        &self,
 1585        cursor_position: DisplayPoint,
 1586        _style: &EditorStyle,
 1587        max_height: Pixels,
 1588        cx: &mut ViewContext<Editor>,
 1589    ) -> (ContextMenuOrigin, AnyElement) {
 1590        let actions = self.actions.clone();
 1591        let selected_item = self.selected_item;
 1592        let element = uniform_list(
 1593            cx.view().clone(),
 1594            "code_actions_menu",
 1595            self.actions.len(),
 1596            move |_this, range, cx| {
 1597                actions
 1598                    .iter()
 1599                    .skip(range.start)
 1600                    .take(range.end - range.start)
 1601                    .enumerate()
 1602                    .map(|(ix, action)| {
 1603                        let item_ix = range.start + ix;
 1604                        let selected = selected_item == item_ix;
 1605                        let colors = cx.theme().colors();
 1606                        div()
 1607                            .px_1()
 1608                            .rounded_md()
 1609                            .text_color(colors.text)
 1610                            .when(selected, |style| {
 1611                                style
 1612                                    .bg(colors.element_active)
 1613                                    .text_color(colors.text_accent)
 1614                            })
 1615                            .hover(|style| {
 1616                                style
 1617                                    .bg(colors.element_hover)
 1618                                    .text_color(colors.text_accent)
 1619                            })
 1620                            .whitespace_nowrap()
 1621                            .when_some(action.as_code_action(), |this, action| {
 1622                                this.on_mouse_down(
 1623                                    MouseButton::Left,
 1624                                    cx.listener(move |editor, _, cx| {
 1625                                        cx.stop_propagation();
 1626                                        if let Some(task) = editor.confirm_code_action(
 1627                                            &ConfirmCodeAction {
 1628                                                item_ix: Some(item_ix),
 1629                                            },
 1630                                            cx,
 1631                                        ) {
 1632                                            task.detach_and_log_err(cx)
 1633                                        }
 1634                                    }),
 1635                                )
 1636                                // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
 1637                                .child(SharedString::from(action.lsp_action.title.clone()))
 1638                            })
 1639                            .when_some(action.as_task(), |this, task| {
 1640                                this.on_mouse_down(
 1641                                    MouseButton::Left,
 1642                                    cx.listener(move |editor, _, cx| {
 1643                                        cx.stop_propagation();
 1644                                        if let Some(task) = editor.confirm_code_action(
 1645                                            &ConfirmCodeAction {
 1646                                                item_ix: Some(item_ix),
 1647                                            },
 1648                                            cx,
 1649                                        ) {
 1650                                            task.detach_and_log_err(cx)
 1651                                        }
 1652                                    }),
 1653                                )
 1654                                .child(SharedString::from(task.resolved_label.clone()))
 1655                            })
 1656                    })
 1657                    .collect()
 1658            },
 1659        )
 1660        .elevation_1(cx)
 1661        .p_1()
 1662        .max_h(max_height)
 1663        .occlude()
 1664        .track_scroll(self.scroll_handle.clone())
 1665        .with_width_from_item(
 1666            self.actions
 1667                .iter()
 1668                .enumerate()
 1669                .max_by_key(|(_, action)| match action {
 1670                    CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
 1671                    CodeActionsItem::CodeAction { action, .. } => {
 1672                        action.lsp_action.title.chars().count()
 1673                    }
 1674                })
 1675                .map(|(ix, _)| ix),
 1676        )
 1677        .with_sizing_behavior(ListSizingBehavior::Infer)
 1678        .into_any_element();
 1679
 1680        let cursor_position = if let Some(row) = self.deployed_from_indicator {
 1681            ContextMenuOrigin::GutterIndicator(row)
 1682        } else {
 1683            ContextMenuOrigin::EditorPoint(cursor_position)
 1684        };
 1685
 1686        (cursor_position, element)
 1687    }
 1688}
 1689
 1690#[derive(Debug)]
 1691struct ActiveDiagnosticGroup {
 1692    primary_range: Range<Anchor>,
 1693    primary_message: String,
 1694    group_id: usize,
 1695    blocks: HashMap<CustomBlockId, Diagnostic>,
 1696    is_valid: bool,
 1697}
 1698
 1699#[derive(Serialize, Deserialize, Clone, Debug)]
 1700pub struct ClipboardSelection {
 1701    pub len: usize,
 1702    pub is_entire_line: bool,
 1703    pub first_line_indent: u32,
 1704}
 1705
 1706#[derive(Debug)]
 1707pub(crate) struct NavigationData {
 1708    cursor_anchor: Anchor,
 1709    cursor_position: Point,
 1710    scroll_anchor: ScrollAnchor,
 1711    scroll_top_row: u32,
 1712}
 1713
 1714#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1715pub enum GotoDefinitionKind {
 1716    Symbol,
 1717    Declaration,
 1718    Type,
 1719    Implementation,
 1720}
 1721
 1722#[derive(Debug, Clone)]
 1723enum InlayHintRefreshReason {
 1724    Toggle(bool),
 1725    SettingsChange(InlayHintSettings),
 1726    NewLinesShown,
 1727    BufferEdited(HashSet<Arc<Language>>),
 1728    RefreshRequested,
 1729    ExcerptsRemoved(Vec<ExcerptId>),
 1730}
 1731
 1732impl InlayHintRefreshReason {
 1733    fn description(&self) -> &'static str {
 1734        match self {
 1735            Self::Toggle(_) => "toggle",
 1736            Self::SettingsChange(_) => "settings change",
 1737            Self::NewLinesShown => "new lines shown",
 1738            Self::BufferEdited(_) => "buffer edited",
 1739            Self::RefreshRequested => "refresh requested",
 1740            Self::ExcerptsRemoved(_) => "excerpts removed",
 1741        }
 1742    }
 1743}
 1744
 1745pub(crate) struct FocusedBlock {
 1746    id: BlockId,
 1747    focus_handle: WeakFocusHandle,
 1748}
 1749
 1750impl Editor {
 1751    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
 1752        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1753        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1754        Self::new(
 1755            EditorMode::SingleLine { auto_width: false },
 1756            buffer,
 1757            None,
 1758            false,
 1759            cx,
 1760        )
 1761    }
 1762
 1763    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
 1764        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1765        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1766        Self::new(EditorMode::Full, buffer, None, false, cx)
 1767    }
 1768
 1769    pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
 1770        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1771        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1772        Self::new(
 1773            EditorMode::SingleLine { auto_width: true },
 1774            buffer,
 1775            None,
 1776            false,
 1777            cx,
 1778        )
 1779    }
 1780
 1781    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
 1782        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1783        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1784        Self::new(
 1785            EditorMode::AutoHeight { max_lines },
 1786            buffer,
 1787            None,
 1788            false,
 1789            cx,
 1790        )
 1791    }
 1792
 1793    pub fn for_buffer(
 1794        buffer: Model<Buffer>,
 1795        project: Option<Model<Project>>,
 1796        cx: &mut ViewContext<Self>,
 1797    ) -> Self {
 1798        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1799        Self::new(EditorMode::Full, buffer, project, false, cx)
 1800    }
 1801
 1802    pub fn for_multibuffer(
 1803        buffer: Model<MultiBuffer>,
 1804        project: Option<Model<Project>>,
 1805        show_excerpt_controls: bool,
 1806        cx: &mut ViewContext<Self>,
 1807    ) -> Self {
 1808        Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
 1809    }
 1810
 1811    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 1812        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1813        let mut clone = Self::new(
 1814            self.mode,
 1815            self.buffer.clone(),
 1816            self.project.clone(),
 1817            show_excerpt_controls,
 1818            cx,
 1819        );
 1820        self.display_map.update(cx, |display_map, cx| {
 1821            let snapshot = display_map.snapshot(cx);
 1822            clone.display_map.update(cx, |display_map, cx| {
 1823                display_map.set_state(&snapshot, cx);
 1824            });
 1825        });
 1826        clone.selections.clone_state(&self.selections);
 1827        clone.scroll_manager.clone_state(&self.scroll_manager);
 1828        clone.searchable = self.searchable;
 1829        clone
 1830    }
 1831
 1832    pub fn new(
 1833        mode: EditorMode,
 1834        buffer: Model<MultiBuffer>,
 1835        project: Option<Model<Project>>,
 1836        show_excerpt_controls: bool,
 1837        cx: &mut ViewContext<Self>,
 1838    ) -> Self {
 1839        let style = cx.text_style();
 1840        let font_size = style.font_size.to_pixels(cx.rem_size());
 1841        let editor = cx.view().downgrade();
 1842        let fold_placeholder = FoldPlaceholder {
 1843            constrain_width: true,
 1844            render: Arc::new(move |fold_id, fold_range, cx| {
 1845                let editor = editor.clone();
 1846                div()
 1847                    .id(fold_id)
 1848                    .bg(cx.theme().colors().ghost_element_background)
 1849                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1850                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1851                    .rounded_sm()
 1852                    .size_full()
 1853                    .cursor_pointer()
 1854                    .child("")
 1855                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 1856                    .on_click(move |_, cx| {
 1857                        editor
 1858                            .update(cx, |editor, cx| {
 1859                                editor.unfold_ranges(
 1860                                    &[fold_range.start..fold_range.end],
 1861                                    true,
 1862                                    false,
 1863                                    cx,
 1864                                );
 1865                                cx.stop_propagation();
 1866                            })
 1867                            .ok();
 1868                    })
 1869                    .into_any()
 1870            }),
 1871            merge_adjacent: true,
 1872            ..Default::default()
 1873        };
 1874        let display_map = cx.new_model(|cx| {
 1875            DisplayMap::new(
 1876                buffer.clone(),
 1877                style.font(),
 1878                font_size,
 1879                None,
 1880                show_excerpt_controls,
 1881                FILE_HEADER_HEIGHT,
 1882                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1883                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1884                fold_placeholder,
 1885                cx,
 1886            )
 1887        });
 1888
 1889        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1890
 1891        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1892
 1893        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1894            .then(|| language_settings::SoftWrap::None);
 1895
 1896        let mut project_subscriptions = Vec::new();
 1897        if mode == EditorMode::Full {
 1898            if let Some(project) = project.as_ref() {
 1899                if buffer.read(cx).is_singleton() {
 1900                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
 1901                        cx.emit(EditorEvent::TitleChanged);
 1902                    }));
 1903                }
 1904                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
 1905                    if let project::Event::RefreshInlayHints = event {
 1906                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1907                    } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1908                        if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1909                            let focus_handle = editor.focus_handle(cx);
 1910                            if focus_handle.is_focused(cx) {
 1911                                let snapshot = buffer.read(cx).snapshot();
 1912                                for (range, snippet) in snippet_edits {
 1913                                    let editor_range =
 1914                                        language::range_from_lsp(*range).to_offset(&snapshot);
 1915                                    editor
 1916                                        .insert_snippet(&[editor_range], snippet.clone(), cx)
 1917                                        .ok();
 1918                                }
 1919                            }
 1920                        }
 1921                    }
 1922                }));
 1923                if let Some(task_inventory) = project
 1924                    .read(cx)
 1925                    .task_store()
 1926                    .read(cx)
 1927                    .task_inventory()
 1928                    .cloned()
 1929                {
 1930                    project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
 1931                        editor.tasks_update_task = Some(editor.refresh_runnables(cx));
 1932                    }));
 1933                }
 1934            }
 1935        }
 1936
 1937        let inlay_hint_settings = inlay_hint_settings(
 1938            selections.newest_anchor().head(),
 1939            &buffer.read(cx).snapshot(cx),
 1940            cx,
 1941        );
 1942        let focus_handle = cx.focus_handle();
 1943        cx.on_focus(&focus_handle, Self::handle_focus).detach();
 1944        cx.on_focus_in(&focus_handle, Self::handle_focus_in)
 1945            .detach();
 1946        cx.on_focus_out(&focus_handle, Self::handle_focus_out)
 1947            .detach();
 1948        cx.on_blur(&focus_handle, Self::handle_blur).detach();
 1949
 1950        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1951            Some(false)
 1952        } else {
 1953            None
 1954        };
 1955
 1956        let mut code_action_providers = Vec::new();
 1957        if let Some(project) = project.clone() {
 1958            code_action_providers.push(Arc::new(project) as Arc<_>);
 1959        }
 1960
 1961        let mut this = Self {
 1962            focus_handle,
 1963            show_cursor_when_unfocused: false,
 1964            last_focused_descendant: None,
 1965            buffer: buffer.clone(),
 1966            display_map: display_map.clone(),
 1967            selections,
 1968            scroll_manager: ScrollManager::new(cx),
 1969            columnar_selection_tail: None,
 1970            add_selections_state: None,
 1971            select_next_state: None,
 1972            select_prev_state: None,
 1973            selection_history: Default::default(),
 1974            autoclose_regions: Default::default(),
 1975            snippet_stack: Default::default(),
 1976            select_larger_syntax_node_stack: Vec::new(),
 1977            ime_transaction: Default::default(),
 1978            active_diagnostics: None,
 1979            soft_wrap_mode_override,
 1980            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1981            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1982            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1983            project,
 1984            blink_manager: blink_manager.clone(),
 1985            show_local_selections: true,
 1986            mode,
 1987            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1988            show_gutter: mode == EditorMode::Full,
 1989            show_line_numbers: None,
 1990            use_relative_line_numbers: None,
 1991            show_git_diff_gutter: None,
 1992            show_code_actions: None,
 1993            show_runnables: None,
 1994            show_wrap_guides: None,
 1995            show_indent_guides,
 1996            placeholder_text: None,
 1997            highlight_order: 0,
 1998            highlighted_rows: HashMap::default(),
 1999            background_highlights: Default::default(),
 2000            gutter_highlights: TreeMap::default(),
 2001            scrollbar_marker_state: ScrollbarMarkerState::default(),
 2002            active_indent_guides_state: ActiveIndentGuidesState::default(),
 2003            nav_history: None,
 2004            context_menu: RwLock::new(None),
 2005            mouse_context_menu: None,
 2006            hunk_controls_menu_handle: PopoverMenuHandle::default(),
 2007            completion_tasks: Default::default(),
 2008            signature_help_state: SignatureHelpState::default(),
 2009            auto_signature_help: None,
 2010            find_all_references_task_sources: Vec::new(),
 2011            next_completion_id: 0,
 2012            completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
 2013            next_inlay_id: 0,
 2014            code_action_providers,
 2015            available_code_actions: Default::default(),
 2016            code_actions_task: Default::default(),
 2017            document_highlights_task: Default::default(),
 2018            linked_editing_range_task: Default::default(),
 2019            pending_rename: Default::default(),
 2020            searchable: true,
 2021            cursor_shape: EditorSettings::get_global(cx)
 2022                .cursor_shape
 2023                .unwrap_or_default(),
 2024            current_line_highlight: None,
 2025            autoindent_mode: Some(AutoindentMode::EachLine),
 2026            collapse_matches: false,
 2027            workspace: None,
 2028            input_enabled: true,
 2029            use_modal_editing: mode == EditorMode::Full,
 2030            read_only: false,
 2031            use_autoclose: true,
 2032            use_auto_surround: true,
 2033            auto_replace_emoji_shortcode: false,
 2034            leader_peer_id: None,
 2035            remote_id: None,
 2036            hover_state: Default::default(),
 2037            hovered_link_state: Default::default(),
 2038            inline_completion_provider: None,
 2039            active_inline_completion: None,
 2040            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 2041            expanded_hunks: ExpandedHunks::default(),
 2042            gutter_hovered: false,
 2043            pixel_position_of_newest_cursor: None,
 2044            last_bounds: None,
 2045            expect_bounds_change: None,
 2046            gutter_dimensions: GutterDimensions::default(),
 2047            style: None,
 2048            show_cursor_names: false,
 2049            hovered_cursors: Default::default(),
 2050            next_editor_action_id: EditorActionId::default(),
 2051            editor_actions: Rc::default(),
 2052            show_inline_completions_override: None,
 2053            enable_inline_completions: true,
 2054            custom_context_menu: None,
 2055            show_git_blame_gutter: false,
 2056            show_git_blame_inline: false,
 2057            show_selection_menu: None,
 2058            show_git_blame_inline_delay_task: None,
 2059            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 2060            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 2061                .session
 2062                .restore_unsaved_buffers,
 2063            blame: None,
 2064            blame_subscription: None,
 2065            tasks: Default::default(),
 2066            _subscriptions: vec![
 2067                cx.observe(&buffer, Self::on_buffer_changed),
 2068                cx.subscribe(&buffer, Self::on_buffer_event),
 2069                cx.observe(&display_map, Self::on_display_map_changed),
 2070                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 2071                cx.observe_global::<SettingsStore>(Self::settings_changed),
 2072                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 2073                cx.observe_window_activation(|editor, cx| {
 2074                    let active = cx.is_window_active();
 2075                    editor.blink_manager.update(cx, |blink_manager, cx| {
 2076                        if active {
 2077                            blink_manager.enable(cx);
 2078                        } else {
 2079                            blink_manager.disable(cx);
 2080                        }
 2081                    });
 2082                }),
 2083            ],
 2084            tasks_update_task: None,
 2085            linked_edit_ranges: Default::default(),
 2086            previous_search_ranges: None,
 2087            breadcrumb_header: None,
 2088            focused_block: None,
 2089            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 2090            addons: HashMap::default(),
 2091            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 2092            text_style_refinement: None,
 2093        };
 2094        this.tasks_update_task = Some(this.refresh_runnables(cx));
 2095        this._subscriptions.extend(project_subscriptions);
 2096
 2097        this.end_selection(cx);
 2098        this.scroll_manager.show_scrollbar(cx);
 2099
 2100        if mode == EditorMode::Full {
 2101            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 2102            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 2103
 2104            if this.git_blame_inline_enabled {
 2105                this.git_blame_inline_enabled = true;
 2106                this.start_git_blame_inline(false, cx);
 2107            }
 2108        }
 2109
 2110        this.report_editor_event("open", None, cx);
 2111        this
 2112    }
 2113
 2114    pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
 2115        self.mouse_context_menu
 2116            .as_ref()
 2117            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
 2118    }
 2119
 2120    fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
 2121        let mut key_context = KeyContext::new_with_defaults();
 2122        key_context.add("Editor");
 2123        let mode = match self.mode {
 2124            EditorMode::SingleLine { .. } => "single_line",
 2125            EditorMode::AutoHeight { .. } => "auto_height",
 2126            EditorMode::Full => "full",
 2127        };
 2128
 2129        if EditorSettings::jupyter_enabled(cx) {
 2130            key_context.add("jupyter");
 2131        }
 2132
 2133        key_context.set("mode", mode);
 2134        if self.pending_rename.is_some() {
 2135            key_context.add("renaming");
 2136        }
 2137        if self.context_menu_visible() {
 2138            match self.context_menu.read().as_ref() {
 2139                Some(ContextMenu::Completions(_)) => {
 2140                    key_context.add("menu");
 2141                    key_context.add("showing_completions")
 2142                }
 2143                Some(ContextMenu::CodeActions(_)) => {
 2144                    key_context.add("menu");
 2145                    key_context.add("showing_code_actions")
 2146                }
 2147                None => {}
 2148            }
 2149        }
 2150
 2151        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 2152        if !self.focus_handle(cx).contains_focused(cx)
 2153            || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
 2154        {
 2155            for addon in self.addons.values() {
 2156                addon.extend_key_context(&mut key_context, cx)
 2157            }
 2158        }
 2159
 2160        if let Some(extension) = self
 2161            .buffer
 2162            .read(cx)
 2163            .as_singleton()
 2164            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 2165        {
 2166            key_context.set("extension", extension.to_string());
 2167        }
 2168
 2169        if self.has_active_inline_completion(cx) {
 2170            key_context.add("copilot_suggestion");
 2171            key_context.add("inline_completion");
 2172        }
 2173
 2174        key_context
 2175    }
 2176
 2177    pub fn new_file(
 2178        workspace: &mut Workspace,
 2179        _: &workspace::NewFile,
 2180        cx: &mut ViewContext<Workspace>,
 2181    ) {
 2182        Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
 2183            "Failed to create buffer",
 2184            cx,
 2185            |e, _| match e.error_code() {
 2186                ErrorCode::RemoteUpgradeRequired => Some(format!(
 2187                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2188                e.error_tag("required").unwrap_or("the latest version")
 2189            )),
 2190                _ => None,
 2191            },
 2192        );
 2193    }
 2194
 2195    pub fn new_in_workspace(
 2196        workspace: &mut Workspace,
 2197        cx: &mut ViewContext<Workspace>,
 2198    ) -> Task<Result<View<Editor>>> {
 2199        let project = workspace.project().clone();
 2200        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2201
 2202        cx.spawn(|workspace, mut cx| async move {
 2203            let buffer = create.await?;
 2204            workspace.update(&mut cx, |workspace, cx| {
 2205                let editor =
 2206                    cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
 2207                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 2208                editor
 2209            })
 2210        })
 2211    }
 2212
 2213    fn new_file_vertical(
 2214        workspace: &mut Workspace,
 2215        _: &workspace::NewFileSplitVertical,
 2216        cx: &mut ViewContext<Workspace>,
 2217    ) {
 2218        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
 2219    }
 2220
 2221    fn new_file_horizontal(
 2222        workspace: &mut Workspace,
 2223        _: &workspace::NewFileSplitHorizontal,
 2224        cx: &mut ViewContext<Workspace>,
 2225    ) {
 2226        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
 2227    }
 2228
 2229    fn new_file_in_direction(
 2230        workspace: &mut Workspace,
 2231        direction: SplitDirection,
 2232        cx: &mut ViewContext<Workspace>,
 2233    ) {
 2234        let project = workspace.project().clone();
 2235        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2236
 2237        cx.spawn(|workspace, mut cx| async move {
 2238            let buffer = create.await?;
 2239            workspace.update(&mut cx, move |workspace, cx| {
 2240                workspace.split_item(
 2241                    direction,
 2242                    Box::new(
 2243                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 2244                    ),
 2245                    cx,
 2246                )
 2247            })?;
 2248            anyhow::Ok(())
 2249        })
 2250        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 2251            ErrorCode::RemoteUpgradeRequired => Some(format!(
 2252                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2253                e.error_tag("required").unwrap_or("the latest version")
 2254            )),
 2255            _ => None,
 2256        });
 2257    }
 2258
 2259    pub fn leader_peer_id(&self) -> Option<PeerId> {
 2260        self.leader_peer_id
 2261    }
 2262
 2263    pub fn buffer(&self) -> &Model<MultiBuffer> {
 2264        &self.buffer
 2265    }
 2266
 2267    pub fn workspace(&self) -> Option<View<Workspace>> {
 2268        self.workspace.as_ref()?.0.upgrade()
 2269    }
 2270
 2271    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
 2272        self.buffer().read(cx).title(cx)
 2273    }
 2274
 2275    pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
 2276        let git_blame_gutter_max_author_length = self
 2277            .render_git_blame_gutter(cx)
 2278            .then(|| {
 2279                if let Some(blame) = self.blame.as_ref() {
 2280                    let max_author_length =
 2281                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 2282                    Some(max_author_length)
 2283                } else {
 2284                    None
 2285                }
 2286            })
 2287            .flatten();
 2288
 2289        EditorSnapshot {
 2290            mode: self.mode,
 2291            show_gutter: self.show_gutter,
 2292            show_line_numbers: self.show_line_numbers,
 2293            show_git_diff_gutter: self.show_git_diff_gutter,
 2294            show_code_actions: self.show_code_actions,
 2295            show_runnables: self.show_runnables,
 2296            git_blame_gutter_max_author_length,
 2297            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 2298            scroll_anchor: self.scroll_manager.anchor(),
 2299            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 2300            placeholder_text: self.placeholder_text.clone(),
 2301            is_focused: self.focus_handle.is_focused(cx),
 2302            current_line_highlight: self
 2303                .current_line_highlight
 2304                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 2305            gutter_hovered: self.gutter_hovered,
 2306        }
 2307    }
 2308
 2309    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
 2310        self.buffer.read(cx).language_at(point, cx)
 2311    }
 2312
 2313    pub fn file_at<T: ToOffset>(
 2314        &self,
 2315        point: T,
 2316        cx: &AppContext,
 2317    ) -> Option<Arc<dyn language::File>> {
 2318        self.buffer.read(cx).read(cx).file_at(point).cloned()
 2319    }
 2320
 2321    pub fn active_excerpt(
 2322        &self,
 2323        cx: &AppContext,
 2324    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
 2325        self.buffer
 2326            .read(cx)
 2327            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 2328    }
 2329
 2330    pub fn mode(&self) -> EditorMode {
 2331        self.mode
 2332    }
 2333
 2334    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 2335        self.collaboration_hub.as_deref()
 2336    }
 2337
 2338    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 2339        self.collaboration_hub = Some(hub);
 2340    }
 2341
 2342    pub fn set_custom_context_menu(
 2343        &mut self,
 2344        f: impl 'static
 2345            + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
 2346    ) {
 2347        self.custom_context_menu = Some(Box::new(f))
 2348    }
 2349
 2350    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 2351        self.completion_provider = provider;
 2352    }
 2353
 2354    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 2355        self.semantics_provider.clone()
 2356    }
 2357
 2358    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 2359        self.semantics_provider = provider;
 2360    }
 2361
 2362    pub fn set_inline_completion_provider<T>(
 2363        &mut self,
 2364        provider: Option<Model<T>>,
 2365        cx: &mut ViewContext<Self>,
 2366    ) where
 2367        T: InlineCompletionProvider,
 2368    {
 2369        self.inline_completion_provider =
 2370            provider.map(|provider| RegisteredInlineCompletionProvider {
 2371                _subscription: cx.observe(&provider, |this, _, cx| {
 2372                    if this.focus_handle.is_focused(cx) {
 2373                        this.update_visible_inline_completion(cx);
 2374                    }
 2375                }),
 2376                provider: Arc::new(provider),
 2377            });
 2378        self.refresh_inline_completion(false, false, cx);
 2379    }
 2380
 2381    pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
 2382        self.placeholder_text.as_deref()
 2383    }
 2384
 2385    pub fn set_placeholder_text(
 2386        &mut self,
 2387        placeholder_text: impl Into<Arc<str>>,
 2388        cx: &mut ViewContext<Self>,
 2389    ) {
 2390        let placeholder_text = Some(placeholder_text.into());
 2391        if self.placeholder_text != placeholder_text {
 2392            self.placeholder_text = placeholder_text;
 2393            cx.notify();
 2394        }
 2395    }
 2396
 2397    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
 2398        self.cursor_shape = cursor_shape;
 2399
 2400        // Disrupt blink for immediate user feedback that the cursor shape has changed
 2401        self.blink_manager.update(cx, BlinkManager::show_cursor);
 2402
 2403        cx.notify();
 2404    }
 2405
 2406    pub fn set_current_line_highlight(
 2407        &mut self,
 2408        current_line_highlight: Option<CurrentLineHighlight>,
 2409    ) {
 2410        self.current_line_highlight = current_line_highlight;
 2411    }
 2412
 2413    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 2414        self.collapse_matches = collapse_matches;
 2415    }
 2416
 2417    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 2418        if self.collapse_matches {
 2419            return range.start..range.start;
 2420        }
 2421        range.clone()
 2422    }
 2423
 2424    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
 2425        if self.display_map.read(cx).clip_at_line_ends != clip {
 2426            self.display_map
 2427                .update(cx, |map, _| map.clip_at_line_ends = clip);
 2428        }
 2429    }
 2430
 2431    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 2432        self.input_enabled = input_enabled;
 2433    }
 2434
 2435    pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
 2436        self.enable_inline_completions = enabled;
 2437    }
 2438
 2439    pub fn set_autoindent(&mut self, autoindent: bool) {
 2440        if autoindent {
 2441            self.autoindent_mode = Some(AutoindentMode::EachLine);
 2442        } else {
 2443            self.autoindent_mode = None;
 2444        }
 2445    }
 2446
 2447    pub fn read_only(&self, cx: &AppContext) -> bool {
 2448        self.read_only || self.buffer.read(cx).read_only()
 2449    }
 2450
 2451    pub fn set_read_only(&mut self, read_only: bool) {
 2452        self.read_only = read_only;
 2453    }
 2454
 2455    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 2456        self.use_autoclose = autoclose;
 2457    }
 2458
 2459    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 2460        self.use_auto_surround = auto_surround;
 2461    }
 2462
 2463    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 2464        self.auto_replace_emoji_shortcode = auto_replace;
 2465    }
 2466
 2467    pub fn toggle_inline_completions(
 2468        &mut self,
 2469        _: &ToggleInlineCompletions,
 2470        cx: &mut ViewContext<Self>,
 2471    ) {
 2472        if self.show_inline_completions_override.is_some() {
 2473            self.set_show_inline_completions(None, cx);
 2474        } else {
 2475            let cursor = self.selections.newest_anchor().head();
 2476            if let Some((buffer, cursor_buffer_position)) =
 2477                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 2478            {
 2479                let show_inline_completions =
 2480                    !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
 2481                self.set_show_inline_completions(Some(show_inline_completions), cx);
 2482            }
 2483        }
 2484    }
 2485
 2486    pub fn set_show_inline_completions(
 2487        &mut self,
 2488        show_inline_completions: Option<bool>,
 2489        cx: &mut ViewContext<Self>,
 2490    ) {
 2491        self.show_inline_completions_override = show_inline_completions;
 2492        self.refresh_inline_completion(false, true, cx);
 2493    }
 2494
 2495    fn should_show_inline_completions(
 2496        &self,
 2497        buffer: &Model<Buffer>,
 2498        buffer_position: language::Anchor,
 2499        cx: &AppContext,
 2500    ) -> bool {
 2501        if !self.snippet_stack.is_empty() {
 2502            return false;
 2503        }
 2504
 2505        if let Some(provider) = self.inline_completion_provider() {
 2506            if let Some(show_inline_completions) = self.show_inline_completions_override {
 2507                show_inline_completions
 2508            } else {
 2509                self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
 2510            }
 2511        } else {
 2512            false
 2513        }
 2514    }
 2515
 2516    pub fn set_use_modal_editing(&mut self, to: bool) {
 2517        self.use_modal_editing = to;
 2518    }
 2519
 2520    pub fn use_modal_editing(&self) -> bool {
 2521        self.use_modal_editing
 2522    }
 2523
 2524    fn selections_did_change(
 2525        &mut self,
 2526        local: bool,
 2527        old_cursor_position: &Anchor,
 2528        show_completions: bool,
 2529        cx: &mut ViewContext<Self>,
 2530    ) {
 2531        cx.invalidate_character_coordinates();
 2532
 2533        // Copy selections to primary selection buffer
 2534        #[cfg(target_os = "linux")]
 2535        if local {
 2536            let selections = self.selections.all::<usize>(cx);
 2537            let buffer_handle = self.buffer.read(cx).read(cx);
 2538
 2539            let mut text = String::new();
 2540            for (index, selection) in selections.iter().enumerate() {
 2541                let text_for_selection = buffer_handle
 2542                    .text_for_range(selection.start..selection.end)
 2543                    .collect::<String>();
 2544
 2545                text.push_str(&text_for_selection);
 2546                if index != selections.len() - 1 {
 2547                    text.push('\n');
 2548                }
 2549            }
 2550
 2551            if !text.is_empty() {
 2552                cx.write_to_primary(ClipboardItem::new_string(text));
 2553            }
 2554        }
 2555
 2556        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
 2557            self.buffer.update(cx, |buffer, cx| {
 2558                buffer.set_active_selections(
 2559                    &self.selections.disjoint_anchors(),
 2560                    self.selections.line_mode,
 2561                    self.cursor_shape,
 2562                    cx,
 2563                )
 2564            });
 2565        }
 2566        let display_map = self
 2567            .display_map
 2568            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2569        let buffer = &display_map.buffer_snapshot;
 2570        self.add_selections_state = None;
 2571        self.select_next_state = None;
 2572        self.select_prev_state = None;
 2573        self.select_larger_syntax_node_stack.clear();
 2574        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2575        self.snippet_stack
 2576            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2577        self.take_rename(false, cx);
 2578
 2579        let new_cursor_position = self.selections.newest_anchor().head();
 2580
 2581        self.push_to_nav_history(
 2582            *old_cursor_position,
 2583            Some(new_cursor_position.to_point(buffer)),
 2584            cx,
 2585        );
 2586
 2587        if local {
 2588            let new_cursor_position = self.selections.newest_anchor().head();
 2589            let mut context_menu = self.context_menu.write();
 2590            let completion_menu = match context_menu.as_ref() {
 2591                Some(ContextMenu::Completions(menu)) => Some(menu),
 2592
 2593                _ => {
 2594                    *context_menu = None;
 2595                    None
 2596                }
 2597            };
 2598
 2599            if let Some(completion_menu) = completion_menu {
 2600                let cursor_position = new_cursor_position.to_offset(buffer);
 2601                let (word_range, kind) =
 2602                    buffer.surrounding_word(completion_menu.initial_position, true);
 2603                if kind == Some(CharKind::Word)
 2604                    && word_range.to_inclusive().contains(&cursor_position)
 2605                {
 2606                    let mut completion_menu = completion_menu.clone();
 2607                    drop(context_menu);
 2608
 2609                    let query = Self::completion_query(buffer, cursor_position);
 2610                    cx.spawn(move |this, mut cx| async move {
 2611                        completion_menu
 2612                            .filter(query.as_deref(), cx.background_executor().clone())
 2613                            .await;
 2614
 2615                        this.update(&mut cx, |this, cx| {
 2616                            let mut context_menu = this.context_menu.write();
 2617                            let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
 2618                                return;
 2619                            };
 2620
 2621                            if menu.id > completion_menu.id {
 2622                                return;
 2623                            }
 2624
 2625                            *context_menu = Some(ContextMenu::Completions(completion_menu));
 2626                            drop(context_menu);
 2627                            cx.notify();
 2628                        })
 2629                    })
 2630                    .detach();
 2631
 2632                    if show_completions {
 2633                        self.show_completions(&ShowCompletions { trigger: None }, cx);
 2634                    }
 2635                } else {
 2636                    drop(context_menu);
 2637                    self.hide_context_menu(cx);
 2638                }
 2639            } else {
 2640                drop(context_menu);
 2641            }
 2642
 2643            hide_hover(self, cx);
 2644
 2645            if old_cursor_position.to_display_point(&display_map).row()
 2646                != new_cursor_position.to_display_point(&display_map).row()
 2647            {
 2648                self.available_code_actions.take();
 2649            }
 2650            self.refresh_code_actions(cx);
 2651            self.refresh_document_highlights(cx);
 2652            refresh_matching_bracket_highlights(self, cx);
 2653            self.discard_inline_completion(false, cx);
 2654            linked_editing_ranges::refresh_linked_ranges(self, cx);
 2655            if self.git_blame_inline_enabled {
 2656                self.start_inline_blame_timer(cx);
 2657            }
 2658        }
 2659
 2660        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2661        cx.emit(EditorEvent::SelectionsChanged { local });
 2662
 2663        if self.selections.disjoint_anchors().len() == 1 {
 2664            cx.emit(SearchEvent::ActiveMatchChanged)
 2665        }
 2666        cx.notify();
 2667    }
 2668
 2669    pub fn change_selections<R>(
 2670        &mut self,
 2671        autoscroll: Option<Autoscroll>,
 2672        cx: &mut ViewContext<Self>,
 2673        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2674    ) -> R {
 2675        self.change_selections_inner(autoscroll, true, cx, change)
 2676    }
 2677
 2678    pub fn change_selections_inner<R>(
 2679        &mut self,
 2680        autoscroll: Option<Autoscroll>,
 2681        request_completions: bool,
 2682        cx: &mut ViewContext<Self>,
 2683        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2684    ) -> R {
 2685        let old_cursor_position = self.selections.newest_anchor().head();
 2686        self.push_to_selection_history();
 2687
 2688        let (changed, result) = self.selections.change_with(cx, change);
 2689
 2690        if changed {
 2691            if let Some(autoscroll) = autoscroll {
 2692                self.request_autoscroll(autoscroll, cx);
 2693            }
 2694            self.selections_did_change(true, &old_cursor_position, request_completions, cx);
 2695
 2696            if self.should_open_signature_help_automatically(
 2697                &old_cursor_position,
 2698                self.signature_help_state.backspace_pressed(),
 2699                cx,
 2700            ) {
 2701                self.show_signature_help(&ShowSignatureHelp, cx);
 2702            }
 2703            self.signature_help_state.set_backspace_pressed(false);
 2704        }
 2705
 2706        result
 2707    }
 2708
 2709    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2710    where
 2711        I: IntoIterator<Item = (Range<S>, T)>,
 2712        S: ToOffset,
 2713        T: Into<Arc<str>>,
 2714    {
 2715        if self.read_only(cx) {
 2716            return;
 2717        }
 2718
 2719        self.buffer
 2720            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2721    }
 2722
 2723    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2724    where
 2725        I: IntoIterator<Item = (Range<S>, T)>,
 2726        S: ToOffset,
 2727        T: Into<Arc<str>>,
 2728    {
 2729        if self.read_only(cx) {
 2730            return;
 2731        }
 2732
 2733        self.buffer.update(cx, |buffer, cx| {
 2734            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2735        });
 2736    }
 2737
 2738    pub fn edit_with_block_indent<I, S, T>(
 2739        &mut self,
 2740        edits: I,
 2741        original_indent_columns: Vec<u32>,
 2742        cx: &mut ViewContext<Self>,
 2743    ) where
 2744        I: IntoIterator<Item = (Range<S>, T)>,
 2745        S: ToOffset,
 2746        T: Into<Arc<str>>,
 2747    {
 2748        if self.read_only(cx) {
 2749            return;
 2750        }
 2751
 2752        self.buffer.update(cx, |buffer, cx| {
 2753            buffer.edit(
 2754                edits,
 2755                Some(AutoindentMode::Block {
 2756                    original_indent_columns,
 2757                }),
 2758                cx,
 2759            )
 2760        });
 2761    }
 2762
 2763    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
 2764        self.hide_context_menu(cx);
 2765
 2766        match phase {
 2767            SelectPhase::Begin {
 2768                position,
 2769                add,
 2770                click_count,
 2771            } => self.begin_selection(position, add, click_count, cx),
 2772            SelectPhase::BeginColumnar {
 2773                position,
 2774                goal_column,
 2775                reset,
 2776            } => self.begin_columnar_selection(position, goal_column, reset, cx),
 2777            SelectPhase::Extend {
 2778                position,
 2779                click_count,
 2780            } => self.extend_selection(position, click_count, cx),
 2781            SelectPhase::Update {
 2782                position,
 2783                goal_column,
 2784                scroll_delta,
 2785            } => self.update_selection(position, goal_column, scroll_delta, cx),
 2786            SelectPhase::End => self.end_selection(cx),
 2787        }
 2788    }
 2789
 2790    fn extend_selection(
 2791        &mut self,
 2792        position: DisplayPoint,
 2793        click_count: usize,
 2794        cx: &mut ViewContext<Self>,
 2795    ) {
 2796        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2797        let tail = self.selections.newest::<usize>(cx).tail();
 2798        self.begin_selection(position, false, click_count, cx);
 2799
 2800        let position = position.to_offset(&display_map, Bias::Left);
 2801        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2802
 2803        let mut pending_selection = self
 2804            .selections
 2805            .pending_anchor()
 2806            .expect("extend_selection not called with pending selection");
 2807        if position >= tail {
 2808            pending_selection.start = tail_anchor;
 2809        } else {
 2810            pending_selection.end = tail_anchor;
 2811            pending_selection.reversed = true;
 2812        }
 2813
 2814        let mut pending_mode = self.selections.pending_mode().unwrap();
 2815        match &mut pending_mode {
 2816            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2817            _ => {}
 2818        }
 2819
 2820        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 2821            s.set_pending(pending_selection, pending_mode)
 2822        });
 2823    }
 2824
 2825    fn begin_selection(
 2826        &mut self,
 2827        position: DisplayPoint,
 2828        add: bool,
 2829        click_count: usize,
 2830        cx: &mut ViewContext<Self>,
 2831    ) {
 2832        if !self.focus_handle.is_focused(cx) {
 2833            self.last_focused_descendant = None;
 2834            cx.focus(&self.focus_handle);
 2835        }
 2836
 2837        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2838        let buffer = &display_map.buffer_snapshot;
 2839        let newest_selection = self.selections.newest_anchor().clone();
 2840        let position = display_map.clip_point(position, Bias::Left);
 2841
 2842        let start;
 2843        let end;
 2844        let mode;
 2845        let auto_scroll;
 2846        match click_count {
 2847            1 => {
 2848                start = buffer.anchor_before(position.to_point(&display_map));
 2849                end = start;
 2850                mode = SelectMode::Character;
 2851                auto_scroll = true;
 2852            }
 2853            2 => {
 2854                let range = movement::surrounding_word(&display_map, position);
 2855                start = buffer.anchor_before(range.start.to_point(&display_map));
 2856                end = buffer.anchor_before(range.end.to_point(&display_map));
 2857                mode = SelectMode::Word(start..end);
 2858                auto_scroll = true;
 2859            }
 2860            3 => {
 2861                let position = display_map
 2862                    .clip_point(position, Bias::Left)
 2863                    .to_point(&display_map);
 2864                let line_start = display_map.prev_line_boundary(position).0;
 2865                let next_line_start = buffer.clip_point(
 2866                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2867                    Bias::Left,
 2868                );
 2869                start = buffer.anchor_before(line_start);
 2870                end = buffer.anchor_before(next_line_start);
 2871                mode = SelectMode::Line(start..end);
 2872                auto_scroll = true;
 2873            }
 2874            _ => {
 2875                start = buffer.anchor_before(0);
 2876                end = buffer.anchor_before(buffer.len());
 2877                mode = SelectMode::All;
 2878                auto_scroll = false;
 2879            }
 2880        }
 2881
 2882        let point_to_delete: Option<usize> = {
 2883            let selected_points: Vec<Selection<Point>> =
 2884                self.selections.disjoint_in_range(start..end, cx);
 2885
 2886            if !add || click_count > 1 {
 2887                None
 2888            } else if !selected_points.is_empty() {
 2889                Some(selected_points[0].id)
 2890            } else {
 2891                let clicked_point_already_selected =
 2892                    self.selections.disjoint.iter().find(|selection| {
 2893                        selection.start.to_point(buffer) == start.to_point(buffer)
 2894                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2895                    });
 2896
 2897                clicked_point_already_selected.map(|selection| selection.id)
 2898            }
 2899        };
 2900
 2901        let selections_count = self.selections.count();
 2902
 2903        self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
 2904            if let Some(point_to_delete) = point_to_delete {
 2905                s.delete(point_to_delete);
 2906
 2907                if selections_count == 1 {
 2908                    s.set_pending_anchor_range(start..end, mode);
 2909                }
 2910            } else {
 2911                if !add {
 2912                    s.clear_disjoint();
 2913                } else if click_count > 1 {
 2914                    s.delete(newest_selection.id)
 2915                }
 2916
 2917                s.set_pending_anchor_range(start..end, mode);
 2918            }
 2919        });
 2920    }
 2921
 2922    fn begin_columnar_selection(
 2923        &mut self,
 2924        position: DisplayPoint,
 2925        goal_column: u32,
 2926        reset: bool,
 2927        cx: &mut ViewContext<Self>,
 2928    ) {
 2929        if !self.focus_handle.is_focused(cx) {
 2930            self.last_focused_descendant = None;
 2931            cx.focus(&self.focus_handle);
 2932        }
 2933
 2934        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2935
 2936        if reset {
 2937            let pointer_position = display_map
 2938                .buffer_snapshot
 2939                .anchor_before(position.to_point(&display_map));
 2940
 2941            self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 2942                s.clear_disjoint();
 2943                s.set_pending_anchor_range(
 2944                    pointer_position..pointer_position,
 2945                    SelectMode::Character,
 2946                );
 2947            });
 2948        }
 2949
 2950        let tail = self.selections.newest::<Point>(cx).tail();
 2951        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2952
 2953        if !reset {
 2954            self.select_columns(
 2955                tail.to_display_point(&display_map),
 2956                position,
 2957                goal_column,
 2958                &display_map,
 2959                cx,
 2960            );
 2961        }
 2962    }
 2963
 2964    fn update_selection(
 2965        &mut self,
 2966        position: DisplayPoint,
 2967        goal_column: u32,
 2968        scroll_delta: gpui::Point<f32>,
 2969        cx: &mut ViewContext<Self>,
 2970    ) {
 2971        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2972
 2973        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2974            let tail = tail.to_display_point(&display_map);
 2975            self.select_columns(tail, position, goal_column, &display_map, cx);
 2976        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2977            let buffer = self.buffer.read(cx).snapshot(cx);
 2978            let head;
 2979            let tail;
 2980            let mode = self.selections.pending_mode().unwrap();
 2981            match &mode {
 2982                SelectMode::Character => {
 2983                    head = position.to_point(&display_map);
 2984                    tail = pending.tail().to_point(&buffer);
 2985                }
 2986                SelectMode::Word(original_range) => {
 2987                    let original_display_range = original_range.start.to_display_point(&display_map)
 2988                        ..original_range.end.to_display_point(&display_map);
 2989                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2990                        ..original_display_range.end.to_point(&display_map);
 2991                    if movement::is_inside_word(&display_map, position)
 2992                        || original_display_range.contains(&position)
 2993                    {
 2994                        let word_range = movement::surrounding_word(&display_map, position);
 2995                        if word_range.start < original_display_range.start {
 2996                            head = word_range.start.to_point(&display_map);
 2997                        } else {
 2998                            head = word_range.end.to_point(&display_map);
 2999                        }
 3000                    } else {
 3001                        head = position.to_point(&display_map);
 3002                    }
 3003
 3004                    if head <= original_buffer_range.start {
 3005                        tail = original_buffer_range.end;
 3006                    } else {
 3007                        tail = original_buffer_range.start;
 3008                    }
 3009                }
 3010                SelectMode::Line(original_range) => {
 3011                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 3012
 3013                    let position = display_map
 3014                        .clip_point(position, Bias::Left)
 3015                        .to_point(&display_map);
 3016                    let line_start = display_map.prev_line_boundary(position).0;
 3017                    let next_line_start = buffer.clip_point(
 3018                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 3019                        Bias::Left,
 3020                    );
 3021
 3022                    if line_start < original_range.start {
 3023                        head = line_start
 3024                    } else {
 3025                        head = next_line_start
 3026                    }
 3027
 3028                    if head <= original_range.start {
 3029                        tail = original_range.end;
 3030                    } else {
 3031                        tail = original_range.start;
 3032                    }
 3033                }
 3034                SelectMode::All => {
 3035                    return;
 3036                }
 3037            };
 3038
 3039            if head < tail {
 3040                pending.start = buffer.anchor_before(head);
 3041                pending.end = buffer.anchor_before(tail);
 3042                pending.reversed = true;
 3043            } else {
 3044                pending.start = buffer.anchor_before(tail);
 3045                pending.end = buffer.anchor_before(head);
 3046                pending.reversed = false;
 3047            }
 3048
 3049            self.change_selections(None, cx, |s| {
 3050                s.set_pending(pending, mode);
 3051            });
 3052        } else {
 3053            log::error!("update_selection dispatched with no pending selection");
 3054            return;
 3055        }
 3056
 3057        self.apply_scroll_delta(scroll_delta, cx);
 3058        cx.notify();
 3059    }
 3060
 3061    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 3062        self.columnar_selection_tail.take();
 3063        if self.selections.pending_anchor().is_some() {
 3064            let selections = self.selections.all::<usize>(cx);
 3065            self.change_selections(None, cx, |s| {
 3066                s.select(selections);
 3067                s.clear_pending();
 3068            });
 3069        }
 3070    }
 3071
 3072    fn select_columns(
 3073        &mut self,
 3074        tail: DisplayPoint,
 3075        head: DisplayPoint,
 3076        goal_column: u32,
 3077        display_map: &DisplaySnapshot,
 3078        cx: &mut ViewContext<Self>,
 3079    ) {
 3080        let start_row = cmp::min(tail.row(), head.row());
 3081        let end_row = cmp::max(tail.row(), head.row());
 3082        let start_column = cmp::min(tail.column(), goal_column);
 3083        let end_column = cmp::max(tail.column(), goal_column);
 3084        let reversed = start_column < tail.column();
 3085
 3086        let selection_ranges = (start_row.0..=end_row.0)
 3087            .map(DisplayRow)
 3088            .filter_map(|row| {
 3089                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 3090                    let start = display_map
 3091                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 3092                        .to_point(display_map);
 3093                    let end = display_map
 3094                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 3095                        .to_point(display_map);
 3096                    if reversed {
 3097                        Some(end..start)
 3098                    } else {
 3099                        Some(start..end)
 3100                    }
 3101                } else {
 3102                    None
 3103                }
 3104            })
 3105            .collect::<Vec<_>>();
 3106
 3107        self.change_selections(None, cx, |s| {
 3108            s.select_ranges(selection_ranges);
 3109        });
 3110        cx.notify();
 3111    }
 3112
 3113    pub fn has_pending_nonempty_selection(&self) -> bool {
 3114        let pending_nonempty_selection = match self.selections.pending_anchor() {
 3115            Some(Selection { start, end, .. }) => start != end,
 3116            None => false,
 3117        };
 3118
 3119        pending_nonempty_selection
 3120            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 3121    }
 3122
 3123    pub fn has_pending_selection(&self) -> bool {
 3124        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 3125    }
 3126
 3127    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 3128        if self.clear_expanded_diff_hunks(cx) {
 3129            cx.notify();
 3130            return;
 3131        }
 3132        if self.dismiss_menus_and_popups(true, cx) {
 3133            return;
 3134        }
 3135
 3136        if self.mode == EditorMode::Full
 3137            && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
 3138        {
 3139            return;
 3140        }
 3141
 3142        cx.propagate();
 3143    }
 3144
 3145    pub fn dismiss_menus_and_popups(
 3146        &mut self,
 3147        should_report_inline_completion_event: bool,
 3148        cx: &mut ViewContext<Self>,
 3149    ) -> bool {
 3150        if self.take_rename(false, cx).is_some() {
 3151            return true;
 3152        }
 3153
 3154        if hide_hover(self, cx) {
 3155            return true;
 3156        }
 3157
 3158        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 3159            return true;
 3160        }
 3161
 3162        if self.hide_context_menu(cx).is_some() {
 3163            return true;
 3164        }
 3165
 3166        if self.mouse_context_menu.take().is_some() {
 3167            return true;
 3168        }
 3169
 3170        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 3171            return true;
 3172        }
 3173
 3174        if self.snippet_stack.pop().is_some() {
 3175            return true;
 3176        }
 3177
 3178        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 3179            self.dismiss_diagnostics(cx);
 3180            return true;
 3181        }
 3182
 3183        false
 3184    }
 3185
 3186    fn linked_editing_ranges_for(
 3187        &self,
 3188        selection: Range<text::Anchor>,
 3189        cx: &AppContext,
 3190    ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
 3191        if self.linked_edit_ranges.is_empty() {
 3192            return None;
 3193        }
 3194        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 3195            selection.end.buffer_id.and_then(|end_buffer_id| {
 3196                if selection.start.buffer_id != Some(end_buffer_id) {
 3197                    return None;
 3198                }
 3199                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 3200                let snapshot = buffer.read(cx).snapshot();
 3201                self.linked_edit_ranges
 3202                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 3203                    .map(|ranges| (ranges, snapshot, buffer))
 3204            })?;
 3205        use text::ToOffset as TO;
 3206        // find offset from the start of current range to current cursor position
 3207        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 3208
 3209        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 3210        let start_difference = start_offset - start_byte_offset;
 3211        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 3212        let end_difference = end_offset - start_byte_offset;
 3213        // Current range has associated linked ranges.
 3214        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3215        for range in linked_ranges.iter() {
 3216            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 3217            let end_offset = start_offset + end_difference;
 3218            let start_offset = start_offset + start_difference;
 3219            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 3220                continue;
 3221            }
 3222            if self.selections.disjoint_anchor_ranges().iter().any(|s| {
 3223                if s.start.buffer_id != selection.start.buffer_id
 3224                    || s.end.buffer_id != selection.end.buffer_id
 3225                {
 3226                    return false;
 3227                }
 3228                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 3229                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 3230            }) {
 3231                continue;
 3232            }
 3233            let start = buffer_snapshot.anchor_after(start_offset);
 3234            let end = buffer_snapshot.anchor_after(end_offset);
 3235            linked_edits
 3236                .entry(buffer.clone())
 3237                .or_default()
 3238                .push(start..end);
 3239        }
 3240        Some(linked_edits)
 3241    }
 3242
 3243    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3244        let text: Arc<str> = text.into();
 3245
 3246        if self.read_only(cx) {
 3247            return;
 3248        }
 3249
 3250        let selections = self.selections.all_adjusted(cx);
 3251        let mut bracket_inserted = false;
 3252        let mut edits = Vec::new();
 3253        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3254        let mut new_selections = Vec::with_capacity(selections.len());
 3255        let mut new_autoclose_regions = Vec::new();
 3256        let snapshot = self.buffer.read(cx).read(cx);
 3257
 3258        for (selection, autoclose_region) in
 3259            self.selections_with_autoclose_regions(selections, &snapshot)
 3260        {
 3261            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 3262                // Determine if the inserted text matches the opening or closing
 3263                // bracket of any of this language's bracket pairs.
 3264                let mut bracket_pair = None;
 3265                let mut is_bracket_pair_start = false;
 3266                let mut is_bracket_pair_end = false;
 3267                if !text.is_empty() {
 3268                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 3269                    //  and they are removing the character that triggered IME popup.
 3270                    for (pair, enabled) in scope.brackets() {
 3271                        if !pair.close && !pair.surround {
 3272                            continue;
 3273                        }
 3274
 3275                        if enabled && pair.start.ends_with(text.as_ref()) {
 3276                            let prefix_len = pair.start.len() - text.len();
 3277                            let preceding_text_matches_prefix = prefix_len == 0
 3278                                || (selection.start.column >= (prefix_len as u32)
 3279                                    && snapshot.contains_str_at(
 3280                                        Point::new(
 3281                                            selection.start.row,
 3282                                            selection.start.column - (prefix_len as u32),
 3283                                        ),
 3284                                        &pair.start[..prefix_len],
 3285                                    ));
 3286                            if preceding_text_matches_prefix {
 3287                                bracket_pair = Some(pair.clone());
 3288                                is_bracket_pair_start = true;
 3289                                break;
 3290                            }
 3291                        }
 3292                        if pair.end.as_str() == text.as_ref() {
 3293                            bracket_pair = Some(pair.clone());
 3294                            is_bracket_pair_end = true;
 3295                            break;
 3296                        }
 3297                    }
 3298                }
 3299
 3300                if let Some(bracket_pair) = bracket_pair {
 3301                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 3302                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 3303                    let auto_surround =
 3304                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 3305                    if selection.is_empty() {
 3306                        if is_bracket_pair_start {
 3307                            // If the inserted text is a suffix of an opening bracket and the
 3308                            // selection is preceded by the rest of the opening bracket, then
 3309                            // insert the closing bracket.
 3310                            let following_text_allows_autoclose = snapshot
 3311                                .chars_at(selection.start)
 3312                                .next()
 3313                                .map_or(true, |c| scope.should_autoclose_before(c));
 3314
 3315                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 3316                                && bracket_pair.start.len() == 1
 3317                            {
 3318                                let target = bracket_pair.start.chars().next().unwrap();
 3319                                let current_line_count = snapshot
 3320                                    .reversed_chars_at(selection.start)
 3321                                    .take_while(|&c| c != '\n')
 3322                                    .filter(|&c| c == target)
 3323                                    .count();
 3324                                current_line_count % 2 == 1
 3325                            } else {
 3326                                false
 3327                            };
 3328
 3329                            if autoclose
 3330                                && bracket_pair.close
 3331                                && following_text_allows_autoclose
 3332                                && !is_closing_quote
 3333                            {
 3334                                let anchor = snapshot.anchor_before(selection.end);
 3335                                new_selections.push((selection.map(|_| anchor), text.len()));
 3336                                new_autoclose_regions.push((
 3337                                    anchor,
 3338                                    text.len(),
 3339                                    selection.id,
 3340                                    bracket_pair.clone(),
 3341                                ));
 3342                                edits.push((
 3343                                    selection.range(),
 3344                                    format!("{}{}", text, bracket_pair.end).into(),
 3345                                ));
 3346                                bracket_inserted = true;
 3347                                continue;
 3348                            }
 3349                        }
 3350
 3351                        if let Some(region) = autoclose_region {
 3352                            // If the selection is followed by an auto-inserted closing bracket,
 3353                            // then don't insert that closing bracket again; just move the selection
 3354                            // past the closing bracket.
 3355                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3356                                && text.as_ref() == region.pair.end.as_str();
 3357                            if should_skip {
 3358                                let anchor = snapshot.anchor_after(selection.end);
 3359                                new_selections
 3360                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3361                                continue;
 3362                            }
 3363                        }
 3364
 3365                        let always_treat_brackets_as_autoclosed = snapshot
 3366                            .settings_at(selection.start, cx)
 3367                            .always_treat_brackets_as_autoclosed;
 3368                        if always_treat_brackets_as_autoclosed
 3369                            && is_bracket_pair_end
 3370                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3371                        {
 3372                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3373                            // and the inserted text is a closing bracket and the selection is followed
 3374                            // by the closing bracket then move the selection past the closing bracket.
 3375                            let anchor = snapshot.anchor_after(selection.end);
 3376                            new_selections.push((selection.map(|_| anchor), text.len()));
 3377                            continue;
 3378                        }
 3379                    }
 3380                    // If an opening bracket is 1 character long and is typed while
 3381                    // text is selected, then surround that text with the bracket pair.
 3382                    else if auto_surround
 3383                        && bracket_pair.surround
 3384                        && is_bracket_pair_start
 3385                        && bracket_pair.start.chars().count() == 1
 3386                    {
 3387                        edits.push((selection.start..selection.start, text.clone()));
 3388                        edits.push((
 3389                            selection.end..selection.end,
 3390                            bracket_pair.end.as_str().into(),
 3391                        ));
 3392                        bracket_inserted = true;
 3393                        new_selections.push((
 3394                            Selection {
 3395                                id: selection.id,
 3396                                start: snapshot.anchor_after(selection.start),
 3397                                end: snapshot.anchor_before(selection.end),
 3398                                reversed: selection.reversed,
 3399                                goal: selection.goal,
 3400                            },
 3401                            0,
 3402                        ));
 3403                        continue;
 3404                    }
 3405                }
 3406            }
 3407
 3408            if self.auto_replace_emoji_shortcode
 3409                && selection.is_empty()
 3410                && text.as_ref().ends_with(':')
 3411            {
 3412                if let Some(possible_emoji_short_code) =
 3413                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3414                {
 3415                    if !possible_emoji_short_code.is_empty() {
 3416                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3417                            let emoji_shortcode_start = Point::new(
 3418                                selection.start.row,
 3419                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3420                            );
 3421
 3422                            // Remove shortcode from buffer
 3423                            edits.push((
 3424                                emoji_shortcode_start..selection.start,
 3425                                "".to_string().into(),
 3426                            ));
 3427                            new_selections.push((
 3428                                Selection {
 3429                                    id: selection.id,
 3430                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3431                                    end: snapshot.anchor_before(selection.start),
 3432                                    reversed: selection.reversed,
 3433                                    goal: selection.goal,
 3434                                },
 3435                                0,
 3436                            ));
 3437
 3438                            // Insert emoji
 3439                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3440                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3441                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3442
 3443                            continue;
 3444                        }
 3445                    }
 3446                }
 3447            }
 3448
 3449            // If not handling any auto-close operation, then just replace the selected
 3450            // text with the given input and move the selection to the end of the
 3451            // newly inserted text.
 3452            let anchor = snapshot.anchor_after(selection.end);
 3453            if !self.linked_edit_ranges.is_empty() {
 3454                let start_anchor = snapshot.anchor_before(selection.start);
 3455
 3456                let is_word_char = text.chars().next().map_or(true, |char| {
 3457                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3458                    classifier.is_word(char)
 3459                });
 3460
 3461                if is_word_char {
 3462                    if let Some(ranges) = self
 3463                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3464                    {
 3465                        for (buffer, edits) in ranges {
 3466                            linked_edits
 3467                                .entry(buffer.clone())
 3468                                .or_default()
 3469                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3470                        }
 3471                    }
 3472                }
 3473            }
 3474
 3475            new_selections.push((selection.map(|_| anchor), 0));
 3476            edits.push((selection.start..selection.end, text.clone()));
 3477        }
 3478
 3479        drop(snapshot);
 3480
 3481        self.transact(cx, |this, cx| {
 3482            this.buffer.update(cx, |buffer, cx| {
 3483                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3484            });
 3485            for (buffer, edits) in linked_edits {
 3486                buffer.update(cx, |buffer, cx| {
 3487                    let snapshot = buffer.snapshot();
 3488                    let edits = edits
 3489                        .into_iter()
 3490                        .map(|(range, text)| {
 3491                            use text::ToPoint as TP;
 3492                            let end_point = TP::to_point(&range.end, &snapshot);
 3493                            let start_point = TP::to_point(&range.start, &snapshot);
 3494                            (start_point..end_point, text)
 3495                        })
 3496                        .sorted_by_key(|(range, _)| range.start)
 3497                        .collect::<Vec<_>>();
 3498                    buffer.edit(edits, None, cx);
 3499                })
 3500            }
 3501            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3502            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3503            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3504            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3505                .zip(new_selection_deltas)
 3506                .map(|(selection, delta)| Selection {
 3507                    id: selection.id,
 3508                    start: selection.start + delta,
 3509                    end: selection.end + delta,
 3510                    reversed: selection.reversed,
 3511                    goal: SelectionGoal::None,
 3512                })
 3513                .collect::<Vec<_>>();
 3514
 3515            let mut i = 0;
 3516            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3517                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3518                let start = map.buffer_snapshot.anchor_before(position);
 3519                let end = map.buffer_snapshot.anchor_after(position);
 3520                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3521                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3522                        Ordering::Less => i += 1,
 3523                        Ordering::Greater => break,
 3524                        Ordering::Equal => {
 3525                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3526                                Ordering::Less => i += 1,
 3527                                Ordering::Equal => break,
 3528                                Ordering::Greater => break,
 3529                            }
 3530                        }
 3531                    }
 3532                }
 3533                this.autoclose_regions.insert(
 3534                    i,
 3535                    AutocloseRegion {
 3536                        selection_id,
 3537                        range: start..end,
 3538                        pair,
 3539                    },
 3540                );
 3541            }
 3542
 3543            let had_active_inline_completion = this.has_active_inline_completion(cx);
 3544            this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
 3545                s.select(new_selections)
 3546            });
 3547
 3548            if !bracket_inserted {
 3549                if let Some(on_type_format_task) =
 3550                    this.trigger_on_type_formatting(text.to_string(), cx)
 3551                {
 3552                    on_type_format_task.detach_and_log_err(cx);
 3553                }
 3554            }
 3555
 3556            let editor_settings = EditorSettings::get_global(cx);
 3557            if bracket_inserted
 3558                && (editor_settings.auto_signature_help
 3559                    || editor_settings.show_signature_help_after_edits)
 3560            {
 3561                this.show_signature_help(&ShowSignatureHelp, cx);
 3562            }
 3563
 3564            let trigger_in_words = !had_active_inline_completion;
 3565            this.trigger_completion_on_input(&text, trigger_in_words, cx);
 3566            linked_editing_ranges::refresh_linked_ranges(this, cx);
 3567            this.refresh_inline_completion(true, false, cx);
 3568        });
 3569    }
 3570
 3571    fn find_possible_emoji_shortcode_at_position(
 3572        snapshot: &MultiBufferSnapshot,
 3573        position: Point,
 3574    ) -> Option<String> {
 3575        let mut chars = Vec::new();
 3576        let mut found_colon = false;
 3577        for char in snapshot.reversed_chars_at(position).take(100) {
 3578            // Found a possible emoji shortcode in the middle of the buffer
 3579            if found_colon {
 3580                if char.is_whitespace() {
 3581                    chars.reverse();
 3582                    return Some(chars.iter().collect());
 3583                }
 3584                // If the previous character is not a whitespace, we are in the middle of a word
 3585                // and we only want to complete the shortcode if the word is made up of other emojis
 3586                let mut containing_word = String::new();
 3587                for ch in snapshot
 3588                    .reversed_chars_at(position)
 3589                    .skip(chars.len() + 1)
 3590                    .take(100)
 3591                {
 3592                    if ch.is_whitespace() {
 3593                        break;
 3594                    }
 3595                    containing_word.push(ch);
 3596                }
 3597                let containing_word = containing_word.chars().rev().collect::<String>();
 3598                if util::word_consists_of_emojis(containing_word.as_str()) {
 3599                    chars.reverse();
 3600                    return Some(chars.iter().collect());
 3601                }
 3602            }
 3603
 3604            if char.is_whitespace() || !char.is_ascii() {
 3605                return None;
 3606            }
 3607            if char == ':' {
 3608                found_colon = true;
 3609            } else {
 3610                chars.push(char);
 3611            }
 3612        }
 3613        // Found a possible emoji shortcode at the beginning of the buffer
 3614        chars.reverse();
 3615        Some(chars.iter().collect())
 3616    }
 3617
 3618    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 3619        self.transact(cx, |this, cx| {
 3620            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3621                let selections = this.selections.all::<usize>(cx);
 3622                let multi_buffer = this.buffer.read(cx);
 3623                let buffer = multi_buffer.snapshot(cx);
 3624                selections
 3625                    .iter()
 3626                    .map(|selection| {
 3627                        let start_point = selection.start.to_point(&buffer);
 3628                        let mut indent =
 3629                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3630                        indent.len = cmp::min(indent.len, start_point.column);
 3631                        let start = selection.start;
 3632                        let end = selection.end;
 3633                        let selection_is_empty = start == end;
 3634                        let language_scope = buffer.language_scope_at(start);
 3635                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3636                            &language_scope
 3637                        {
 3638                            let leading_whitespace_len = buffer
 3639                                .reversed_chars_at(start)
 3640                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3641                                .map(|c| c.len_utf8())
 3642                                .sum::<usize>();
 3643
 3644                            let trailing_whitespace_len = buffer
 3645                                .chars_at(end)
 3646                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3647                                .map(|c| c.len_utf8())
 3648                                .sum::<usize>();
 3649
 3650                            let insert_extra_newline =
 3651                                language.brackets().any(|(pair, enabled)| {
 3652                                    let pair_start = pair.start.trim_end();
 3653                                    let pair_end = pair.end.trim_start();
 3654
 3655                                    enabled
 3656                                        && pair.newline
 3657                                        && buffer.contains_str_at(
 3658                                            end + trailing_whitespace_len,
 3659                                            pair_end,
 3660                                        )
 3661                                        && buffer.contains_str_at(
 3662                                            (start - leading_whitespace_len)
 3663                                                .saturating_sub(pair_start.len()),
 3664                                            pair_start,
 3665                                        )
 3666                                });
 3667
 3668                            // Comment extension on newline is allowed only for cursor selections
 3669                            let comment_delimiter = maybe!({
 3670                                if !selection_is_empty {
 3671                                    return None;
 3672                                }
 3673
 3674                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3675                                    return None;
 3676                                }
 3677
 3678                                let delimiters = language.line_comment_prefixes();
 3679                                let max_len_of_delimiter =
 3680                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3681                                let (snapshot, range) =
 3682                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3683
 3684                                let mut index_of_first_non_whitespace = 0;
 3685                                let comment_candidate = snapshot
 3686                                    .chars_for_range(range)
 3687                                    .skip_while(|c| {
 3688                                        let should_skip = c.is_whitespace();
 3689                                        if should_skip {
 3690                                            index_of_first_non_whitespace += 1;
 3691                                        }
 3692                                        should_skip
 3693                                    })
 3694                                    .take(max_len_of_delimiter)
 3695                                    .collect::<String>();
 3696                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3697                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3698                                })?;
 3699                                let cursor_is_placed_after_comment_marker =
 3700                                    index_of_first_non_whitespace + comment_prefix.len()
 3701                                        <= start_point.column as usize;
 3702                                if cursor_is_placed_after_comment_marker {
 3703                                    Some(comment_prefix.clone())
 3704                                } else {
 3705                                    None
 3706                                }
 3707                            });
 3708                            (comment_delimiter, insert_extra_newline)
 3709                        } else {
 3710                            (None, false)
 3711                        };
 3712
 3713                        let capacity_for_delimiter = comment_delimiter
 3714                            .as_deref()
 3715                            .map(str::len)
 3716                            .unwrap_or_default();
 3717                        let mut new_text =
 3718                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3719                        new_text.push('\n');
 3720                        new_text.extend(indent.chars());
 3721                        if let Some(delimiter) = &comment_delimiter {
 3722                            new_text.push_str(delimiter);
 3723                        }
 3724                        if insert_extra_newline {
 3725                            new_text = new_text.repeat(2);
 3726                        }
 3727
 3728                        let anchor = buffer.anchor_after(end);
 3729                        let new_selection = selection.map(|_| anchor);
 3730                        (
 3731                            (start..end, new_text),
 3732                            (insert_extra_newline, new_selection),
 3733                        )
 3734                    })
 3735                    .unzip()
 3736            };
 3737
 3738            this.edit_with_autoindent(edits, cx);
 3739            let buffer = this.buffer.read(cx).snapshot(cx);
 3740            let new_selections = selection_fixup_info
 3741                .into_iter()
 3742                .map(|(extra_newline_inserted, new_selection)| {
 3743                    let mut cursor = new_selection.end.to_point(&buffer);
 3744                    if extra_newline_inserted {
 3745                        cursor.row -= 1;
 3746                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3747                    }
 3748                    new_selection.map(|_| cursor)
 3749                })
 3750                .collect();
 3751
 3752            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3753            this.refresh_inline_completion(true, false, cx);
 3754        });
 3755    }
 3756
 3757    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3758        let buffer = self.buffer.read(cx);
 3759        let snapshot = buffer.snapshot(cx);
 3760
 3761        let mut edits = Vec::new();
 3762        let mut rows = Vec::new();
 3763
 3764        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3765            let cursor = selection.head();
 3766            let row = cursor.row;
 3767
 3768            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3769
 3770            let newline = "\n".to_string();
 3771            edits.push((start_of_line..start_of_line, newline));
 3772
 3773            rows.push(row + rows_inserted as u32);
 3774        }
 3775
 3776        self.transact(cx, |editor, cx| {
 3777            editor.edit(edits, cx);
 3778
 3779            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3780                let mut index = 0;
 3781                s.move_cursors_with(|map, _, _| {
 3782                    let row = rows[index];
 3783                    index += 1;
 3784
 3785                    let point = Point::new(row, 0);
 3786                    let boundary = map.next_line_boundary(point).1;
 3787                    let clipped = map.clip_point(boundary, Bias::Left);
 3788
 3789                    (clipped, SelectionGoal::None)
 3790                });
 3791            });
 3792
 3793            let mut indent_edits = Vec::new();
 3794            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3795            for row in rows {
 3796                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3797                for (row, indent) in indents {
 3798                    if indent.len == 0 {
 3799                        continue;
 3800                    }
 3801
 3802                    let text = match indent.kind {
 3803                        IndentKind::Space => " ".repeat(indent.len as usize),
 3804                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3805                    };
 3806                    let point = Point::new(row.0, 0);
 3807                    indent_edits.push((point..point, text));
 3808                }
 3809            }
 3810            editor.edit(indent_edits, cx);
 3811        });
 3812    }
 3813
 3814    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3815        let buffer = self.buffer.read(cx);
 3816        let snapshot = buffer.snapshot(cx);
 3817
 3818        let mut edits = Vec::new();
 3819        let mut rows = Vec::new();
 3820        let mut rows_inserted = 0;
 3821
 3822        for selection in self.selections.all_adjusted(cx) {
 3823            let cursor = selection.head();
 3824            let row = cursor.row;
 3825
 3826            let point = Point::new(row + 1, 0);
 3827            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3828
 3829            let newline = "\n".to_string();
 3830            edits.push((start_of_line..start_of_line, newline));
 3831
 3832            rows_inserted += 1;
 3833            rows.push(row + rows_inserted);
 3834        }
 3835
 3836        self.transact(cx, |editor, cx| {
 3837            editor.edit(edits, cx);
 3838
 3839            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3840                let mut index = 0;
 3841                s.move_cursors_with(|map, _, _| {
 3842                    let row = rows[index];
 3843                    index += 1;
 3844
 3845                    let point = Point::new(row, 0);
 3846                    let boundary = map.next_line_boundary(point).1;
 3847                    let clipped = map.clip_point(boundary, Bias::Left);
 3848
 3849                    (clipped, SelectionGoal::None)
 3850                });
 3851            });
 3852
 3853            let mut indent_edits = Vec::new();
 3854            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3855            for row in rows {
 3856                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3857                for (row, indent) in indents {
 3858                    if indent.len == 0 {
 3859                        continue;
 3860                    }
 3861
 3862                    let text = match indent.kind {
 3863                        IndentKind::Space => " ".repeat(indent.len as usize),
 3864                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3865                    };
 3866                    let point = Point::new(row.0, 0);
 3867                    indent_edits.push((point..point, text));
 3868                }
 3869            }
 3870            editor.edit(indent_edits, cx);
 3871        });
 3872    }
 3873
 3874    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3875        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3876            original_indent_columns: Vec::new(),
 3877        });
 3878        self.insert_with_autoindent_mode(text, autoindent, cx);
 3879    }
 3880
 3881    fn insert_with_autoindent_mode(
 3882        &mut self,
 3883        text: &str,
 3884        autoindent_mode: Option<AutoindentMode>,
 3885        cx: &mut ViewContext<Self>,
 3886    ) {
 3887        if self.read_only(cx) {
 3888            return;
 3889        }
 3890
 3891        let text: Arc<str> = text.into();
 3892        self.transact(cx, |this, cx| {
 3893            let old_selections = this.selections.all_adjusted(cx);
 3894            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3895                let anchors = {
 3896                    let snapshot = buffer.read(cx);
 3897                    old_selections
 3898                        .iter()
 3899                        .map(|s| {
 3900                            let anchor = snapshot.anchor_after(s.head());
 3901                            s.map(|_| anchor)
 3902                        })
 3903                        .collect::<Vec<_>>()
 3904                };
 3905                buffer.edit(
 3906                    old_selections
 3907                        .iter()
 3908                        .map(|s| (s.start..s.end, text.clone())),
 3909                    autoindent_mode,
 3910                    cx,
 3911                );
 3912                anchors
 3913            });
 3914
 3915            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3916                s.select_anchors(selection_anchors);
 3917            })
 3918        });
 3919    }
 3920
 3921    fn trigger_completion_on_input(
 3922        &mut self,
 3923        text: &str,
 3924        trigger_in_words: bool,
 3925        cx: &mut ViewContext<Self>,
 3926    ) {
 3927        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3928            self.show_completions(
 3929                &ShowCompletions {
 3930                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3931                },
 3932                cx,
 3933            );
 3934        } else {
 3935            self.hide_context_menu(cx);
 3936        }
 3937    }
 3938
 3939    fn is_completion_trigger(
 3940        &self,
 3941        text: &str,
 3942        trigger_in_words: bool,
 3943        cx: &mut ViewContext<Self>,
 3944    ) -> bool {
 3945        let position = self.selections.newest_anchor().head();
 3946        let multibuffer = self.buffer.read(cx);
 3947        let Some(buffer) = position
 3948            .buffer_id
 3949            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3950        else {
 3951            return false;
 3952        };
 3953
 3954        if let Some(completion_provider) = &self.completion_provider {
 3955            completion_provider.is_completion_trigger(
 3956                &buffer,
 3957                position.text_anchor,
 3958                text,
 3959                trigger_in_words,
 3960                cx,
 3961            )
 3962        } else {
 3963            false
 3964        }
 3965    }
 3966
 3967    /// If any empty selections is touching the start of its innermost containing autoclose
 3968    /// region, expand it to select the brackets.
 3969    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 3970        let selections = self.selections.all::<usize>(cx);
 3971        let buffer = self.buffer.read(cx).read(cx);
 3972        let new_selections = self
 3973            .selections_with_autoclose_regions(selections, &buffer)
 3974            .map(|(mut selection, region)| {
 3975                if !selection.is_empty() {
 3976                    return selection;
 3977                }
 3978
 3979                if let Some(region) = region {
 3980                    let mut range = region.range.to_offset(&buffer);
 3981                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3982                        range.start -= region.pair.start.len();
 3983                        if buffer.contains_str_at(range.start, &region.pair.start)
 3984                            && buffer.contains_str_at(range.end, &region.pair.end)
 3985                        {
 3986                            range.end += region.pair.end.len();
 3987                            selection.start = range.start;
 3988                            selection.end = range.end;
 3989
 3990                            return selection;
 3991                        }
 3992                    }
 3993                }
 3994
 3995                let always_treat_brackets_as_autoclosed = buffer
 3996                    .settings_at(selection.start, cx)
 3997                    .always_treat_brackets_as_autoclosed;
 3998
 3999                if !always_treat_brackets_as_autoclosed {
 4000                    return selection;
 4001                }
 4002
 4003                if let Some(scope) = buffer.language_scope_at(selection.start) {
 4004                    for (pair, enabled) in scope.brackets() {
 4005                        if !enabled || !pair.close {
 4006                            continue;
 4007                        }
 4008
 4009                        if buffer.contains_str_at(selection.start, &pair.end) {
 4010                            let pair_start_len = pair.start.len();
 4011                            if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
 4012                            {
 4013                                selection.start -= pair_start_len;
 4014                                selection.end += pair.end.len();
 4015
 4016                                return selection;
 4017                            }
 4018                        }
 4019                    }
 4020                }
 4021
 4022                selection
 4023            })
 4024            .collect();
 4025
 4026        drop(buffer);
 4027        self.change_selections(None, cx, |selections| selections.select(new_selections));
 4028    }
 4029
 4030    /// Iterate the given selections, and for each one, find the smallest surrounding
 4031    /// autoclose region. This uses the ordering of the selections and the autoclose
 4032    /// regions to avoid repeated comparisons.
 4033    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 4034        &'a self,
 4035        selections: impl IntoIterator<Item = Selection<D>>,
 4036        buffer: &'a MultiBufferSnapshot,
 4037    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 4038        let mut i = 0;
 4039        let mut regions = self.autoclose_regions.as_slice();
 4040        selections.into_iter().map(move |selection| {
 4041            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 4042
 4043            let mut enclosing = None;
 4044            while let Some(pair_state) = regions.get(i) {
 4045                if pair_state.range.end.to_offset(buffer) < range.start {
 4046                    regions = &regions[i + 1..];
 4047                    i = 0;
 4048                } else if pair_state.range.start.to_offset(buffer) > range.end {
 4049                    break;
 4050                } else {
 4051                    if pair_state.selection_id == selection.id {
 4052                        enclosing = Some(pair_state);
 4053                    }
 4054                    i += 1;
 4055                }
 4056            }
 4057
 4058            (selection, enclosing)
 4059        })
 4060    }
 4061
 4062    /// Remove any autoclose regions that no longer contain their selection.
 4063    fn invalidate_autoclose_regions(
 4064        &mut self,
 4065        mut selections: &[Selection<Anchor>],
 4066        buffer: &MultiBufferSnapshot,
 4067    ) {
 4068        self.autoclose_regions.retain(|state| {
 4069            let mut i = 0;
 4070            while let Some(selection) = selections.get(i) {
 4071                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 4072                    selections = &selections[1..];
 4073                    continue;
 4074                }
 4075                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 4076                    break;
 4077                }
 4078                if selection.id == state.selection_id {
 4079                    return true;
 4080                } else {
 4081                    i += 1;
 4082                }
 4083            }
 4084            false
 4085        });
 4086    }
 4087
 4088    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 4089        let offset = position.to_offset(buffer);
 4090        let (word_range, kind) = buffer.surrounding_word(offset, true);
 4091        if offset > word_range.start && kind == Some(CharKind::Word) {
 4092            Some(
 4093                buffer
 4094                    .text_for_range(word_range.start..offset)
 4095                    .collect::<String>(),
 4096            )
 4097        } else {
 4098            None
 4099        }
 4100    }
 4101
 4102    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 4103        self.refresh_inlay_hints(
 4104            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 4105            cx,
 4106        );
 4107    }
 4108
 4109    pub fn inlay_hints_enabled(&self) -> bool {
 4110        self.inlay_hint_cache.enabled
 4111    }
 4112
 4113    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 4114        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 4115            return;
 4116        }
 4117
 4118        let reason_description = reason.description();
 4119        let ignore_debounce = matches!(
 4120            reason,
 4121            InlayHintRefreshReason::SettingsChange(_)
 4122                | InlayHintRefreshReason::Toggle(_)
 4123                | InlayHintRefreshReason::ExcerptsRemoved(_)
 4124        );
 4125        let (invalidate_cache, required_languages) = match reason {
 4126            InlayHintRefreshReason::Toggle(enabled) => {
 4127                self.inlay_hint_cache.enabled = enabled;
 4128                if enabled {
 4129                    (InvalidationStrategy::RefreshRequested, None)
 4130                } else {
 4131                    self.inlay_hint_cache.clear();
 4132                    self.splice_inlays(
 4133                        self.visible_inlay_hints(cx)
 4134                            .iter()
 4135                            .map(|inlay| inlay.id)
 4136                            .collect(),
 4137                        Vec::new(),
 4138                        cx,
 4139                    );
 4140                    return;
 4141                }
 4142            }
 4143            InlayHintRefreshReason::SettingsChange(new_settings) => {
 4144                match self.inlay_hint_cache.update_settings(
 4145                    &self.buffer,
 4146                    new_settings,
 4147                    self.visible_inlay_hints(cx),
 4148                    cx,
 4149                ) {
 4150                    ControlFlow::Break(Some(InlaySplice {
 4151                        to_remove,
 4152                        to_insert,
 4153                    })) => {
 4154                        self.splice_inlays(to_remove, to_insert, cx);
 4155                        return;
 4156                    }
 4157                    ControlFlow::Break(None) => return,
 4158                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 4159                }
 4160            }
 4161            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 4162                if let Some(InlaySplice {
 4163                    to_remove,
 4164                    to_insert,
 4165                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 4166                {
 4167                    self.splice_inlays(to_remove, to_insert, cx);
 4168                }
 4169                return;
 4170            }
 4171            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 4172            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 4173                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 4174            }
 4175            InlayHintRefreshReason::RefreshRequested => {
 4176                (InvalidationStrategy::RefreshRequested, None)
 4177            }
 4178        };
 4179
 4180        if let Some(InlaySplice {
 4181            to_remove,
 4182            to_insert,
 4183        }) = self.inlay_hint_cache.spawn_hint_refresh(
 4184            reason_description,
 4185            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 4186            invalidate_cache,
 4187            ignore_debounce,
 4188            cx,
 4189        ) {
 4190            self.splice_inlays(to_remove, to_insert, cx);
 4191        }
 4192    }
 4193
 4194    fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
 4195        self.display_map
 4196            .read(cx)
 4197            .current_inlays()
 4198            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 4199            .cloned()
 4200            .collect()
 4201    }
 4202
 4203    pub fn excerpts_for_inlay_hints_query(
 4204        &self,
 4205        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 4206        cx: &mut ViewContext<Editor>,
 4207    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 4208        let Some(project) = self.project.as_ref() else {
 4209            return HashMap::default();
 4210        };
 4211        let project = project.read(cx);
 4212        let multi_buffer = self.buffer().read(cx);
 4213        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 4214        let multi_buffer_visible_start = self
 4215            .scroll_manager
 4216            .anchor()
 4217            .anchor
 4218            .to_point(&multi_buffer_snapshot);
 4219        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 4220            multi_buffer_visible_start
 4221                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 4222            Bias::Left,
 4223        );
 4224        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 4225        multi_buffer
 4226            .range_to_buffer_ranges(multi_buffer_visible_range, cx)
 4227            .into_iter()
 4228            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 4229            .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
 4230                let buffer = buffer_handle.read(cx);
 4231                let buffer_file = project::File::from_dyn(buffer.file())?;
 4232                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 4233                let worktree_entry = buffer_worktree
 4234                    .read(cx)
 4235                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 4236                if worktree_entry.is_ignored {
 4237                    return None;
 4238                }
 4239
 4240                let language = buffer.language()?;
 4241                if let Some(restrict_to_languages) = restrict_to_languages {
 4242                    if !restrict_to_languages.contains(language) {
 4243                        return None;
 4244                    }
 4245                }
 4246                Some((
 4247                    excerpt_id,
 4248                    (
 4249                        buffer_handle,
 4250                        buffer.version().clone(),
 4251                        excerpt_visible_range,
 4252                    ),
 4253                ))
 4254            })
 4255            .collect()
 4256    }
 4257
 4258    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 4259        TextLayoutDetails {
 4260            text_system: cx.text_system().clone(),
 4261            editor_style: self.style.clone().unwrap(),
 4262            rem_size: cx.rem_size(),
 4263            scroll_anchor: self.scroll_manager.anchor(),
 4264            visible_rows: self.visible_line_count(),
 4265            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 4266        }
 4267    }
 4268
 4269    fn splice_inlays(
 4270        &self,
 4271        to_remove: Vec<InlayId>,
 4272        to_insert: Vec<Inlay>,
 4273        cx: &mut ViewContext<Self>,
 4274    ) {
 4275        self.display_map.update(cx, |display_map, cx| {
 4276            display_map.splice_inlays(to_remove, to_insert, cx);
 4277        });
 4278        cx.notify();
 4279    }
 4280
 4281    fn trigger_on_type_formatting(
 4282        &self,
 4283        input: String,
 4284        cx: &mut ViewContext<Self>,
 4285    ) -> Option<Task<Result<()>>> {
 4286        if input.len() != 1 {
 4287            return None;
 4288        }
 4289
 4290        let project = self.project.as_ref()?;
 4291        let position = self.selections.newest_anchor().head();
 4292        let (buffer, buffer_position) = self
 4293            .buffer
 4294            .read(cx)
 4295            .text_anchor_for_position(position, cx)?;
 4296
 4297        let settings = language_settings::language_settings(
 4298            buffer
 4299                .read(cx)
 4300                .language_at(buffer_position)
 4301                .map(|l| l.name()),
 4302            buffer.read(cx).file(),
 4303            cx,
 4304        );
 4305        if !settings.use_on_type_format {
 4306            return None;
 4307        }
 4308
 4309        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 4310        // hence we do LSP request & edit on host side only — add formats to host's history.
 4311        let push_to_lsp_host_history = true;
 4312        // If this is not the host, append its history with new edits.
 4313        let push_to_client_history = project.read(cx).is_via_collab();
 4314
 4315        let on_type_formatting = project.update(cx, |project, cx| {
 4316            project.on_type_format(
 4317                buffer.clone(),
 4318                buffer_position,
 4319                input,
 4320                push_to_lsp_host_history,
 4321                cx,
 4322            )
 4323        });
 4324        Some(cx.spawn(|editor, mut cx| async move {
 4325            if let Some(transaction) = on_type_formatting.await? {
 4326                if push_to_client_history {
 4327                    buffer
 4328                        .update(&mut cx, |buffer, _| {
 4329                            buffer.push_transaction(transaction, Instant::now());
 4330                        })
 4331                        .ok();
 4332                }
 4333                editor.update(&mut cx, |editor, cx| {
 4334                    editor.refresh_document_highlights(cx);
 4335                })?;
 4336            }
 4337            Ok(())
 4338        }))
 4339    }
 4340
 4341    pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
 4342        if self.pending_rename.is_some() {
 4343            return;
 4344        }
 4345
 4346        let Some(provider) = self.completion_provider.as_ref() else {
 4347            return;
 4348        };
 4349
 4350        let position = self.selections.newest_anchor().head();
 4351        let (buffer, buffer_position) =
 4352            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4353                output
 4354            } else {
 4355                return;
 4356            };
 4357
 4358        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4359        let is_followup_invoke = {
 4360            let context_menu_state = self.context_menu.read();
 4361            matches!(
 4362                context_menu_state.deref(),
 4363                Some(ContextMenu::Completions(_))
 4364            )
 4365        };
 4366        let trigger_kind = match (&options.trigger, is_followup_invoke) {
 4367            (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
 4368            (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4369                CompletionTriggerKind::TRIGGER_CHARACTER
 4370            }
 4371
 4372            _ => CompletionTriggerKind::INVOKED,
 4373        };
 4374        let completion_context = CompletionContext {
 4375            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 4376                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4377                    Some(String::from(trigger))
 4378                } else {
 4379                    None
 4380                }
 4381            }),
 4382            trigger_kind,
 4383        };
 4384        let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
 4385        let sort_completions = provider.sort_completions();
 4386
 4387        let id = post_inc(&mut self.next_completion_id);
 4388        let task = cx.spawn(|this, mut cx| {
 4389            async move {
 4390                this.update(&mut cx, |this, _| {
 4391                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4392                })?;
 4393                let completions = completions.await.log_err();
 4394                let menu = if let Some(completions) = completions {
 4395                    let mut menu = CompletionsMenu {
 4396                        id,
 4397                        sort_completions,
 4398                        initial_position: position,
 4399                        match_candidates: completions
 4400                            .iter()
 4401                            .enumerate()
 4402                            .map(|(id, completion)| {
 4403                                StringMatchCandidate::new(
 4404                                    id,
 4405                                    completion.label.text[completion.label.filter_range.clone()]
 4406                                        .into(),
 4407                                )
 4408                            })
 4409                            .collect(),
 4410                        buffer: buffer.clone(),
 4411                        completions: Arc::new(RwLock::new(completions.into())),
 4412                        matches: Vec::new().into(),
 4413                        selected_item: 0,
 4414                        scroll_handle: UniformListScrollHandle::new(),
 4415                        selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
 4416                            DebouncedDelay::new(),
 4417                        )),
 4418                    };
 4419                    menu.filter(query.as_deref(), cx.background_executor().clone())
 4420                        .await;
 4421
 4422                    if menu.matches.is_empty() {
 4423                        None
 4424                    } else {
 4425                        this.update(&mut cx, |editor, cx| {
 4426                            let completions = menu.completions.clone();
 4427                            let matches = menu.matches.clone();
 4428
 4429                            let delay_ms = EditorSettings::get_global(cx)
 4430                                .completion_documentation_secondary_query_debounce;
 4431                            let delay = Duration::from_millis(delay_ms);
 4432                            editor
 4433                                .completion_documentation_pre_resolve_debounce
 4434                                .fire_new(delay, cx, |editor, cx| {
 4435                                    CompletionsMenu::pre_resolve_completion_documentation(
 4436                                        buffer,
 4437                                        completions,
 4438                                        matches,
 4439                                        editor,
 4440                                        cx,
 4441                                    )
 4442                                });
 4443                        })
 4444                        .ok();
 4445                        Some(menu)
 4446                    }
 4447                } else {
 4448                    None
 4449                };
 4450
 4451                this.update(&mut cx, |this, cx| {
 4452                    let mut context_menu = this.context_menu.write();
 4453                    match context_menu.as_ref() {
 4454                        None => {}
 4455
 4456                        Some(ContextMenu::Completions(prev_menu)) => {
 4457                            if prev_menu.id > id {
 4458                                return;
 4459                            }
 4460                        }
 4461
 4462                        _ => return,
 4463                    }
 4464
 4465                    if this.focus_handle.is_focused(cx) && menu.is_some() {
 4466                        let menu = menu.unwrap();
 4467                        *context_menu = Some(ContextMenu::Completions(menu));
 4468                        drop(context_menu);
 4469                        this.discard_inline_completion(false, cx);
 4470                        cx.notify();
 4471                    } else if this.completion_tasks.len() <= 1 {
 4472                        // If there are no more completion tasks and the last menu was
 4473                        // empty, we should hide it. If it was already hidden, we should
 4474                        // also show the copilot completion when available.
 4475                        drop(context_menu);
 4476                        if this.hide_context_menu(cx).is_none() {
 4477                            this.update_visible_inline_completion(cx);
 4478                        }
 4479                    }
 4480                })?;
 4481
 4482                Ok::<_, anyhow::Error>(())
 4483            }
 4484            .log_err()
 4485        });
 4486
 4487        self.completion_tasks.push((id, task));
 4488    }
 4489
 4490    pub fn confirm_completion(
 4491        &mut self,
 4492        action: &ConfirmCompletion,
 4493        cx: &mut ViewContext<Self>,
 4494    ) -> Option<Task<Result<()>>> {
 4495        self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
 4496    }
 4497
 4498    pub fn compose_completion(
 4499        &mut self,
 4500        action: &ComposeCompletion,
 4501        cx: &mut ViewContext<Self>,
 4502    ) -> Option<Task<Result<()>>> {
 4503        self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
 4504    }
 4505
 4506    fn do_completion(
 4507        &mut self,
 4508        item_ix: Option<usize>,
 4509        intent: CompletionIntent,
 4510        cx: &mut ViewContext<Editor>,
 4511    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 4512        use language::ToOffset as _;
 4513
 4514        let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 4515            menu
 4516        } else {
 4517            return None;
 4518        };
 4519
 4520        let mat = completions_menu
 4521            .matches
 4522            .get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4523        let buffer_handle = completions_menu.buffer;
 4524        let completions = completions_menu.completions.read();
 4525        let completion = completions.get(mat.candidate_id)?;
 4526        cx.stop_propagation();
 4527
 4528        let snippet;
 4529        let text;
 4530
 4531        if completion.is_snippet() {
 4532            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4533            text = snippet.as_ref().unwrap().text.clone();
 4534        } else {
 4535            snippet = None;
 4536            text = completion.new_text.clone();
 4537        };
 4538        let selections = self.selections.all::<usize>(cx);
 4539        let buffer = buffer_handle.read(cx);
 4540        let old_range = completion.old_range.to_offset(buffer);
 4541        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4542
 4543        let newest_selection = self.selections.newest_anchor();
 4544        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4545            return None;
 4546        }
 4547
 4548        let lookbehind = newest_selection
 4549            .start
 4550            .text_anchor
 4551            .to_offset(buffer)
 4552            .saturating_sub(old_range.start);
 4553        let lookahead = old_range
 4554            .end
 4555            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4556        let mut common_prefix_len = old_text
 4557            .bytes()
 4558            .zip(text.bytes())
 4559            .take_while(|(a, b)| a == b)
 4560            .count();
 4561
 4562        let snapshot = self.buffer.read(cx).snapshot(cx);
 4563        let mut range_to_replace: Option<Range<isize>> = None;
 4564        let mut ranges = Vec::new();
 4565        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4566        for selection in &selections {
 4567            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4568                let start = selection.start.saturating_sub(lookbehind);
 4569                let end = selection.end + lookahead;
 4570                if selection.id == newest_selection.id {
 4571                    range_to_replace = Some(
 4572                        ((start + common_prefix_len) as isize - selection.start as isize)
 4573                            ..(end as isize - selection.start as isize),
 4574                    );
 4575                }
 4576                ranges.push(start + common_prefix_len..end);
 4577            } else {
 4578                common_prefix_len = 0;
 4579                ranges.clear();
 4580                ranges.extend(selections.iter().map(|s| {
 4581                    if s.id == newest_selection.id {
 4582                        range_to_replace = Some(
 4583                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4584                                - selection.start as isize
 4585                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4586                                    - selection.start as isize,
 4587                        );
 4588                        old_range.clone()
 4589                    } else {
 4590                        s.start..s.end
 4591                    }
 4592                }));
 4593                break;
 4594            }
 4595            if !self.linked_edit_ranges.is_empty() {
 4596                let start_anchor = snapshot.anchor_before(selection.head());
 4597                let end_anchor = snapshot.anchor_after(selection.tail());
 4598                if let Some(ranges) = self
 4599                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4600                {
 4601                    for (buffer, edits) in ranges {
 4602                        linked_edits.entry(buffer.clone()).or_default().extend(
 4603                            edits
 4604                                .into_iter()
 4605                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4606                        );
 4607                    }
 4608                }
 4609            }
 4610        }
 4611        let text = &text[common_prefix_len..];
 4612
 4613        cx.emit(EditorEvent::InputHandled {
 4614            utf16_range_to_replace: range_to_replace,
 4615            text: text.into(),
 4616        });
 4617
 4618        self.transact(cx, |this, cx| {
 4619            if let Some(mut snippet) = snippet {
 4620                snippet.text = text.to_string();
 4621                for tabstop in snippet.tabstops.iter_mut().flatten() {
 4622                    tabstop.start -= common_prefix_len as isize;
 4623                    tabstop.end -= common_prefix_len as isize;
 4624                }
 4625
 4626                this.insert_snippet(&ranges, snippet, cx).log_err();
 4627            } else {
 4628                this.buffer.update(cx, |buffer, cx| {
 4629                    buffer.edit(
 4630                        ranges.iter().map(|range| (range.clone(), text)),
 4631                        this.autoindent_mode.clone(),
 4632                        cx,
 4633                    );
 4634                });
 4635            }
 4636            for (buffer, edits) in linked_edits {
 4637                buffer.update(cx, |buffer, cx| {
 4638                    let snapshot = buffer.snapshot();
 4639                    let edits = edits
 4640                        .into_iter()
 4641                        .map(|(range, text)| {
 4642                            use text::ToPoint as TP;
 4643                            let end_point = TP::to_point(&range.end, &snapshot);
 4644                            let start_point = TP::to_point(&range.start, &snapshot);
 4645                            (start_point..end_point, text)
 4646                        })
 4647                        .sorted_by_key(|(range, _)| range.start)
 4648                        .collect::<Vec<_>>();
 4649                    buffer.edit(edits, None, cx);
 4650                })
 4651            }
 4652
 4653            this.refresh_inline_completion(true, false, cx);
 4654        });
 4655
 4656        let show_new_completions_on_confirm = completion
 4657            .confirm
 4658            .as_ref()
 4659            .map_or(false, |confirm| confirm(intent, cx));
 4660        if show_new_completions_on_confirm {
 4661            self.show_completions(&ShowCompletions { trigger: None }, cx);
 4662        }
 4663
 4664        let provider = self.completion_provider.as_ref()?;
 4665        let apply_edits = provider.apply_additional_edits_for_completion(
 4666            buffer_handle,
 4667            completion.clone(),
 4668            true,
 4669            cx,
 4670        );
 4671
 4672        let editor_settings = EditorSettings::get_global(cx);
 4673        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4674            // After the code completion is finished, users often want to know what signatures are needed.
 4675            // so we should automatically call signature_help
 4676            self.show_signature_help(&ShowSignatureHelp, cx);
 4677        }
 4678
 4679        Some(cx.foreground_executor().spawn(async move {
 4680            apply_edits.await?;
 4681            Ok(())
 4682        }))
 4683    }
 4684
 4685    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 4686        let mut context_menu = self.context_menu.write();
 4687        if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4688            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4689                // Toggle if we're selecting the same one
 4690                *context_menu = None;
 4691                cx.notify();
 4692                return;
 4693            } else {
 4694                // Otherwise, clear it and start a new one
 4695                *context_menu = None;
 4696                cx.notify();
 4697            }
 4698        }
 4699        drop(context_menu);
 4700        let snapshot = self.snapshot(cx);
 4701        let deployed_from_indicator = action.deployed_from_indicator;
 4702        let mut task = self.code_actions_task.take();
 4703        let action = action.clone();
 4704        cx.spawn(|editor, mut cx| async move {
 4705            while let Some(prev_task) = task {
 4706                prev_task.await.log_err();
 4707                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4708            }
 4709
 4710            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 4711                if editor.focus_handle.is_focused(cx) {
 4712                    let multibuffer_point = action
 4713                        .deployed_from_indicator
 4714                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4715                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4716                    let (buffer, buffer_row) = snapshot
 4717                        .buffer_snapshot
 4718                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4719                        .and_then(|(buffer_snapshot, range)| {
 4720                            editor
 4721                                .buffer
 4722                                .read(cx)
 4723                                .buffer(buffer_snapshot.remote_id())
 4724                                .map(|buffer| (buffer, range.start.row))
 4725                        })?;
 4726                    let (_, code_actions) = editor
 4727                        .available_code_actions
 4728                        .clone()
 4729                        .and_then(|(location, code_actions)| {
 4730                            let snapshot = location.buffer.read(cx).snapshot();
 4731                            let point_range = location.range.to_point(&snapshot);
 4732                            let point_range = point_range.start.row..=point_range.end.row;
 4733                            if point_range.contains(&buffer_row) {
 4734                                Some((location, code_actions))
 4735                            } else {
 4736                                None
 4737                            }
 4738                        })
 4739                        .unzip();
 4740                    let buffer_id = buffer.read(cx).remote_id();
 4741                    let tasks = editor
 4742                        .tasks
 4743                        .get(&(buffer_id, buffer_row))
 4744                        .map(|t| Arc::new(t.to_owned()));
 4745                    if tasks.is_none() && code_actions.is_none() {
 4746                        return None;
 4747                    }
 4748
 4749                    editor.completion_tasks.clear();
 4750                    editor.discard_inline_completion(false, cx);
 4751                    let task_context =
 4752                        tasks
 4753                            .as_ref()
 4754                            .zip(editor.project.clone())
 4755                            .map(|(tasks, project)| {
 4756                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4757                            });
 4758
 4759                    Some(cx.spawn(|editor, mut cx| async move {
 4760                        let task_context = match task_context {
 4761                            Some(task_context) => task_context.await,
 4762                            None => None,
 4763                        };
 4764                        let resolved_tasks =
 4765                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4766                                Arc::new(ResolvedTasks {
 4767                                    templates: tasks.resolve(&task_context).collect(),
 4768                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4769                                        multibuffer_point.row,
 4770                                        tasks.column,
 4771                                    )),
 4772                                })
 4773                            });
 4774                        let spawn_straight_away = resolved_tasks
 4775                            .as_ref()
 4776                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4777                            && code_actions
 4778                                .as_ref()
 4779                                .map_or(true, |actions| actions.is_empty());
 4780                        if let Ok(task) = editor.update(&mut cx, |editor, cx| {
 4781                            *editor.context_menu.write() =
 4782                                Some(ContextMenu::CodeActions(CodeActionsMenu {
 4783                                    buffer,
 4784                                    actions: CodeActionContents {
 4785                                        tasks: resolved_tasks,
 4786                                        actions: code_actions,
 4787                                    },
 4788                                    selected_item: Default::default(),
 4789                                    scroll_handle: UniformListScrollHandle::default(),
 4790                                    deployed_from_indicator,
 4791                                }));
 4792                            if spawn_straight_away {
 4793                                if let Some(task) = editor.confirm_code_action(
 4794                                    &ConfirmCodeAction { item_ix: Some(0) },
 4795                                    cx,
 4796                                ) {
 4797                                    cx.notify();
 4798                                    return task;
 4799                                }
 4800                            }
 4801                            cx.notify();
 4802                            Task::ready(Ok(()))
 4803                        }) {
 4804                            task.await
 4805                        } else {
 4806                            Ok(())
 4807                        }
 4808                    }))
 4809                } else {
 4810                    Some(Task::ready(Ok(())))
 4811                }
 4812            })?;
 4813            if let Some(task) = spawned_test_task {
 4814                task.await?;
 4815            }
 4816
 4817            Ok::<_, anyhow::Error>(())
 4818        })
 4819        .detach_and_log_err(cx);
 4820    }
 4821
 4822    pub fn confirm_code_action(
 4823        &mut self,
 4824        action: &ConfirmCodeAction,
 4825        cx: &mut ViewContext<Self>,
 4826    ) -> Option<Task<Result<()>>> {
 4827        let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4828            menu
 4829        } else {
 4830            return None;
 4831        };
 4832        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4833        let action = actions_menu.actions.get(action_ix)?;
 4834        let title = action.label();
 4835        let buffer = actions_menu.buffer;
 4836        let workspace = self.workspace()?;
 4837
 4838        match action {
 4839            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4840                workspace.update(cx, |workspace, cx| {
 4841                    workspace::tasks::schedule_resolved_task(
 4842                        workspace,
 4843                        task_source_kind,
 4844                        resolved_task,
 4845                        false,
 4846                        cx,
 4847                    );
 4848
 4849                    Some(Task::ready(Ok(())))
 4850                })
 4851            }
 4852            CodeActionsItem::CodeAction {
 4853                excerpt_id,
 4854                action,
 4855                provider,
 4856            } => {
 4857                let apply_code_action =
 4858                    provider.apply_code_action(buffer, action, excerpt_id, true, cx);
 4859                let workspace = workspace.downgrade();
 4860                Some(cx.spawn(|editor, cx| async move {
 4861                    let project_transaction = apply_code_action.await?;
 4862                    Self::open_project_transaction(
 4863                        &editor,
 4864                        workspace,
 4865                        project_transaction,
 4866                        title,
 4867                        cx,
 4868                    )
 4869                    .await
 4870                }))
 4871            }
 4872        }
 4873    }
 4874
 4875    pub async fn open_project_transaction(
 4876        this: &WeakView<Editor>,
 4877        workspace: WeakView<Workspace>,
 4878        transaction: ProjectTransaction,
 4879        title: String,
 4880        mut cx: AsyncWindowContext,
 4881    ) -> Result<()> {
 4882        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4883        cx.update(|cx| {
 4884            entries.sort_unstable_by_key(|(buffer, _)| {
 4885                buffer.read(cx).file().map(|f| f.path().clone())
 4886            });
 4887        })?;
 4888
 4889        // If the project transaction's edits are all contained within this editor, then
 4890        // avoid opening a new editor to display them.
 4891
 4892        if let Some((buffer, transaction)) = entries.first() {
 4893            if entries.len() == 1 {
 4894                let excerpt = this.update(&mut cx, |editor, cx| {
 4895                    editor
 4896                        .buffer()
 4897                        .read(cx)
 4898                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4899                })?;
 4900                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4901                    if excerpted_buffer == *buffer {
 4902                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4903                            let excerpt_range = excerpt_range.to_offset(buffer);
 4904                            buffer
 4905                                .edited_ranges_for_transaction::<usize>(transaction)
 4906                                .all(|range| {
 4907                                    excerpt_range.start <= range.start
 4908                                        && excerpt_range.end >= range.end
 4909                                })
 4910                        })?;
 4911
 4912                        if all_edits_within_excerpt {
 4913                            return Ok(());
 4914                        }
 4915                    }
 4916                }
 4917            }
 4918        } else {
 4919            return Ok(());
 4920        }
 4921
 4922        let mut ranges_to_highlight = Vec::new();
 4923        let excerpt_buffer = cx.new_model(|cx| {
 4924            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4925            for (buffer_handle, transaction) in &entries {
 4926                let buffer = buffer_handle.read(cx);
 4927                ranges_to_highlight.extend(
 4928                    multibuffer.push_excerpts_with_context_lines(
 4929                        buffer_handle.clone(),
 4930                        buffer
 4931                            .edited_ranges_for_transaction::<usize>(transaction)
 4932                            .collect(),
 4933                        DEFAULT_MULTIBUFFER_CONTEXT,
 4934                        cx,
 4935                    ),
 4936                );
 4937            }
 4938            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4939            multibuffer
 4940        })?;
 4941
 4942        workspace.update(&mut cx, |workspace, cx| {
 4943            let project = workspace.project().clone();
 4944            let editor =
 4945                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 4946            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 4947            editor.update(cx, |editor, cx| {
 4948                editor.highlight_background::<Self>(
 4949                    &ranges_to_highlight,
 4950                    |theme| theme.editor_highlighted_line_background,
 4951                    cx,
 4952                );
 4953            });
 4954        })?;
 4955
 4956        Ok(())
 4957    }
 4958
 4959    pub fn clear_code_action_providers(&mut self) {
 4960        self.code_action_providers.clear();
 4961        self.available_code_actions.take();
 4962    }
 4963
 4964    pub fn push_code_action_provider(
 4965        &mut self,
 4966        provider: Arc<dyn CodeActionProvider>,
 4967        cx: &mut ViewContext<Self>,
 4968    ) {
 4969        self.code_action_providers.push(provider);
 4970        self.refresh_code_actions(cx);
 4971    }
 4972
 4973    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4974        let buffer = self.buffer.read(cx);
 4975        let newest_selection = self.selections.newest_anchor().clone();
 4976        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4977        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4978        if start_buffer != end_buffer {
 4979            return None;
 4980        }
 4981
 4982        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 4983            cx.background_executor()
 4984                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4985                .await;
 4986
 4987            let (providers, tasks) = this.update(&mut cx, |this, cx| {
 4988                let providers = this.code_action_providers.clone();
 4989                let tasks = this
 4990                    .code_action_providers
 4991                    .iter()
 4992                    .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
 4993                    .collect::<Vec<_>>();
 4994                (providers, tasks)
 4995            })?;
 4996
 4997            let mut actions = Vec::new();
 4998            for (provider, provider_actions) in
 4999                providers.into_iter().zip(future::join_all(tasks).await)
 5000            {
 5001                if let Some(provider_actions) = provider_actions.log_err() {
 5002                    actions.extend(provider_actions.into_iter().map(|action| {
 5003                        AvailableCodeAction {
 5004                            excerpt_id: newest_selection.start.excerpt_id,
 5005                            action,
 5006                            provider: provider.clone(),
 5007                        }
 5008                    }));
 5009                }
 5010            }
 5011
 5012            this.update(&mut cx, |this, cx| {
 5013                this.available_code_actions = if actions.is_empty() {
 5014                    None
 5015                } else {
 5016                    Some((
 5017                        Location {
 5018                            buffer: start_buffer,
 5019                            range: start..end,
 5020                        },
 5021                        actions.into(),
 5022                    ))
 5023                };
 5024                cx.notify();
 5025            })
 5026        }));
 5027        None
 5028    }
 5029
 5030    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 5031        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 5032            self.show_git_blame_inline = false;
 5033
 5034            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 5035                cx.background_executor().timer(delay).await;
 5036
 5037                this.update(&mut cx, |this, cx| {
 5038                    this.show_git_blame_inline = true;
 5039                    cx.notify();
 5040                })
 5041                .log_err();
 5042            }));
 5043        }
 5044    }
 5045
 5046    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 5047        if self.pending_rename.is_some() {
 5048            return None;
 5049        }
 5050
 5051        let provider = self.semantics_provider.clone()?;
 5052        let buffer = self.buffer.read(cx);
 5053        let newest_selection = self.selections.newest_anchor().clone();
 5054        let cursor_position = newest_selection.head();
 5055        let (cursor_buffer, cursor_buffer_position) =
 5056            buffer.text_anchor_for_position(cursor_position, cx)?;
 5057        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 5058        if cursor_buffer != tail_buffer {
 5059            return None;
 5060        }
 5061
 5062        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 5063            cx.background_executor()
 5064                .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
 5065                .await;
 5066
 5067            let highlights = if let Some(highlights) = cx
 5068                .update(|cx| {
 5069                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 5070                })
 5071                .ok()
 5072                .flatten()
 5073            {
 5074                highlights.await.log_err()
 5075            } else {
 5076                None
 5077            };
 5078
 5079            if let Some(highlights) = highlights {
 5080                this.update(&mut cx, |this, cx| {
 5081                    if this.pending_rename.is_some() {
 5082                        return;
 5083                    }
 5084
 5085                    let buffer_id = cursor_position.buffer_id;
 5086                    let buffer = this.buffer.read(cx);
 5087                    if !buffer
 5088                        .text_anchor_for_position(cursor_position, cx)
 5089                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 5090                    {
 5091                        return;
 5092                    }
 5093
 5094                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 5095                    let mut write_ranges = Vec::new();
 5096                    let mut read_ranges = Vec::new();
 5097                    for highlight in highlights {
 5098                        for (excerpt_id, excerpt_range) in
 5099                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 5100                        {
 5101                            let start = highlight
 5102                                .range
 5103                                .start
 5104                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 5105                            let end = highlight
 5106                                .range
 5107                                .end
 5108                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 5109                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 5110                                continue;
 5111                            }
 5112
 5113                            let range = Anchor {
 5114                                buffer_id,
 5115                                excerpt_id,
 5116                                text_anchor: start,
 5117                            }..Anchor {
 5118                                buffer_id,
 5119                                excerpt_id,
 5120                                text_anchor: end,
 5121                            };
 5122                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 5123                                write_ranges.push(range);
 5124                            } else {
 5125                                read_ranges.push(range);
 5126                            }
 5127                        }
 5128                    }
 5129
 5130                    this.highlight_background::<DocumentHighlightRead>(
 5131                        &read_ranges,
 5132                        |theme| theme.editor_document_highlight_read_background,
 5133                        cx,
 5134                    );
 5135                    this.highlight_background::<DocumentHighlightWrite>(
 5136                        &write_ranges,
 5137                        |theme| theme.editor_document_highlight_write_background,
 5138                        cx,
 5139                    );
 5140                    cx.notify();
 5141                })
 5142                .log_err();
 5143            }
 5144        }));
 5145        None
 5146    }
 5147
 5148    pub fn refresh_inline_completion(
 5149        &mut self,
 5150        debounce: bool,
 5151        user_requested: bool,
 5152        cx: &mut ViewContext<Self>,
 5153    ) -> Option<()> {
 5154        let provider = self.inline_completion_provider()?;
 5155        let cursor = self.selections.newest_anchor().head();
 5156        let (buffer, cursor_buffer_position) =
 5157            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5158
 5159        if !user_requested
 5160            && (!self.enable_inline_completions
 5161                || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx))
 5162        {
 5163            self.discard_inline_completion(false, cx);
 5164            return None;
 5165        }
 5166
 5167        self.update_visible_inline_completion(cx);
 5168        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 5169        Some(())
 5170    }
 5171
 5172    fn cycle_inline_completion(
 5173        &mut self,
 5174        direction: Direction,
 5175        cx: &mut ViewContext<Self>,
 5176    ) -> Option<()> {
 5177        let provider = self.inline_completion_provider()?;
 5178        let cursor = self.selections.newest_anchor().head();
 5179        let (buffer, cursor_buffer_position) =
 5180            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5181        if !self.enable_inline_completions
 5182            || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 5183        {
 5184            return None;
 5185        }
 5186
 5187        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5188        self.update_visible_inline_completion(cx);
 5189
 5190        Some(())
 5191    }
 5192
 5193    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 5194        if !self.has_active_inline_completion(cx) {
 5195            self.refresh_inline_completion(false, true, cx);
 5196            return;
 5197        }
 5198
 5199        self.update_visible_inline_completion(cx);
 5200    }
 5201
 5202    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 5203        self.show_cursor_names(cx);
 5204    }
 5205
 5206    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 5207        self.show_cursor_names = true;
 5208        cx.notify();
 5209        cx.spawn(|this, mut cx| async move {
 5210            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5211            this.update(&mut cx, |this, cx| {
 5212                this.show_cursor_names = false;
 5213                cx.notify()
 5214            })
 5215            .ok()
 5216        })
 5217        .detach();
 5218    }
 5219
 5220    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 5221        if self.has_active_inline_completion(cx) {
 5222            self.cycle_inline_completion(Direction::Next, cx);
 5223        } else {
 5224            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5225            if is_copilot_disabled {
 5226                cx.propagate();
 5227            }
 5228        }
 5229    }
 5230
 5231    pub fn previous_inline_completion(
 5232        &mut self,
 5233        _: &PreviousInlineCompletion,
 5234        cx: &mut ViewContext<Self>,
 5235    ) {
 5236        if self.has_active_inline_completion(cx) {
 5237            self.cycle_inline_completion(Direction::Prev, cx);
 5238        } else {
 5239            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5240            if is_copilot_disabled {
 5241                cx.propagate();
 5242            }
 5243        }
 5244    }
 5245
 5246    pub fn accept_inline_completion(
 5247        &mut self,
 5248        _: &AcceptInlineCompletion,
 5249        cx: &mut ViewContext<Self>,
 5250    ) {
 5251        let Some(completion) = self.take_active_inline_completion(cx) else {
 5252            return;
 5253        };
 5254        if let Some(provider) = self.inline_completion_provider() {
 5255            provider.accept(cx);
 5256        }
 5257
 5258        cx.emit(EditorEvent::InputHandled {
 5259            utf16_range_to_replace: None,
 5260            text: completion.text.to_string().into(),
 5261        });
 5262
 5263        if let Some(range) = completion.delete_range {
 5264            self.change_selections(None, cx, |s| s.select_ranges([range]))
 5265        }
 5266        self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
 5267        self.refresh_inline_completion(true, true, cx);
 5268        cx.notify();
 5269    }
 5270
 5271    pub fn accept_partial_inline_completion(
 5272        &mut self,
 5273        _: &AcceptPartialInlineCompletion,
 5274        cx: &mut ViewContext<Self>,
 5275    ) {
 5276        if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
 5277            if let Some(completion) = self.take_active_inline_completion(cx) {
 5278                let mut partial_completion = completion
 5279                    .text
 5280                    .chars()
 5281                    .by_ref()
 5282                    .take_while(|c| c.is_alphabetic())
 5283                    .collect::<String>();
 5284                if partial_completion.is_empty() {
 5285                    partial_completion = completion
 5286                        .text
 5287                        .chars()
 5288                        .by_ref()
 5289                        .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5290                        .collect::<String>();
 5291                }
 5292
 5293                cx.emit(EditorEvent::InputHandled {
 5294                    utf16_range_to_replace: None,
 5295                    text: partial_completion.clone().into(),
 5296                });
 5297
 5298                if let Some(range) = completion.delete_range {
 5299                    self.change_selections(None, cx, |s| s.select_ranges([range]))
 5300                }
 5301                self.insert_with_autoindent_mode(&partial_completion, None, cx);
 5302
 5303                self.refresh_inline_completion(true, true, cx);
 5304                cx.notify();
 5305            }
 5306        }
 5307    }
 5308
 5309    fn discard_inline_completion(
 5310        &mut self,
 5311        should_report_inline_completion_event: bool,
 5312        cx: &mut ViewContext<Self>,
 5313    ) -> bool {
 5314        if let Some(provider) = self.inline_completion_provider() {
 5315            provider.discard(should_report_inline_completion_event, cx);
 5316        }
 5317
 5318        self.take_active_inline_completion(cx).is_some()
 5319    }
 5320
 5321    pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
 5322        if let Some(completion) = self.active_inline_completion.as_ref() {
 5323            let buffer = self.buffer.read(cx).read(cx);
 5324            completion.position.is_valid(&buffer)
 5325        } else {
 5326            false
 5327        }
 5328    }
 5329
 5330    fn take_active_inline_completion(
 5331        &mut self,
 5332        cx: &mut ViewContext<Self>,
 5333    ) -> Option<CompletionState> {
 5334        let completion = self.active_inline_completion.take()?;
 5335        let render_inlay_ids = completion.render_inlay_ids.clone();
 5336        self.display_map.update(cx, |map, cx| {
 5337            map.splice_inlays(render_inlay_ids, Default::default(), cx);
 5338        });
 5339        let buffer = self.buffer.read(cx).read(cx);
 5340
 5341        if completion.position.is_valid(&buffer) {
 5342            Some(completion)
 5343        } else {
 5344            None
 5345        }
 5346    }
 5347
 5348    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
 5349        let selection = self.selections.newest_anchor();
 5350        let cursor = selection.head();
 5351
 5352        let excerpt_id = cursor.excerpt_id;
 5353
 5354        if self.context_menu.read().is_none()
 5355            && self.completion_tasks.is_empty()
 5356            && selection.start == selection.end
 5357        {
 5358            if let Some(provider) = self.inline_completion_provider() {
 5359                if let Some((buffer, cursor_buffer_position)) =
 5360                    self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5361                {
 5362                    if let Some(proposal) =
 5363                        provider.active_completion_text(&buffer, cursor_buffer_position, cx)
 5364                    {
 5365                        let mut to_remove = Vec::new();
 5366                        if let Some(completion) = self.active_inline_completion.take() {
 5367                            to_remove.extend(completion.render_inlay_ids.iter());
 5368                        }
 5369
 5370                        let to_add = proposal
 5371                            .inlays
 5372                            .iter()
 5373                            .filter_map(|inlay| {
 5374                                let snapshot = self.buffer.read(cx).snapshot(cx);
 5375                                let id = post_inc(&mut self.next_inlay_id);
 5376                                match inlay {
 5377                                    InlayProposal::Hint(position, hint) => {
 5378                                        let position =
 5379                                            snapshot.anchor_in_excerpt(excerpt_id, *position)?;
 5380                                        Some(Inlay::hint(id, position, hint))
 5381                                    }
 5382                                    InlayProposal::Suggestion(position, text) => {
 5383                                        let position =
 5384                                            snapshot.anchor_in_excerpt(excerpt_id, *position)?;
 5385                                        Some(Inlay::suggestion(id, position, text.clone()))
 5386                                    }
 5387                                }
 5388                            })
 5389                            .collect_vec();
 5390
 5391                        self.active_inline_completion = Some(CompletionState {
 5392                            position: cursor,
 5393                            text: proposal.text,
 5394                            delete_range: proposal.delete_range.and_then(|range| {
 5395                                let snapshot = self.buffer.read(cx).snapshot(cx);
 5396                                let start = snapshot.anchor_in_excerpt(excerpt_id, range.start);
 5397                                let end = snapshot.anchor_in_excerpt(excerpt_id, range.end);
 5398                                Some(start?..end?)
 5399                            }),
 5400                            render_inlay_ids: to_add.iter().map(|i| i.id).collect(),
 5401                        });
 5402
 5403                        self.display_map
 5404                            .update(cx, move |map, cx| map.splice_inlays(to_remove, to_add, cx));
 5405
 5406                        cx.notify();
 5407                        return;
 5408                    }
 5409                }
 5410            }
 5411        }
 5412
 5413        self.discard_inline_completion(false, cx);
 5414    }
 5415
 5416    fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5417        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 5418    }
 5419
 5420    fn render_code_actions_indicator(
 5421        &self,
 5422        _style: &EditorStyle,
 5423        row: DisplayRow,
 5424        is_active: bool,
 5425        cx: &mut ViewContext<Self>,
 5426    ) -> Option<IconButton> {
 5427        if self.available_code_actions.is_some() {
 5428            Some(
 5429                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5430                    .shape(ui::IconButtonShape::Square)
 5431                    .icon_size(IconSize::XSmall)
 5432                    .icon_color(Color::Muted)
 5433                    .selected(is_active)
 5434                    .tooltip({
 5435                        let focus_handle = self.focus_handle.clone();
 5436                        move |cx| {
 5437                            Tooltip::for_action_in(
 5438                                "Toggle Code Actions",
 5439                                &ToggleCodeActions {
 5440                                    deployed_from_indicator: None,
 5441                                },
 5442                                &focus_handle,
 5443                                cx,
 5444                            )
 5445                        }
 5446                    })
 5447                    .on_click(cx.listener(move |editor, _e, cx| {
 5448                        editor.focus(cx);
 5449                        editor.toggle_code_actions(
 5450                            &ToggleCodeActions {
 5451                                deployed_from_indicator: Some(row),
 5452                            },
 5453                            cx,
 5454                        );
 5455                    })),
 5456            )
 5457        } else {
 5458            None
 5459        }
 5460    }
 5461
 5462    fn clear_tasks(&mut self) {
 5463        self.tasks.clear()
 5464    }
 5465
 5466    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5467        if self.tasks.insert(key, value).is_some() {
 5468            // This case should hopefully be rare, but just in case...
 5469            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5470        }
 5471    }
 5472
 5473    fn build_tasks_context(
 5474        project: &Model<Project>,
 5475        buffer: &Model<Buffer>,
 5476        buffer_row: u32,
 5477        tasks: &Arc<RunnableTasks>,
 5478        cx: &mut ViewContext<Self>,
 5479    ) -> Task<Option<task::TaskContext>> {
 5480        let position = Point::new(buffer_row, tasks.column);
 5481        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5482        let location = Location {
 5483            buffer: buffer.clone(),
 5484            range: range_start..range_start,
 5485        };
 5486        // Fill in the environmental variables from the tree-sitter captures
 5487        let mut captured_task_variables = TaskVariables::default();
 5488        for (capture_name, value) in tasks.extra_variables.clone() {
 5489            captured_task_variables.insert(
 5490                task::VariableName::Custom(capture_name.into()),
 5491                value.clone(),
 5492            );
 5493        }
 5494        project.update(cx, |project, cx| {
 5495            project.task_store().update(cx, |task_store, cx| {
 5496                task_store.task_context_for_location(captured_task_variables, location, cx)
 5497            })
 5498        })
 5499    }
 5500
 5501    pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
 5502        let Some((workspace, _)) = self.workspace.clone() else {
 5503            return;
 5504        };
 5505        let Some(project) = self.project.clone() else {
 5506            return;
 5507        };
 5508
 5509        // Try to find a closest, enclosing node using tree-sitter that has a
 5510        // task
 5511        let Some((buffer, buffer_row, tasks)) = self
 5512            .find_enclosing_node_task(cx)
 5513            // Or find the task that's closest in row-distance.
 5514            .or_else(|| self.find_closest_task(cx))
 5515        else {
 5516            return;
 5517        };
 5518
 5519        let reveal_strategy = action.reveal;
 5520        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5521        cx.spawn(|_, mut cx| async move {
 5522            let context = task_context.await?;
 5523            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5524
 5525            let resolved = resolved_task.resolved.as_mut()?;
 5526            resolved.reveal = reveal_strategy;
 5527
 5528            workspace
 5529                .update(&mut cx, |workspace, cx| {
 5530                    workspace::tasks::schedule_resolved_task(
 5531                        workspace,
 5532                        task_source_kind,
 5533                        resolved_task,
 5534                        false,
 5535                        cx,
 5536                    );
 5537                })
 5538                .ok()
 5539        })
 5540        .detach();
 5541    }
 5542
 5543    fn find_closest_task(
 5544        &mut self,
 5545        cx: &mut ViewContext<Self>,
 5546    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5547        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5548
 5549        let ((buffer_id, row), tasks) = self
 5550            .tasks
 5551            .iter()
 5552            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5553
 5554        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5555        let tasks = Arc::new(tasks.to_owned());
 5556        Some((buffer, *row, tasks))
 5557    }
 5558
 5559    fn find_enclosing_node_task(
 5560        &mut self,
 5561        cx: &mut ViewContext<Self>,
 5562    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5563        let snapshot = self.buffer.read(cx).snapshot(cx);
 5564        let offset = self.selections.newest::<usize>(cx).head();
 5565        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5566        let buffer_id = excerpt.buffer().remote_id();
 5567
 5568        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5569        let mut cursor = layer.node().walk();
 5570
 5571        while cursor.goto_first_child_for_byte(offset).is_some() {
 5572            if cursor.node().end_byte() == offset {
 5573                cursor.goto_next_sibling();
 5574            }
 5575        }
 5576
 5577        // Ascend to the smallest ancestor that contains the range and has a task.
 5578        loop {
 5579            let node = cursor.node();
 5580            let node_range = node.byte_range();
 5581            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5582
 5583            // Check if this node contains our offset
 5584            if node_range.start <= offset && node_range.end >= offset {
 5585                // If it contains offset, check for task
 5586                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5587                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5588                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5589                }
 5590            }
 5591
 5592            if !cursor.goto_parent() {
 5593                break;
 5594            }
 5595        }
 5596        None
 5597    }
 5598
 5599    fn render_run_indicator(
 5600        &self,
 5601        _style: &EditorStyle,
 5602        is_active: bool,
 5603        row: DisplayRow,
 5604        cx: &mut ViewContext<Self>,
 5605    ) -> IconButton {
 5606        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5607            .shape(ui::IconButtonShape::Square)
 5608            .icon_size(IconSize::XSmall)
 5609            .icon_color(Color::Muted)
 5610            .selected(is_active)
 5611            .on_click(cx.listener(move |editor, _e, cx| {
 5612                editor.focus(cx);
 5613                editor.toggle_code_actions(
 5614                    &ToggleCodeActions {
 5615                        deployed_from_indicator: Some(row),
 5616                    },
 5617                    cx,
 5618                );
 5619            }))
 5620    }
 5621
 5622    pub fn context_menu_visible(&self) -> bool {
 5623        self.context_menu
 5624            .read()
 5625            .as_ref()
 5626            .map_or(false, |menu| menu.visible())
 5627    }
 5628
 5629    fn render_context_menu(
 5630        &self,
 5631        cursor_position: DisplayPoint,
 5632        style: &EditorStyle,
 5633        max_height: Pixels,
 5634        cx: &mut ViewContext<Editor>,
 5635    ) -> Option<(ContextMenuOrigin, AnyElement)> {
 5636        self.context_menu.read().as_ref().map(|menu| {
 5637            menu.render(
 5638                cursor_position,
 5639                style,
 5640                max_height,
 5641                self.workspace.as_ref().map(|(w, _)| w.clone()),
 5642                cx,
 5643            )
 5644        })
 5645    }
 5646
 5647    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
 5648        cx.notify();
 5649        self.completion_tasks.clear();
 5650        let context_menu = self.context_menu.write().take();
 5651        if context_menu.is_some() {
 5652            self.update_visible_inline_completion(cx);
 5653        }
 5654        context_menu
 5655    }
 5656
 5657    pub fn insert_snippet(
 5658        &mut self,
 5659        insertion_ranges: &[Range<usize>],
 5660        snippet: Snippet,
 5661        cx: &mut ViewContext<Self>,
 5662    ) -> Result<()> {
 5663        struct Tabstop<T> {
 5664            is_end_tabstop: bool,
 5665            ranges: Vec<Range<T>>,
 5666        }
 5667
 5668        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5669            let snippet_text: Arc<str> = snippet.text.clone().into();
 5670            buffer.edit(
 5671                insertion_ranges
 5672                    .iter()
 5673                    .cloned()
 5674                    .map(|range| (range, snippet_text.clone())),
 5675                Some(AutoindentMode::EachLine),
 5676                cx,
 5677            );
 5678
 5679            let snapshot = &*buffer.read(cx);
 5680            let snippet = &snippet;
 5681            snippet
 5682                .tabstops
 5683                .iter()
 5684                .map(|tabstop| {
 5685                    let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
 5686                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5687                    });
 5688                    let mut tabstop_ranges = tabstop
 5689                        .iter()
 5690                        .flat_map(|tabstop_range| {
 5691                            let mut delta = 0_isize;
 5692                            insertion_ranges.iter().map(move |insertion_range| {
 5693                                let insertion_start = insertion_range.start as isize + delta;
 5694                                delta +=
 5695                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5696
 5697                                let start = ((insertion_start + tabstop_range.start) as usize)
 5698                                    .min(snapshot.len());
 5699                                let end = ((insertion_start + tabstop_range.end) as usize)
 5700                                    .min(snapshot.len());
 5701                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5702                            })
 5703                        })
 5704                        .collect::<Vec<_>>();
 5705                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5706
 5707                    Tabstop {
 5708                        is_end_tabstop,
 5709                        ranges: tabstop_ranges,
 5710                    }
 5711                })
 5712                .collect::<Vec<_>>()
 5713        });
 5714        if let Some(tabstop) = tabstops.first() {
 5715            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5716                s.select_ranges(tabstop.ranges.iter().cloned());
 5717            });
 5718
 5719            // If we're already at the last tabstop and it's at the end of the snippet,
 5720            // we're done, we don't need to keep the state around.
 5721            if !tabstop.is_end_tabstop {
 5722                let ranges = tabstops
 5723                    .into_iter()
 5724                    .map(|tabstop| tabstop.ranges)
 5725                    .collect::<Vec<_>>();
 5726                self.snippet_stack.push(SnippetState {
 5727                    active_index: 0,
 5728                    ranges,
 5729                });
 5730            }
 5731
 5732            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5733            if self.autoclose_regions.is_empty() {
 5734                let snapshot = self.buffer.read(cx).snapshot(cx);
 5735                for selection in &mut self.selections.all::<Point>(cx) {
 5736                    let selection_head = selection.head();
 5737                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5738                        continue;
 5739                    };
 5740
 5741                    let mut bracket_pair = None;
 5742                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5743                    let prev_chars = snapshot
 5744                        .reversed_chars_at(selection_head)
 5745                        .collect::<String>();
 5746                    for (pair, enabled) in scope.brackets() {
 5747                        if enabled
 5748                            && pair.close
 5749                            && prev_chars.starts_with(pair.start.as_str())
 5750                            && next_chars.starts_with(pair.end.as_str())
 5751                        {
 5752                            bracket_pair = Some(pair.clone());
 5753                            break;
 5754                        }
 5755                    }
 5756                    if let Some(pair) = bracket_pair {
 5757                        let start = snapshot.anchor_after(selection_head);
 5758                        let end = snapshot.anchor_after(selection_head);
 5759                        self.autoclose_regions.push(AutocloseRegion {
 5760                            selection_id: selection.id,
 5761                            range: start..end,
 5762                            pair,
 5763                        });
 5764                    }
 5765                }
 5766            }
 5767        }
 5768        Ok(())
 5769    }
 5770
 5771    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5772        self.move_to_snippet_tabstop(Bias::Right, cx)
 5773    }
 5774
 5775    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5776        self.move_to_snippet_tabstop(Bias::Left, cx)
 5777    }
 5778
 5779    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5780        if let Some(mut snippet) = self.snippet_stack.pop() {
 5781            match bias {
 5782                Bias::Left => {
 5783                    if snippet.active_index > 0 {
 5784                        snippet.active_index -= 1;
 5785                    } else {
 5786                        self.snippet_stack.push(snippet);
 5787                        return false;
 5788                    }
 5789                }
 5790                Bias::Right => {
 5791                    if snippet.active_index + 1 < snippet.ranges.len() {
 5792                        snippet.active_index += 1;
 5793                    } else {
 5794                        self.snippet_stack.push(snippet);
 5795                        return false;
 5796                    }
 5797                }
 5798            }
 5799            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5800                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5801                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5802                });
 5803                // If snippet state is not at the last tabstop, push it back on the stack
 5804                if snippet.active_index + 1 < snippet.ranges.len() {
 5805                    self.snippet_stack.push(snippet);
 5806                }
 5807                return true;
 5808            }
 5809        }
 5810
 5811        false
 5812    }
 5813
 5814    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 5815        self.transact(cx, |this, cx| {
 5816            this.select_all(&SelectAll, cx);
 5817            this.insert("", cx);
 5818        });
 5819    }
 5820
 5821    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 5822        self.transact(cx, |this, cx| {
 5823            this.select_autoclose_pair(cx);
 5824            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5825            if !this.linked_edit_ranges.is_empty() {
 5826                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5827                let snapshot = this.buffer.read(cx).snapshot(cx);
 5828
 5829                for selection in selections.iter() {
 5830                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5831                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 5832                    if selection_start.buffer_id != selection_end.buffer_id {
 5833                        continue;
 5834                    }
 5835                    if let Some(ranges) =
 5836                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 5837                    {
 5838                        for (buffer, entries) in ranges {
 5839                            linked_ranges.entry(buffer).or_default().extend(entries);
 5840                        }
 5841                    }
 5842                }
 5843            }
 5844
 5845            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 5846            if !this.selections.line_mode {
 5847                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 5848                for selection in &mut selections {
 5849                    if selection.is_empty() {
 5850                        let old_head = selection.head();
 5851                        let mut new_head =
 5852                            movement::left(&display_map, old_head.to_display_point(&display_map))
 5853                                .to_point(&display_map);
 5854                        if let Some((buffer, line_buffer_range)) = display_map
 5855                            .buffer_snapshot
 5856                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 5857                        {
 5858                            let indent_size =
 5859                                buffer.indent_size_for_line(line_buffer_range.start.row);
 5860                            let indent_len = match indent_size.kind {
 5861                                IndentKind::Space => {
 5862                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 5863                                }
 5864                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 5865                            };
 5866                            if old_head.column <= indent_size.len && old_head.column > 0 {
 5867                                let indent_len = indent_len.get();
 5868                                new_head = cmp::min(
 5869                                    new_head,
 5870                                    MultiBufferPoint::new(
 5871                                        old_head.row,
 5872                                        ((old_head.column - 1) / indent_len) * indent_len,
 5873                                    ),
 5874                                );
 5875                            }
 5876                        }
 5877
 5878                        selection.set_head(new_head, SelectionGoal::None);
 5879                    }
 5880                }
 5881            }
 5882
 5883            this.signature_help_state.set_backspace_pressed(true);
 5884            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5885            this.insert("", cx);
 5886            let empty_str: Arc<str> = Arc::from("");
 5887            for (buffer, edits) in linked_ranges {
 5888                let snapshot = buffer.read(cx).snapshot();
 5889                use text::ToPoint as TP;
 5890
 5891                let edits = edits
 5892                    .into_iter()
 5893                    .map(|range| {
 5894                        let end_point = TP::to_point(&range.end, &snapshot);
 5895                        let mut start_point = TP::to_point(&range.start, &snapshot);
 5896
 5897                        if end_point == start_point {
 5898                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 5899                                .saturating_sub(1);
 5900                            start_point = TP::to_point(&offset, &snapshot);
 5901                        };
 5902
 5903                        (start_point..end_point, empty_str.clone())
 5904                    })
 5905                    .sorted_by_key(|(range, _)| range.start)
 5906                    .collect::<Vec<_>>();
 5907                buffer.update(cx, |this, cx| {
 5908                    this.edit(edits, None, cx);
 5909                })
 5910            }
 5911            this.refresh_inline_completion(true, false, cx);
 5912            linked_editing_ranges::refresh_linked_ranges(this, cx);
 5913        });
 5914    }
 5915
 5916    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 5917        self.transact(cx, |this, cx| {
 5918            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5919                let line_mode = s.line_mode;
 5920                s.move_with(|map, selection| {
 5921                    if selection.is_empty() && !line_mode {
 5922                        let cursor = movement::right(map, selection.head());
 5923                        selection.end = cursor;
 5924                        selection.reversed = true;
 5925                        selection.goal = SelectionGoal::None;
 5926                    }
 5927                })
 5928            });
 5929            this.insert("", cx);
 5930            this.refresh_inline_completion(true, false, cx);
 5931        });
 5932    }
 5933
 5934    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 5935        if self.move_to_prev_snippet_tabstop(cx) {
 5936            return;
 5937        }
 5938
 5939        self.outdent(&Outdent, cx);
 5940    }
 5941
 5942    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 5943        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 5944            return;
 5945        }
 5946
 5947        let mut selections = self.selections.all_adjusted(cx);
 5948        let buffer = self.buffer.read(cx);
 5949        let snapshot = buffer.snapshot(cx);
 5950        let rows_iter = selections.iter().map(|s| s.head().row);
 5951        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 5952
 5953        let mut edits = Vec::new();
 5954        let mut prev_edited_row = 0;
 5955        let mut row_delta = 0;
 5956        for selection in &mut selections {
 5957            if selection.start.row != prev_edited_row {
 5958                row_delta = 0;
 5959            }
 5960            prev_edited_row = selection.end.row;
 5961
 5962            // If the selection is non-empty, then increase the indentation of the selected lines.
 5963            if !selection.is_empty() {
 5964                row_delta =
 5965                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5966                continue;
 5967            }
 5968
 5969            // If the selection is empty and the cursor is in the leading whitespace before the
 5970            // suggested indentation, then auto-indent the line.
 5971            let cursor = selection.head();
 5972            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 5973            if let Some(suggested_indent) =
 5974                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 5975            {
 5976                if cursor.column < suggested_indent.len
 5977                    && cursor.column <= current_indent.len
 5978                    && current_indent.len <= suggested_indent.len
 5979                {
 5980                    selection.start = Point::new(cursor.row, suggested_indent.len);
 5981                    selection.end = selection.start;
 5982                    if row_delta == 0 {
 5983                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 5984                            cursor.row,
 5985                            current_indent,
 5986                            suggested_indent,
 5987                        ));
 5988                        row_delta = suggested_indent.len - current_indent.len;
 5989                    }
 5990                    continue;
 5991                }
 5992            }
 5993
 5994            // Otherwise, insert a hard or soft tab.
 5995            let settings = buffer.settings_at(cursor, cx);
 5996            let tab_size = if settings.hard_tabs {
 5997                IndentSize::tab()
 5998            } else {
 5999                let tab_size = settings.tab_size.get();
 6000                let char_column = snapshot
 6001                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 6002                    .flat_map(str::chars)
 6003                    .count()
 6004                    + row_delta as usize;
 6005                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 6006                IndentSize::spaces(chars_to_next_tab_stop)
 6007            };
 6008            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 6009            selection.end = selection.start;
 6010            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 6011            row_delta += tab_size.len;
 6012        }
 6013
 6014        self.transact(cx, |this, cx| {
 6015            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6016            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6017            this.refresh_inline_completion(true, false, cx);
 6018        });
 6019    }
 6020
 6021    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 6022        if self.read_only(cx) {
 6023            return;
 6024        }
 6025        let mut selections = self.selections.all::<Point>(cx);
 6026        let mut prev_edited_row = 0;
 6027        let mut row_delta = 0;
 6028        let mut edits = Vec::new();
 6029        let buffer = self.buffer.read(cx);
 6030        let snapshot = buffer.snapshot(cx);
 6031        for selection in &mut selections {
 6032            if selection.start.row != prev_edited_row {
 6033                row_delta = 0;
 6034            }
 6035            prev_edited_row = selection.end.row;
 6036
 6037            row_delta =
 6038                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6039        }
 6040
 6041        self.transact(cx, |this, cx| {
 6042            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6043            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6044        });
 6045    }
 6046
 6047    fn indent_selection(
 6048        buffer: &MultiBuffer,
 6049        snapshot: &MultiBufferSnapshot,
 6050        selection: &mut Selection<Point>,
 6051        edits: &mut Vec<(Range<Point>, String)>,
 6052        delta_for_start_row: u32,
 6053        cx: &AppContext,
 6054    ) -> u32 {
 6055        let settings = buffer.settings_at(selection.start, cx);
 6056        let tab_size = settings.tab_size.get();
 6057        let indent_kind = if settings.hard_tabs {
 6058            IndentKind::Tab
 6059        } else {
 6060            IndentKind::Space
 6061        };
 6062        let mut start_row = selection.start.row;
 6063        let mut end_row = selection.end.row + 1;
 6064
 6065        // If a selection ends at the beginning of a line, don't indent
 6066        // that last line.
 6067        if selection.end.column == 0 && selection.end.row > selection.start.row {
 6068            end_row -= 1;
 6069        }
 6070
 6071        // Avoid re-indenting a row that has already been indented by a
 6072        // previous selection, but still update this selection's column
 6073        // to reflect that indentation.
 6074        if delta_for_start_row > 0 {
 6075            start_row += 1;
 6076            selection.start.column += delta_for_start_row;
 6077            if selection.end.row == selection.start.row {
 6078                selection.end.column += delta_for_start_row;
 6079            }
 6080        }
 6081
 6082        let mut delta_for_end_row = 0;
 6083        let has_multiple_rows = start_row + 1 != end_row;
 6084        for row in start_row..end_row {
 6085            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 6086            let indent_delta = match (current_indent.kind, indent_kind) {
 6087                (IndentKind::Space, IndentKind::Space) => {
 6088                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 6089                    IndentSize::spaces(columns_to_next_tab_stop)
 6090                }
 6091                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 6092                (_, IndentKind::Tab) => IndentSize::tab(),
 6093            };
 6094
 6095            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 6096                0
 6097            } else {
 6098                selection.start.column
 6099            };
 6100            let row_start = Point::new(row, start);
 6101            edits.push((
 6102                row_start..row_start,
 6103                indent_delta.chars().collect::<String>(),
 6104            ));
 6105
 6106            // Update this selection's endpoints to reflect the indentation.
 6107            if row == selection.start.row {
 6108                selection.start.column += indent_delta.len;
 6109            }
 6110            if row == selection.end.row {
 6111                selection.end.column += indent_delta.len;
 6112                delta_for_end_row = indent_delta.len;
 6113            }
 6114        }
 6115
 6116        if selection.start.row == selection.end.row {
 6117            delta_for_start_row + delta_for_end_row
 6118        } else {
 6119            delta_for_end_row
 6120        }
 6121    }
 6122
 6123    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 6124        if self.read_only(cx) {
 6125            return;
 6126        }
 6127        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6128        let selections = self.selections.all::<Point>(cx);
 6129        let mut deletion_ranges = Vec::new();
 6130        let mut last_outdent = None;
 6131        {
 6132            let buffer = self.buffer.read(cx);
 6133            let snapshot = buffer.snapshot(cx);
 6134            for selection in &selections {
 6135                let settings = buffer.settings_at(selection.start, cx);
 6136                let tab_size = settings.tab_size.get();
 6137                let mut rows = selection.spanned_rows(false, &display_map);
 6138
 6139                // Avoid re-outdenting a row that has already been outdented by a
 6140                // previous selection.
 6141                if let Some(last_row) = last_outdent {
 6142                    if last_row == rows.start {
 6143                        rows.start = rows.start.next_row();
 6144                    }
 6145                }
 6146                let has_multiple_rows = rows.len() > 1;
 6147                for row in rows.iter_rows() {
 6148                    let indent_size = snapshot.indent_size_for_line(row);
 6149                    if indent_size.len > 0 {
 6150                        let deletion_len = match indent_size.kind {
 6151                            IndentKind::Space => {
 6152                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 6153                                if columns_to_prev_tab_stop == 0 {
 6154                                    tab_size
 6155                                } else {
 6156                                    columns_to_prev_tab_stop
 6157                                }
 6158                            }
 6159                            IndentKind::Tab => 1,
 6160                        };
 6161                        let start = if has_multiple_rows
 6162                            || deletion_len > selection.start.column
 6163                            || indent_size.len < selection.start.column
 6164                        {
 6165                            0
 6166                        } else {
 6167                            selection.start.column - deletion_len
 6168                        };
 6169                        deletion_ranges.push(
 6170                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 6171                        );
 6172                        last_outdent = Some(row);
 6173                    }
 6174                }
 6175            }
 6176        }
 6177
 6178        self.transact(cx, |this, cx| {
 6179            this.buffer.update(cx, |buffer, cx| {
 6180                let empty_str: Arc<str> = Arc::default();
 6181                buffer.edit(
 6182                    deletion_ranges
 6183                        .into_iter()
 6184                        .map(|range| (range, empty_str.clone())),
 6185                    None,
 6186                    cx,
 6187                );
 6188            });
 6189            let selections = this.selections.all::<usize>(cx);
 6190            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6191        });
 6192    }
 6193
 6194    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 6195        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6196        let selections = self.selections.all::<Point>(cx);
 6197
 6198        let mut new_cursors = Vec::new();
 6199        let mut edit_ranges = Vec::new();
 6200        let mut selections = selections.iter().peekable();
 6201        while let Some(selection) = selections.next() {
 6202            let mut rows = selection.spanned_rows(false, &display_map);
 6203            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6204
 6205            // Accumulate contiguous regions of rows that we want to delete.
 6206            while let Some(next_selection) = selections.peek() {
 6207                let next_rows = next_selection.spanned_rows(false, &display_map);
 6208                if next_rows.start <= rows.end {
 6209                    rows.end = next_rows.end;
 6210                    selections.next().unwrap();
 6211                } else {
 6212                    break;
 6213                }
 6214            }
 6215
 6216            let buffer = &display_map.buffer_snapshot;
 6217            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6218            let edit_end;
 6219            let cursor_buffer_row;
 6220            if buffer.max_point().row >= rows.end.0 {
 6221                // If there's a line after the range, delete the \n from the end of the row range
 6222                // and position the cursor on the next line.
 6223                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6224                cursor_buffer_row = rows.end;
 6225            } else {
 6226                // If there isn't a line after the range, delete the \n from the line before the
 6227                // start of the row range and position the cursor there.
 6228                edit_start = edit_start.saturating_sub(1);
 6229                edit_end = buffer.len();
 6230                cursor_buffer_row = rows.start.previous_row();
 6231            }
 6232
 6233            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6234            *cursor.column_mut() =
 6235                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6236
 6237            new_cursors.push((
 6238                selection.id,
 6239                buffer.anchor_after(cursor.to_point(&display_map)),
 6240            ));
 6241            edit_ranges.push(edit_start..edit_end);
 6242        }
 6243
 6244        self.transact(cx, |this, cx| {
 6245            let buffer = this.buffer.update(cx, |buffer, cx| {
 6246                let empty_str: Arc<str> = Arc::default();
 6247                buffer.edit(
 6248                    edit_ranges
 6249                        .into_iter()
 6250                        .map(|range| (range, empty_str.clone())),
 6251                    None,
 6252                    cx,
 6253                );
 6254                buffer.snapshot(cx)
 6255            });
 6256            let new_selections = new_cursors
 6257                .into_iter()
 6258                .map(|(id, cursor)| {
 6259                    let cursor = cursor.to_point(&buffer);
 6260                    Selection {
 6261                        id,
 6262                        start: cursor,
 6263                        end: cursor,
 6264                        reversed: false,
 6265                        goal: SelectionGoal::None,
 6266                    }
 6267                })
 6268                .collect();
 6269
 6270            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6271                s.select(new_selections);
 6272            });
 6273        });
 6274    }
 6275
 6276    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 6277        if self.read_only(cx) {
 6278            return;
 6279        }
 6280        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6281        for selection in self.selections.all::<Point>(cx) {
 6282            let start = MultiBufferRow(selection.start.row);
 6283            let end = if selection.start.row == selection.end.row {
 6284                MultiBufferRow(selection.start.row + 1)
 6285            } else {
 6286                MultiBufferRow(selection.end.row)
 6287            };
 6288
 6289            if let Some(last_row_range) = row_ranges.last_mut() {
 6290                if start <= last_row_range.end {
 6291                    last_row_range.end = end;
 6292                    continue;
 6293                }
 6294            }
 6295            row_ranges.push(start..end);
 6296        }
 6297
 6298        let snapshot = self.buffer.read(cx).snapshot(cx);
 6299        let mut cursor_positions = Vec::new();
 6300        for row_range in &row_ranges {
 6301            let anchor = snapshot.anchor_before(Point::new(
 6302                row_range.end.previous_row().0,
 6303                snapshot.line_len(row_range.end.previous_row()),
 6304            ));
 6305            cursor_positions.push(anchor..anchor);
 6306        }
 6307
 6308        self.transact(cx, |this, cx| {
 6309            for row_range in row_ranges.into_iter().rev() {
 6310                for row in row_range.iter_rows().rev() {
 6311                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6312                    let next_line_row = row.next_row();
 6313                    let indent = snapshot.indent_size_for_line(next_line_row);
 6314                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 6315
 6316                    let replace = if snapshot.line_len(next_line_row) > indent.len {
 6317                        " "
 6318                    } else {
 6319                        ""
 6320                    };
 6321
 6322                    this.buffer.update(cx, |buffer, cx| {
 6323                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6324                    });
 6325                }
 6326            }
 6327
 6328            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6329                s.select_anchor_ranges(cursor_positions)
 6330            });
 6331        });
 6332    }
 6333
 6334    pub fn sort_lines_case_sensitive(
 6335        &mut self,
 6336        _: &SortLinesCaseSensitive,
 6337        cx: &mut ViewContext<Self>,
 6338    ) {
 6339        self.manipulate_lines(cx, |lines| lines.sort())
 6340    }
 6341
 6342    pub fn sort_lines_case_insensitive(
 6343        &mut self,
 6344        _: &SortLinesCaseInsensitive,
 6345        cx: &mut ViewContext<Self>,
 6346    ) {
 6347        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 6348    }
 6349
 6350    pub fn unique_lines_case_insensitive(
 6351        &mut self,
 6352        _: &UniqueLinesCaseInsensitive,
 6353        cx: &mut ViewContext<Self>,
 6354    ) {
 6355        self.manipulate_lines(cx, |lines| {
 6356            let mut seen = HashSet::default();
 6357            lines.retain(|line| seen.insert(line.to_lowercase()));
 6358        })
 6359    }
 6360
 6361    pub fn unique_lines_case_sensitive(
 6362        &mut self,
 6363        _: &UniqueLinesCaseSensitive,
 6364        cx: &mut ViewContext<Self>,
 6365    ) {
 6366        self.manipulate_lines(cx, |lines| {
 6367            let mut seen = HashSet::default();
 6368            lines.retain(|line| seen.insert(*line));
 6369        })
 6370    }
 6371
 6372    pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
 6373        let mut revert_changes = HashMap::default();
 6374        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 6375        for hunk in hunks_for_rows(
 6376            Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
 6377            &multi_buffer_snapshot,
 6378        ) {
 6379            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 6380        }
 6381        if !revert_changes.is_empty() {
 6382            self.transact(cx, |editor, cx| {
 6383                editor.revert(revert_changes, cx);
 6384            });
 6385        }
 6386    }
 6387
 6388    pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
 6389        let Some(project) = self.project.clone() else {
 6390            return;
 6391        };
 6392        self.reload(project, cx).detach_and_notify_err(cx);
 6393    }
 6394
 6395    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 6396        let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
 6397        if !revert_changes.is_empty() {
 6398            self.transact(cx, |editor, cx| {
 6399                editor.revert(revert_changes, cx);
 6400            });
 6401        }
 6402    }
 6403
 6404    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 6405        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6406            let project_path = buffer.read(cx).project_path(cx)?;
 6407            let project = self.project.as_ref()?.read(cx);
 6408            let entry = project.entry_for_path(&project_path, cx)?;
 6409            let parent = match &entry.canonical_path {
 6410                Some(canonical_path) => canonical_path.to_path_buf(),
 6411                None => project.absolute_path(&project_path, cx)?,
 6412            }
 6413            .parent()?
 6414            .to_path_buf();
 6415            Some(parent)
 6416        }) {
 6417            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 6418        }
 6419    }
 6420
 6421    fn gather_revert_changes(
 6422        &mut self,
 6423        selections: &[Selection<Anchor>],
 6424        cx: &mut ViewContext<'_, Editor>,
 6425    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 6426        let mut revert_changes = HashMap::default();
 6427        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 6428        for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
 6429            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 6430        }
 6431        revert_changes
 6432    }
 6433
 6434    pub fn prepare_revert_change(
 6435        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6436        multi_buffer: &Model<MultiBuffer>,
 6437        hunk: &MultiBufferDiffHunk,
 6438        cx: &AppContext,
 6439    ) -> Option<()> {
 6440        let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
 6441        let buffer = buffer.read(cx);
 6442        let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
 6443        let buffer_snapshot = buffer.snapshot();
 6444        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6445        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6446            probe
 6447                .0
 6448                .start
 6449                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6450                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6451        }) {
 6452            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6453            Some(())
 6454        } else {
 6455            None
 6456        }
 6457    }
 6458
 6459    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 6460        self.manipulate_lines(cx, |lines| lines.reverse())
 6461    }
 6462
 6463    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 6464        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 6465    }
 6466
 6467    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6468    where
 6469        Fn: FnMut(&mut Vec<&str>),
 6470    {
 6471        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6472        let buffer = self.buffer.read(cx).snapshot(cx);
 6473
 6474        let mut edits = Vec::new();
 6475
 6476        let selections = self.selections.all::<Point>(cx);
 6477        let mut selections = selections.iter().peekable();
 6478        let mut contiguous_row_selections = Vec::new();
 6479        let mut new_selections = Vec::new();
 6480        let mut added_lines = 0;
 6481        let mut removed_lines = 0;
 6482
 6483        while let Some(selection) = selections.next() {
 6484            let (start_row, end_row) = consume_contiguous_rows(
 6485                &mut contiguous_row_selections,
 6486                selection,
 6487                &display_map,
 6488                &mut selections,
 6489            );
 6490
 6491            let start_point = Point::new(start_row.0, 0);
 6492            let end_point = Point::new(
 6493                end_row.previous_row().0,
 6494                buffer.line_len(end_row.previous_row()),
 6495            );
 6496            let text = buffer
 6497                .text_for_range(start_point..end_point)
 6498                .collect::<String>();
 6499
 6500            let mut lines = text.split('\n').collect_vec();
 6501
 6502            let lines_before = lines.len();
 6503            callback(&mut lines);
 6504            let lines_after = lines.len();
 6505
 6506            edits.push((start_point..end_point, lines.join("\n")));
 6507
 6508            // Selections must change based on added and removed line count
 6509            let start_row =
 6510                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6511            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6512            new_selections.push(Selection {
 6513                id: selection.id,
 6514                start: start_row,
 6515                end: end_row,
 6516                goal: SelectionGoal::None,
 6517                reversed: selection.reversed,
 6518            });
 6519
 6520            if lines_after > lines_before {
 6521                added_lines += lines_after - lines_before;
 6522            } else if lines_before > lines_after {
 6523                removed_lines += lines_before - lines_after;
 6524            }
 6525        }
 6526
 6527        self.transact(cx, |this, cx| {
 6528            let buffer = this.buffer.update(cx, |buffer, cx| {
 6529                buffer.edit(edits, None, cx);
 6530                buffer.snapshot(cx)
 6531            });
 6532
 6533            // Recalculate offsets on newly edited buffer
 6534            let new_selections = new_selections
 6535                .iter()
 6536                .map(|s| {
 6537                    let start_point = Point::new(s.start.0, 0);
 6538                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6539                    Selection {
 6540                        id: s.id,
 6541                        start: buffer.point_to_offset(start_point),
 6542                        end: buffer.point_to_offset(end_point),
 6543                        goal: s.goal,
 6544                        reversed: s.reversed,
 6545                    }
 6546                })
 6547                .collect();
 6548
 6549            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6550                s.select(new_selections);
 6551            });
 6552
 6553            this.request_autoscroll(Autoscroll::fit(), cx);
 6554        });
 6555    }
 6556
 6557    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 6558        self.manipulate_text(cx, |text| text.to_uppercase())
 6559    }
 6560
 6561    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 6562        self.manipulate_text(cx, |text| text.to_lowercase())
 6563    }
 6564
 6565    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 6566        self.manipulate_text(cx, |text| {
 6567            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6568            // https://github.com/rutrum/convert-case/issues/16
 6569            text.split('\n')
 6570                .map(|line| line.to_case(Case::Title))
 6571                .join("\n")
 6572        })
 6573    }
 6574
 6575    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6576        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6577    }
 6578
 6579    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6580        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6581    }
 6582
 6583    pub fn convert_to_upper_camel_case(
 6584        &mut self,
 6585        _: &ConvertToUpperCamelCase,
 6586        cx: &mut ViewContext<Self>,
 6587    ) {
 6588        self.manipulate_text(cx, |text| {
 6589            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6590            // https://github.com/rutrum/convert-case/issues/16
 6591            text.split('\n')
 6592                .map(|line| line.to_case(Case::UpperCamel))
 6593                .join("\n")
 6594        })
 6595    }
 6596
 6597    pub fn convert_to_lower_camel_case(
 6598        &mut self,
 6599        _: &ConvertToLowerCamelCase,
 6600        cx: &mut ViewContext<Self>,
 6601    ) {
 6602        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6603    }
 6604
 6605    pub fn convert_to_opposite_case(
 6606        &mut self,
 6607        _: &ConvertToOppositeCase,
 6608        cx: &mut ViewContext<Self>,
 6609    ) {
 6610        self.manipulate_text(cx, |text| {
 6611            text.chars()
 6612                .fold(String::with_capacity(text.len()), |mut t, c| {
 6613                    if c.is_uppercase() {
 6614                        t.extend(c.to_lowercase());
 6615                    } else {
 6616                        t.extend(c.to_uppercase());
 6617                    }
 6618                    t
 6619                })
 6620        })
 6621    }
 6622
 6623    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6624    where
 6625        Fn: FnMut(&str) -> String,
 6626    {
 6627        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6628        let buffer = self.buffer.read(cx).snapshot(cx);
 6629
 6630        let mut new_selections = Vec::new();
 6631        let mut edits = Vec::new();
 6632        let mut selection_adjustment = 0i32;
 6633
 6634        for selection in self.selections.all::<usize>(cx) {
 6635            let selection_is_empty = selection.is_empty();
 6636
 6637            let (start, end) = if selection_is_empty {
 6638                let word_range = movement::surrounding_word(
 6639                    &display_map,
 6640                    selection.start.to_display_point(&display_map),
 6641                );
 6642                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6643                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6644                (start, end)
 6645            } else {
 6646                (selection.start, selection.end)
 6647            };
 6648
 6649            let text = buffer.text_for_range(start..end).collect::<String>();
 6650            let old_length = text.len() as i32;
 6651            let text = callback(&text);
 6652
 6653            new_selections.push(Selection {
 6654                start: (start as i32 - selection_adjustment) as usize,
 6655                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6656                goal: SelectionGoal::None,
 6657                ..selection
 6658            });
 6659
 6660            selection_adjustment += old_length - text.len() as i32;
 6661
 6662            edits.push((start..end, text));
 6663        }
 6664
 6665        self.transact(cx, |this, cx| {
 6666            this.buffer.update(cx, |buffer, cx| {
 6667                buffer.edit(edits, None, cx);
 6668            });
 6669
 6670            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6671                s.select(new_selections);
 6672            });
 6673
 6674            this.request_autoscroll(Autoscroll::fit(), cx);
 6675        });
 6676    }
 6677
 6678    pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
 6679        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6680        let buffer = &display_map.buffer_snapshot;
 6681        let selections = self.selections.all::<Point>(cx);
 6682
 6683        let mut edits = Vec::new();
 6684        let mut selections_iter = selections.iter().peekable();
 6685        while let Some(selection) = selections_iter.next() {
 6686            // Avoid duplicating the same lines twice.
 6687            let mut rows = selection.spanned_rows(false, &display_map);
 6688
 6689            while let Some(next_selection) = selections_iter.peek() {
 6690                let next_rows = next_selection.spanned_rows(false, &display_map);
 6691                if next_rows.start < rows.end {
 6692                    rows.end = next_rows.end;
 6693                    selections_iter.next().unwrap();
 6694                } else {
 6695                    break;
 6696                }
 6697            }
 6698
 6699            // Copy the text from the selected row region and splice it either at the start
 6700            // or end of the region.
 6701            let start = Point::new(rows.start.0, 0);
 6702            let end = Point::new(
 6703                rows.end.previous_row().0,
 6704                buffer.line_len(rows.end.previous_row()),
 6705            );
 6706            let text = buffer
 6707                .text_for_range(start..end)
 6708                .chain(Some("\n"))
 6709                .collect::<String>();
 6710            let insert_location = if upwards {
 6711                Point::new(rows.end.0, 0)
 6712            } else {
 6713                start
 6714            };
 6715            edits.push((insert_location..insert_location, text));
 6716        }
 6717
 6718        self.transact(cx, |this, cx| {
 6719            this.buffer.update(cx, |buffer, cx| {
 6720                buffer.edit(edits, None, cx);
 6721            });
 6722
 6723            this.request_autoscroll(Autoscroll::fit(), cx);
 6724        });
 6725    }
 6726
 6727    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6728        self.duplicate_line(true, cx);
 6729    }
 6730
 6731    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6732        self.duplicate_line(false, cx);
 6733    }
 6734
 6735    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6736        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6737        let buffer = self.buffer.read(cx).snapshot(cx);
 6738
 6739        let mut edits = Vec::new();
 6740        let mut unfold_ranges = Vec::new();
 6741        let mut refold_ranges = Vec::new();
 6742
 6743        let selections = self.selections.all::<Point>(cx);
 6744        let mut selections = selections.iter().peekable();
 6745        let mut contiguous_row_selections = Vec::new();
 6746        let mut new_selections = Vec::new();
 6747
 6748        while let Some(selection) = selections.next() {
 6749            // Find all the selections that span a contiguous row range
 6750            let (start_row, end_row) = consume_contiguous_rows(
 6751                &mut contiguous_row_selections,
 6752                selection,
 6753                &display_map,
 6754                &mut selections,
 6755            );
 6756
 6757            // Move the text spanned by the row range to be before the line preceding the row range
 6758            if start_row.0 > 0 {
 6759                let range_to_move = Point::new(
 6760                    start_row.previous_row().0,
 6761                    buffer.line_len(start_row.previous_row()),
 6762                )
 6763                    ..Point::new(
 6764                        end_row.previous_row().0,
 6765                        buffer.line_len(end_row.previous_row()),
 6766                    );
 6767                let insertion_point = display_map
 6768                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6769                    .0;
 6770
 6771                // Don't move lines across excerpts
 6772                if buffer
 6773                    .excerpt_boundaries_in_range((
 6774                        Bound::Excluded(insertion_point),
 6775                        Bound::Included(range_to_move.end),
 6776                    ))
 6777                    .next()
 6778                    .is_none()
 6779                {
 6780                    let text = buffer
 6781                        .text_for_range(range_to_move.clone())
 6782                        .flat_map(|s| s.chars())
 6783                        .skip(1)
 6784                        .chain(['\n'])
 6785                        .collect::<String>();
 6786
 6787                    edits.push((
 6788                        buffer.anchor_after(range_to_move.start)
 6789                            ..buffer.anchor_before(range_to_move.end),
 6790                        String::new(),
 6791                    ));
 6792                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6793                    edits.push((insertion_anchor..insertion_anchor, text));
 6794
 6795                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6796
 6797                    // Move selections up
 6798                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6799                        |mut selection| {
 6800                            selection.start.row -= row_delta;
 6801                            selection.end.row -= row_delta;
 6802                            selection
 6803                        },
 6804                    ));
 6805
 6806                    // Move folds up
 6807                    unfold_ranges.push(range_to_move.clone());
 6808                    for fold in display_map.folds_in_range(
 6809                        buffer.anchor_before(range_to_move.start)
 6810                            ..buffer.anchor_after(range_to_move.end),
 6811                    ) {
 6812                        let mut start = fold.range.start.to_point(&buffer);
 6813                        let mut end = fold.range.end.to_point(&buffer);
 6814                        start.row -= row_delta;
 6815                        end.row -= row_delta;
 6816                        refold_ranges.push((start..end, fold.placeholder.clone()));
 6817                    }
 6818                }
 6819            }
 6820
 6821            // If we didn't move line(s), preserve the existing selections
 6822            new_selections.append(&mut contiguous_row_selections);
 6823        }
 6824
 6825        self.transact(cx, |this, cx| {
 6826            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6827            this.buffer.update(cx, |buffer, cx| {
 6828                for (range, text) in edits {
 6829                    buffer.edit([(range, text)], None, cx);
 6830                }
 6831            });
 6832            this.fold_ranges(refold_ranges, true, cx);
 6833            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6834                s.select(new_selections);
 6835            })
 6836        });
 6837    }
 6838
 6839    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 6840        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6841        let buffer = self.buffer.read(cx).snapshot(cx);
 6842
 6843        let mut edits = Vec::new();
 6844        let mut unfold_ranges = Vec::new();
 6845        let mut refold_ranges = Vec::new();
 6846
 6847        let selections = self.selections.all::<Point>(cx);
 6848        let mut selections = selections.iter().peekable();
 6849        let mut contiguous_row_selections = Vec::new();
 6850        let mut new_selections = Vec::new();
 6851
 6852        while let Some(selection) = selections.next() {
 6853            // Find all the selections that span a contiguous row range
 6854            let (start_row, end_row) = consume_contiguous_rows(
 6855                &mut contiguous_row_selections,
 6856                selection,
 6857                &display_map,
 6858                &mut selections,
 6859            );
 6860
 6861            // Move the text spanned by the row range to be after the last line of the row range
 6862            if end_row.0 <= buffer.max_point().row {
 6863                let range_to_move =
 6864                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 6865                let insertion_point = display_map
 6866                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 6867                    .0;
 6868
 6869                // Don't move lines across excerpt boundaries
 6870                if buffer
 6871                    .excerpt_boundaries_in_range((
 6872                        Bound::Excluded(range_to_move.start),
 6873                        Bound::Included(insertion_point),
 6874                    ))
 6875                    .next()
 6876                    .is_none()
 6877                {
 6878                    let mut text = String::from("\n");
 6879                    text.extend(buffer.text_for_range(range_to_move.clone()));
 6880                    text.pop(); // Drop trailing newline
 6881                    edits.push((
 6882                        buffer.anchor_after(range_to_move.start)
 6883                            ..buffer.anchor_before(range_to_move.end),
 6884                        String::new(),
 6885                    ));
 6886                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6887                    edits.push((insertion_anchor..insertion_anchor, text));
 6888
 6889                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 6890
 6891                    // Move selections down
 6892                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6893                        |mut selection| {
 6894                            selection.start.row += row_delta;
 6895                            selection.end.row += row_delta;
 6896                            selection
 6897                        },
 6898                    ));
 6899
 6900                    // Move folds down
 6901                    unfold_ranges.push(range_to_move.clone());
 6902                    for fold in display_map.folds_in_range(
 6903                        buffer.anchor_before(range_to_move.start)
 6904                            ..buffer.anchor_after(range_to_move.end),
 6905                    ) {
 6906                        let mut start = fold.range.start.to_point(&buffer);
 6907                        let mut end = fold.range.end.to_point(&buffer);
 6908                        start.row += row_delta;
 6909                        end.row += row_delta;
 6910                        refold_ranges.push((start..end, fold.placeholder.clone()));
 6911                    }
 6912                }
 6913            }
 6914
 6915            // If we didn't move line(s), preserve the existing selections
 6916            new_selections.append(&mut contiguous_row_selections);
 6917        }
 6918
 6919        self.transact(cx, |this, cx| {
 6920            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6921            this.buffer.update(cx, |buffer, cx| {
 6922                for (range, text) in edits {
 6923                    buffer.edit([(range, text)], None, cx);
 6924                }
 6925            });
 6926            this.fold_ranges(refold_ranges, true, cx);
 6927            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 6928        });
 6929    }
 6930
 6931    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 6932        let text_layout_details = &self.text_layout_details(cx);
 6933        self.transact(cx, |this, cx| {
 6934            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6935                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 6936                let line_mode = s.line_mode;
 6937                s.move_with(|display_map, selection| {
 6938                    if !selection.is_empty() || line_mode {
 6939                        return;
 6940                    }
 6941
 6942                    let mut head = selection.head();
 6943                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 6944                    if head.column() == display_map.line_len(head.row()) {
 6945                        transpose_offset = display_map
 6946                            .buffer_snapshot
 6947                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6948                    }
 6949
 6950                    if transpose_offset == 0 {
 6951                        return;
 6952                    }
 6953
 6954                    *head.column_mut() += 1;
 6955                    head = display_map.clip_point(head, Bias::Right);
 6956                    let goal = SelectionGoal::HorizontalPosition(
 6957                        display_map
 6958                            .x_for_display_point(head, text_layout_details)
 6959                            .into(),
 6960                    );
 6961                    selection.collapse_to(head, goal);
 6962
 6963                    let transpose_start = display_map
 6964                        .buffer_snapshot
 6965                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6966                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 6967                        let transpose_end = display_map
 6968                            .buffer_snapshot
 6969                            .clip_offset(transpose_offset + 1, Bias::Right);
 6970                        if let Some(ch) =
 6971                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 6972                        {
 6973                            edits.push((transpose_start..transpose_offset, String::new()));
 6974                            edits.push((transpose_end..transpose_end, ch.to_string()));
 6975                        }
 6976                    }
 6977                });
 6978                edits
 6979            });
 6980            this.buffer
 6981                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6982            let selections = this.selections.all::<usize>(cx);
 6983            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6984                s.select(selections);
 6985            });
 6986        });
 6987    }
 6988
 6989    pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
 6990        self.rewrap_impl(true, cx)
 6991    }
 6992
 6993    pub fn rewrap_impl(&mut self, only_text: bool, cx: &mut ViewContext<Self>) {
 6994        let buffer = self.buffer.read(cx).snapshot(cx);
 6995        let selections = self.selections.all::<Point>(cx);
 6996        let mut selections = selections.iter().peekable();
 6997
 6998        let mut edits = Vec::new();
 6999        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 7000
 7001        while let Some(selection) = selections.next() {
 7002            let mut start_row = selection.start.row;
 7003            let mut end_row = selection.end.row;
 7004
 7005            // Skip selections that overlap with a range that has already been rewrapped.
 7006            let selection_range = start_row..end_row;
 7007            if rewrapped_row_ranges
 7008                .iter()
 7009                .any(|range| range.overlaps(&selection_range))
 7010            {
 7011                continue;
 7012            }
 7013
 7014            let mut should_rewrap = !only_text;
 7015
 7016            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 7017                match language_scope.language_name().0.as_ref() {
 7018                    "Markdown" | "Plain Text" => {
 7019                        should_rewrap = true;
 7020                    }
 7021                    _ => {}
 7022                }
 7023            }
 7024
 7025            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 7026
 7027            // Since not all lines in the selection may be at the same indent
 7028            // level, choose the indent size that is the most common between all
 7029            // of the lines.
 7030            //
 7031            // If there is a tie, we use the deepest indent.
 7032            let (indent_size, indent_end) = {
 7033                let mut indent_size_occurrences = HashMap::default();
 7034                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 7035
 7036                for row in start_row..=end_row {
 7037                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 7038                    rows_by_indent_size.entry(indent).or_default().push(row);
 7039                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 7040                }
 7041
 7042                let indent_size = indent_size_occurrences
 7043                    .into_iter()
 7044                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 7045                    .map(|(indent, _)| indent)
 7046                    .unwrap_or_default();
 7047                let row = rows_by_indent_size[&indent_size][0];
 7048                let indent_end = Point::new(row, indent_size.len);
 7049
 7050                (indent_size, indent_end)
 7051            };
 7052
 7053            let mut line_prefix = indent_size.chars().collect::<String>();
 7054
 7055            if let Some(comment_prefix) =
 7056                buffer
 7057                    .language_scope_at(selection.head())
 7058                    .and_then(|language| {
 7059                        language
 7060                            .line_comment_prefixes()
 7061                            .iter()
 7062                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 7063                            .cloned()
 7064                    })
 7065            {
 7066                line_prefix.push_str(&comment_prefix);
 7067                should_rewrap = true;
 7068            }
 7069
 7070            if !should_rewrap {
 7071                continue;
 7072            }
 7073
 7074            if selection.is_empty() {
 7075                'expand_upwards: while start_row > 0 {
 7076                    let prev_row = start_row - 1;
 7077                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 7078                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 7079                    {
 7080                        start_row = prev_row;
 7081                    } else {
 7082                        break 'expand_upwards;
 7083                    }
 7084                }
 7085
 7086                'expand_downwards: while end_row < buffer.max_point().row {
 7087                    let next_row = end_row + 1;
 7088                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 7089                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 7090                    {
 7091                        end_row = next_row;
 7092                    } else {
 7093                        break 'expand_downwards;
 7094                    }
 7095                }
 7096            }
 7097
 7098            let start = Point::new(start_row, 0);
 7099            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 7100            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 7101            let Some(lines_without_prefixes) = selection_text
 7102                .lines()
 7103                .map(|line| {
 7104                    line.strip_prefix(&line_prefix)
 7105                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 7106                        .ok_or_else(|| {
 7107                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 7108                        })
 7109                })
 7110                .collect::<Result<Vec<_>, _>>()
 7111                .log_err()
 7112            else {
 7113                continue;
 7114            };
 7115
 7116            let wrap_column = buffer
 7117                .settings_at(Point::new(start_row, 0), cx)
 7118                .preferred_line_length as usize;
 7119            let wrapped_text = wrap_with_prefix(
 7120                line_prefix,
 7121                lines_without_prefixes.join(" "),
 7122                wrap_column,
 7123                tab_size,
 7124            );
 7125
 7126            let diff = TextDiff::from_lines(&selection_text, &wrapped_text);
 7127            let mut offset = start.to_offset(&buffer);
 7128            let mut moved_since_edit = true;
 7129
 7130            for change in diff.iter_all_changes() {
 7131                let value = change.value();
 7132                match change.tag() {
 7133                    ChangeTag::Equal => {
 7134                        offset += value.len();
 7135                        moved_since_edit = true;
 7136                    }
 7137                    ChangeTag::Delete => {
 7138                        let start = buffer.anchor_after(offset);
 7139                        let end = buffer.anchor_before(offset + value.len());
 7140
 7141                        if moved_since_edit {
 7142                            edits.push((start..end, String::new()));
 7143                        } else {
 7144                            edits.last_mut().unwrap().0.end = end;
 7145                        }
 7146
 7147                        offset += value.len();
 7148                        moved_since_edit = false;
 7149                    }
 7150                    ChangeTag::Insert => {
 7151                        if moved_since_edit {
 7152                            let anchor = buffer.anchor_after(offset);
 7153                            edits.push((anchor..anchor, value.to_string()));
 7154                        } else {
 7155                            edits.last_mut().unwrap().1.push_str(value);
 7156                        }
 7157
 7158                        moved_since_edit = false;
 7159                    }
 7160                }
 7161            }
 7162
 7163            rewrapped_row_ranges.push(start_row..=end_row);
 7164        }
 7165
 7166        self.buffer
 7167            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7168    }
 7169
 7170    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 7171        let mut text = String::new();
 7172        let buffer = self.buffer.read(cx).snapshot(cx);
 7173        let mut selections = self.selections.all::<Point>(cx);
 7174        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7175        {
 7176            let max_point = buffer.max_point();
 7177            let mut is_first = true;
 7178            for selection in &mut selections {
 7179                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7180                if is_entire_line {
 7181                    selection.start = Point::new(selection.start.row, 0);
 7182                    if !selection.is_empty() && selection.end.column == 0 {
 7183                        selection.end = cmp::min(max_point, selection.end);
 7184                    } else {
 7185                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7186                    }
 7187                    selection.goal = SelectionGoal::None;
 7188                }
 7189                if is_first {
 7190                    is_first = false;
 7191                } else {
 7192                    text += "\n";
 7193                }
 7194                let mut len = 0;
 7195                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7196                    text.push_str(chunk);
 7197                    len += chunk.len();
 7198                }
 7199                clipboard_selections.push(ClipboardSelection {
 7200                    len,
 7201                    is_entire_line,
 7202                    first_line_indent: buffer
 7203                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7204                        .len,
 7205                });
 7206            }
 7207        }
 7208
 7209        self.transact(cx, |this, cx| {
 7210            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7211                s.select(selections);
 7212            });
 7213            this.insert("", cx);
 7214            cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7215                text,
 7216                clipboard_selections,
 7217            ));
 7218        });
 7219    }
 7220
 7221    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 7222        let selections = self.selections.all::<Point>(cx);
 7223        let buffer = self.buffer.read(cx).read(cx);
 7224        let mut text = String::new();
 7225
 7226        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7227        {
 7228            let max_point = buffer.max_point();
 7229            let mut is_first = true;
 7230            for selection in selections.iter() {
 7231                let mut start = selection.start;
 7232                let mut end = selection.end;
 7233                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7234                if is_entire_line {
 7235                    start = Point::new(start.row, 0);
 7236                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 7237                }
 7238                if is_first {
 7239                    is_first = false;
 7240                } else {
 7241                    text += "\n";
 7242                }
 7243                let mut len = 0;
 7244                for chunk in buffer.text_for_range(start..end) {
 7245                    text.push_str(chunk);
 7246                    len += chunk.len();
 7247                }
 7248                clipboard_selections.push(ClipboardSelection {
 7249                    len,
 7250                    is_entire_line,
 7251                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 7252                });
 7253            }
 7254        }
 7255
 7256        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7257            text,
 7258            clipboard_selections,
 7259        ));
 7260    }
 7261
 7262    pub fn do_paste(
 7263        &mut self,
 7264        text: &String,
 7265        clipboard_selections: Option<Vec<ClipboardSelection>>,
 7266        handle_entire_lines: bool,
 7267        cx: &mut ViewContext<Self>,
 7268    ) {
 7269        if self.read_only(cx) {
 7270            return;
 7271        }
 7272
 7273        let clipboard_text = Cow::Borrowed(text);
 7274
 7275        self.transact(cx, |this, cx| {
 7276            if let Some(mut clipboard_selections) = clipboard_selections {
 7277                let old_selections = this.selections.all::<usize>(cx);
 7278                let all_selections_were_entire_line =
 7279                    clipboard_selections.iter().all(|s| s.is_entire_line);
 7280                let first_selection_indent_column =
 7281                    clipboard_selections.first().map(|s| s.first_line_indent);
 7282                if clipboard_selections.len() != old_selections.len() {
 7283                    clipboard_selections.drain(..);
 7284                }
 7285                let cursor_offset = this.selections.last::<usize>(cx).head();
 7286                let mut auto_indent_on_paste = true;
 7287
 7288                this.buffer.update(cx, |buffer, cx| {
 7289                    let snapshot = buffer.read(cx);
 7290                    auto_indent_on_paste =
 7291                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 7292
 7293                    let mut start_offset = 0;
 7294                    let mut edits = Vec::new();
 7295                    let mut original_indent_columns = Vec::new();
 7296                    for (ix, selection) in old_selections.iter().enumerate() {
 7297                        let to_insert;
 7298                        let entire_line;
 7299                        let original_indent_column;
 7300                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 7301                            let end_offset = start_offset + clipboard_selection.len;
 7302                            to_insert = &clipboard_text[start_offset..end_offset];
 7303                            entire_line = clipboard_selection.is_entire_line;
 7304                            start_offset = end_offset + 1;
 7305                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7306                        } else {
 7307                            to_insert = clipboard_text.as_str();
 7308                            entire_line = all_selections_were_entire_line;
 7309                            original_indent_column = first_selection_indent_column
 7310                        }
 7311
 7312                        // If the corresponding selection was empty when this slice of the
 7313                        // clipboard text was written, then the entire line containing the
 7314                        // selection was copied. If this selection is also currently empty,
 7315                        // then paste the line before the current line of the buffer.
 7316                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7317                            let column = selection.start.to_point(&snapshot).column as usize;
 7318                            let line_start = selection.start - column;
 7319                            line_start..line_start
 7320                        } else {
 7321                            selection.range()
 7322                        };
 7323
 7324                        edits.push((range, to_insert));
 7325                        original_indent_columns.extend(original_indent_column);
 7326                    }
 7327                    drop(snapshot);
 7328
 7329                    buffer.edit(
 7330                        edits,
 7331                        if auto_indent_on_paste {
 7332                            Some(AutoindentMode::Block {
 7333                                original_indent_columns,
 7334                            })
 7335                        } else {
 7336                            None
 7337                        },
 7338                        cx,
 7339                    );
 7340                });
 7341
 7342                let selections = this.selections.all::<usize>(cx);
 7343                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 7344            } else {
 7345                this.insert(&clipboard_text, cx);
 7346            }
 7347        });
 7348    }
 7349
 7350    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 7351        if let Some(item) = cx.read_from_clipboard() {
 7352            let entries = item.entries();
 7353
 7354            match entries.first() {
 7355                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7356                // of all the pasted entries.
 7357                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7358                    .do_paste(
 7359                        clipboard_string.text(),
 7360                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7361                        true,
 7362                        cx,
 7363                    ),
 7364                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
 7365            }
 7366        }
 7367    }
 7368
 7369    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 7370        if self.read_only(cx) {
 7371            return;
 7372        }
 7373
 7374        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7375            if let Some((selections, _)) =
 7376                self.selection_history.transaction(transaction_id).cloned()
 7377            {
 7378                self.change_selections(None, cx, |s| {
 7379                    s.select_anchors(selections.to_vec());
 7380                });
 7381            }
 7382            self.request_autoscroll(Autoscroll::fit(), cx);
 7383            self.unmark_text(cx);
 7384            self.refresh_inline_completion(true, false, cx);
 7385            cx.emit(EditorEvent::Edited { transaction_id });
 7386            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7387        }
 7388    }
 7389
 7390    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 7391        if self.read_only(cx) {
 7392            return;
 7393        }
 7394
 7395        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7396            if let Some((_, Some(selections))) =
 7397                self.selection_history.transaction(transaction_id).cloned()
 7398            {
 7399                self.change_selections(None, cx, |s| {
 7400                    s.select_anchors(selections.to_vec());
 7401                });
 7402            }
 7403            self.request_autoscroll(Autoscroll::fit(), cx);
 7404            self.unmark_text(cx);
 7405            self.refresh_inline_completion(true, false, cx);
 7406            cx.emit(EditorEvent::Edited { transaction_id });
 7407        }
 7408    }
 7409
 7410    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 7411        self.buffer
 7412            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7413    }
 7414
 7415    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 7416        self.buffer
 7417            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7418    }
 7419
 7420    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 7421        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7422            let line_mode = s.line_mode;
 7423            s.move_with(|map, selection| {
 7424                let cursor = if selection.is_empty() && !line_mode {
 7425                    movement::left(map, selection.start)
 7426                } else {
 7427                    selection.start
 7428                };
 7429                selection.collapse_to(cursor, SelectionGoal::None);
 7430            });
 7431        })
 7432    }
 7433
 7434    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 7435        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7436            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7437        })
 7438    }
 7439
 7440    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 7441        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7442            let line_mode = s.line_mode;
 7443            s.move_with(|map, selection| {
 7444                let cursor = if selection.is_empty() && !line_mode {
 7445                    movement::right(map, selection.end)
 7446                } else {
 7447                    selection.end
 7448                };
 7449                selection.collapse_to(cursor, SelectionGoal::None)
 7450            });
 7451        })
 7452    }
 7453
 7454    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 7455        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7456            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7457        })
 7458    }
 7459
 7460    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 7461        if self.take_rename(true, cx).is_some() {
 7462            return;
 7463        }
 7464
 7465        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7466            cx.propagate();
 7467            return;
 7468        }
 7469
 7470        let text_layout_details = &self.text_layout_details(cx);
 7471        let selection_count = self.selections.count();
 7472        let first_selection = self.selections.first_anchor();
 7473
 7474        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7475            let line_mode = s.line_mode;
 7476            s.move_with(|map, selection| {
 7477                if !selection.is_empty() && !line_mode {
 7478                    selection.goal = SelectionGoal::None;
 7479                }
 7480                let (cursor, goal) = movement::up(
 7481                    map,
 7482                    selection.start,
 7483                    selection.goal,
 7484                    false,
 7485                    text_layout_details,
 7486                );
 7487                selection.collapse_to(cursor, goal);
 7488            });
 7489        });
 7490
 7491        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7492        {
 7493            cx.propagate();
 7494        }
 7495    }
 7496
 7497    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 7498        if self.take_rename(true, cx).is_some() {
 7499            return;
 7500        }
 7501
 7502        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7503            cx.propagate();
 7504            return;
 7505        }
 7506
 7507        let text_layout_details = &self.text_layout_details(cx);
 7508
 7509        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7510            let line_mode = s.line_mode;
 7511            s.move_with(|map, selection| {
 7512                if !selection.is_empty() && !line_mode {
 7513                    selection.goal = SelectionGoal::None;
 7514                }
 7515                let (cursor, goal) = movement::up_by_rows(
 7516                    map,
 7517                    selection.start,
 7518                    action.lines,
 7519                    selection.goal,
 7520                    false,
 7521                    text_layout_details,
 7522                );
 7523                selection.collapse_to(cursor, goal);
 7524            });
 7525        })
 7526    }
 7527
 7528    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 7529        if self.take_rename(true, cx).is_some() {
 7530            return;
 7531        }
 7532
 7533        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7534            cx.propagate();
 7535            return;
 7536        }
 7537
 7538        let text_layout_details = &self.text_layout_details(cx);
 7539
 7540        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7541            let line_mode = s.line_mode;
 7542            s.move_with(|map, selection| {
 7543                if !selection.is_empty() && !line_mode {
 7544                    selection.goal = SelectionGoal::None;
 7545                }
 7546                let (cursor, goal) = movement::down_by_rows(
 7547                    map,
 7548                    selection.start,
 7549                    action.lines,
 7550                    selection.goal,
 7551                    false,
 7552                    text_layout_details,
 7553                );
 7554                selection.collapse_to(cursor, goal);
 7555            });
 7556        })
 7557    }
 7558
 7559    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 7560        let text_layout_details = &self.text_layout_details(cx);
 7561        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7562            s.move_heads_with(|map, head, goal| {
 7563                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7564            })
 7565        })
 7566    }
 7567
 7568    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 7569        let text_layout_details = &self.text_layout_details(cx);
 7570        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7571            s.move_heads_with(|map, head, goal| {
 7572                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7573            })
 7574        })
 7575    }
 7576
 7577    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 7578        let Some(row_count) = self.visible_row_count() else {
 7579            return;
 7580        };
 7581
 7582        let text_layout_details = &self.text_layout_details(cx);
 7583
 7584        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7585            s.move_heads_with(|map, head, goal| {
 7586                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7587            })
 7588        })
 7589    }
 7590
 7591    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 7592        if self.take_rename(true, cx).is_some() {
 7593            return;
 7594        }
 7595
 7596        if self
 7597            .context_menu
 7598            .write()
 7599            .as_mut()
 7600            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 7601            .unwrap_or(false)
 7602        {
 7603            return;
 7604        }
 7605
 7606        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7607            cx.propagate();
 7608            return;
 7609        }
 7610
 7611        let Some(row_count) = self.visible_row_count() else {
 7612            return;
 7613        };
 7614
 7615        let autoscroll = if action.center_cursor {
 7616            Autoscroll::center()
 7617        } else {
 7618            Autoscroll::fit()
 7619        };
 7620
 7621        let text_layout_details = &self.text_layout_details(cx);
 7622
 7623        self.change_selections(Some(autoscroll), cx, |s| {
 7624            let line_mode = s.line_mode;
 7625            s.move_with(|map, selection| {
 7626                if !selection.is_empty() && !line_mode {
 7627                    selection.goal = SelectionGoal::None;
 7628                }
 7629                let (cursor, goal) = movement::up_by_rows(
 7630                    map,
 7631                    selection.end,
 7632                    row_count,
 7633                    selection.goal,
 7634                    false,
 7635                    text_layout_details,
 7636                );
 7637                selection.collapse_to(cursor, goal);
 7638            });
 7639        });
 7640    }
 7641
 7642    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 7643        let text_layout_details = &self.text_layout_details(cx);
 7644        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7645            s.move_heads_with(|map, head, goal| {
 7646                movement::up(map, head, goal, false, text_layout_details)
 7647            })
 7648        })
 7649    }
 7650
 7651    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 7652        self.take_rename(true, cx);
 7653
 7654        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7655            cx.propagate();
 7656            return;
 7657        }
 7658
 7659        let text_layout_details = &self.text_layout_details(cx);
 7660        let selection_count = self.selections.count();
 7661        let first_selection = self.selections.first_anchor();
 7662
 7663        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7664            let line_mode = s.line_mode;
 7665            s.move_with(|map, selection| {
 7666                if !selection.is_empty() && !line_mode {
 7667                    selection.goal = SelectionGoal::None;
 7668                }
 7669                let (cursor, goal) = movement::down(
 7670                    map,
 7671                    selection.end,
 7672                    selection.goal,
 7673                    false,
 7674                    text_layout_details,
 7675                );
 7676                selection.collapse_to(cursor, goal);
 7677            });
 7678        });
 7679
 7680        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7681        {
 7682            cx.propagate();
 7683        }
 7684    }
 7685
 7686    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 7687        let Some(row_count) = self.visible_row_count() else {
 7688            return;
 7689        };
 7690
 7691        let text_layout_details = &self.text_layout_details(cx);
 7692
 7693        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7694            s.move_heads_with(|map, head, goal| {
 7695                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 7696            })
 7697        })
 7698    }
 7699
 7700    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 7701        if self.take_rename(true, cx).is_some() {
 7702            return;
 7703        }
 7704
 7705        if self
 7706            .context_menu
 7707            .write()
 7708            .as_mut()
 7709            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 7710            .unwrap_or(false)
 7711        {
 7712            return;
 7713        }
 7714
 7715        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7716            cx.propagate();
 7717            return;
 7718        }
 7719
 7720        let Some(row_count) = self.visible_row_count() else {
 7721            return;
 7722        };
 7723
 7724        let autoscroll = if action.center_cursor {
 7725            Autoscroll::center()
 7726        } else {
 7727            Autoscroll::fit()
 7728        };
 7729
 7730        let text_layout_details = &self.text_layout_details(cx);
 7731        self.change_selections(Some(autoscroll), cx, |s| {
 7732            let line_mode = s.line_mode;
 7733            s.move_with(|map, selection| {
 7734                if !selection.is_empty() && !line_mode {
 7735                    selection.goal = SelectionGoal::None;
 7736                }
 7737                let (cursor, goal) = movement::down_by_rows(
 7738                    map,
 7739                    selection.end,
 7740                    row_count,
 7741                    selection.goal,
 7742                    false,
 7743                    text_layout_details,
 7744                );
 7745                selection.collapse_to(cursor, goal);
 7746            });
 7747        });
 7748    }
 7749
 7750    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 7751        let text_layout_details = &self.text_layout_details(cx);
 7752        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7753            s.move_heads_with(|map, head, goal| {
 7754                movement::down(map, head, goal, false, text_layout_details)
 7755            })
 7756        });
 7757    }
 7758
 7759    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 7760        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7761            context_menu.select_first(self.completion_provider.as_deref(), cx);
 7762        }
 7763    }
 7764
 7765    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 7766        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7767            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 7768        }
 7769    }
 7770
 7771    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7772        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7773            context_menu.select_next(self.completion_provider.as_deref(), cx);
 7774        }
 7775    }
 7776
 7777    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 7778        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7779            context_menu.select_last(self.completion_provider.as_deref(), cx);
 7780        }
 7781    }
 7782
 7783    pub fn move_to_previous_word_start(
 7784        &mut self,
 7785        _: &MoveToPreviousWordStart,
 7786        cx: &mut ViewContext<Self>,
 7787    ) {
 7788        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7789            s.move_cursors_with(|map, head, _| {
 7790                (
 7791                    movement::previous_word_start(map, head),
 7792                    SelectionGoal::None,
 7793                )
 7794            });
 7795        })
 7796    }
 7797
 7798    pub fn move_to_previous_subword_start(
 7799        &mut self,
 7800        _: &MoveToPreviousSubwordStart,
 7801        cx: &mut ViewContext<Self>,
 7802    ) {
 7803        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7804            s.move_cursors_with(|map, head, _| {
 7805                (
 7806                    movement::previous_subword_start(map, head),
 7807                    SelectionGoal::None,
 7808                )
 7809            });
 7810        })
 7811    }
 7812
 7813    pub fn select_to_previous_word_start(
 7814        &mut self,
 7815        _: &SelectToPreviousWordStart,
 7816        cx: &mut ViewContext<Self>,
 7817    ) {
 7818        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7819            s.move_heads_with(|map, head, _| {
 7820                (
 7821                    movement::previous_word_start(map, head),
 7822                    SelectionGoal::None,
 7823                )
 7824            });
 7825        })
 7826    }
 7827
 7828    pub fn select_to_previous_subword_start(
 7829        &mut self,
 7830        _: &SelectToPreviousSubwordStart,
 7831        cx: &mut ViewContext<Self>,
 7832    ) {
 7833        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7834            s.move_heads_with(|map, head, _| {
 7835                (
 7836                    movement::previous_subword_start(map, head),
 7837                    SelectionGoal::None,
 7838                )
 7839            });
 7840        })
 7841    }
 7842
 7843    pub fn delete_to_previous_word_start(
 7844        &mut self,
 7845        action: &DeleteToPreviousWordStart,
 7846        cx: &mut ViewContext<Self>,
 7847    ) {
 7848        self.transact(cx, |this, cx| {
 7849            this.select_autoclose_pair(cx);
 7850            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7851                let line_mode = s.line_mode;
 7852                s.move_with(|map, selection| {
 7853                    if selection.is_empty() && !line_mode {
 7854                        let cursor = if action.ignore_newlines {
 7855                            movement::previous_word_start(map, selection.head())
 7856                        } else {
 7857                            movement::previous_word_start_or_newline(map, selection.head())
 7858                        };
 7859                        selection.set_head(cursor, SelectionGoal::None);
 7860                    }
 7861                });
 7862            });
 7863            this.insert("", cx);
 7864        });
 7865    }
 7866
 7867    pub fn delete_to_previous_subword_start(
 7868        &mut self,
 7869        _: &DeleteToPreviousSubwordStart,
 7870        cx: &mut ViewContext<Self>,
 7871    ) {
 7872        self.transact(cx, |this, cx| {
 7873            this.select_autoclose_pair(cx);
 7874            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7875                let line_mode = s.line_mode;
 7876                s.move_with(|map, selection| {
 7877                    if selection.is_empty() && !line_mode {
 7878                        let cursor = movement::previous_subword_start(map, selection.head());
 7879                        selection.set_head(cursor, SelectionGoal::None);
 7880                    }
 7881                });
 7882            });
 7883            this.insert("", cx);
 7884        });
 7885    }
 7886
 7887    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 7888        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7889            s.move_cursors_with(|map, head, _| {
 7890                (movement::next_word_end(map, head), SelectionGoal::None)
 7891            });
 7892        })
 7893    }
 7894
 7895    pub fn move_to_next_subword_end(
 7896        &mut self,
 7897        _: &MoveToNextSubwordEnd,
 7898        cx: &mut ViewContext<Self>,
 7899    ) {
 7900        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7901            s.move_cursors_with(|map, head, _| {
 7902                (movement::next_subword_end(map, head), SelectionGoal::None)
 7903            });
 7904        })
 7905    }
 7906
 7907    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 7908        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7909            s.move_heads_with(|map, head, _| {
 7910                (movement::next_word_end(map, head), SelectionGoal::None)
 7911            });
 7912        })
 7913    }
 7914
 7915    pub fn select_to_next_subword_end(
 7916        &mut self,
 7917        _: &SelectToNextSubwordEnd,
 7918        cx: &mut ViewContext<Self>,
 7919    ) {
 7920        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7921            s.move_heads_with(|map, head, _| {
 7922                (movement::next_subword_end(map, head), SelectionGoal::None)
 7923            });
 7924        })
 7925    }
 7926
 7927    pub fn delete_to_next_word_end(
 7928        &mut self,
 7929        action: &DeleteToNextWordEnd,
 7930        cx: &mut ViewContext<Self>,
 7931    ) {
 7932        self.transact(cx, |this, cx| {
 7933            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7934                let line_mode = s.line_mode;
 7935                s.move_with(|map, selection| {
 7936                    if selection.is_empty() && !line_mode {
 7937                        let cursor = if action.ignore_newlines {
 7938                            movement::next_word_end(map, selection.head())
 7939                        } else {
 7940                            movement::next_word_end_or_newline(map, selection.head())
 7941                        };
 7942                        selection.set_head(cursor, SelectionGoal::None);
 7943                    }
 7944                });
 7945            });
 7946            this.insert("", cx);
 7947        });
 7948    }
 7949
 7950    pub fn delete_to_next_subword_end(
 7951        &mut self,
 7952        _: &DeleteToNextSubwordEnd,
 7953        cx: &mut ViewContext<Self>,
 7954    ) {
 7955        self.transact(cx, |this, cx| {
 7956            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7957                s.move_with(|map, selection| {
 7958                    if selection.is_empty() {
 7959                        let cursor = movement::next_subword_end(map, selection.head());
 7960                        selection.set_head(cursor, SelectionGoal::None);
 7961                    }
 7962                });
 7963            });
 7964            this.insert("", cx);
 7965        });
 7966    }
 7967
 7968    pub fn move_to_beginning_of_line(
 7969        &mut self,
 7970        action: &MoveToBeginningOfLine,
 7971        cx: &mut ViewContext<Self>,
 7972    ) {
 7973        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7974            s.move_cursors_with(|map, head, _| {
 7975                (
 7976                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7977                    SelectionGoal::None,
 7978                )
 7979            });
 7980        })
 7981    }
 7982
 7983    pub fn select_to_beginning_of_line(
 7984        &mut self,
 7985        action: &SelectToBeginningOfLine,
 7986        cx: &mut ViewContext<Self>,
 7987    ) {
 7988        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7989            s.move_heads_with(|map, head, _| {
 7990                (
 7991                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7992                    SelectionGoal::None,
 7993                )
 7994            });
 7995        });
 7996    }
 7997
 7998    pub fn delete_to_beginning_of_line(
 7999        &mut self,
 8000        _: &DeleteToBeginningOfLine,
 8001        cx: &mut ViewContext<Self>,
 8002    ) {
 8003        self.transact(cx, |this, cx| {
 8004            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8005                s.move_with(|_, selection| {
 8006                    selection.reversed = true;
 8007                });
 8008            });
 8009
 8010            this.select_to_beginning_of_line(
 8011                &SelectToBeginningOfLine {
 8012                    stop_at_soft_wraps: false,
 8013                },
 8014                cx,
 8015            );
 8016            this.backspace(&Backspace, cx);
 8017        });
 8018    }
 8019
 8020    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 8021        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8022            s.move_cursors_with(|map, head, _| {
 8023                (
 8024                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8025                    SelectionGoal::None,
 8026                )
 8027            });
 8028        })
 8029    }
 8030
 8031    pub fn select_to_end_of_line(
 8032        &mut self,
 8033        action: &SelectToEndOfLine,
 8034        cx: &mut ViewContext<Self>,
 8035    ) {
 8036        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8037            s.move_heads_with(|map, head, _| {
 8038                (
 8039                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8040                    SelectionGoal::None,
 8041                )
 8042            });
 8043        })
 8044    }
 8045
 8046    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 8047        self.transact(cx, |this, cx| {
 8048            this.select_to_end_of_line(
 8049                &SelectToEndOfLine {
 8050                    stop_at_soft_wraps: false,
 8051                },
 8052                cx,
 8053            );
 8054            this.delete(&Delete, cx);
 8055        });
 8056    }
 8057
 8058    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 8059        self.transact(cx, |this, cx| {
 8060            this.select_to_end_of_line(
 8061                &SelectToEndOfLine {
 8062                    stop_at_soft_wraps: false,
 8063                },
 8064                cx,
 8065            );
 8066            this.cut(&Cut, cx);
 8067        });
 8068    }
 8069
 8070    pub fn move_to_start_of_paragraph(
 8071        &mut self,
 8072        _: &MoveToStartOfParagraph,
 8073        cx: &mut ViewContext<Self>,
 8074    ) {
 8075        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8076            cx.propagate();
 8077            return;
 8078        }
 8079
 8080        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8081            s.move_with(|map, selection| {
 8082                selection.collapse_to(
 8083                    movement::start_of_paragraph(map, selection.head(), 1),
 8084                    SelectionGoal::None,
 8085                )
 8086            });
 8087        })
 8088    }
 8089
 8090    pub fn move_to_end_of_paragraph(
 8091        &mut self,
 8092        _: &MoveToEndOfParagraph,
 8093        cx: &mut ViewContext<Self>,
 8094    ) {
 8095        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8096            cx.propagate();
 8097            return;
 8098        }
 8099
 8100        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8101            s.move_with(|map, selection| {
 8102                selection.collapse_to(
 8103                    movement::end_of_paragraph(map, selection.head(), 1),
 8104                    SelectionGoal::None,
 8105                )
 8106            });
 8107        })
 8108    }
 8109
 8110    pub fn select_to_start_of_paragraph(
 8111        &mut self,
 8112        _: &SelectToStartOfParagraph,
 8113        cx: &mut ViewContext<Self>,
 8114    ) {
 8115        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8116            cx.propagate();
 8117            return;
 8118        }
 8119
 8120        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8121            s.move_heads_with(|map, head, _| {
 8122                (
 8123                    movement::start_of_paragraph(map, head, 1),
 8124                    SelectionGoal::None,
 8125                )
 8126            });
 8127        })
 8128    }
 8129
 8130    pub fn select_to_end_of_paragraph(
 8131        &mut self,
 8132        _: &SelectToEndOfParagraph,
 8133        cx: &mut ViewContext<Self>,
 8134    ) {
 8135        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8136            cx.propagate();
 8137            return;
 8138        }
 8139
 8140        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8141            s.move_heads_with(|map, head, _| {
 8142                (
 8143                    movement::end_of_paragraph(map, head, 1),
 8144                    SelectionGoal::None,
 8145                )
 8146            });
 8147        })
 8148    }
 8149
 8150    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 8151        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8152            cx.propagate();
 8153            return;
 8154        }
 8155
 8156        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8157            s.select_ranges(vec![0..0]);
 8158        });
 8159    }
 8160
 8161    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 8162        let mut selection = self.selections.last::<Point>(cx);
 8163        selection.set_head(Point::zero(), SelectionGoal::None);
 8164
 8165        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8166            s.select(vec![selection]);
 8167        });
 8168    }
 8169
 8170    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 8171        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8172            cx.propagate();
 8173            return;
 8174        }
 8175
 8176        let cursor = self.buffer.read(cx).read(cx).len();
 8177        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8178            s.select_ranges(vec![cursor..cursor])
 8179        });
 8180    }
 8181
 8182    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 8183        self.nav_history = nav_history;
 8184    }
 8185
 8186    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 8187        self.nav_history.as_ref()
 8188    }
 8189
 8190    fn push_to_nav_history(
 8191        &mut self,
 8192        cursor_anchor: Anchor,
 8193        new_position: Option<Point>,
 8194        cx: &mut ViewContext<Self>,
 8195    ) {
 8196        if let Some(nav_history) = self.nav_history.as_mut() {
 8197            let buffer = self.buffer.read(cx).read(cx);
 8198            let cursor_position = cursor_anchor.to_point(&buffer);
 8199            let scroll_state = self.scroll_manager.anchor();
 8200            let scroll_top_row = scroll_state.top_row(&buffer);
 8201            drop(buffer);
 8202
 8203            if let Some(new_position) = new_position {
 8204                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 8205                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 8206                    return;
 8207                }
 8208            }
 8209
 8210            nav_history.push(
 8211                Some(NavigationData {
 8212                    cursor_anchor,
 8213                    cursor_position,
 8214                    scroll_anchor: scroll_state,
 8215                    scroll_top_row,
 8216                }),
 8217                cx,
 8218            );
 8219        }
 8220    }
 8221
 8222    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 8223        let buffer = self.buffer.read(cx).snapshot(cx);
 8224        let mut selection = self.selections.first::<usize>(cx);
 8225        selection.set_head(buffer.len(), SelectionGoal::None);
 8226        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8227            s.select(vec![selection]);
 8228        });
 8229    }
 8230
 8231    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 8232        let end = self.buffer.read(cx).read(cx).len();
 8233        self.change_selections(None, cx, |s| {
 8234            s.select_ranges(vec![0..end]);
 8235        });
 8236    }
 8237
 8238    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 8239        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8240        let mut selections = self.selections.all::<Point>(cx);
 8241        let max_point = display_map.buffer_snapshot.max_point();
 8242        for selection in &mut selections {
 8243            let rows = selection.spanned_rows(true, &display_map);
 8244            selection.start = Point::new(rows.start.0, 0);
 8245            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 8246            selection.reversed = false;
 8247        }
 8248        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8249            s.select(selections);
 8250        });
 8251    }
 8252
 8253    pub fn split_selection_into_lines(
 8254        &mut self,
 8255        _: &SplitSelectionIntoLines,
 8256        cx: &mut ViewContext<Self>,
 8257    ) {
 8258        let mut to_unfold = Vec::new();
 8259        let mut new_selection_ranges = Vec::new();
 8260        {
 8261            let selections = self.selections.all::<Point>(cx);
 8262            let buffer = self.buffer.read(cx).read(cx);
 8263            for selection in selections {
 8264                for row in selection.start.row..selection.end.row {
 8265                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 8266                    new_selection_ranges.push(cursor..cursor);
 8267                }
 8268                new_selection_ranges.push(selection.end..selection.end);
 8269                to_unfold.push(selection.start..selection.end);
 8270            }
 8271        }
 8272        self.unfold_ranges(&to_unfold, true, true, cx);
 8273        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8274            s.select_ranges(new_selection_ranges);
 8275        });
 8276    }
 8277
 8278    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 8279        self.add_selection(true, cx);
 8280    }
 8281
 8282    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 8283        self.add_selection(false, cx);
 8284    }
 8285
 8286    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 8287        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8288        let mut selections = self.selections.all::<Point>(cx);
 8289        let text_layout_details = self.text_layout_details(cx);
 8290        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 8291            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 8292            let range = oldest_selection.display_range(&display_map).sorted();
 8293
 8294            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 8295            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 8296            let positions = start_x.min(end_x)..start_x.max(end_x);
 8297
 8298            selections.clear();
 8299            let mut stack = Vec::new();
 8300            for row in range.start.row().0..=range.end.row().0 {
 8301                if let Some(selection) = self.selections.build_columnar_selection(
 8302                    &display_map,
 8303                    DisplayRow(row),
 8304                    &positions,
 8305                    oldest_selection.reversed,
 8306                    &text_layout_details,
 8307                ) {
 8308                    stack.push(selection.id);
 8309                    selections.push(selection);
 8310                }
 8311            }
 8312
 8313            if above {
 8314                stack.reverse();
 8315            }
 8316
 8317            AddSelectionsState { above, stack }
 8318        });
 8319
 8320        let last_added_selection = *state.stack.last().unwrap();
 8321        let mut new_selections = Vec::new();
 8322        if above == state.above {
 8323            let end_row = if above {
 8324                DisplayRow(0)
 8325            } else {
 8326                display_map.max_point().row()
 8327            };
 8328
 8329            'outer: for selection in selections {
 8330                if selection.id == last_added_selection {
 8331                    let range = selection.display_range(&display_map).sorted();
 8332                    debug_assert_eq!(range.start.row(), range.end.row());
 8333                    let mut row = range.start.row();
 8334                    let positions =
 8335                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 8336                            px(start)..px(end)
 8337                        } else {
 8338                            let start_x =
 8339                                display_map.x_for_display_point(range.start, &text_layout_details);
 8340                            let end_x =
 8341                                display_map.x_for_display_point(range.end, &text_layout_details);
 8342                            start_x.min(end_x)..start_x.max(end_x)
 8343                        };
 8344
 8345                    while row != end_row {
 8346                        if above {
 8347                            row.0 -= 1;
 8348                        } else {
 8349                            row.0 += 1;
 8350                        }
 8351
 8352                        if let Some(new_selection) = self.selections.build_columnar_selection(
 8353                            &display_map,
 8354                            row,
 8355                            &positions,
 8356                            selection.reversed,
 8357                            &text_layout_details,
 8358                        ) {
 8359                            state.stack.push(new_selection.id);
 8360                            if above {
 8361                                new_selections.push(new_selection);
 8362                                new_selections.push(selection);
 8363                            } else {
 8364                                new_selections.push(selection);
 8365                                new_selections.push(new_selection);
 8366                            }
 8367
 8368                            continue 'outer;
 8369                        }
 8370                    }
 8371                }
 8372
 8373                new_selections.push(selection);
 8374            }
 8375        } else {
 8376            new_selections = selections;
 8377            new_selections.retain(|s| s.id != last_added_selection);
 8378            state.stack.pop();
 8379        }
 8380
 8381        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8382            s.select(new_selections);
 8383        });
 8384        if state.stack.len() > 1 {
 8385            self.add_selections_state = Some(state);
 8386        }
 8387    }
 8388
 8389    pub fn select_next_match_internal(
 8390        &mut self,
 8391        display_map: &DisplaySnapshot,
 8392        replace_newest: bool,
 8393        autoscroll: Option<Autoscroll>,
 8394        cx: &mut ViewContext<Self>,
 8395    ) -> Result<()> {
 8396        fn select_next_match_ranges(
 8397            this: &mut Editor,
 8398            range: Range<usize>,
 8399            replace_newest: bool,
 8400            auto_scroll: Option<Autoscroll>,
 8401            cx: &mut ViewContext<Editor>,
 8402        ) {
 8403            this.unfold_ranges(&[range.clone()], false, true, cx);
 8404            this.change_selections(auto_scroll, cx, |s| {
 8405                if replace_newest {
 8406                    s.delete(s.newest_anchor().id);
 8407                }
 8408                s.insert_range(range.clone());
 8409            });
 8410        }
 8411
 8412        let buffer = &display_map.buffer_snapshot;
 8413        let mut selections = self.selections.all::<usize>(cx);
 8414        if let Some(mut select_next_state) = self.select_next_state.take() {
 8415            let query = &select_next_state.query;
 8416            if !select_next_state.done {
 8417                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8418                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8419                let mut next_selected_range = None;
 8420
 8421                let bytes_after_last_selection =
 8422                    buffer.bytes_in_range(last_selection.end..buffer.len());
 8423                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 8424                let query_matches = query
 8425                    .stream_find_iter(bytes_after_last_selection)
 8426                    .map(|result| (last_selection.end, result))
 8427                    .chain(
 8428                        query
 8429                            .stream_find_iter(bytes_before_first_selection)
 8430                            .map(|result| (0, result)),
 8431                    );
 8432
 8433                for (start_offset, query_match) in query_matches {
 8434                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8435                    let offset_range =
 8436                        start_offset + query_match.start()..start_offset + query_match.end();
 8437                    let display_range = offset_range.start.to_display_point(display_map)
 8438                        ..offset_range.end.to_display_point(display_map);
 8439
 8440                    if !select_next_state.wordwise
 8441                        || (!movement::is_inside_word(display_map, display_range.start)
 8442                            && !movement::is_inside_word(display_map, display_range.end))
 8443                    {
 8444                        // TODO: This is n^2, because we might check all the selections
 8445                        if !selections
 8446                            .iter()
 8447                            .any(|selection| selection.range().overlaps(&offset_range))
 8448                        {
 8449                            next_selected_range = Some(offset_range);
 8450                            break;
 8451                        }
 8452                    }
 8453                }
 8454
 8455                if let Some(next_selected_range) = next_selected_range {
 8456                    select_next_match_ranges(
 8457                        self,
 8458                        next_selected_range,
 8459                        replace_newest,
 8460                        autoscroll,
 8461                        cx,
 8462                    );
 8463                } else {
 8464                    select_next_state.done = true;
 8465                }
 8466            }
 8467
 8468            self.select_next_state = Some(select_next_state);
 8469        } else {
 8470            let mut only_carets = true;
 8471            let mut same_text_selected = true;
 8472            let mut selected_text = None;
 8473
 8474            let mut selections_iter = selections.iter().peekable();
 8475            while let Some(selection) = selections_iter.next() {
 8476                if selection.start != selection.end {
 8477                    only_carets = false;
 8478                }
 8479
 8480                if same_text_selected {
 8481                    if selected_text.is_none() {
 8482                        selected_text =
 8483                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8484                    }
 8485
 8486                    if let Some(next_selection) = selections_iter.peek() {
 8487                        if next_selection.range().len() == selection.range().len() {
 8488                            let next_selected_text = buffer
 8489                                .text_for_range(next_selection.range())
 8490                                .collect::<String>();
 8491                            if Some(next_selected_text) != selected_text {
 8492                                same_text_selected = false;
 8493                                selected_text = None;
 8494                            }
 8495                        } else {
 8496                            same_text_selected = false;
 8497                            selected_text = None;
 8498                        }
 8499                    }
 8500                }
 8501            }
 8502
 8503            if only_carets {
 8504                for selection in &mut selections {
 8505                    let word_range = movement::surrounding_word(
 8506                        display_map,
 8507                        selection.start.to_display_point(display_map),
 8508                    );
 8509                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 8510                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 8511                    selection.goal = SelectionGoal::None;
 8512                    selection.reversed = false;
 8513                    select_next_match_ranges(
 8514                        self,
 8515                        selection.start..selection.end,
 8516                        replace_newest,
 8517                        autoscroll,
 8518                        cx,
 8519                    );
 8520                }
 8521
 8522                if selections.len() == 1 {
 8523                    let selection = selections
 8524                        .last()
 8525                        .expect("ensured that there's only one selection");
 8526                    let query = buffer
 8527                        .text_for_range(selection.start..selection.end)
 8528                        .collect::<String>();
 8529                    let is_empty = query.is_empty();
 8530                    let select_state = SelectNextState {
 8531                        query: AhoCorasick::new(&[query])?,
 8532                        wordwise: true,
 8533                        done: is_empty,
 8534                    };
 8535                    self.select_next_state = Some(select_state);
 8536                } else {
 8537                    self.select_next_state = None;
 8538                }
 8539            } else if let Some(selected_text) = selected_text {
 8540                self.select_next_state = Some(SelectNextState {
 8541                    query: AhoCorasick::new(&[selected_text])?,
 8542                    wordwise: false,
 8543                    done: false,
 8544                });
 8545                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 8546            }
 8547        }
 8548        Ok(())
 8549    }
 8550
 8551    pub fn select_all_matches(
 8552        &mut self,
 8553        _action: &SelectAllMatches,
 8554        cx: &mut ViewContext<Self>,
 8555    ) -> Result<()> {
 8556        self.push_to_selection_history();
 8557        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8558
 8559        self.select_next_match_internal(&display_map, false, None, cx)?;
 8560        let Some(select_next_state) = self.select_next_state.as_mut() else {
 8561            return Ok(());
 8562        };
 8563        if select_next_state.done {
 8564            return Ok(());
 8565        }
 8566
 8567        let mut new_selections = self.selections.all::<usize>(cx);
 8568
 8569        let buffer = &display_map.buffer_snapshot;
 8570        let query_matches = select_next_state
 8571            .query
 8572            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 8573
 8574        for query_match in query_matches {
 8575            let query_match = query_match.unwrap(); // can only fail due to I/O
 8576            let offset_range = query_match.start()..query_match.end();
 8577            let display_range = offset_range.start.to_display_point(&display_map)
 8578                ..offset_range.end.to_display_point(&display_map);
 8579
 8580            if !select_next_state.wordwise
 8581                || (!movement::is_inside_word(&display_map, display_range.start)
 8582                    && !movement::is_inside_word(&display_map, display_range.end))
 8583            {
 8584                self.selections.change_with(cx, |selections| {
 8585                    new_selections.push(Selection {
 8586                        id: selections.new_selection_id(),
 8587                        start: offset_range.start,
 8588                        end: offset_range.end,
 8589                        reversed: false,
 8590                        goal: SelectionGoal::None,
 8591                    });
 8592                });
 8593            }
 8594        }
 8595
 8596        new_selections.sort_by_key(|selection| selection.start);
 8597        let mut ix = 0;
 8598        while ix + 1 < new_selections.len() {
 8599            let current_selection = &new_selections[ix];
 8600            let next_selection = &new_selections[ix + 1];
 8601            if current_selection.range().overlaps(&next_selection.range()) {
 8602                if current_selection.id < next_selection.id {
 8603                    new_selections.remove(ix + 1);
 8604                } else {
 8605                    new_selections.remove(ix);
 8606                }
 8607            } else {
 8608                ix += 1;
 8609            }
 8610        }
 8611
 8612        select_next_state.done = true;
 8613        self.unfold_ranges(
 8614            &new_selections
 8615                .iter()
 8616                .map(|selection| selection.range())
 8617                .collect::<Vec<_>>(),
 8618            false,
 8619            false,
 8620            cx,
 8621        );
 8622        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 8623            selections.select(new_selections)
 8624        });
 8625
 8626        Ok(())
 8627    }
 8628
 8629    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 8630        self.push_to_selection_history();
 8631        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8632        self.select_next_match_internal(
 8633            &display_map,
 8634            action.replace_newest,
 8635            Some(Autoscroll::newest()),
 8636            cx,
 8637        )?;
 8638        Ok(())
 8639    }
 8640
 8641    pub fn select_previous(
 8642        &mut self,
 8643        action: &SelectPrevious,
 8644        cx: &mut ViewContext<Self>,
 8645    ) -> Result<()> {
 8646        self.push_to_selection_history();
 8647        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8648        let buffer = &display_map.buffer_snapshot;
 8649        let mut selections = self.selections.all::<usize>(cx);
 8650        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8651            let query = &select_prev_state.query;
 8652            if !select_prev_state.done {
 8653                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8654                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8655                let mut next_selected_range = None;
 8656                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8657                let bytes_before_last_selection =
 8658                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8659                let bytes_after_first_selection =
 8660                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8661                let query_matches = query
 8662                    .stream_find_iter(bytes_before_last_selection)
 8663                    .map(|result| (last_selection.start, result))
 8664                    .chain(
 8665                        query
 8666                            .stream_find_iter(bytes_after_first_selection)
 8667                            .map(|result| (buffer.len(), result)),
 8668                    );
 8669                for (end_offset, query_match) in query_matches {
 8670                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8671                    let offset_range =
 8672                        end_offset - query_match.end()..end_offset - query_match.start();
 8673                    let display_range = offset_range.start.to_display_point(&display_map)
 8674                        ..offset_range.end.to_display_point(&display_map);
 8675
 8676                    if !select_prev_state.wordwise
 8677                        || (!movement::is_inside_word(&display_map, display_range.start)
 8678                            && !movement::is_inside_word(&display_map, display_range.end))
 8679                    {
 8680                        next_selected_range = Some(offset_range);
 8681                        break;
 8682                    }
 8683                }
 8684
 8685                if let Some(next_selected_range) = next_selected_range {
 8686                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 8687                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8688                        if action.replace_newest {
 8689                            s.delete(s.newest_anchor().id);
 8690                        }
 8691                        s.insert_range(next_selected_range);
 8692                    });
 8693                } else {
 8694                    select_prev_state.done = true;
 8695                }
 8696            }
 8697
 8698            self.select_prev_state = Some(select_prev_state);
 8699        } else {
 8700            let mut only_carets = true;
 8701            let mut same_text_selected = true;
 8702            let mut selected_text = None;
 8703
 8704            let mut selections_iter = selections.iter().peekable();
 8705            while let Some(selection) = selections_iter.next() {
 8706                if selection.start != selection.end {
 8707                    only_carets = false;
 8708                }
 8709
 8710                if same_text_selected {
 8711                    if selected_text.is_none() {
 8712                        selected_text =
 8713                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8714                    }
 8715
 8716                    if let Some(next_selection) = selections_iter.peek() {
 8717                        if next_selection.range().len() == selection.range().len() {
 8718                            let next_selected_text = buffer
 8719                                .text_for_range(next_selection.range())
 8720                                .collect::<String>();
 8721                            if Some(next_selected_text) != selected_text {
 8722                                same_text_selected = false;
 8723                                selected_text = None;
 8724                            }
 8725                        } else {
 8726                            same_text_selected = false;
 8727                            selected_text = None;
 8728                        }
 8729                    }
 8730                }
 8731            }
 8732
 8733            if only_carets {
 8734                for selection in &mut selections {
 8735                    let word_range = movement::surrounding_word(
 8736                        &display_map,
 8737                        selection.start.to_display_point(&display_map),
 8738                    );
 8739                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8740                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8741                    selection.goal = SelectionGoal::None;
 8742                    selection.reversed = false;
 8743                }
 8744                if selections.len() == 1 {
 8745                    let selection = selections
 8746                        .last()
 8747                        .expect("ensured that there's only one selection");
 8748                    let query = buffer
 8749                        .text_for_range(selection.start..selection.end)
 8750                        .collect::<String>();
 8751                    let is_empty = query.is_empty();
 8752                    let select_state = SelectNextState {
 8753                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8754                        wordwise: true,
 8755                        done: is_empty,
 8756                    };
 8757                    self.select_prev_state = Some(select_state);
 8758                } else {
 8759                    self.select_prev_state = None;
 8760                }
 8761
 8762                self.unfold_ranges(
 8763                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8764                    false,
 8765                    true,
 8766                    cx,
 8767                );
 8768                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8769                    s.select(selections);
 8770                });
 8771            } else if let Some(selected_text) = selected_text {
 8772                self.select_prev_state = Some(SelectNextState {
 8773                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8774                    wordwise: false,
 8775                    done: false,
 8776                });
 8777                self.select_previous(action, cx)?;
 8778            }
 8779        }
 8780        Ok(())
 8781    }
 8782
 8783    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 8784        let text_layout_details = &self.text_layout_details(cx);
 8785        self.transact(cx, |this, cx| {
 8786            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8787            let mut edits = Vec::new();
 8788            let mut selection_edit_ranges = Vec::new();
 8789            let mut last_toggled_row = None;
 8790            let snapshot = this.buffer.read(cx).read(cx);
 8791            let empty_str: Arc<str> = Arc::default();
 8792            let mut suffixes_inserted = Vec::new();
 8793            let ignore_indent = action.ignore_indent;
 8794
 8795            fn comment_prefix_range(
 8796                snapshot: &MultiBufferSnapshot,
 8797                row: MultiBufferRow,
 8798                comment_prefix: &str,
 8799                comment_prefix_whitespace: &str,
 8800                ignore_indent: bool,
 8801            ) -> Range<Point> {
 8802                let indent_size = if ignore_indent {
 8803                    0
 8804                } else {
 8805                    snapshot.indent_size_for_line(row).len
 8806                };
 8807
 8808                let start = Point::new(row.0, indent_size);
 8809
 8810                let mut line_bytes = snapshot
 8811                    .bytes_in_range(start..snapshot.max_point())
 8812                    .flatten()
 8813                    .copied();
 8814
 8815                // If this line currently begins with the line comment prefix, then record
 8816                // the range containing the prefix.
 8817                if line_bytes
 8818                    .by_ref()
 8819                    .take(comment_prefix.len())
 8820                    .eq(comment_prefix.bytes())
 8821                {
 8822                    // Include any whitespace that matches the comment prefix.
 8823                    let matching_whitespace_len = line_bytes
 8824                        .zip(comment_prefix_whitespace.bytes())
 8825                        .take_while(|(a, b)| a == b)
 8826                        .count() as u32;
 8827                    let end = Point::new(
 8828                        start.row,
 8829                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 8830                    );
 8831                    start..end
 8832                } else {
 8833                    start..start
 8834                }
 8835            }
 8836
 8837            fn comment_suffix_range(
 8838                snapshot: &MultiBufferSnapshot,
 8839                row: MultiBufferRow,
 8840                comment_suffix: &str,
 8841                comment_suffix_has_leading_space: bool,
 8842            ) -> Range<Point> {
 8843                let end = Point::new(row.0, snapshot.line_len(row));
 8844                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 8845
 8846                let mut line_end_bytes = snapshot
 8847                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 8848                    .flatten()
 8849                    .copied();
 8850
 8851                let leading_space_len = if suffix_start_column > 0
 8852                    && line_end_bytes.next() == Some(b' ')
 8853                    && comment_suffix_has_leading_space
 8854                {
 8855                    1
 8856                } else {
 8857                    0
 8858                };
 8859
 8860                // If this line currently begins with the line comment prefix, then record
 8861                // the range containing the prefix.
 8862                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 8863                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 8864                    start..end
 8865                } else {
 8866                    end..end
 8867                }
 8868            }
 8869
 8870            // TODO: Handle selections that cross excerpts
 8871            for selection in &mut selections {
 8872                let start_column = snapshot
 8873                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 8874                    .len;
 8875                let language = if let Some(language) =
 8876                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 8877                {
 8878                    language
 8879                } else {
 8880                    continue;
 8881                };
 8882
 8883                selection_edit_ranges.clear();
 8884
 8885                // If multiple selections contain a given row, avoid processing that
 8886                // row more than once.
 8887                let mut start_row = MultiBufferRow(selection.start.row);
 8888                if last_toggled_row == Some(start_row) {
 8889                    start_row = start_row.next_row();
 8890                }
 8891                let end_row =
 8892                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 8893                        MultiBufferRow(selection.end.row - 1)
 8894                    } else {
 8895                        MultiBufferRow(selection.end.row)
 8896                    };
 8897                last_toggled_row = Some(end_row);
 8898
 8899                if start_row > end_row {
 8900                    continue;
 8901                }
 8902
 8903                // If the language has line comments, toggle those.
 8904                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 8905
 8906                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 8907                if ignore_indent {
 8908                    full_comment_prefixes = full_comment_prefixes
 8909                        .into_iter()
 8910                        .map(|s| Arc::from(s.trim_end()))
 8911                        .collect();
 8912                }
 8913
 8914                if !full_comment_prefixes.is_empty() {
 8915                    let first_prefix = full_comment_prefixes
 8916                        .first()
 8917                        .expect("prefixes is non-empty");
 8918                    let prefix_trimmed_lengths = full_comment_prefixes
 8919                        .iter()
 8920                        .map(|p| p.trim_end_matches(' ').len())
 8921                        .collect::<SmallVec<[usize; 4]>>();
 8922
 8923                    let mut all_selection_lines_are_comments = true;
 8924
 8925                    for row in start_row.0..=end_row.0 {
 8926                        let row = MultiBufferRow(row);
 8927                        if start_row < end_row && snapshot.is_line_blank(row) {
 8928                            continue;
 8929                        }
 8930
 8931                        let prefix_range = full_comment_prefixes
 8932                            .iter()
 8933                            .zip(prefix_trimmed_lengths.iter().copied())
 8934                            .map(|(prefix, trimmed_prefix_len)| {
 8935                                comment_prefix_range(
 8936                                    snapshot.deref(),
 8937                                    row,
 8938                                    &prefix[..trimmed_prefix_len],
 8939                                    &prefix[trimmed_prefix_len..],
 8940                                    ignore_indent,
 8941                                )
 8942                            })
 8943                            .max_by_key(|range| range.end.column - range.start.column)
 8944                            .expect("prefixes is non-empty");
 8945
 8946                        if prefix_range.is_empty() {
 8947                            all_selection_lines_are_comments = false;
 8948                        }
 8949
 8950                        selection_edit_ranges.push(prefix_range);
 8951                    }
 8952
 8953                    if all_selection_lines_are_comments {
 8954                        edits.extend(
 8955                            selection_edit_ranges
 8956                                .iter()
 8957                                .cloned()
 8958                                .map(|range| (range, empty_str.clone())),
 8959                        );
 8960                    } else {
 8961                        let min_column = selection_edit_ranges
 8962                            .iter()
 8963                            .map(|range| range.start.column)
 8964                            .min()
 8965                            .unwrap_or(0);
 8966                        edits.extend(selection_edit_ranges.iter().map(|range| {
 8967                            let position = Point::new(range.start.row, min_column);
 8968                            (position..position, first_prefix.clone())
 8969                        }));
 8970                    }
 8971                } else if let Some((full_comment_prefix, comment_suffix)) =
 8972                    language.block_comment_delimiters()
 8973                {
 8974                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 8975                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 8976                    let prefix_range = comment_prefix_range(
 8977                        snapshot.deref(),
 8978                        start_row,
 8979                        comment_prefix,
 8980                        comment_prefix_whitespace,
 8981                        ignore_indent,
 8982                    );
 8983                    let suffix_range = comment_suffix_range(
 8984                        snapshot.deref(),
 8985                        end_row,
 8986                        comment_suffix.trim_start_matches(' '),
 8987                        comment_suffix.starts_with(' '),
 8988                    );
 8989
 8990                    if prefix_range.is_empty() || suffix_range.is_empty() {
 8991                        edits.push((
 8992                            prefix_range.start..prefix_range.start,
 8993                            full_comment_prefix.clone(),
 8994                        ));
 8995                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 8996                        suffixes_inserted.push((end_row, comment_suffix.len()));
 8997                    } else {
 8998                        edits.push((prefix_range, empty_str.clone()));
 8999                        edits.push((suffix_range, empty_str.clone()));
 9000                    }
 9001                } else {
 9002                    continue;
 9003                }
 9004            }
 9005
 9006            drop(snapshot);
 9007            this.buffer.update(cx, |buffer, cx| {
 9008                buffer.edit(edits, None, cx);
 9009            });
 9010
 9011            // Adjust selections so that they end before any comment suffixes that
 9012            // were inserted.
 9013            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 9014            let mut selections = this.selections.all::<Point>(cx);
 9015            let snapshot = this.buffer.read(cx).read(cx);
 9016            for selection in &mut selections {
 9017                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 9018                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 9019                        Ordering::Less => {
 9020                            suffixes_inserted.next();
 9021                            continue;
 9022                        }
 9023                        Ordering::Greater => break,
 9024                        Ordering::Equal => {
 9025                            if selection.end.column == snapshot.line_len(row) {
 9026                                if selection.is_empty() {
 9027                                    selection.start.column -= suffix_len as u32;
 9028                                }
 9029                                selection.end.column -= suffix_len as u32;
 9030                            }
 9031                            break;
 9032                        }
 9033                    }
 9034                }
 9035            }
 9036
 9037            drop(snapshot);
 9038            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 9039
 9040            let selections = this.selections.all::<Point>(cx);
 9041            let selections_on_single_row = selections.windows(2).all(|selections| {
 9042                selections[0].start.row == selections[1].start.row
 9043                    && selections[0].end.row == selections[1].end.row
 9044                    && selections[0].start.row == selections[0].end.row
 9045            });
 9046            let selections_selecting = selections
 9047                .iter()
 9048                .any(|selection| selection.start != selection.end);
 9049            let advance_downwards = action.advance_downwards
 9050                && selections_on_single_row
 9051                && !selections_selecting
 9052                && !matches!(this.mode, EditorMode::SingleLine { .. });
 9053
 9054            if advance_downwards {
 9055                let snapshot = this.buffer.read(cx).snapshot(cx);
 9056
 9057                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9058                    s.move_cursors_with(|display_snapshot, display_point, _| {
 9059                        let mut point = display_point.to_point(display_snapshot);
 9060                        point.row += 1;
 9061                        point = snapshot.clip_point(point, Bias::Left);
 9062                        let display_point = point.to_display_point(display_snapshot);
 9063                        let goal = SelectionGoal::HorizontalPosition(
 9064                            display_snapshot
 9065                                .x_for_display_point(display_point, text_layout_details)
 9066                                .into(),
 9067                        );
 9068                        (display_point, goal)
 9069                    })
 9070                });
 9071            }
 9072        });
 9073    }
 9074
 9075    pub fn select_enclosing_symbol(
 9076        &mut self,
 9077        _: &SelectEnclosingSymbol,
 9078        cx: &mut ViewContext<Self>,
 9079    ) {
 9080        let buffer = self.buffer.read(cx).snapshot(cx);
 9081        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9082
 9083        fn update_selection(
 9084            selection: &Selection<usize>,
 9085            buffer_snap: &MultiBufferSnapshot,
 9086        ) -> Option<Selection<usize>> {
 9087            let cursor = selection.head();
 9088            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 9089            for symbol in symbols.iter().rev() {
 9090                let start = symbol.range.start.to_offset(buffer_snap);
 9091                let end = symbol.range.end.to_offset(buffer_snap);
 9092                let new_range = start..end;
 9093                if start < selection.start || end > selection.end {
 9094                    return Some(Selection {
 9095                        id: selection.id,
 9096                        start: new_range.start,
 9097                        end: new_range.end,
 9098                        goal: SelectionGoal::None,
 9099                        reversed: selection.reversed,
 9100                    });
 9101                }
 9102            }
 9103            None
 9104        }
 9105
 9106        let mut selected_larger_symbol = false;
 9107        let new_selections = old_selections
 9108            .iter()
 9109            .map(|selection| match update_selection(selection, &buffer) {
 9110                Some(new_selection) => {
 9111                    if new_selection.range() != selection.range() {
 9112                        selected_larger_symbol = true;
 9113                    }
 9114                    new_selection
 9115                }
 9116                None => selection.clone(),
 9117            })
 9118            .collect::<Vec<_>>();
 9119
 9120        if selected_larger_symbol {
 9121            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9122                s.select(new_selections);
 9123            });
 9124        }
 9125    }
 9126
 9127    pub fn select_larger_syntax_node(
 9128        &mut self,
 9129        _: &SelectLargerSyntaxNode,
 9130        cx: &mut ViewContext<Self>,
 9131    ) {
 9132        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9133        let buffer = self.buffer.read(cx).snapshot(cx);
 9134        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9135
 9136        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9137        let mut selected_larger_node = false;
 9138        let new_selections = old_selections
 9139            .iter()
 9140            .map(|selection| {
 9141                let old_range = selection.start..selection.end;
 9142                let mut new_range = old_range.clone();
 9143                while let Some(containing_range) =
 9144                    buffer.range_for_syntax_ancestor(new_range.clone())
 9145                {
 9146                    new_range = containing_range;
 9147                    if !display_map.intersects_fold(new_range.start)
 9148                        && !display_map.intersects_fold(new_range.end)
 9149                    {
 9150                        break;
 9151                    }
 9152                }
 9153
 9154                selected_larger_node |= new_range != old_range;
 9155                Selection {
 9156                    id: selection.id,
 9157                    start: new_range.start,
 9158                    end: new_range.end,
 9159                    goal: SelectionGoal::None,
 9160                    reversed: selection.reversed,
 9161                }
 9162            })
 9163            .collect::<Vec<_>>();
 9164
 9165        if selected_larger_node {
 9166            stack.push(old_selections);
 9167            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9168                s.select(new_selections);
 9169            });
 9170        }
 9171        self.select_larger_syntax_node_stack = stack;
 9172    }
 9173
 9174    pub fn select_smaller_syntax_node(
 9175        &mut self,
 9176        _: &SelectSmallerSyntaxNode,
 9177        cx: &mut ViewContext<Self>,
 9178    ) {
 9179        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9180        if let Some(selections) = stack.pop() {
 9181            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9182                s.select(selections.to_vec());
 9183            });
 9184        }
 9185        self.select_larger_syntax_node_stack = stack;
 9186    }
 9187
 9188    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 9189        if !EditorSettings::get_global(cx).gutter.runnables {
 9190            self.clear_tasks();
 9191            return Task::ready(());
 9192        }
 9193        let project = self.project.clone();
 9194        cx.spawn(|this, mut cx| async move {
 9195            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 9196                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 9197            }) else {
 9198                return;
 9199            };
 9200
 9201            let Some(project) = project else {
 9202                return;
 9203            };
 9204
 9205            let hide_runnables = project
 9206                .update(&mut cx, |project, cx| {
 9207                    // Do not display any test indicators in non-dev server remote projects.
 9208                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 9209                })
 9210                .unwrap_or(true);
 9211            if hide_runnables {
 9212                return;
 9213            }
 9214            let new_rows =
 9215                cx.background_executor()
 9216                    .spawn({
 9217                        let snapshot = display_snapshot.clone();
 9218                        async move {
 9219                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 9220                        }
 9221                    })
 9222                    .await;
 9223            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 9224
 9225            this.update(&mut cx, |this, _| {
 9226                this.clear_tasks();
 9227                for (key, value) in rows {
 9228                    this.insert_tasks(key, value);
 9229                }
 9230            })
 9231            .ok();
 9232        })
 9233    }
 9234    fn fetch_runnable_ranges(
 9235        snapshot: &DisplaySnapshot,
 9236        range: Range<Anchor>,
 9237    ) -> Vec<language::RunnableRange> {
 9238        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 9239    }
 9240
 9241    fn runnable_rows(
 9242        project: Model<Project>,
 9243        snapshot: DisplaySnapshot,
 9244        runnable_ranges: Vec<RunnableRange>,
 9245        mut cx: AsyncWindowContext,
 9246    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 9247        runnable_ranges
 9248            .into_iter()
 9249            .filter_map(|mut runnable| {
 9250                let tasks = cx
 9251                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 9252                    .ok()?;
 9253                if tasks.is_empty() {
 9254                    return None;
 9255                }
 9256
 9257                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 9258
 9259                let row = snapshot
 9260                    .buffer_snapshot
 9261                    .buffer_line_for_row(MultiBufferRow(point.row))?
 9262                    .1
 9263                    .start
 9264                    .row;
 9265
 9266                let context_range =
 9267                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 9268                Some((
 9269                    (runnable.buffer_id, row),
 9270                    RunnableTasks {
 9271                        templates: tasks,
 9272                        offset: MultiBufferOffset(runnable.run_range.start),
 9273                        context_range,
 9274                        column: point.column,
 9275                        extra_variables: runnable.extra_captures,
 9276                    },
 9277                ))
 9278            })
 9279            .collect()
 9280    }
 9281
 9282    fn templates_with_tags(
 9283        project: &Model<Project>,
 9284        runnable: &mut Runnable,
 9285        cx: &WindowContext<'_>,
 9286    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 9287        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 9288            let (worktree_id, file) = project
 9289                .buffer_for_id(runnable.buffer, cx)
 9290                .and_then(|buffer| buffer.read(cx).file())
 9291                .map(|file| (file.worktree_id(cx), file.clone()))
 9292                .unzip();
 9293
 9294            (
 9295                project.task_store().read(cx).task_inventory().cloned(),
 9296                worktree_id,
 9297                file,
 9298            )
 9299        });
 9300
 9301        let tags = mem::take(&mut runnable.tags);
 9302        let mut tags: Vec<_> = tags
 9303            .into_iter()
 9304            .flat_map(|tag| {
 9305                let tag = tag.0.clone();
 9306                inventory
 9307                    .as_ref()
 9308                    .into_iter()
 9309                    .flat_map(|inventory| {
 9310                        inventory.read(cx).list_tasks(
 9311                            file.clone(),
 9312                            Some(runnable.language.clone()),
 9313                            worktree_id,
 9314                            cx,
 9315                        )
 9316                    })
 9317                    .filter(move |(_, template)| {
 9318                        template.tags.iter().any(|source_tag| source_tag == &tag)
 9319                    })
 9320            })
 9321            .sorted_by_key(|(kind, _)| kind.to_owned())
 9322            .collect();
 9323        if let Some((leading_tag_source, _)) = tags.first() {
 9324            // Strongest source wins; if we have worktree tag binding, prefer that to
 9325            // global and language bindings;
 9326            // if we have a global binding, prefer that to language binding.
 9327            let first_mismatch = tags
 9328                .iter()
 9329                .position(|(tag_source, _)| tag_source != leading_tag_source);
 9330            if let Some(index) = first_mismatch {
 9331                tags.truncate(index);
 9332            }
 9333        }
 9334
 9335        tags
 9336    }
 9337
 9338    pub fn move_to_enclosing_bracket(
 9339        &mut self,
 9340        _: &MoveToEnclosingBracket,
 9341        cx: &mut ViewContext<Self>,
 9342    ) {
 9343        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9344            s.move_offsets_with(|snapshot, selection| {
 9345                let Some(enclosing_bracket_ranges) =
 9346                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 9347                else {
 9348                    return;
 9349                };
 9350
 9351                let mut best_length = usize::MAX;
 9352                let mut best_inside = false;
 9353                let mut best_in_bracket_range = false;
 9354                let mut best_destination = None;
 9355                for (open, close) in enclosing_bracket_ranges {
 9356                    let close = close.to_inclusive();
 9357                    let length = close.end() - open.start;
 9358                    let inside = selection.start >= open.end && selection.end <= *close.start();
 9359                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 9360                        || close.contains(&selection.head());
 9361
 9362                    // If best is next to a bracket and current isn't, skip
 9363                    if !in_bracket_range && best_in_bracket_range {
 9364                        continue;
 9365                    }
 9366
 9367                    // Prefer smaller lengths unless best is inside and current isn't
 9368                    if length > best_length && (best_inside || !inside) {
 9369                        continue;
 9370                    }
 9371
 9372                    best_length = length;
 9373                    best_inside = inside;
 9374                    best_in_bracket_range = in_bracket_range;
 9375                    best_destination = Some(
 9376                        if close.contains(&selection.start) && close.contains(&selection.end) {
 9377                            if inside {
 9378                                open.end
 9379                            } else {
 9380                                open.start
 9381                            }
 9382                        } else if inside {
 9383                            *close.start()
 9384                        } else {
 9385                            *close.end()
 9386                        },
 9387                    );
 9388                }
 9389
 9390                if let Some(destination) = best_destination {
 9391                    selection.collapse_to(destination, SelectionGoal::None);
 9392                }
 9393            })
 9394        });
 9395    }
 9396
 9397    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 9398        self.end_selection(cx);
 9399        self.selection_history.mode = SelectionHistoryMode::Undoing;
 9400        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 9401            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9402            self.select_next_state = entry.select_next_state;
 9403            self.select_prev_state = entry.select_prev_state;
 9404            self.add_selections_state = entry.add_selections_state;
 9405            self.request_autoscroll(Autoscroll::newest(), cx);
 9406        }
 9407        self.selection_history.mode = SelectionHistoryMode::Normal;
 9408    }
 9409
 9410    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 9411        self.end_selection(cx);
 9412        self.selection_history.mode = SelectionHistoryMode::Redoing;
 9413        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 9414            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9415            self.select_next_state = entry.select_next_state;
 9416            self.select_prev_state = entry.select_prev_state;
 9417            self.add_selections_state = entry.add_selections_state;
 9418            self.request_autoscroll(Autoscroll::newest(), cx);
 9419        }
 9420        self.selection_history.mode = SelectionHistoryMode::Normal;
 9421    }
 9422
 9423    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 9424        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 9425    }
 9426
 9427    pub fn expand_excerpts_down(
 9428        &mut self,
 9429        action: &ExpandExcerptsDown,
 9430        cx: &mut ViewContext<Self>,
 9431    ) {
 9432        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 9433    }
 9434
 9435    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 9436        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 9437    }
 9438
 9439    pub fn expand_excerpts_for_direction(
 9440        &mut self,
 9441        lines: u32,
 9442        direction: ExpandExcerptDirection,
 9443        cx: &mut ViewContext<Self>,
 9444    ) {
 9445        let selections = self.selections.disjoint_anchors();
 9446
 9447        let lines = if lines == 0 {
 9448            EditorSettings::get_global(cx).expand_excerpt_lines
 9449        } else {
 9450            lines
 9451        };
 9452
 9453        self.buffer.update(cx, |buffer, cx| {
 9454            buffer.expand_excerpts(
 9455                selections
 9456                    .iter()
 9457                    .map(|selection| selection.head().excerpt_id)
 9458                    .dedup(),
 9459                lines,
 9460                direction,
 9461                cx,
 9462            )
 9463        })
 9464    }
 9465
 9466    pub fn expand_excerpt(
 9467        &mut self,
 9468        excerpt: ExcerptId,
 9469        direction: ExpandExcerptDirection,
 9470        cx: &mut ViewContext<Self>,
 9471    ) {
 9472        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 9473        self.buffer.update(cx, |buffer, cx| {
 9474            buffer.expand_excerpts([excerpt], lines, direction, cx)
 9475        })
 9476    }
 9477
 9478    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 9479        self.go_to_diagnostic_impl(Direction::Next, cx)
 9480    }
 9481
 9482    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 9483        self.go_to_diagnostic_impl(Direction::Prev, cx)
 9484    }
 9485
 9486    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 9487        let buffer = self.buffer.read(cx).snapshot(cx);
 9488        let selection = self.selections.newest::<usize>(cx);
 9489
 9490        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 9491        if direction == Direction::Next {
 9492            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 9493                let (group_id, jump_to) = popover.activation_info();
 9494                if self.activate_diagnostics(group_id, cx) {
 9495                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9496                        let mut new_selection = s.newest_anchor().clone();
 9497                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 9498                        s.select_anchors(vec![new_selection.clone()]);
 9499                    });
 9500                }
 9501                return;
 9502            }
 9503        }
 9504
 9505        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 9506            active_diagnostics
 9507                .primary_range
 9508                .to_offset(&buffer)
 9509                .to_inclusive()
 9510        });
 9511        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 9512            if active_primary_range.contains(&selection.head()) {
 9513                *active_primary_range.start()
 9514            } else {
 9515                selection.head()
 9516            }
 9517        } else {
 9518            selection.head()
 9519        };
 9520        let snapshot = self.snapshot(cx);
 9521        loop {
 9522            let diagnostics = if direction == Direction::Prev {
 9523                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 9524            } else {
 9525                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 9526            }
 9527            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 9528            let group = diagnostics
 9529                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 9530                // be sorted in a stable way
 9531                // skip until we are at current active diagnostic, if it exists
 9532                .skip_while(|entry| {
 9533                    (match direction {
 9534                        Direction::Prev => entry.range.start >= search_start,
 9535                        Direction::Next => entry.range.start <= search_start,
 9536                    }) && self
 9537                        .active_diagnostics
 9538                        .as_ref()
 9539                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 9540                })
 9541                .find_map(|entry| {
 9542                    if entry.diagnostic.is_primary
 9543                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 9544                        && !entry.range.is_empty()
 9545                        // if we match with the active diagnostic, skip it
 9546                        && Some(entry.diagnostic.group_id)
 9547                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 9548                    {
 9549                        Some((entry.range, entry.diagnostic.group_id))
 9550                    } else {
 9551                        None
 9552                    }
 9553                });
 9554
 9555            if let Some((primary_range, group_id)) = group {
 9556                if self.activate_diagnostics(group_id, cx) {
 9557                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9558                        s.select(vec![Selection {
 9559                            id: selection.id,
 9560                            start: primary_range.start,
 9561                            end: primary_range.start,
 9562                            reversed: false,
 9563                            goal: SelectionGoal::None,
 9564                        }]);
 9565                    });
 9566                }
 9567                break;
 9568            } else {
 9569                // Cycle around to the start of the buffer, potentially moving back to the start of
 9570                // the currently active diagnostic.
 9571                active_primary_range.take();
 9572                if direction == Direction::Prev {
 9573                    if search_start == buffer.len() {
 9574                        break;
 9575                    } else {
 9576                        search_start = buffer.len();
 9577                    }
 9578                } else if search_start == 0 {
 9579                    break;
 9580                } else {
 9581                    search_start = 0;
 9582                }
 9583            }
 9584        }
 9585    }
 9586
 9587    fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 9588        let snapshot = self
 9589            .display_map
 9590            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9591        let selection = self.selections.newest::<Point>(cx);
 9592        self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
 9593    }
 9594
 9595    fn go_to_hunk_after_position(
 9596        &mut self,
 9597        snapshot: &DisplaySnapshot,
 9598        position: Point,
 9599        cx: &mut ViewContext<'_, Editor>,
 9600    ) -> Option<MultiBufferDiffHunk> {
 9601        if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9602            snapshot,
 9603            position,
 9604            false,
 9605            snapshot
 9606                .buffer_snapshot
 9607                .git_diff_hunks_in_range(MultiBufferRow(position.row + 1)..MultiBufferRow::MAX),
 9608            cx,
 9609        ) {
 9610            return Some(hunk);
 9611        }
 9612
 9613        let wrapped_point = Point::zero();
 9614        self.go_to_next_hunk_in_direction(
 9615            snapshot,
 9616            wrapped_point,
 9617            true,
 9618            snapshot.buffer_snapshot.git_diff_hunks_in_range(
 9619                MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
 9620            ),
 9621            cx,
 9622        )
 9623    }
 9624
 9625    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 9626        let snapshot = self
 9627            .display_map
 9628            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9629        let selection = self.selections.newest::<Point>(cx);
 9630
 9631        self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
 9632    }
 9633
 9634    fn go_to_hunk_before_position(
 9635        &mut self,
 9636        snapshot: &DisplaySnapshot,
 9637        position: Point,
 9638        cx: &mut ViewContext<'_, Editor>,
 9639    ) -> Option<MultiBufferDiffHunk> {
 9640        if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9641            snapshot,
 9642            position,
 9643            false,
 9644            snapshot
 9645                .buffer_snapshot
 9646                .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(position.row)),
 9647            cx,
 9648        ) {
 9649            return Some(hunk);
 9650        }
 9651
 9652        let wrapped_point = snapshot.buffer_snapshot.max_point();
 9653        self.go_to_next_hunk_in_direction(
 9654            snapshot,
 9655            wrapped_point,
 9656            true,
 9657            snapshot
 9658                .buffer_snapshot
 9659                .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(wrapped_point.row)),
 9660            cx,
 9661        )
 9662    }
 9663
 9664    fn go_to_next_hunk_in_direction(
 9665        &mut self,
 9666        snapshot: &DisplaySnapshot,
 9667        initial_point: Point,
 9668        is_wrapped: bool,
 9669        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
 9670        cx: &mut ViewContext<Editor>,
 9671    ) -> Option<MultiBufferDiffHunk> {
 9672        let display_point = initial_point.to_display_point(snapshot);
 9673        let mut hunks = hunks
 9674            .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
 9675            .filter(|(display_hunk, _)| {
 9676                is_wrapped || !display_hunk.contains_display_row(display_point.row())
 9677            })
 9678            .dedup();
 9679
 9680        if let Some((display_hunk, hunk)) = hunks.next() {
 9681            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9682                let row = display_hunk.start_display_row();
 9683                let point = DisplayPoint::new(row, 0);
 9684                s.select_display_ranges([point..point]);
 9685            });
 9686
 9687            Some(hunk)
 9688        } else {
 9689            None
 9690        }
 9691    }
 9692
 9693    pub fn go_to_definition(
 9694        &mut self,
 9695        _: &GoToDefinition,
 9696        cx: &mut ViewContext<Self>,
 9697    ) -> Task<Result<Navigated>> {
 9698        let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
 9699        cx.spawn(|editor, mut cx| async move {
 9700            if definition.await? == Navigated::Yes {
 9701                return Ok(Navigated::Yes);
 9702            }
 9703            match editor.update(&mut cx, |editor, cx| {
 9704                editor.find_all_references(&FindAllReferences, cx)
 9705            })? {
 9706                Some(references) => references.await,
 9707                None => Ok(Navigated::No),
 9708            }
 9709        })
 9710    }
 9711
 9712    pub fn go_to_declaration(
 9713        &mut self,
 9714        _: &GoToDeclaration,
 9715        cx: &mut ViewContext<Self>,
 9716    ) -> Task<Result<Navigated>> {
 9717        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
 9718    }
 9719
 9720    pub fn go_to_declaration_split(
 9721        &mut self,
 9722        _: &GoToDeclaration,
 9723        cx: &mut ViewContext<Self>,
 9724    ) -> Task<Result<Navigated>> {
 9725        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
 9726    }
 9727
 9728    pub fn go_to_implementation(
 9729        &mut self,
 9730        _: &GoToImplementation,
 9731        cx: &mut ViewContext<Self>,
 9732    ) -> Task<Result<Navigated>> {
 9733        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 9734    }
 9735
 9736    pub fn go_to_implementation_split(
 9737        &mut self,
 9738        _: &GoToImplementationSplit,
 9739        cx: &mut ViewContext<Self>,
 9740    ) -> Task<Result<Navigated>> {
 9741        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 9742    }
 9743
 9744    pub fn go_to_type_definition(
 9745        &mut self,
 9746        _: &GoToTypeDefinition,
 9747        cx: &mut ViewContext<Self>,
 9748    ) -> Task<Result<Navigated>> {
 9749        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 9750    }
 9751
 9752    pub fn go_to_definition_split(
 9753        &mut self,
 9754        _: &GoToDefinitionSplit,
 9755        cx: &mut ViewContext<Self>,
 9756    ) -> Task<Result<Navigated>> {
 9757        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 9758    }
 9759
 9760    pub fn go_to_type_definition_split(
 9761        &mut self,
 9762        _: &GoToTypeDefinitionSplit,
 9763        cx: &mut ViewContext<Self>,
 9764    ) -> Task<Result<Navigated>> {
 9765        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 9766    }
 9767
 9768    fn go_to_definition_of_kind(
 9769        &mut self,
 9770        kind: GotoDefinitionKind,
 9771        split: bool,
 9772        cx: &mut ViewContext<Self>,
 9773    ) -> Task<Result<Navigated>> {
 9774        let Some(provider) = self.semantics_provider.clone() else {
 9775            return Task::ready(Ok(Navigated::No));
 9776        };
 9777        let head = self.selections.newest::<usize>(cx).head();
 9778        let buffer = self.buffer.read(cx);
 9779        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 9780            text_anchor
 9781        } else {
 9782            return Task::ready(Ok(Navigated::No));
 9783        };
 9784
 9785        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
 9786            return Task::ready(Ok(Navigated::No));
 9787        };
 9788
 9789        cx.spawn(|editor, mut cx| async move {
 9790            let definitions = definitions.await?;
 9791            let navigated = editor
 9792                .update(&mut cx, |editor, cx| {
 9793                    editor.navigate_to_hover_links(
 9794                        Some(kind),
 9795                        definitions
 9796                            .into_iter()
 9797                            .filter(|location| {
 9798                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 9799                            })
 9800                            .map(HoverLink::Text)
 9801                            .collect::<Vec<_>>(),
 9802                        split,
 9803                        cx,
 9804                    )
 9805                })?
 9806                .await?;
 9807            anyhow::Ok(navigated)
 9808        })
 9809    }
 9810
 9811    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 9812        let position = self.selections.newest_anchor().head();
 9813        let Some((buffer, buffer_position)) =
 9814            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9815        else {
 9816            return;
 9817        };
 9818
 9819        cx.spawn(|editor, mut cx| async move {
 9820            if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
 9821                editor.update(&mut cx, |_, cx| {
 9822                    cx.open_url(&url);
 9823                })
 9824            } else {
 9825                Ok(())
 9826            }
 9827        })
 9828        .detach();
 9829    }
 9830
 9831    pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
 9832        let Some(workspace) = self.workspace() else {
 9833            return;
 9834        };
 9835
 9836        let position = self.selections.newest_anchor().head();
 9837
 9838        let Some((buffer, buffer_position)) =
 9839            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9840        else {
 9841            return;
 9842        };
 9843
 9844        let project = self.project.clone();
 9845
 9846        cx.spawn(|_, mut cx| async move {
 9847            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
 9848
 9849            if let Some((_, path)) = result {
 9850                workspace
 9851                    .update(&mut cx, |workspace, cx| {
 9852                        workspace.open_resolved_path(path, cx)
 9853                    })?
 9854                    .await?;
 9855            }
 9856            anyhow::Ok(())
 9857        })
 9858        .detach();
 9859    }
 9860
 9861    pub(crate) fn navigate_to_hover_links(
 9862        &mut self,
 9863        kind: Option<GotoDefinitionKind>,
 9864        mut definitions: Vec<HoverLink>,
 9865        split: bool,
 9866        cx: &mut ViewContext<Editor>,
 9867    ) -> Task<Result<Navigated>> {
 9868        // If there is one definition, just open it directly
 9869        if definitions.len() == 1 {
 9870            let definition = definitions.pop().unwrap();
 9871
 9872            enum TargetTaskResult {
 9873                Location(Option<Location>),
 9874                AlreadyNavigated,
 9875            }
 9876
 9877            let target_task = match definition {
 9878                HoverLink::Text(link) => {
 9879                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
 9880                }
 9881                HoverLink::InlayHint(lsp_location, server_id) => {
 9882                    let computation = self.compute_target_location(lsp_location, server_id, cx);
 9883                    cx.background_executor().spawn(async move {
 9884                        let location = computation.await?;
 9885                        Ok(TargetTaskResult::Location(location))
 9886                    })
 9887                }
 9888                HoverLink::Url(url) => {
 9889                    cx.open_url(&url);
 9890                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
 9891                }
 9892                HoverLink::File(path) => {
 9893                    if let Some(workspace) = self.workspace() {
 9894                        cx.spawn(|_, mut cx| async move {
 9895                            workspace
 9896                                .update(&mut cx, |workspace, cx| {
 9897                                    workspace.open_resolved_path(path, cx)
 9898                                })?
 9899                                .await
 9900                                .map(|_| TargetTaskResult::AlreadyNavigated)
 9901                        })
 9902                    } else {
 9903                        Task::ready(Ok(TargetTaskResult::Location(None)))
 9904                    }
 9905                }
 9906            };
 9907            cx.spawn(|editor, mut cx| async move {
 9908                let target = match target_task.await.context("target resolution task")? {
 9909                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
 9910                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
 9911                    TargetTaskResult::Location(Some(target)) => target,
 9912                };
 9913
 9914                editor.update(&mut cx, |editor, cx| {
 9915                    let Some(workspace) = editor.workspace() else {
 9916                        return Navigated::No;
 9917                    };
 9918                    let pane = workspace.read(cx).active_pane().clone();
 9919
 9920                    let range = target.range.to_offset(target.buffer.read(cx));
 9921                    let range = editor.range_for_match(&range);
 9922
 9923                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 9924                        let buffer = target.buffer.read(cx);
 9925                        let range = check_multiline_range(buffer, range);
 9926                        editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9927                            s.select_ranges([range]);
 9928                        });
 9929                    } else {
 9930                        cx.window_context().defer(move |cx| {
 9931                            let target_editor: View<Self> =
 9932                                workspace.update(cx, |workspace, cx| {
 9933                                    let pane = if split {
 9934                                        workspace.adjacent_pane(cx)
 9935                                    } else {
 9936                                        workspace.active_pane().clone()
 9937                                    };
 9938
 9939                                    workspace.open_project_item(
 9940                                        pane,
 9941                                        target.buffer.clone(),
 9942                                        true,
 9943                                        true,
 9944                                        cx,
 9945                                    )
 9946                                });
 9947                            target_editor.update(cx, |target_editor, cx| {
 9948                                // When selecting a definition in a different buffer, disable the nav history
 9949                                // to avoid creating a history entry at the previous cursor location.
 9950                                pane.update(cx, |pane, _| pane.disable_history());
 9951                                let buffer = target.buffer.read(cx);
 9952                                let range = check_multiline_range(buffer, range);
 9953                                target_editor.change_selections(
 9954                                    Some(Autoscroll::focused()),
 9955                                    cx,
 9956                                    |s| {
 9957                                        s.select_ranges([range]);
 9958                                    },
 9959                                );
 9960                                pane.update(cx, |pane, _| pane.enable_history());
 9961                            });
 9962                        });
 9963                    }
 9964                    Navigated::Yes
 9965                })
 9966            })
 9967        } else if !definitions.is_empty() {
 9968            cx.spawn(|editor, mut cx| async move {
 9969                let (title, location_tasks, workspace) = editor
 9970                    .update(&mut cx, |editor, cx| {
 9971                        let tab_kind = match kind {
 9972                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 9973                            _ => "Definitions",
 9974                        };
 9975                        let title = definitions
 9976                            .iter()
 9977                            .find_map(|definition| match definition {
 9978                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 9979                                    let buffer = origin.buffer.read(cx);
 9980                                    format!(
 9981                                        "{} for {}",
 9982                                        tab_kind,
 9983                                        buffer
 9984                                            .text_for_range(origin.range.clone())
 9985                                            .collect::<String>()
 9986                                    )
 9987                                }),
 9988                                HoverLink::InlayHint(_, _) => None,
 9989                                HoverLink::Url(_) => None,
 9990                                HoverLink::File(_) => None,
 9991                            })
 9992                            .unwrap_or(tab_kind.to_string());
 9993                        let location_tasks = definitions
 9994                            .into_iter()
 9995                            .map(|definition| match definition {
 9996                                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 9997                                HoverLink::InlayHint(lsp_location, server_id) => {
 9998                                    editor.compute_target_location(lsp_location, server_id, cx)
 9999                                }
10000                                HoverLink::Url(_) => Task::ready(Ok(None)),
10001                                HoverLink::File(_) => Task::ready(Ok(None)),
10002                            })
10003                            .collect::<Vec<_>>();
10004                        (title, location_tasks, editor.workspace().clone())
10005                    })
10006                    .context("location tasks preparation")?;
10007
10008                let locations = future::join_all(location_tasks)
10009                    .await
10010                    .into_iter()
10011                    .filter_map(|location| location.transpose())
10012                    .collect::<Result<_>>()
10013                    .context("location tasks")?;
10014
10015                let Some(workspace) = workspace else {
10016                    return Ok(Navigated::No);
10017                };
10018                let opened = workspace
10019                    .update(&mut cx, |workspace, cx| {
10020                        Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
10021                    })
10022                    .ok();
10023
10024                anyhow::Ok(Navigated::from_bool(opened.is_some()))
10025            })
10026        } else {
10027            Task::ready(Ok(Navigated::No))
10028        }
10029    }
10030
10031    fn compute_target_location(
10032        &self,
10033        lsp_location: lsp::Location,
10034        server_id: LanguageServerId,
10035        cx: &mut ViewContext<Self>,
10036    ) -> Task<anyhow::Result<Option<Location>>> {
10037        let Some(project) = self.project.clone() else {
10038            return Task::Ready(Some(Ok(None)));
10039        };
10040
10041        cx.spawn(move |editor, mut cx| async move {
10042            let location_task = editor.update(&mut cx, |_, cx| {
10043                project.update(cx, |project, cx| {
10044                    let language_server_name = project
10045                        .language_server_statuses(cx)
10046                        .find(|(id, _)| server_id == *id)
10047                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10048                    language_server_name.map(|language_server_name| {
10049                        project.open_local_buffer_via_lsp(
10050                            lsp_location.uri.clone(),
10051                            server_id,
10052                            language_server_name,
10053                            cx,
10054                        )
10055                    })
10056                })
10057            })?;
10058            let location = match location_task {
10059                Some(task) => Some({
10060                    let target_buffer_handle = task.await.context("open local buffer")?;
10061                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10062                        let target_start = target_buffer
10063                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10064                        let target_end = target_buffer
10065                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10066                        target_buffer.anchor_after(target_start)
10067                            ..target_buffer.anchor_before(target_end)
10068                    })?;
10069                    Location {
10070                        buffer: target_buffer_handle,
10071                        range,
10072                    }
10073                }),
10074                None => None,
10075            };
10076            Ok(location)
10077        })
10078    }
10079
10080    pub fn find_all_references(
10081        &mut self,
10082        _: &FindAllReferences,
10083        cx: &mut ViewContext<Self>,
10084    ) -> Option<Task<Result<Navigated>>> {
10085        let selection = self.selections.newest::<usize>(cx);
10086        let multi_buffer = self.buffer.read(cx);
10087        let head = selection.head();
10088
10089        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10090        let head_anchor = multi_buffer_snapshot.anchor_at(
10091            head,
10092            if head < selection.tail() {
10093                Bias::Right
10094            } else {
10095                Bias::Left
10096            },
10097        );
10098
10099        match self
10100            .find_all_references_task_sources
10101            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10102        {
10103            Ok(_) => {
10104                log::info!(
10105                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
10106                );
10107                return None;
10108            }
10109            Err(i) => {
10110                self.find_all_references_task_sources.insert(i, head_anchor);
10111            }
10112        }
10113
10114        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10115        let workspace = self.workspace()?;
10116        let project = workspace.read(cx).project().clone();
10117        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10118        Some(cx.spawn(|editor, mut cx| async move {
10119            let _cleanup = defer({
10120                let mut cx = cx.clone();
10121                move || {
10122                    let _ = editor.update(&mut cx, |editor, _| {
10123                        if let Ok(i) =
10124                            editor
10125                                .find_all_references_task_sources
10126                                .binary_search_by(|anchor| {
10127                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10128                                })
10129                        {
10130                            editor.find_all_references_task_sources.remove(i);
10131                        }
10132                    });
10133                }
10134            });
10135
10136            let locations = references.await?;
10137            if locations.is_empty() {
10138                return anyhow::Ok(Navigated::No);
10139            }
10140
10141            workspace.update(&mut cx, |workspace, cx| {
10142                let title = locations
10143                    .first()
10144                    .as_ref()
10145                    .map(|location| {
10146                        let buffer = location.buffer.read(cx);
10147                        format!(
10148                            "References to `{}`",
10149                            buffer
10150                                .text_for_range(location.range.clone())
10151                                .collect::<String>()
10152                        )
10153                    })
10154                    .unwrap();
10155                Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
10156                Navigated::Yes
10157            })
10158        }))
10159    }
10160
10161    /// Opens a multibuffer with the given project locations in it
10162    pub fn open_locations_in_multibuffer(
10163        workspace: &mut Workspace,
10164        mut locations: Vec<Location>,
10165        title: String,
10166        split: bool,
10167        cx: &mut ViewContext<Workspace>,
10168    ) {
10169        // If there are multiple definitions, open them in a multibuffer
10170        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10171        let mut locations = locations.into_iter().peekable();
10172        let mut ranges_to_highlight = Vec::new();
10173        let capability = workspace.project().read(cx).capability();
10174
10175        let excerpt_buffer = cx.new_model(|cx| {
10176            let mut multibuffer = MultiBuffer::new(capability);
10177            while let Some(location) = locations.next() {
10178                let buffer = location.buffer.read(cx);
10179                let mut ranges_for_buffer = Vec::new();
10180                let range = location.range.to_offset(buffer);
10181                ranges_for_buffer.push(range.clone());
10182
10183                while let Some(next_location) = locations.peek() {
10184                    if next_location.buffer == location.buffer {
10185                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
10186                        locations.next();
10187                    } else {
10188                        break;
10189                    }
10190                }
10191
10192                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10193                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
10194                    location.buffer.clone(),
10195                    ranges_for_buffer,
10196                    DEFAULT_MULTIBUFFER_CONTEXT,
10197                    cx,
10198                ))
10199            }
10200
10201            multibuffer.with_title(title)
10202        });
10203
10204        let editor = cx.new_view(|cx| {
10205            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
10206        });
10207        editor.update(cx, |editor, cx| {
10208            if let Some(first_range) = ranges_to_highlight.first() {
10209                editor.change_selections(None, cx, |selections| {
10210                    selections.clear_disjoint();
10211                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10212                });
10213            }
10214            editor.highlight_background::<Self>(
10215                &ranges_to_highlight,
10216                |theme| theme.editor_highlighted_line_background,
10217                cx,
10218            );
10219        });
10220
10221        let item = Box::new(editor);
10222        let item_id = item.item_id();
10223
10224        if split {
10225            workspace.split_item(SplitDirection::Right, item.clone(), cx);
10226        } else {
10227            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10228                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10229                    pane.close_current_preview_item(cx)
10230                } else {
10231                    None
10232                }
10233            });
10234            workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
10235        }
10236        workspace.active_pane().update(cx, |pane, cx| {
10237            pane.set_preview_item_id(Some(item_id), cx);
10238        });
10239    }
10240
10241    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10242        use language::ToOffset as _;
10243
10244        let provider = self.semantics_provider.clone()?;
10245        let selection = self.selections.newest_anchor().clone();
10246        let (cursor_buffer, cursor_buffer_position) = self
10247            .buffer
10248            .read(cx)
10249            .text_anchor_for_position(selection.head(), cx)?;
10250        let (tail_buffer, cursor_buffer_position_end) = self
10251            .buffer
10252            .read(cx)
10253            .text_anchor_for_position(selection.tail(), cx)?;
10254        if tail_buffer != cursor_buffer {
10255            return None;
10256        }
10257
10258        let snapshot = cursor_buffer.read(cx).snapshot();
10259        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10260        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10261        let prepare_rename = provider
10262            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10263            .unwrap_or_else(|| Task::ready(Ok(None)));
10264        drop(snapshot);
10265
10266        Some(cx.spawn(|this, mut cx| async move {
10267            let rename_range = if let Some(range) = prepare_rename.await? {
10268                Some(range)
10269            } else {
10270                this.update(&mut cx, |this, cx| {
10271                    let buffer = this.buffer.read(cx).snapshot(cx);
10272                    let mut buffer_highlights = this
10273                        .document_highlights_for_position(selection.head(), &buffer)
10274                        .filter(|highlight| {
10275                            highlight.start.excerpt_id == selection.head().excerpt_id
10276                                && highlight.end.excerpt_id == selection.head().excerpt_id
10277                        });
10278                    buffer_highlights
10279                        .next()
10280                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10281                })?
10282            };
10283            if let Some(rename_range) = rename_range {
10284                this.update(&mut cx, |this, cx| {
10285                    let snapshot = cursor_buffer.read(cx).snapshot();
10286                    let rename_buffer_range = rename_range.to_offset(&snapshot);
10287                    let cursor_offset_in_rename_range =
10288                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10289                    let cursor_offset_in_rename_range_end =
10290                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10291
10292                    this.take_rename(false, cx);
10293                    let buffer = this.buffer.read(cx).read(cx);
10294                    let cursor_offset = selection.head().to_offset(&buffer);
10295                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10296                    let rename_end = rename_start + rename_buffer_range.len();
10297                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10298                    let mut old_highlight_id = None;
10299                    let old_name: Arc<str> = buffer
10300                        .chunks(rename_start..rename_end, true)
10301                        .map(|chunk| {
10302                            if old_highlight_id.is_none() {
10303                                old_highlight_id = chunk.syntax_highlight_id;
10304                            }
10305                            chunk.text
10306                        })
10307                        .collect::<String>()
10308                        .into();
10309
10310                    drop(buffer);
10311
10312                    // Position the selection in the rename editor so that it matches the current selection.
10313                    this.show_local_selections = false;
10314                    let rename_editor = cx.new_view(|cx| {
10315                        let mut editor = Editor::single_line(cx);
10316                        editor.buffer.update(cx, |buffer, cx| {
10317                            buffer.edit([(0..0, old_name.clone())], None, cx)
10318                        });
10319                        let rename_selection_range = match cursor_offset_in_rename_range
10320                            .cmp(&cursor_offset_in_rename_range_end)
10321                        {
10322                            Ordering::Equal => {
10323                                editor.select_all(&SelectAll, cx);
10324                                return editor;
10325                            }
10326                            Ordering::Less => {
10327                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10328                            }
10329                            Ordering::Greater => {
10330                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10331                            }
10332                        };
10333                        if rename_selection_range.end > old_name.len() {
10334                            editor.select_all(&SelectAll, cx);
10335                        } else {
10336                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10337                                s.select_ranges([rename_selection_range]);
10338                            });
10339                        }
10340                        editor
10341                    });
10342                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10343                        if e == &EditorEvent::Focused {
10344                            cx.emit(EditorEvent::FocusedIn)
10345                        }
10346                    })
10347                    .detach();
10348
10349                    let write_highlights =
10350                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10351                    let read_highlights =
10352                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
10353                    let ranges = write_highlights
10354                        .iter()
10355                        .flat_map(|(_, ranges)| ranges.iter())
10356                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10357                        .cloned()
10358                        .collect();
10359
10360                    this.highlight_text::<Rename>(
10361                        ranges,
10362                        HighlightStyle {
10363                            fade_out: Some(0.6),
10364                            ..Default::default()
10365                        },
10366                        cx,
10367                    );
10368                    let rename_focus_handle = rename_editor.focus_handle(cx);
10369                    cx.focus(&rename_focus_handle);
10370                    let block_id = this.insert_blocks(
10371                        [BlockProperties {
10372                            style: BlockStyle::Flex,
10373                            placement: BlockPlacement::Below(range.start),
10374                            height: 1,
10375                            render: Box::new({
10376                                let rename_editor = rename_editor.clone();
10377                                move |cx: &mut BlockContext| {
10378                                    let mut text_style = cx.editor_style.text.clone();
10379                                    if let Some(highlight_style) = old_highlight_id
10380                                        .and_then(|h| h.style(&cx.editor_style.syntax))
10381                                    {
10382                                        text_style = text_style.highlight(highlight_style);
10383                                    }
10384                                    div()
10385                                        .pl(cx.anchor_x)
10386                                        .child(EditorElement::new(
10387                                            &rename_editor,
10388                                            EditorStyle {
10389                                                background: cx.theme().system().transparent,
10390                                                local_player: cx.editor_style.local_player,
10391                                                text: text_style,
10392                                                scrollbar_width: cx.editor_style.scrollbar_width,
10393                                                syntax: cx.editor_style.syntax.clone(),
10394                                                status: cx.editor_style.status.clone(),
10395                                                inlay_hints_style: HighlightStyle {
10396                                                    font_weight: Some(FontWeight::BOLD),
10397                                                    ..make_inlay_hints_style(cx)
10398                                                },
10399                                                suggestions_style: HighlightStyle {
10400                                                    color: Some(cx.theme().status().predictive),
10401                                                    ..HighlightStyle::default()
10402                                                },
10403                                                ..EditorStyle::default()
10404                                            },
10405                                        ))
10406                                        .into_any_element()
10407                                }
10408                            }),
10409                            priority: 0,
10410                        }],
10411                        Some(Autoscroll::fit()),
10412                        cx,
10413                    )[0];
10414                    this.pending_rename = Some(RenameState {
10415                        range,
10416                        old_name,
10417                        editor: rename_editor,
10418                        block_id,
10419                    });
10420                })?;
10421            }
10422
10423            Ok(())
10424        }))
10425    }
10426
10427    pub fn confirm_rename(
10428        &mut self,
10429        _: &ConfirmRename,
10430        cx: &mut ViewContext<Self>,
10431    ) -> Option<Task<Result<()>>> {
10432        let rename = self.take_rename(false, cx)?;
10433        let workspace = self.workspace()?.downgrade();
10434        let (buffer, start) = self
10435            .buffer
10436            .read(cx)
10437            .text_anchor_for_position(rename.range.start, cx)?;
10438        let (end_buffer, _) = self
10439            .buffer
10440            .read(cx)
10441            .text_anchor_for_position(rename.range.end, cx)?;
10442        if buffer != end_buffer {
10443            return None;
10444        }
10445
10446        let old_name = rename.old_name;
10447        let new_name = rename.editor.read(cx).text(cx);
10448
10449        let rename = self.semantics_provider.as_ref()?.perform_rename(
10450            &buffer,
10451            start,
10452            new_name.clone(),
10453            cx,
10454        )?;
10455
10456        Some(cx.spawn(|editor, mut cx| async move {
10457            let project_transaction = rename.await?;
10458            Self::open_project_transaction(
10459                &editor,
10460                workspace,
10461                project_transaction,
10462                format!("Rename: {}{}", old_name, new_name),
10463                cx.clone(),
10464            )
10465            .await?;
10466
10467            editor.update(&mut cx, |editor, cx| {
10468                editor.refresh_document_highlights(cx);
10469            })?;
10470            Ok(())
10471        }))
10472    }
10473
10474    fn take_rename(
10475        &mut self,
10476        moving_cursor: bool,
10477        cx: &mut ViewContext<Self>,
10478    ) -> Option<RenameState> {
10479        let rename = self.pending_rename.take()?;
10480        if rename.editor.focus_handle(cx).is_focused(cx) {
10481            cx.focus(&self.focus_handle);
10482        }
10483
10484        self.remove_blocks(
10485            [rename.block_id].into_iter().collect(),
10486            Some(Autoscroll::fit()),
10487            cx,
10488        );
10489        self.clear_highlights::<Rename>(cx);
10490        self.show_local_selections = true;
10491
10492        if moving_cursor {
10493            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10494                editor.selections.newest::<usize>(cx).head()
10495            });
10496
10497            // Update the selection to match the position of the selection inside
10498            // the rename editor.
10499            let snapshot = self.buffer.read(cx).read(cx);
10500            let rename_range = rename.range.to_offset(&snapshot);
10501            let cursor_in_editor = snapshot
10502                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10503                .min(rename_range.end);
10504            drop(snapshot);
10505
10506            self.change_selections(None, cx, |s| {
10507                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10508            });
10509        } else {
10510            self.refresh_document_highlights(cx);
10511        }
10512
10513        Some(rename)
10514    }
10515
10516    pub fn pending_rename(&self) -> Option<&RenameState> {
10517        self.pending_rename.as_ref()
10518    }
10519
10520    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10521        let project = match &self.project {
10522            Some(project) => project.clone(),
10523            None => return None,
10524        };
10525
10526        Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10527    }
10528
10529    fn format_selections(
10530        &mut self,
10531        _: &FormatSelections,
10532        cx: &mut ViewContext<Self>,
10533    ) -> Option<Task<Result<()>>> {
10534        let project = match &self.project {
10535            Some(project) => project.clone(),
10536            None => return None,
10537        };
10538
10539        let selections = self
10540            .selections
10541            .all_adjusted(cx)
10542            .into_iter()
10543            .filter(|s| !s.is_empty())
10544            .collect_vec();
10545
10546        Some(self.perform_format(
10547            project,
10548            FormatTrigger::Manual,
10549            FormatTarget::Ranges(selections),
10550            cx,
10551        ))
10552    }
10553
10554    fn perform_format(
10555        &mut self,
10556        project: Model<Project>,
10557        trigger: FormatTrigger,
10558        target: FormatTarget,
10559        cx: &mut ViewContext<Self>,
10560    ) -> Task<Result<()>> {
10561        let buffer = self.buffer().clone();
10562        let mut buffers = buffer.read(cx).all_buffers();
10563        if trigger == FormatTrigger::Save {
10564            buffers.retain(|buffer| buffer.read(cx).is_dirty());
10565        }
10566
10567        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10568        let format = project.update(cx, |project, cx| {
10569            project.format(buffers, true, trigger, target, cx)
10570        });
10571
10572        cx.spawn(|_, mut cx| async move {
10573            let transaction = futures::select_biased! {
10574                () = timeout => {
10575                    log::warn!("timed out waiting for formatting");
10576                    None
10577                }
10578                transaction = format.log_err().fuse() => transaction,
10579            };
10580
10581            buffer
10582                .update(&mut cx, |buffer, cx| {
10583                    if let Some(transaction) = transaction {
10584                        if !buffer.is_singleton() {
10585                            buffer.push_transaction(&transaction.0, cx);
10586                        }
10587                    }
10588
10589                    cx.notify();
10590                })
10591                .ok();
10592
10593            Ok(())
10594        })
10595    }
10596
10597    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10598        if let Some(project) = self.project.clone() {
10599            self.buffer.update(cx, |multi_buffer, cx| {
10600                project.update(cx, |project, cx| {
10601                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10602                });
10603            })
10604        }
10605    }
10606
10607    fn cancel_language_server_work(
10608        &mut self,
10609        _: &actions::CancelLanguageServerWork,
10610        cx: &mut ViewContext<Self>,
10611    ) {
10612        if let Some(project) = self.project.clone() {
10613            self.buffer.update(cx, |multi_buffer, cx| {
10614                project.update(cx, |project, cx| {
10615                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10616                });
10617            })
10618        }
10619    }
10620
10621    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10622        cx.show_character_palette();
10623    }
10624
10625    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10626        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10627            let buffer = self.buffer.read(cx).snapshot(cx);
10628            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10629            let is_valid = buffer
10630                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10631                .any(|entry| {
10632                    entry.diagnostic.is_primary
10633                        && !entry.range.is_empty()
10634                        && entry.range.start == primary_range_start
10635                        && entry.diagnostic.message == active_diagnostics.primary_message
10636                });
10637
10638            if is_valid != active_diagnostics.is_valid {
10639                active_diagnostics.is_valid = is_valid;
10640                let mut new_styles = HashMap::default();
10641                for (block_id, diagnostic) in &active_diagnostics.blocks {
10642                    new_styles.insert(
10643                        *block_id,
10644                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10645                    );
10646                }
10647                self.display_map.update(cx, |display_map, _cx| {
10648                    display_map.replace_blocks(new_styles)
10649                });
10650            }
10651        }
10652    }
10653
10654    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10655        self.dismiss_diagnostics(cx);
10656        let snapshot = self.snapshot(cx);
10657        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10658            let buffer = self.buffer.read(cx).snapshot(cx);
10659
10660            let mut primary_range = None;
10661            let mut primary_message = None;
10662            let mut group_end = Point::zero();
10663            let diagnostic_group = buffer
10664                .diagnostic_group::<MultiBufferPoint>(group_id)
10665                .filter_map(|entry| {
10666                    if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10667                        && (entry.range.start.row == entry.range.end.row
10668                            || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10669                    {
10670                        return None;
10671                    }
10672                    if entry.range.end > group_end {
10673                        group_end = entry.range.end;
10674                    }
10675                    if entry.diagnostic.is_primary {
10676                        primary_range = Some(entry.range.clone());
10677                        primary_message = Some(entry.diagnostic.message.clone());
10678                    }
10679                    Some(entry)
10680                })
10681                .collect::<Vec<_>>();
10682            let primary_range = primary_range?;
10683            let primary_message = primary_message?;
10684            let primary_range =
10685                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10686
10687            let blocks = display_map
10688                .insert_blocks(
10689                    diagnostic_group.iter().map(|entry| {
10690                        let diagnostic = entry.diagnostic.clone();
10691                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10692                        BlockProperties {
10693                            style: BlockStyle::Fixed,
10694                            placement: BlockPlacement::Below(
10695                                buffer.anchor_after(entry.range.start),
10696                            ),
10697                            height: message_height,
10698                            render: diagnostic_block_renderer(diagnostic, None, true, true),
10699                            priority: 0,
10700                        }
10701                    }),
10702                    cx,
10703                )
10704                .into_iter()
10705                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10706                .collect();
10707
10708            Some(ActiveDiagnosticGroup {
10709                primary_range,
10710                primary_message,
10711                group_id,
10712                blocks,
10713                is_valid: true,
10714            })
10715        });
10716        self.active_diagnostics.is_some()
10717    }
10718
10719    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10720        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10721            self.display_map.update(cx, |display_map, cx| {
10722                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10723            });
10724            cx.notify();
10725        }
10726    }
10727
10728    pub fn set_selections_from_remote(
10729        &mut self,
10730        selections: Vec<Selection<Anchor>>,
10731        pending_selection: Option<Selection<Anchor>>,
10732        cx: &mut ViewContext<Self>,
10733    ) {
10734        let old_cursor_position = self.selections.newest_anchor().head();
10735        self.selections.change_with(cx, |s| {
10736            s.select_anchors(selections);
10737            if let Some(pending_selection) = pending_selection {
10738                s.set_pending(pending_selection, SelectMode::Character);
10739            } else {
10740                s.clear_pending();
10741            }
10742        });
10743        self.selections_did_change(false, &old_cursor_position, true, cx);
10744    }
10745
10746    fn push_to_selection_history(&mut self) {
10747        self.selection_history.push(SelectionHistoryEntry {
10748            selections: self.selections.disjoint_anchors(),
10749            select_next_state: self.select_next_state.clone(),
10750            select_prev_state: self.select_prev_state.clone(),
10751            add_selections_state: self.add_selections_state.clone(),
10752        });
10753    }
10754
10755    pub fn transact(
10756        &mut self,
10757        cx: &mut ViewContext<Self>,
10758        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10759    ) -> Option<TransactionId> {
10760        self.start_transaction_at(Instant::now(), cx);
10761        update(self, cx);
10762        self.end_transaction_at(Instant::now(), cx)
10763    }
10764
10765    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10766        self.end_selection(cx);
10767        if let Some(tx_id) = self
10768            .buffer
10769            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10770        {
10771            self.selection_history
10772                .insert_transaction(tx_id, self.selections.disjoint_anchors());
10773            cx.emit(EditorEvent::TransactionBegun {
10774                transaction_id: tx_id,
10775            })
10776        }
10777    }
10778
10779    fn end_transaction_at(
10780        &mut self,
10781        now: Instant,
10782        cx: &mut ViewContext<Self>,
10783    ) -> Option<TransactionId> {
10784        if let Some(transaction_id) = self
10785            .buffer
10786            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10787        {
10788            if let Some((_, end_selections)) =
10789                self.selection_history.transaction_mut(transaction_id)
10790            {
10791                *end_selections = Some(self.selections.disjoint_anchors());
10792            } else {
10793                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10794            }
10795
10796            cx.emit(EditorEvent::Edited { transaction_id });
10797            Some(transaction_id)
10798        } else {
10799            None
10800        }
10801    }
10802
10803    pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10804        let selection = self.selections.newest::<Point>(cx);
10805
10806        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10807        let range = if selection.is_empty() {
10808            let point = selection.head().to_display_point(&display_map);
10809            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10810            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10811                .to_point(&display_map);
10812            start..end
10813        } else {
10814            selection.range()
10815        };
10816        if display_map.folds_in_range(range).next().is_some() {
10817            self.unfold_lines(&Default::default(), cx)
10818        } else {
10819            self.fold(&Default::default(), cx)
10820        }
10821    }
10822
10823    pub fn toggle_fold_recursive(
10824        &mut self,
10825        _: &actions::ToggleFoldRecursive,
10826        cx: &mut ViewContext<Self>,
10827    ) {
10828        let selection = self.selections.newest::<Point>(cx);
10829
10830        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10831        let range = if selection.is_empty() {
10832            let point = selection.head().to_display_point(&display_map);
10833            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10834            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10835                .to_point(&display_map);
10836            start..end
10837        } else {
10838            selection.range()
10839        };
10840        if display_map.folds_in_range(range).next().is_some() {
10841            self.unfold_recursive(&Default::default(), cx)
10842        } else {
10843            self.fold_recursive(&Default::default(), cx)
10844        }
10845    }
10846
10847    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10848        let mut fold_ranges = Vec::new();
10849        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10850        let selections = self.selections.all_adjusted(cx);
10851
10852        for selection in selections {
10853            let range = selection.range().sorted();
10854            let buffer_start_row = range.start.row;
10855
10856            if range.start.row != range.end.row {
10857                let mut found = false;
10858                let mut row = range.start.row;
10859                while row <= range.end.row {
10860                    if let Some((foldable_range, fold_text)) =
10861                        { display_map.foldable_range(MultiBufferRow(row)) }
10862                    {
10863                        found = true;
10864                        row = foldable_range.end.row + 1;
10865                        fold_ranges.push((foldable_range, fold_text));
10866                    } else {
10867                        row += 1
10868                    }
10869                }
10870                if found {
10871                    continue;
10872                }
10873            }
10874
10875            for row in (0..=range.start.row).rev() {
10876                if let Some((foldable_range, fold_text)) =
10877                    display_map.foldable_range(MultiBufferRow(row))
10878                {
10879                    if foldable_range.end.row >= buffer_start_row {
10880                        fold_ranges.push((foldable_range, fold_text));
10881                        if row <= range.start.row {
10882                            break;
10883                        }
10884                    }
10885                }
10886            }
10887        }
10888
10889        self.fold_ranges(fold_ranges, true, cx);
10890    }
10891
10892    fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10893        let fold_at_level = fold_at.level;
10894        let snapshot = self.buffer.read(cx).snapshot(cx);
10895        let mut fold_ranges = Vec::new();
10896        let mut stack = vec![(0, snapshot.max_buffer_row().0, 1)];
10897
10898        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10899            while start_row < end_row {
10900                match self.snapshot(cx).foldable_range(MultiBufferRow(start_row)) {
10901                    Some(foldable_range) => {
10902                        let nested_start_row = foldable_range.0.start.row + 1;
10903                        let nested_end_row = foldable_range.0.end.row;
10904
10905                        if current_level < fold_at_level {
10906                            stack.push((nested_start_row, nested_end_row, current_level + 1));
10907                        } else if current_level == fold_at_level {
10908                            fold_ranges.push(foldable_range);
10909                        }
10910
10911                        start_row = nested_end_row + 1;
10912                    }
10913                    None => start_row += 1,
10914                }
10915            }
10916        }
10917
10918        self.fold_ranges(fold_ranges, true, cx);
10919    }
10920
10921    pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10922        let mut fold_ranges = Vec::new();
10923        let snapshot = self.buffer.read(cx).snapshot(cx);
10924
10925        for row in 0..snapshot.max_buffer_row().0 {
10926            if let Some(foldable_range) = self.snapshot(cx).foldable_range(MultiBufferRow(row)) {
10927                fold_ranges.push(foldable_range);
10928            }
10929        }
10930
10931        self.fold_ranges(fold_ranges, true, cx);
10932    }
10933
10934    pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10935        let mut fold_ranges = Vec::new();
10936        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10937        let selections = self.selections.all_adjusted(cx);
10938
10939        for selection in selections {
10940            let range = selection.range().sorted();
10941            let buffer_start_row = range.start.row;
10942
10943            if range.start.row != range.end.row {
10944                let mut found = false;
10945                for row in range.start.row..=range.end.row {
10946                    if let Some((foldable_range, fold_text)) =
10947                        { display_map.foldable_range(MultiBufferRow(row)) }
10948                    {
10949                        found = true;
10950                        fold_ranges.push((foldable_range, fold_text));
10951                    }
10952                }
10953                if found {
10954                    continue;
10955                }
10956            }
10957
10958            for row in (0..=range.start.row).rev() {
10959                if let Some((foldable_range, fold_text)) =
10960                    display_map.foldable_range(MultiBufferRow(row))
10961                {
10962                    if foldable_range.end.row >= buffer_start_row {
10963                        fold_ranges.push((foldable_range, fold_text));
10964                    } else {
10965                        break;
10966                    }
10967                }
10968            }
10969        }
10970
10971        self.fold_ranges(fold_ranges, true, cx);
10972    }
10973
10974    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10975        let buffer_row = fold_at.buffer_row;
10976        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10977
10978        if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
10979            let autoscroll = self
10980                .selections
10981                .all::<Point>(cx)
10982                .iter()
10983                .any(|selection| fold_range.overlaps(&selection.range()));
10984
10985            self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
10986        }
10987    }
10988
10989    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10990        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10991        let buffer = &display_map.buffer_snapshot;
10992        let selections = self.selections.all::<Point>(cx);
10993        let ranges = selections
10994            .iter()
10995            .map(|s| {
10996                let range = s.display_range(&display_map).sorted();
10997                let mut start = range.start.to_point(&display_map);
10998                let mut end = range.end.to_point(&display_map);
10999                start.column = 0;
11000                end.column = buffer.line_len(MultiBufferRow(end.row));
11001                start..end
11002            })
11003            .collect::<Vec<_>>();
11004
11005        self.unfold_ranges(&ranges, true, true, cx);
11006    }
11007
11008    pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
11009        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11010        let selections = self.selections.all::<Point>(cx);
11011        let ranges = selections
11012            .iter()
11013            .map(|s| {
11014                let mut range = s.display_range(&display_map).sorted();
11015                *range.start.column_mut() = 0;
11016                *range.end.column_mut() = display_map.line_len(range.end.row());
11017                let start = range.start.to_point(&display_map);
11018                let end = range.end.to_point(&display_map);
11019                start..end
11020            })
11021            .collect::<Vec<_>>();
11022
11023        self.unfold_ranges(&ranges, true, true, cx);
11024    }
11025
11026    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
11027        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11028
11029        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
11030            ..Point::new(
11031                unfold_at.buffer_row.0,
11032                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
11033            );
11034
11035        let autoscroll = self
11036            .selections
11037            .all::<Point>(cx)
11038            .iter()
11039            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
11040
11041        self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
11042    }
11043
11044    pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
11045        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11046        self.unfold_ranges(
11047            &[Point::zero()..display_map.max_point().to_point(&display_map)],
11048            true,
11049            true,
11050            cx,
11051        );
11052    }
11053
11054    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
11055        let selections = self.selections.all::<Point>(cx);
11056        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11057        let line_mode = self.selections.line_mode;
11058        let ranges = selections.into_iter().map(|s| {
11059            if line_mode {
11060                let start = Point::new(s.start.row, 0);
11061                let end = Point::new(
11062                    s.end.row,
11063                    display_map
11064                        .buffer_snapshot
11065                        .line_len(MultiBufferRow(s.end.row)),
11066                );
11067                (start..end, display_map.fold_placeholder.clone())
11068            } else {
11069                (s.start..s.end, display_map.fold_placeholder.clone())
11070            }
11071        });
11072        self.fold_ranges(ranges, true, cx);
11073    }
11074
11075    pub fn fold_ranges<T: ToOffset + Clone>(
11076        &mut self,
11077        ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
11078        auto_scroll: bool,
11079        cx: &mut ViewContext<Self>,
11080    ) {
11081        let mut fold_ranges = Vec::new();
11082        let mut buffers_affected = HashMap::default();
11083        let multi_buffer = self.buffer().read(cx);
11084        for (fold_range, fold_text) in ranges {
11085            if let Some((_, buffer, _)) =
11086                multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
11087            {
11088                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
11089            };
11090            fold_ranges.push((fold_range, fold_text));
11091        }
11092
11093        let mut ranges = fold_ranges.into_iter().peekable();
11094        if ranges.peek().is_some() {
11095            self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
11096
11097            if auto_scroll {
11098                self.request_autoscroll(Autoscroll::fit(), cx);
11099            }
11100
11101            for buffer in buffers_affected.into_values() {
11102                self.sync_expanded_diff_hunks(buffer, cx);
11103            }
11104
11105            cx.notify();
11106
11107            if let Some(active_diagnostics) = self.active_diagnostics.take() {
11108                // Clear diagnostics block when folding a range that contains it.
11109                let snapshot = self.snapshot(cx);
11110                if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
11111                    drop(snapshot);
11112                    self.active_diagnostics = Some(active_diagnostics);
11113                    self.dismiss_diagnostics(cx);
11114                } else {
11115                    self.active_diagnostics = Some(active_diagnostics);
11116                }
11117            }
11118
11119            self.scrollbar_marker_state.dirty = true;
11120        }
11121    }
11122
11123    /// Removes any folds whose ranges intersect any of the given ranges.
11124    pub fn unfold_ranges<T: ToOffset + Clone>(
11125        &mut self,
11126        ranges: &[Range<T>],
11127        inclusive: bool,
11128        auto_scroll: bool,
11129        cx: &mut ViewContext<Self>,
11130    ) {
11131        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11132            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
11133        });
11134    }
11135
11136    /// Removes any folds with the given ranges.
11137    pub fn remove_folds_with_type<T: ToOffset + Clone>(
11138        &mut self,
11139        ranges: &[Range<T>],
11140        type_id: TypeId,
11141        auto_scroll: bool,
11142        cx: &mut ViewContext<Self>,
11143    ) {
11144        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11145            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
11146        });
11147    }
11148
11149    fn remove_folds_with<T: ToOffset + Clone>(
11150        &mut self,
11151        ranges: &[Range<T>],
11152        auto_scroll: bool,
11153        cx: &mut ViewContext<Self>,
11154        update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
11155    ) {
11156        if ranges.is_empty() {
11157            return;
11158        }
11159
11160        let mut buffers_affected = HashMap::default();
11161        let multi_buffer = self.buffer().read(cx);
11162        for range in ranges {
11163            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11164                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
11165            };
11166        }
11167
11168        self.display_map.update(cx, update);
11169        if auto_scroll {
11170            self.request_autoscroll(Autoscroll::fit(), cx);
11171        }
11172
11173        for buffer in buffers_affected.into_values() {
11174            self.sync_expanded_diff_hunks(buffer, cx);
11175        }
11176
11177        cx.notify();
11178        self.scrollbar_marker_state.dirty = true;
11179        self.active_indent_guides_state.dirty = true;
11180    }
11181
11182    pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
11183        self.display_map.read(cx).fold_placeholder.clone()
11184    }
11185
11186    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11187        if hovered != self.gutter_hovered {
11188            self.gutter_hovered = hovered;
11189            cx.notify();
11190        }
11191    }
11192
11193    pub fn insert_blocks(
11194        &mut self,
11195        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11196        autoscroll: Option<Autoscroll>,
11197        cx: &mut ViewContext<Self>,
11198    ) -> Vec<CustomBlockId> {
11199        let blocks = self
11200            .display_map
11201            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11202        if let Some(autoscroll) = autoscroll {
11203            self.request_autoscroll(autoscroll, cx);
11204        }
11205        cx.notify();
11206        blocks
11207    }
11208
11209    pub fn resize_blocks(
11210        &mut self,
11211        heights: HashMap<CustomBlockId, u32>,
11212        autoscroll: Option<Autoscroll>,
11213        cx: &mut ViewContext<Self>,
11214    ) {
11215        self.display_map
11216            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11217        if let Some(autoscroll) = autoscroll {
11218            self.request_autoscroll(autoscroll, cx);
11219        }
11220        cx.notify();
11221    }
11222
11223    pub fn replace_blocks(
11224        &mut self,
11225        renderers: HashMap<CustomBlockId, RenderBlock>,
11226        autoscroll: Option<Autoscroll>,
11227        cx: &mut ViewContext<Self>,
11228    ) {
11229        self.display_map
11230            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11231        if let Some(autoscroll) = autoscroll {
11232            self.request_autoscroll(autoscroll, cx);
11233        }
11234        cx.notify();
11235    }
11236
11237    pub fn remove_blocks(
11238        &mut self,
11239        block_ids: HashSet<CustomBlockId>,
11240        autoscroll: Option<Autoscroll>,
11241        cx: &mut ViewContext<Self>,
11242    ) {
11243        self.display_map.update(cx, |display_map, cx| {
11244            display_map.remove_blocks(block_ids, cx)
11245        });
11246        if let Some(autoscroll) = autoscroll {
11247            self.request_autoscroll(autoscroll, cx);
11248        }
11249        cx.notify();
11250    }
11251
11252    pub fn row_for_block(
11253        &self,
11254        block_id: CustomBlockId,
11255        cx: &mut ViewContext<Self>,
11256    ) -> Option<DisplayRow> {
11257        self.display_map
11258            .update(cx, |map, cx| map.row_for_block(block_id, cx))
11259    }
11260
11261    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11262        self.focused_block = Some(focused_block);
11263    }
11264
11265    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11266        self.focused_block.take()
11267    }
11268
11269    pub fn insert_creases(
11270        &mut self,
11271        creases: impl IntoIterator<Item = Crease>,
11272        cx: &mut ViewContext<Self>,
11273    ) -> Vec<CreaseId> {
11274        self.display_map
11275            .update(cx, |map, cx| map.insert_creases(creases, cx))
11276    }
11277
11278    pub fn remove_creases(
11279        &mut self,
11280        ids: impl IntoIterator<Item = CreaseId>,
11281        cx: &mut ViewContext<Self>,
11282    ) {
11283        self.display_map
11284            .update(cx, |map, cx| map.remove_creases(ids, cx));
11285    }
11286
11287    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11288        self.display_map
11289            .update(cx, |map, cx| map.snapshot(cx))
11290            .longest_row()
11291    }
11292
11293    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11294        self.display_map
11295            .update(cx, |map, cx| map.snapshot(cx))
11296            .max_point()
11297    }
11298
11299    pub fn text(&self, cx: &AppContext) -> String {
11300        self.buffer.read(cx).read(cx).text()
11301    }
11302
11303    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11304        let text = self.text(cx);
11305        let text = text.trim();
11306
11307        if text.is_empty() {
11308            return None;
11309        }
11310
11311        Some(text.to_string())
11312    }
11313
11314    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11315        self.transact(cx, |this, cx| {
11316            this.buffer
11317                .read(cx)
11318                .as_singleton()
11319                .expect("you can only call set_text on editors for singleton buffers")
11320                .update(cx, |buffer, cx| buffer.set_text(text, cx));
11321        });
11322    }
11323
11324    pub fn display_text(&self, cx: &mut AppContext) -> String {
11325        self.display_map
11326            .update(cx, |map, cx| map.snapshot(cx))
11327            .text()
11328    }
11329
11330    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11331        let mut wrap_guides = smallvec::smallvec![];
11332
11333        if self.show_wrap_guides == Some(false) {
11334            return wrap_guides;
11335        }
11336
11337        let settings = self.buffer.read(cx).settings_at(0, cx);
11338        if settings.show_wrap_guides {
11339            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11340                wrap_guides.push((soft_wrap as usize, true));
11341            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11342                wrap_guides.push((soft_wrap as usize, true));
11343            }
11344            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11345        }
11346
11347        wrap_guides
11348    }
11349
11350    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11351        let settings = self.buffer.read(cx).settings_at(0, cx);
11352        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11353        match mode {
11354            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11355                SoftWrap::None
11356            }
11357            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11358            language_settings::SoftWrap::PreferredLineLength => {
11359                SoftWrap::Column(settings.preferred_line_length)
11360            }
11361            language_settings::SoftWrap::Bounded => {
11362                SoftWrap::Bounded(settings.preferred_line_length)
11363            }
11364        }
11365    }
11366
11367    pub fn set_soft_wrap_mode(
11368        &mut self,
11369        mode: language_settings::SoftWrap,
11370        cx: &mut ViewContext<Self>,
11371    ) {
11372        self.soft_wrap_mode_override = Some(mode);
11373        cx.notify();
11374    }
11375
11376    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11377        self.text_style_refinement = Some(style);
11378    }
11379
11380    /// called by the Element so we know what style we were most recently rendered with.
11381    pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11382        let rem_size = cx.rem_size();
11383        self.display_map.update(cx, |map, cx| {
11384            map.set_font(
11385                style.text.font(),
11386                style.text.font_size.to_pixels(rem_size),
11387                cx,
11388            )
11389        });
11390        self.style = Some(style);
11391    }
11392
11393    pub fn style(&self) -> Option<&EditorStyle> {
11394        self.style.as_ref()
11395    }
11396
11397    // Called by the element. This method is not designed to be called outside of the editor
11398    // element's layout code because it does not notify when rewrapping is computed synchronously.
11399    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11400        self.display_map
11401            .update(cx, |map, cx| map.set_wrap_width(width, cx))
11402    }
11403
11404    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11405        if self.soft_wrap_mode_override.is_some() {
11406            self.soft_wrap_mode_override.take();
11407        } else {
11408            let soft_wrap = match self.soft_wrap_mode(cx) {
11409                SoftWrap::GitDiff => return,
11410                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11411                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11412                    language_settings::SoftWrap::None
11413                }
11414            };
11415            self.soft_wrap_mode_override = Some(soft_wrap);
11416        }
11417        cx.notify();
11418    }
11419
11420    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11421        let Some(workspace) = self.workspace() else {
11422            return;
11423        };
11424        let fs = workspace.read(cx).app_state().fs.clone();
11425        let current_show = TabBarSettings::get_global(cx).show;
11426        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11427            setting.show = Some(!current_show);
11428        });
11429    }
11430
11431    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11432        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11433            self.buffer
11434                .read(cx)
11435                .settings_at(0, cx)
11436                .indent_guides
11437                .enabled
11438        });
11439        self.show_indent_guides = Some(!currently_enabled);
11440        cx.notify();
11441    }
11442
11443    fn should_show_indent_guides(&self) -> Option<bool> {
11444        self.show_indent_guides
11445    }
11446
11447    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11448        let mut editor_settings = EditorSettings::get_global(cx).clone();
11449        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11450        EditorSettings::override_global(editor_settings, cx);
11451    }
11452
11453    pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11454        self.use_relative_line_numbers
11455            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11456    }
11457
11458    pub fn toggle_relative_line_numbers(
11459        &mut self,
11460        _: &ToggleRelativeLineNumbers,
11461        cx: &mut ViewContext<Self>,
11462    ) {
11463        let is_relative = self.should_use_relative_line_numbers(cx);
11464        self.set_relative_line_number(Some(!is_relative), cx)
11465    }
11466
11467    pub fn set_relative_line_number(
11468        &mut self,
11469        is_relative: Option<bool>,
11470        cx: &mut ViewContext<Self>,
11471    ) {
11472        self.use_relative_line_numbers = is_relative;
11473        cx.notify();
11474    }
11475
11476    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11477        self.show_gutter = show_gutter;
11478        cx.notify();
11479    }
11480
11481    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11482        self.show_line_numbers = Some(show_line_numbers);
11483        cx.notify();
11484    }
11485
11486    pub fn set_show_git_diff_gutter(
11487        &mut self,
11488        show_git_diff_gutter: bool,
11489        cx: &mut ViewContext<Self>,
11490    ) {
11491        self.show_git_diff_gutter = Some(show_git_diff_gutter);
11492        cx.notify();
11493    }
11494
11495    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11496        self.show_code_actions = Some(show_code_actions);
11497        cx.notify();
11498    }
11499
11500    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11501        self.show_runnables = Some(show_runnables);
11502        cx.notify();
11503    }
11504
11505    pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11506        if self.display_map.read(cx).masked != masked {
11507            self.display_map.update(cx, |map, _| map.masked = masked);
11508        }
11509        cx.notify()
11510    }
11511
11512    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11513        self.show_wrap_guides = Some(show_wrap_guides);
11514        cx.notify();
11515    }
11516
11517    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11518        self.show_indent_guides = Some(show_indent_guides);
11519        cx.notify();
11520    }
11521
11522    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11523        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11524            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11525                if let Some(dir) = file.abs_path(cx).parent() {
11526                    return Some(dir.to_owned());
11527                }
11528            }
11529
11530            if let Some(project_path) = buffer.read(cx).project_path(cx) {
11531                return Some(project_path.path.to_path_buf());
11532            }
11533        }
11534
11535        None
11536    }
11537
11538    fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11539        self.active_excerpt(cx)?
11540            .1
11541            .read(cx)
11542            .file()
11543            .and_then(|f| f.as_local())
11544    }
11545
11546    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11547        if let Some(target) = self.target_file(cx) {
11548            cx.reveal_path(&target.abs_path(cx));
11549        }
11550    }
11551
11552    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11553        if let Some(file) = self.target_file(cx) {
11554            if let Some(path) = file.abs_path(cx).to_str() {
11555                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11556            }
11557        }
11558    }
11559
11560    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11561        if let Some(file) = self.target_file(cx) {
11562            if let Some(path) = file.path().to_str() {
11563                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11564            }
11565        }
11566    }
11567
11568    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11569        self.show_git_blame_gutter = !self.show_git_blame_gutter;
11570
11571        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11572            self.start_git_blame(true, cx);
11573        }
11574
11575        cx.notify();
11576    }
11577
11578    pub fn toggle_git_blame_inline(
11579        &mut self,
11580        _: &ToggleGitBlameInline,
11581        cx: &mut ViewContext<Self>,
11582    ) {
11583        self.toggle_git_blame_inline_internal(true, cx);
11584        cx.notify();
11585    }
11586
11587    pub fn git_blame_inline_enabled(&self) -> bool {
11588        self.git_blame_inline_enabled
11589    }
11590
11591    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11592        self.show_selection_menu = self
11593            .show_selection_menu
11594            .map(|show_selections_menu| !show_selections_menu)
11595            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11596
11597        cx.notify();
11598    }
11599
11600    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11601        self.show_selection_menu
11602            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11603    }
11604
11605    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11606        if let Some(project) = self.project.as_ref() {
11607            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11608                return;
11609            };
11610
11611            if buffer.read(cx).file().is_none() {
11612                return;
11613            }
11614
11615            let focused = self.focus_handle(cx).contains_focused(cx);
11616
11617            let project = project.clone();
11618            let blame =
11619                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11620            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11621            self.blame = Some(blame);
11622        }
11623    }
11624
11625    fn toggle_git_blame_inline_internal(
11626        &mut self,
11627        user_triggered: bool,
11628        cx: &mut ViewContext<Self>,
11629    ) {
11630        if self.git_blame_inline_enabled {
11631            self.git_blame_inline_enabled = false;
11632            self.show_git_blame_inline = false;
11633            self.show_git_blame_inline_delay_task.take();
11634        } else {
11635            self.git_blame_inline_enabled = true;
11636            self.start_git_blame_inline(user_triggered, cx);
11637        }
11638
11639        cx.notify();
11640    }
11641
11642    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11643        self.start_git_blame(user_triggered, cx);
11644
11645        if ProjectSettings::get_global(cx)
11646            .git
11647            .inline_blame_delay()
11648            .is_some()
11649        {
11650            self.start_inline_blame_timer(cx);
11651        } else {
11652            self.show_git_blame_inline = true
11653        }
11654    }
11655
11656    pub fn blame(&self) -> Option<&Model<GitBlame>> {
11657        self.blame.as_ref()
11658    }
11659
11660    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11661        self.show_git_blame_gutter && self.has_blame_entries(cx)
11662    }
11663
11664    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11665        self.show_git_blame_inline
11666            && self.focus_handle.is_focused(cx)
11667            && !self.newest_selection_head_on_empty_line(cx)
11668            && self.has_blame_entries(cx)
11669    }
11670
11671    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11672        self.blame()
11673            .map_or(false, |blame| blame.read(cx).has_generated_entries())
11674    }
11675
11676    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11677        let cursor_anchor = self.selections.newest_anchor().head();
11678
11679        let snapshot = self.buffer.read(cx).snapshot(cx);
11680        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11681
11682        snapshot.line_len(buffer_row) == 0
11683    }
11684
11685    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11686        let buffer_and_selection = maybe!({
11687            let selection = self.selections.newest::<Point>(cx);
11688            let selection_range = selection.range();
11689
11690            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11691                (buffer, selection_range.start.row..selection_range.end.row)
11692            } else {
11693                let buffer_ranges = self
11694                    .buffer()
11695                    .read(cx)
11696                    .range_to_buffer_ranges(selection_range, cx);
11697
11698                let (buffer, range, _) = if selection.reversed {
11699                    buffer_ranges.first()
11700                } else {
11701                    buffer_ranges.last()
11702                }?;
11703
11704                let snapshot = buffer.read(cx).snapshot();
11705                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11706                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
11707                (buffer.clone(), selection)
11708            };
11709
11710            Some((buffer, selection))
11711        });
11712
11713        let Some((buffer, selection)) = buffer_and_selection else {
11714            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11715        };
11716
11717        let Some(project) = self.project.as_ref() else {
11718            return Task::ready(Err(anyhow!("editor does not have project")));
11719        };
11720
11721        project.update(cx, |project, cx| {
11722            project.get_permalink_to_line(&buffer, selection, cx)
11723        })
11724    }
11725
11726    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11727        let permalink_task = self.get_permalink_to_line(cx);
11728        let workspace = self.workspace();
11729
11730        cx.spawn(|_, mut cx| async move {
11731            match permalink_task.await {
11732                Ok(permalink) => {
11733                    cx.update(|cx| {
11734                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11735                    })
11736                    .ok();
11737                }
11738                Err(err) => {
11739                    let message = format!("Failed to copy permalink: {err}");
11740
11741                    Err::<(), anyhow::Error>(err).log_err();
11742
11743                    if let Some(workspace) = workspace {
11744                        workspace
11745                            .update(&mut cx, |workspace, cx| {
11746                                struct CopyPermalinkToLine;
11747
11748                                workspace.show_toast(
11749                                    Toast::new(
11750                                        NotificationId::unique::<CopyPermalinkToLine>(),
11751                                        message,
11752                                    ),
11753                                    cx,
11754                                )
11755                            })
11756                            .ok();
11757                    }
11758                }
11759            }
11760        })
11761        .detach();
11762    }
11763
11764    pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11765        let selection = self.selections.newest::<Point>(cx).start.row + 1;
11766        if let Some(file) = self.target_file(cx) {
11767            if let Some(path) = file.path().to_str() {
11768                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11769            }
11770        }
11771    }
11772
11773    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11774        let permalink_task = self.get_permalink_to_line(cx);
11775        let workspace = self.workspace();
11776
11777        cx.spawn(|_, mut cx| async move {
11778            match permalink_task.await {
11779                Ok(permalink) => {
11780                    cx.update(|cx| {
11781                        cx.open_url(permalink.as_ref());
11782                    })
11783                    .ok();
11784                }
11785                Err(err) => {
11786                    let message = format!("Failed to open permalink: {err}");
11787
11788                    Err::<(), anyhow::Error>(err).log_err();
11789
11790                    if let Some(workspace) = workspace {
11791                        workspace
11792                            .update(&mut cx, |workspace, cx| {
11793                                struct OpenPermalinkToLine;
11794
11795                                workspace.show_toast(
11796                                    Toast::new(
11797                                        NotificationId::unique::<OpenPermalinkToLine>(),
11798                                        message,
11799                                    ),
11800                                    cx,
11801                                )
11802                            })
11803                            .ok();
11804                    }
11805                }
11806            }
11807        })
11808        .detach();
11809    }
11810
11811    /// Adds a row highlight for the given range. If a row has multiple highlights, the
11812    /// last highlight added will be used.
11813    ///
11814    /// If the range ends at the beginning of a line, then that line will not be highlighted.
11815    pub fn highlight_rows<T: 'static>(
11816        &mut self,
11817        range: Range<Anchor>,
11818        color: Hsla,
11819        should_autoscroll: bool,
11820        cx: &mut ViewContext<Self>,
11821    ) {
11822        let snapshot = self.buffer().read(cx).snapshot(cx);
11823        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11824        let ix = row_highlights.binary_search_by(|highlight| {
11825            Ordering::Equal
11826                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11827                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11828        });
11829
11830        if let Err(mut ix) = ix {
11831            let index = post_inc(&mut self.highlight_order);
11832
11833            // If this range intersects with the preceding highlight, then merge it with
11834            // the preceding highlight. Otherwise insert a new highlight.
11835            let mut merged = false;
11836            if ix > 0 {
11837                let prev_highlight = &mut row_highlights[ix - 1];
11838                if prev_highlight
11839                    .range
11840                    .end
11841                    .cmp(&range.start, &snapshot)
11842                    .is_ge()
11843                {
11844                    ix -= 1;
11845                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11846                        prev_highlight.range.end = range.end;
11847                    }
11848                    merged = true;
11849                    prev_highlight.index = index;
11850                    prev_highlight.color = color;
11851                    prev_highlight.should_autoscroll = should_autoscroll;
11852                }
11853            }
11854
11855            if !merged {
11856                row_highlights.insert(
11857                    ix,
11858                    RowHighlight {
11859                        range: range.clone(),
11860                        index,
11861                        color,
11862                        should_autoscroll,
11863                    },
11864                );
11865            }
11866
11867            // If any of the following highlights intersect with this one, merge them.
11868            while let Some(next_highlight) = row_highlights.get(ix + 1) {
11869                let highlight = &row_highlights[ix];
11870                if next_highlight
11871                    .range
11872                    .start
11873                    .cmp(&highlight.range.end, &snapshot)
11874                    .is_le()
11875                {
11876                    if next_highlight
11877                        .range
11878                        .end
11879                        .cmp(&highlight.range.end, &snapshot)
11880                        .is_gt()
11881                    {
11882                        row_highlights[ix].range.end = next_highlight.range.end;
11883                    }
11884                    row_highlights.remove(ix + 1);
11885                } else {
11886                    break;
11887                }
11888            }
11889        }
11890    }
11891
11892    /// Remove any highlighted row ranges of the given type that intersect the
11893    /// given ranges.
11894    pub fn remove_highlighted_rows<T: 'static>(
11895        &mut self,
11896        ranges_to_remove: Vec<Range<Anchor>>,
11897        cx: &mut ViewContext<Self>,
11898    ) {
11899        let snapshot = self.buffer().read(cx).snapshot(cx);
11900        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11901        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11902        row_highlights.retain(|highlight| {
11903            while let Some(range_to_remove) = ranges_to_remove.peek() {
11904                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11905                    Ordering::Less | Ordering::Equal => {
11906                        ranges_to_remove.next();
11907                    }
11908                    Ordering::Greater => {
11909                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11910                            Ordering::Less | Ordering::Equal => {
11911                                return false;
11912                            }
11913                            Ordering::Greater => break,
11914                        }
11915                    }
11916                }
11917            }
11918
11919            true
11920        })
11921    }
11922
11923    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11924    pub fn clear_row_highlights<T: 'static>(&mut self) {
11925        self.highlighted_rows.remove(&TypeId::of::<T>());
11926    }
11927
11928    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11929    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11930        self.highlighted_rows
11931            .get(&TypeId::of::<T>())
11932            .map_or(&[] as &[_], |vec| vec.as_slice())
11933            .iter()
11934            .map(|highlight| (highlight.range.clone(), highlight.color))
11935    }
11936
11937    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11938    /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11939    /// Allows to ignore certain kinds of highlights.
11940    pub fn highlighted_display_rows(
11941        &mut self,
11942        cx: &mut WindowContext,
11943    ) -> BTreeMap<DisplayRow, Hsla> {
11944        let snapshot = self.snapshot(cx);
11945        let mut used_highlight_orders = HashMap::default();
11946        self.highlighted_rows
11947            .iter()
11948            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11949            .fold(
11950                BTreeMap::<DisplayRow, Hsla>::new(),
11951                |mut unique_rows, highlight| {
11952                    let start = highlight.range.start.to_display_point(&snapshot);
11953                    let end = highlight.range.end.to_display_point(&snapshot);
11954                    let start_row = start.row().0;
11955                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11956                        && end.column() == 0
11957                    {
11958                        end.row().0.saturating_sub(1)
11959                    } else {
11960                        end.row().0
11961                    };
11962                    for row in start_row..=end_row {
11963                        let used_index =
11964                            used_highlight_orders.entry(row).or_insert(highlight.index);
11965                        if highlight.index >= *used_index {
11966                            *used_index = highlight.index;
11967                            unique_rows.insert(DisplayRow(row), highlight.color);
11968                        }
11969                    }
11970                    unique_rows
11971                },
11972            )
11973    }
11974
11975    pub fn highlighted_display_row_for_autoscroll(
11976        &self,
11977        snapshot: &DisplaySnapshot,
11978    ) -> Option<DisplayRow> {
11979        self.highlighted_rows
11980            .values()
11981            .flat_map(|highlighted_rows| highlighted_rows.iter())
11982            .filter_map(|highlight| {
11983                if highlight.should_autoscroll {
11984                    Some(highlight.range.start.to_display_point(snapshot).row())
11985                } else {
11986                    None
11987                }
11988            })
11989            .min()
11990    }
11991
11992    pub fn set_search_within_ranges(
11993        &mut self,
11994        ranges: &[Range<Anchor>],
11995        cx: &mut ViewContext<Self>,
11996    ) {
11997        self.highlight_background::<SearchWithinRange>(
11998            ranges,
11999            |colors| colors.editor_document_highlight_read_background,
12000            cx,
12001        )
12002    }
12003
12004    pub fn set_breadcrumb_header(&mut self, new_header: String) {
12005        self.breadcrumb_header = Some(new_header);
12006    }
12007
12008    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
12009        self.clear_background_highlights::<SearchWithinRange>(cx);
12010    }
12011
12012    pub fn highlight_background<T: 'static>(
12013        &mut self,
12014        ranges: &[Range<Anchor>],
12015        color_fetcher: fn(&ThemeColors) -> Hsla,
12016        cx: &mut ViewContext<Self>,
12017    ) {
12018        self.background_highlights
12019            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12020        self.scrollbar_marker_state.dirty = true;
12021        cx.notify();
12022    }
12023
12024    pub fn clear_background_highlights<T: 'static>(
12025        &mut self,
12026        cx: &mut ViewContext<Self>,
12027    ) -> Option<BackgroundHighlight> {
12028        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
12029        if !text_highlights.1.is_empty() {
12030            self.scrollbar_marker_state.dirty = true;
12031            cx.notify();
12032        }
12033        Some(text_highlights)
12034    }
12035
12036    pub fn highlight_gutter<T: 'static>(
12037        &mut self,
12038        ranges: &[Range<Anchor>],
12039        color_fetcher: fn(&AppContext) -> Hsla,
12040        cx: &mut ViewContext<Self>,
12041    ) {
12042        self.gutter_highlights
12043            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12044        cx.notify();
12045    }
12046
12047    pub fn clear_gutter_highlights<T: 'static>(
12048        &mut self,
12049        cx: &mut ViewContext<Self>,
12050    ) -> Option<GutterHighlight> {
12051        cx.notify();
12052        self.gutter_highlights.remove(&TypeId::of::<T>())
12053    }
12054
12055    #[cfg(feature = "test-support")]
12056    pub fn all_text_background_highlights(
12057        &mut self,
12058        cx: &mut ViewContext<Self>,
12059    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12060        let snapshot = self.snapshot(cx);
12061        let buffer = &snapshot.buffer_snapshot;
12062        let start = buffer.anchor_before(0);
12063        let end = buffer.anchor_after(buffer.len());
12064        let theme = cx.theme().colors();
12065        self.background_highlights_in_range(start..end, &snapshot, theme)
12066    }
12067
12068    #[cfg(feature = "test-support")]
12069    pub fn search_background_highlights(
12070        &mut self,
12071        cx: &mut ViewContext<Self>,
12072    ) -> Vec<Range<Point>> {
12073        let snapshot = self.buffer().read(cx).snapshot(cx);
12074
12075        let highlights = self
12076            .background_highlights
12077            .get(&TypeId::of::<items::BufferSearchHighlights>());
12078
12079        if let Some((_color, ranges)) = highlights {
12080            ranges
12081                .iter()
12082                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
12083                .collect_vec()
12084        } else {
12085            vec![]
12086        }
12087    }
12088
12089    fn document_highlights_for_position<'a>(
12090        &'a self,
12091        position: Anchor,
12092        buffer: &'a MultiBufferSnapshot,
12093    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
12094        let read_highlights = self
12095            .background_highlights
12096            .get(&TypeId::of::<DocumentHighlightRead>())
12097            .map(|h| &h.1);
12098        let write_highlights = self
12099            .background_highlights
12100            .get(&TypeId::of::<DocumentHighlightWrite>())
12101            .map(|h| &h.1);
12102        let left_position = position.bias_left(buffer);
12103        let right_position = position.bias_right(buffer);
12104        read_highlights
12105            .into_iter()
12106            .chain(write_highlights)
12107            .flat_map(move |ranges| {
12108                let start_ix = match ranges.binary_search_by(|probe| {
12109                    let cmp = probe.end.cmp(&left_position, buffer);
12110                    if cmp.is_ge() {
12111                        Ordering::Greater
12112                    } else {
12113                        Ordering::Less
12114                    }
12115                }) {
12116                    Ok(i) | Err(i) => i,
12117                };
12118
12119                ranges[start_ix..]
12120                    .iter()
12121                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
12122            })
12123    }
12124
12125    pub fn has_background_highlights<T: 'static>(&self) -> bool {
12126        self.background_highlights
12127            .get(&TypeId::of::<T>())
12128            .map_or(false, |(_, highlights)| !highlights.is_empty())
12129    }
12130
12131    pub fn background_highlights_in_range(
12132        &self,
12133        search_range: Range<Anchor>,
12134        display_snapshot: &DisplaySnapshot,
12135        theme: &ThemeColors,
12136    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12137        let mut results = Vec::new();
12138        for (color_fetcher, ranges) in self.background_highlights.values() {
12139            let color = color_fetcher(theme);
12140            let start_ix = match ranges.binary_search_by(|probe| {
12141                let cmp = probe
12142                    .end
12143                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12144                if cmp.is_gt() {
12145                    Ordering::Greater
12146                } else {
12147                    Ordering::Less
12148                }
12149            }) {
12150                Ok(i) | Err(i) => i,
12151            };
12152            for range in &ranges[start_ix..] {
12153                if range
12154                    .start
12155                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12156                    .is_ge()
12157                {
12158                    break;
12159                }
12160
12161                let start = range.start.to_display_point(display_snapshot);
12162                let end = range.end.to_display_point(display_snapshot);
12163                results.push((start..end, color))
12164            }
12165        }
12166        results
12167    }
12168
12169    pub fn background_highlight_row_ranges<T: 'static>(
12170        &self,
12171        search_range: Range<Anchor>,
12172        display_snapshot: &DisplaySnapshot,
12173        count: usize,
12174    ) -> Vec<RangeInclusive<DisplayPoint>> {
12175        let mut results = Vec::new();
12176        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12177            return vec![];
12178        };
12179
12180        let start_ix = match ranges.binary_search_by(|probe| {
12181            let cmp = probe
12182                .end
12183                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12184            if cmp.is_gt() {
12185                Ordering::Greater
12186            } else {
12187                Ordering::Less
12188            }
12189        }) {
12190            Ok(i) | Err(i) => i,
12191        };
12192        let mut push_region = |start: Option<Point>, end: Option<Point>| {
12193            if let (Some(start_display), Some(end_display)) = (start, end) {
12194                results.push(
12195                    start_display.to_display_point(display_snapshot)
12196                        ..=end_display.to_display_point(display_snapshot),
12197                );
12198            }
12199        };
12200        let mut start_row: Option<Point> = None;
12201        let mut end_row: Option<Point> = None;
12202        if ranges.len() > count {
12203            return Vec::new();
12204        }
12205        for range in &ranges[start_ix..] {
12206            if range
12207                .start
12208                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12209                .is_ge()
12210            {
12211                break;
12212            }
12213            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12214            if let Some(current_row) = &end_row {
12215                if end.row == current_row.row {
12216                    continue;
12217                }
12218            }
12219            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12220            if start_row.is_none() {
12221                assert_eq!(end_row, None);
12222                start_row = Some(start);
12223                end_row = Some(end);
12224                continue;
12225            }
12226            if let Some(current_end) = end_row.as_mut() {
12227                if start.row > current_end.row + 1 {
12228                    push_region(start_row, end_row);
12229                    start_row = Some(start);
12230                    end_row = Some(end);
12231                } else {
12232                    // Merge two hunks.
12233                    *current_end = end;
12234                }
12235            } else {
12236                unreachable!();
12237            }
12238        }
12239        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12240        push_region(start_row, end_row);
12241        results
12242    }
12243
12244    pub fn gutter_highlights_in_range(
12245        &self,
12246        search_range: Range<Anchor>,
12247        display_snapshot: &DisplaySnapshot,
12248        cx: &AppContext,
12249    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12250        let mut results = Vec::new();
12251        for (color_fetcher, ranges) in self.gutter_highlights.values() {
12252            let color = color_fetcher(cx);
12253            let start_ix = match ranges.binary_search_by(|probe| {
12254                let cmp = probe
12255                    .end
12256                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12257                if cmp.is_gt() {
12258                    Ordering::Greater
12259                } else {
12260                    Ordering::Less
12261                }
12262            }) {
12263                Ok(i) | Err(i) => i,
12264            };
12265            for range in &ranges[start_ix..] {
12266                if range
12267                    .start
12268                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12269                    .is_ge()
12270                {
12271                    break;
12272                }
12273
12274                let start = range.start.to_display_point(display_snapshot);
12275                let end = range.end.to_display_point(display_snapshot);
12276                results.push((start..end, color))
12277            }
12278        }
12279        results
12280    }
12281
12282    /// Get the text ranges corresponding to the redaction query
12283    pub fn redacted_ranges(
12284        &self,
12285        search_range: Range<Anchor>,
12286        display_snapshot: &DisplaySnapshot,
12287        cx: &WindowContext,
12288    ) -> Vec<Range<DisplayPoint>> {
12289        display_snapshot
12290            .buffer_snapshot
12291            .redacted_ranges(search_range, |file| {
12292                if let Some(file) = file {
12293                    file.is_private()
12294                        && EditorSettings::get(
12295                            Some(SettingsLocation {
12296                                worktree_id: file.worktree_id(cx),
12297                                path: file.path().as_ref(),
12298                            }),
12299                            cx,
12300                        )
12301                        .redact_private_values
12302                } else {
12303                    false
12304                }
12305            })
12306            .map(|range| {
12307                range.start.to_display_point(display_snapshot)
12308                    ..range.end.to_display_point(display_snapshot)
12309            })
12310            .collect()
12311    }
12312
12313    pub fn highlight_text<T: 'static>(
12314        &mut self,
12315        ranges: Vec<Range<Anchor>>,
12316        style: HighlightStyle,
12317        cx: &mut ViewContext<Self>,
12318    ) {
12319        self.display_map.update(cx, |map, _| {
12320            map.highlight_text(TypeId::of::<T>(), ranges, style)
12321        });
12322        cx.notify();
12323    }
12324
12325    pub(crate) fn highlight_inlays<T: 'static>(
12326        &mut self,
12327        highlights: Vec<InlayHighlight>,
12328        style: HighlightStyle,
12329        cx: &mut ViewContext<Self>,
12330    ) {
12331        self.display_map.update(cx, |map, _| {
12332            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12333        });
12334        cx.notify();
12335    }
12336
12337    pub fn text_highlights<'a, T: 'static>(
12338        &'a self,
12339        cx: &'a AppContext,
12340    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12341        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12342    }
12343
12344    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12345        let cleared = self
12346            .display_map
12347            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12348        if cleared {
12349            cx.notify();
12350        }
12351    }
12352
12353    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12354        (self.read_only(cx) || self.blink_manager.read(cx).visible())
12355            && self.focus_handle.is_focused(cx)
12356    }
12357
12358    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12359        self.show_cursor_when_unfocused = is_enabled;
12360        cx.notify();
12361    }
12362
12363    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12364        cx.notify();
12365    }
12366
12367    fn on_buffer_event(
12368        &mut self,
12369        multibuffer: Model<MultiBuffer>,
12370        event: &multi_buffer::Event,
12371        cx: &mut ViewContext<Self>,
12372    ) {
12373        match event {
12374            multi_buffer::Event::Edited {
12375                singleton_buffer_edited,
12376            } => {
12377                self.scrollbar_marker_state.dirty = true;
12378                self.active_indent_guides_state.dirty = true;
12379                self.refresh_active_diagnostics(cx);
12380                self.refresh_code_actions(cx);
12381                if self.has_active_inline_completion(cx) {
12382                    self.update_visible_inline_completion(cx);
12383                }
12384                cx.emit(EditorEvent::BufferEdited);
12385                cx.emit(SearchEvent::MatchesInvalidated);
12386                if *singleton_buffer_edited {
12387                    if let Some(project) = &self.project {
12388                        let project = project.read(cx);
12389                        #[allow(clippy::mutable_key_type)]
12390                        let languages_affected = multibuffer
12391                            .read(cx)
12392                            .all_buffers()
12393                            .into_iter()
12394                            .filter_map(|buffer| {
12395                                let buffer = buffer.read(cx);
12396                                let language = buffer.language()?;
12397                                if project.is_local()
12398                                    && project.language_servers_for_buffer(buffer, cx).count() == 0
12399                                {
12400                                    None
12401                                } else {
12402                                    Some(language)
12403                                }
12404                            })
12405                            .cloned()
12406                            .collect::<HashSet<_>>();
12407                        if !languages_affected.is_empty() {
12408                            self.refresh_inlay_hints(
12409                                InlayHintRefreshReason::BufferEdited(languages_affected),
12410                                cx,
12411                            );
12412                        }
12413                    }
12414                }
12415
12416                let Some(project) = &self.project else { return };
12417                let (telemetry, is_via_ssh) = {
12418                    let project = project.read(cx);
12419                    let telemetry = project.client().telemetry().clone();
12420                    let is_via_ssh = project.is_via_ssh();
12421                    (telemetry, is_via_ssh)
12422                };
12423                refresh_linked_ranges(self, cx);
12424                telemetry.log_edit_event("editor", is_via_ssh);
12425            }
12426            multi_buffer::Event::ExcerptsAdded {
12427                buffer,
12428                predecessor,
12429                excerpts,
12430            } => {
12431                self.tasks_update_task = Some(self.refresh_runnables(cx));
12432                cx.emit(EditorEvent::ExcerptsAdded {
12433                    buffer: buffer.clone(),
12434                    predecessor: *predecessor,
12435                    excerpts: excerpts.clone(),
12436                });
12437                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12438            }
12439            multi_buffer::Event::ExcerptsRemoved { ids } => {
12440                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12441                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12442            }
12443            multi_buffer::Event::ExcerptsEdited { ids } => {
12444                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12445            }
12446            multi_buffer::Event::ExcerptsExpanded { ids } => {
12447                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12448            }
12449            multi_buffer::Event::Reparsed(buffer_id) => {
12450                self.tasks_update_task = Some(self.refresh_runnables(cx));
12451
12452                cx.emit(EditorEvent::Reparsed(*buffer_id));
12453            }
12454            multi_buffer::Event::LanguageChanged(buffer_id) => {
12455                linked_editing_ranges::refresh_linked_ranges(self, cx);
12456                cx.emit(EditorEvent::Reparsed(*buffer_id));
12457                cx.notify();
12458            }
12459            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12460            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12461            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12462                cx.emit(EditorEvent::TitleChanged)
12463            }
12464            multi_buffer::Event::DiffBaseChanged => {
12465                self.scrollbar_marker_state.dirty = true;
12466                cx.emit(EditorEvent::DiffBaseChanged);
12467                cx.notify();
12468            }
12469            multi_buffer::Event::DiffUpdated { buffer } => {
12470                self.sync_expanded_diff_hunks(buffer.clone(), cx);
12471                cx.notify();
12472            }
12473            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12474            multi_buffer::Event::DiagnosticsUpdated => {
12475                self.refresh_active_diagnostics(cx);
12476                self.scrollbar_marker_state.dirty = true;
12477                cx.notify();
12478            }
12479            _ => {}
12480        };
12481    }
12482
12483    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12484        cx.notify();
12485    }
12486
12487    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12488        self.tasks_update_task = Some(self.refresh_runnables(cx));
12489        self.refresh_inline_completion(true, false, cx);
12490        self.refresh_inlay_hints(
12491            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12492                self.selections.newest_anchor().head(),
12493                &self.buffer.read(cx).snapshot(cx),
12494                cx,
12495            )),
12496            cx,
12497        );
12498
12499        let old_cursor_shape = self.cursor_shape;
12500
12501        {
12502            let editor_settings = EditorSettings::get_global(cx);
12503            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12504            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12505            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12506        }
12507
12508        if old_cursor_shape != self.cursor_shape {
12509            cx.emit(EditorEvent::CursorShapeChanged);
12510        }
12511
12512        let project_settings = ProjectSettings::get_global(cx);
12513        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12514
12515        if self.mode == EditorMode::Full {
12516            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12517            if self.git_blame_inline_enabled != inline_blame_enabled {
12518                self.toggle_git_blame_inline_internal(false, cx);
12519            }
12520        }
12521
12522        cx.notify();
12523    }
12524
12525    pub fn set_searchable(&mut self, searchable: bool) {
12526        self.searchable = searchable;
12527    }
12528
12529    pub fn searchable(&self) -> bool {
12530        self.searchable
12531    }
12532
12533    fn open_proposed_changes_editor(
12534        &mut self,
12535        _: &OpenProposedChangesEditor,
12536        cx: &mut ViewContext<Self>,
12537    ) {
12538        let Some(workspace) = self.workspace() else {
12539            cx.propagate();
12540            return;
12541        };
12542
12543        let selections = self.selections.all::<usize>(cx);
12544        let buffer = self.buffer.read(cx);
12545        let mut new_selections_by_buffer = HashMap::default();
12546        for selection in selections {
12547            for (buffer, range, _) in
12548                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12549            {
12550                let mut range = range.to_point(buffer.read(cx));
12551                range.start.column = 0;
12552                range.end.column = buffer.read(cx).line_len(range.end.row);
12553                new_selections_by_buffer
12554                    .entry(buffer)
12555                    .or_insert(Vec::new())
12556                    .push(range)
12557            }
12558        }
12559
12560        let proposed_changes_buffers = new_selections_by_buffer
12561            .into_iter()
12562            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12563            .collect::<Vec<_>>();
12564        let proposed_changes_editor = cx.new_view(|cx| {
12565            ProposedChangesEditor::new(
12566                "Proposed changes",
12567                proposed_changes_buffers,
12568                self.project.clone(),
12569                cx,
12570            )
12571        });
12572
12573        cx.window_context().defer(move |cx| {
12574            workspace.update(cx, |workspace, cx| {
12575                workspace.active_pane().update(cx, |pane, cx| {
12576                    pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12577                });
12578            });
12579        });
12580    }
12581
12582    fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12583        self.open_excerpts_common(true, cx)
12584    }
12585
12586    fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12587        self.open_excerpts_common(false, cx)
12588    }
12589
12590    fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
12591        let selections = self.selections.all::<usize>(cx);
12592        let buffer = self.buffer.read(cx);
12593        if buffer.is_singleton() {
12594            cx.propagate();
12595            return;
12596        }
12597
12598        let Some(workspace) = self.workspace() else {
12599            cx.propagate();
12600            return;
12601        };
12602
12603        let mut new_selections_by_buffer = HashMap::default();
12604        for selection in selections {
12605            for (mut buffer_handle, mut range, _) in
12606                buffer.range_to_buffer_ranges(selection.range(), cx)
12607            {
12608                // When editing branch buffers, jump to the corresponding location
12609                // in their base buffer.
12610                let buffer = buffer_handle.read(cx);
12611                if let Some(base_buffer) = buffer.diff_base_buffer() {
12612                    range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12613                    buffer_handle = base_buffer;
12614                }
12615
12616                if selection.reversed {
12617                    mem::swap(&mut range.start, &mut range.end);
12618                }
12619                new_selections_by_buffer
12620                    .entry(buffer_handle)
12621                    .or_insert(Vec::new())
12622                    .push(range)
12623            }
12624        }
12625
12626        // We defer the pane interaction because we ourselves are a workspace item
12627        // and activating a new item causes the pane to call a method on us reentrantly,
12628        // which panics if we're on the stack.
12629        cx.window_context().defer(move |cx| {
12630            workspace.update(cx, |workspace, cx| {
12631                let pane = if split {
12632                    workspace.adjacent_pane(cx)
12633                } else {
12634                    workspace.active_pane().clone()
12635                };
12636
12637                for (buffer, ranges) in new_selections_by_buffer {
12638                    let editor =
12639                        workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
12640                    editor.update(cx, |editor, cx| {
12641                        editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
12642                            s.select_ranges(ranges);
12643                        });
12644                    });
12645                }
12646            })
12647        });
12648    }
12649
12650    fn jump(
12651        &mut self,
12652        path: ProjectPath,
12653        position: Point,
12654        anchor: language::Anchor,
12655        offset_from_top: u32,
12656        cx: &mut ViewContext<Self>,
12657    ) {
12658        let workspace = self.workspace();
12659        cx.spawn(|_, mut cx| async move {
12660            let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
12661            let editor = workspace.update(&mut cx, |workspace, cx| {
12662                // Reset the preview item id before opening the new item
12663                workspace.active_pane().update(cx, |pane, cx| {
12664                    pane.set_preview_item_id(None, cx);
12665                });
12666                workspace.open_path_preview(path, None, true, true, cx)
12667            })?;
12668            let editor = editor
12669                .await?
12670                .downcast::<Editor>()
12671                .ok_or_else(|| anyhow!("opened item was not an editor"))?
12672                .downgrade();
12673            editor.update(&mut cx, |editor, cx| {
12674                let buffer = editor
12675                    .buffer()
12676                    .read(cx)
12677                    .as_singleton()
12678                    .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
12679                let buffer = buffer.read(cx);
12680                let cursor = if buffer.can_resolve(&anchor) {
12681                    language::ToPoint::to_point(&anchor, buffer)
12682                } else {
12683                    buffer.clip_point(position, Bias::Left)
12684                };
12685
12686                let nav_history = editor.nav_history.take();
12687                editor.change_selections(
12688                    Some(Autoscroll::top_relative(offset_from_top as usize)),
12689                    cx,
12690                    |s| {
12691                        s.select_ranges([cursor..cursor]);
12692                    },
12693                );
12694                editor.nav_history = nav_history;
12695
12696                anyhow::Ok(())
12697            })??;
12698
12699            anyhow::Ok(())
12700        })
12701        .detach_and_log_err(cx);
12702    }
12703
12704    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12705        let snapshot = self.buffer.read(cx).read(cx);
12706        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12707        Some(
12708            ranges
12709                .iter()
12710                .map(move |range| {
12711                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12712                })
12713                .collect(),
12714        )
12715    }
12716
12717    fn selection_replacement_ranges(
12718        &self,
12719        range: Range<OffsetUtf16>,
12720        cx: &mut AppContext,
12721    ) -> Vec<Range<OffsetUtf16>> {
12722        let selections = self.selections.all::<OffsetUtf16>(cx);
12723        let newest_selection = selections
12724            .iter()
12725            .max_by_key(|selection| selection.id)
12726            .unwrap();
12727        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12728        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12729        let snapshot = self.buffer.read(cx).read(cx);
12730        selections
12731            .into_iter()
12732            .map(|mut selection| {
12733                selection.start.0 =
12734                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
12735                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12736                snapshot.clip_offset_utf16(selection.start, Bias::Left)
12737                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12738            })
12739            .collect()
12740    }
12741
12742    fn report_editor_event(
12743        &self,
12744        operation: &'static str,
12745        file_extension: Option<String>,
12746        cx: &AppContext,
12747    ) {
12748        if cfg!(any(test, feature = "test-support")) {
12749            return;
12750        }
12751
12752        let Some(project) = &self.project else { return };
12753
12754        // If None, we are in a file without an extension
12755        let file = self
12756            .buffer
12757            .read(cx)
12758            .as_singleton()
12759            .and_then(|b| b.read(cx).file());
12760        let file_extension = file_extension.or(file
12761            .as_ref()
12762            .and_then(|file| Path::new(file.file_name(cx)).extension())
12763            .and_then(|e| e.to_str())
12764            .map(|a| a.to_string()));
12765
12766        let vim_mode = cx
12767            .global::<SettingsStore>()
12768            .raw_user_settings()
12769            .get("vim_mode")
12770            == Some(&serde_json::Value::Bool(true));
12771
12772        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12773            == language::language_settings::InlineCompletionProvider::Copilot;
12774        let copilot_enabled_for_language = self
12775            .buffer
12776            .read(cx)
12777            .settings_at(0, cx)
12778            .show_inline_completions;
12779
12780        let project = project.read(cx);
12781        let telemetry = project.client().telemetry().clone();
12782        telemetry.report_editor_event(
12783            file_extension,
12784            vim_mode,
12785            operation,
12786            copilot_enabled,
12787            copilot_enabled_for_language,
12788            project.is_via_ssh(),
12789        )
12790    }
12791
12792    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12793    /// with each line being an array of {text, highlight} objects.
12794    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12795        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12796            return;
12797        };
12798
12799        #[derive(Serialize)]
12800        struct Chunk<'a> {
12801            text: String,
12802            highlight: Option<&'a str>,
12803        }
12804
12805        let snapshot = buffer.read(cx).snapshot();
12806        let range = self
12807            .selected_text_range(false, cx)
12808            .and_then(|selection| {
12809                if selection.range.is_empty() {
12810                    None
12811                } else {
12812                    Some(selection.range)
12813                }
12814            })
12815            .unwrap_or_else(|| 0..snapshot.len());
12816
12817        let chunks = snapshot.chunks(range, true);
12818        let mut lines = Vec::new();
12819        let mut line: VecDeque<Chunk> = VecDeque::new();
12820
12821        let Some(style) = self.style.as_ref() else {
12822            return;
12823        };
12824
12825        for chunk in chunks {
12826            let highlight = chunk
12827                .syntax_highlight_id
12828                .and_then(|id| id.name(&style.syntax));
12829            let mut chunk_lines = chunk.text.split('\n').peekable();
12830            while let Some(text) = chunk_lines.next() {
12831                let mut merged_with_last_token = false;
12832                if let Some(last_token) = line.back_mut() {
12833                    if last_token.highlight == highlight {
12834                        last_token.text.push_str(text);
12835                        merged_with_last_token = true;
12836                    }
12837                }
12838
12839                if !merged_with_last_token {
12840                    line.push_back(Chunk {
12841                        text: text.into(),
12842                        highlight,
12843                    });
12844                }
12845
12846                if chunk_lines.peek().is_some() {
12847                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
12848                        line.pop_front();
12849                    }
12850                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
12851                        line.pop_back();
12852                    }
12853
12854                    lines.push(mem::take(&mut line));
12855                }
12856            }
12857        }
12858
12859        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12860            return;
12861        };
12862        cx.write_to_clipboard(ClipboardItem::new_string(lines));
12863    }
12864
12865    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12866        &self.inlay_hint_cache
12867    }
12868
12869    pub fn replay_insert_event(
12870        &mut self,
12871        text: &str,
12872        relative_utf16_range: Option<Range<isize>>,
12873        cx: &mut ViewContext<Self>,
12874    ) {
12875        if !self.input_enabled {
12876            cx.emit(EditorEvent::InputIgnored { text: text.into() });
12877            return;
12878        }
12879        if let Some(relative_utf16_range) = relative_utf16_range {
12880            let selections = self.selections.all::<OffsetUtf16>(cx);
12881            self.change_selections(None, cx, |s| {
12882                let new_ranges = selections.into_iter().map(|range| {
12883                    let start = OffsetUtf16(
12884                        range
12885                            .head()
12886                            .0
12887                            .saturating_add_signed(relative_utf16_range.start),
12888                    );
12889                    let end = OffsetUtf16(
12890                        range
12891                            .head()
12892                            .0
12893                            .saturating_add_signed(relative_utf16_range.end),
12894                    );
12895                    start..end
12896                });
12897                s.select_ranges(new_ranges);
12898            });
12899        }
12900
12901        self.handle_input(text, cx);
12902    }
12903
12904    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12905        let Some(provider) = self.semantics_provider.as_ref() else {
12906            return false;
12907        };
12908
12909        let mut supports = false;
12910        self.buffer().read(cx).for_each_buffer(|buffer| {
12911            supports |= provider.supports_inlay_hints(buffer, cx);
12912        });
12913        supports
12914    }
12915
12916    pub fn focus(&self, cx: &mut WindowContext) {
12917        cx.focus(&self.focus_handle)
12918    }
12919
12920    pub fn is_focused(&self, cx: &WindowContext) -> bool {
12921        self.focus_handle.is_focused(cx)
12922    }
12923
12924    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12925        cx.emit(EditorEvent::Focused);
12926
12927        if let Some(descendant) = self
12928            .last_focused_descendant
12929            .take()
12930            .and_then(|descendant| descendant.upgrade())
12931        {
12932            cx.focus(&descendant);
12933        } else {
12934            if let Some(blame) = self.blame.as_ref() {
12935                blame.update(cx, GitBlame::focus)
12936            }
12937
12938            self.blink_manager.update(cx, BlinkManager::enable);
12939            self.show_cursor_names(cx);
12940            self.buffer.update(cx, |buffer, cx| {
12941                buffer.finalize_last_transaction(cx);
12942                if self.leader_peer_id.is_none() {
12943                    buffer.set_active_selections(
12944                        &self.selections.disjoint_anchors(),
12945                        self.selections.line_mode,
12946                        self.cursor_shape,
12947                        cx,
12948                    );
12949                }
12950            });
12951        }
12952    }
12953
12954    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12955        cx.emit(EditorEvent::FocusedIn)
12956    }
12957
12958    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12959        if event.blurred != self.focus_handle {
12960            self.last_focused_descendant = Some(event.blurred);
12961        }
12962    }
12963
12964    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12965        self.blink_manager.update(cx, BlinkManager::disable);
12966        self.buffer
12967            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12968
12969        if let Some(blame) = self.blame.as_ref() {
12970            blame.update(cx, GitBlame::blur)
12971        }
12972        if !self.hover_state.focused(cx) {
12973            hide_hover(self, cx);
12974        }
12975
12976        self.hide_context_menu(cx);
12977        cx.emit(EditorEvent::Blurred);
12978        cx.notify();
12979    }
12980
12981    pub fn register_action<A: Action>(
12982        &mut self,
12983        listener: impl Fn(&A, &mut WindowContext) + 'static,
12984    ) -> Subscription {
12985        let id = self.next_editor_action_id.post_inc();
12986        let listener = Arc::new(listener);
12987        self.editor_actions.borrow_mut().insert(
12988            id,
12989            Box::new(move |cx| {
12990                let cx = cx.window_context();
12991                let listener = listener.clone();
12992                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12993                    let action = action.downcast_ref().unwrap();
12994                    if phase == DispatchPhase::Bubble {
12995                        listener(action, cx)
12996                    }
12997                })
12998            }),
12999        );
13000
13001        let editor_actions = self.editor_actions.clone();
13002        Subscription::new(move || {
13003            editor_actions.borrow_mut().remove(&id);
13004        })
13005    }
13006
13007    pub fn file_header_size(&self) -> u32 {
13008        FILE_HEADER_HEIGHT
13009    }
13010
13011    pub fn revert(
13012        &mut self,
13013        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
13014        cx: &mut ViewContext<Self>,
13015    ) {
13016        self.buffer().update(cx, |multi_buffer, cx| {
13017            for (buffer_id, changes) in revert_changes {
13018                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13019                    buffer.update(cx, |buffer, cx| {
13020                        buffer.edit(
13021                            changes.into_iter().map(|(range, text)| {
13022                                (range, text.to_string().map(Arc::<str>::from))
13023                            }),
13024                            None,
13025                            cx,
13026                        );
13027                    });
13028                }
13029            }
13030        });
13031        self.change_selections(None, cx, |selections| selections.refresh());
13032    }
13033
13034    pub fn to_pixel_point(
13035        &mut self,
13036        source: multi_buffer::Anchor,
13037        editor_snapshot: &EditorSnapshot,
13038        cx: &mut ViewContext<Self>,
13039    ) -> Option<gpui::Point<Pixels>> {
13040        let source_point = source.to_display_point(editor_snapshot);
13041        self.display_to_pixel_point(source_point, editor_snapshot, cx)
13042    }
13043
13044    pub fn display_to_pixel_point(
13045        &mut self,
13046        source: DisplayPoint,
13047        editor_snapshot: &EditorSnapshot,
13048        cx: &mut ViewContext<Self>,
13049    ) -> Option<gpui::Point<Pixels>> {
13050        let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
13051        let text_layout_details = self.text_layout_details(cx);
13052        let scroll_top = text_layout_details
13053            .scroll_anchor
13054            .scroll_position(editor_snapshot)
13055            .y;
13056
13057        if source.row().as_f32() < scroll_top.floor() {
13058            return None;
13059        }
13060        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
13061        let source_y = line_height * (source.row().as_f32() - scroll_top);
13062        Some(gpui::Point::new(source_x, source_y))
13063    }
13064
13065    pub fn has_active_completions_menu(&self) -> bool {
13066        self.context_menu.read().as_ref().map_or(false, |menu| {
13067            menu.visible() && matches!(menu, ContextMenu::Completions(_))
13068        })
13069    }
13070
13071    pub fn register_addon<T: Addon>(&mut self, instance: T) {
13072        self.addons
13073            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
13074    }
13075
13076    pub fn unregister_addon<T: Addon>(&mut self) {
13077        self.addons.remove(&std::any::TypeId::of::<T>());
13078    }
13079
13080    pub fn addon<T: Addon>(&self) -> Option<&T> {
13081        let type_id = std::any::TypeId::of::<T>();
13082        self.addons
13083            .get(&type_id)
13084            .and_then(|item| item.to_any().downcast_ref::<T>())
13085    }
13086}
13087
13088fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13089    let tab_size = tab_size.get() as usize;
13090    let mut width = offset;
13091
13092    for ch in text.chars() {
13093        width += if ch == '\t' {
13094            tab_size - (width % tab_size)
13095        } else {
13096            1
13097        };
13098    }
13099
13100    width - offset
13101}
13102
13103#[cfg(test)]
13104mod tests {
13105    use super::*;
13106
13107    #[test]
13108    fn test_string_size_with_expanded_tabs() {
13109        let nz = |val| NonZeroU32::new(val).unwrap();
13110        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13111        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13112        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13113        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13114        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13115        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13116        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13117        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13118    }
13119}
13120
13121/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13122struct WordBreakingTokenizer<'a> {
13123    input: &'a str,
13124}
13125
13126impl<'a> WordBreakingTokenizer<'a> {
13127    fn new(input: &'a str) -> Self {
13128        Self { input }
13129    }
13130}
13131
13132fn is_char_ideographic(ch: char) -> bool {
13133    use unicode_script::Script::*;
13134    use unicode_script::UnicodeScript;
13135    matches!(ch.script(), Han | Tangut | Yi)
13136}
13137
13138fn is_grapheme_ideographic(text: &str) -> bool {
13139    text.chars().any(is_char_ideographic)
13140}
13141
13142fn is_grapheme_whitespace(text: &str) -> bool {
13143    text.chars().any(|x| x.is_whitespace())
13144}
13145
13146fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13147    text.chars().next().map_or(false, |ch| {
13148        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13149    })
13150}
13151
13152#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13153struct WordBreakToken<'a> {
13154    token: &'a str,
13155    grapheme_len: usize,
13156    is_whitespace: bool,
13157}
13158
13159impl<'a> Iterator for WordBreakingTokenizer<'a> {
13160    /// Yields a span, the count of graphemes in the token, and whether it was
13161    /// whitespace. Note that it also breaks at word boundaries.
13162    type Item = WordBreakToken<'a>;
13163
13164    fn next(&mut self) -> Option<Self::Item> {
13165        use unicode_segmentation::UnicodeSegmentation;
13166        if self.input.is_empty() {
13167            return None;
13168        }
13169
13170        let mut iter = self.input.graphemes(true).peekable();
13171        let mut offset = 0;
13172        let mut graphemes = 0;
13173        if let Some(first_grapheme) = iter.next() {
13174            let is_whitespace = is_grapheme_whitespace(first_grapheme);
13175            offset += first_grapheme.len();
13176            graphemes += 1;
13177            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13178                if let Some(grapheme) = iter.peek().copied() {
13179                    if should_stay_with_preceding_ideograph(grapheme) {
13180                        offset += grapheme.len();
13181                        graphemes += 1;
13182                    }
13183                }
13184            } else {
13185                let mut words = self.input[offset..].split_word_bound_indices().peekable();
13186                let mut next_word_bound = words.peek().copied();
13187                if next_word_bound.map_or(false, |(i, _)| i == 0) {
13188                    next_word_bound = words.next();
13189                }
13190                while let Some(grapheme) = iter.peek().copied() {
13191                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
13192                        break;
13193                    };
13194                    if is_grapheme_whitespace(grapheme) != is_whitespace {
13195                        break;
13196                    };
13197                    offset += grapheme.len();
13198                    graphemes += 1;
13199                    iter.next();
13200                }
13201            }
13202            let token = &self.input[..offset];
13203            self.input = &self.input[offset..];
13204            if is_whitespace {
13205                Some(WordBreakToken {
13206                    token: " ",
13207                    grapheme_len: 1,
13208                    is_whitespace: true,
13209                })
13210            } else {
13211                Some(WordBreakToken {
13212                    token,
13213                    grapheme_len: graphemes,
13214                    is_whitespace: false,
13215                })
13216            }
13217        } else {
13218            None
13219        }
13220    }
13221}
13222
13223#[test]
13224fn test_word_breaking_tokenizer() {
13225    let tests: &[(&str, &[(&str, usize, bool)])] = &[
13226        ("", &[]),
13227        ("  ", &[(" ", 1, true)]),
13228        ("Ʒ", &[("Ʒ", 1, false)]),
13229        ("Ǽ", &[("Ǽ", 1, false)]),
13230        ("", &[("", 1, false)]),
13231        ("⋑⋑", &[("⋑⋑", 2, false)]),
13232        (
13233            "原理,进而",
13234            &[
13235                ("", 1, false),
13236                ("理,", 2, false),
13237                ("", 1, false),
13238                ("", 1, false),
13239            ],
13240        ),
13241        (
13242            "hello world",
13243            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13244        ),
13245        (
13246            "hello, world",
13247            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13248        ),
13249        (
13250            "  hello world",
13251            &[
13252                (" ", 1, true),
13253                ("hello", 5, false),
13254                (" ", 1, true),
13255                ("world", 5, false),
13256            ],
13257        ),
13258        (
13259            "这是什么 \n 钢笔",
13260            &[
13261                ("", 1, false),
13262                ("", 1, false),
13263                ("", 1, false),
13264                ("", 1, false),
13265                (" ", 1, true),
13266                ("", 1, false),
13267                ("", 1, false),
13268            ],
13269        ),
13270        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13271    ];
13272
13273    for (input, result) in tests {
13274        assert_eq!(
13275            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13276            result
13277                .iter()
13278                .copied()
13279                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13280                    token,
13281                    grapheme_len,
13282                    is_whitespace,
13283                })
13284                .collect::<Vec<_>>()
13285        );
13286    }
13287}
13288
13289fn wrap_with_prefix(
13290    line_prefix: String,
13291    unwrapped_text: String,
13292    wrap_column: usize,
13293    tab_size: NonZeroU32,
13294) -> String {
13295    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13296    let mut wrapped_text = String::new();
13297    let mut current_line = line_prefix.clone();
13298
13299    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13300    let mut current_line_len = line_prefix_len;
13301    for WordBreakToken {
13302        token,
13303        grapheme_len,
13304        is_whitespace,
13305    } in tokenizer
13306    {
13307        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13308            wrapped_text.push_str(current_line.trim_end());
13309            wrapped_text.push('\n');
13310            current_line.truncate(line_prefix.len());
13311            current_line_len = line_prefix_len;
13312            if !is_whitespace {
13313                current_line.push_str(token);
13314                current_line_len += grapheme_len;
13315            }
13316        } else if !is_whitespace {
13317            current_line.push_str(token);
13318            current_line_len += grapheme_len;
13319        } else if current_line_len != line_prefix_len {
13320            current_line.push(' ');
13321            current_line_len += 1;
13322        }
13323    }
13324
13325    if !current_line.is_empty() {
13326        wrapped_text.push_str(&current_line);
13327    }
13328    wrapped_text
13329}
13330
13331#[test]
13332fn test_wrap_with_prefix() {
13333    assert_eq!(
13334        wrap_with_prefix(
13335            "# ".to_string(),
13336            "abcdefg".to_string(),
13337            4,
13338            NonZeroU32::new(4).unwrap()
13339        ),
13340        "# abcdefg"
13341    );
13342    assert_eq!(
13343        wrap_with_prefix(
13344            "".to_string(),
13345            "\thello world".to_string(),
13346            8,
13347            NonZeroU32::new(4).unwrap()
13348        ),
13349        "hello\nworld"
13350    );
13351    assert_eq!(
13352        wrap_with_prefix(
13353            "// ".to_string(),
13354            "xx \nyy zz aa bb cc".to_string(),
13355            12,
13356            NonZeroU32::new(4).unwrap()
13357        ),
13358        "// xx yy zz\n// aa bb cc"
13359    );
13360    assert_eq!(
13361        wrap_with_prefix(
13362            String::new(),
13363            "这是什么 \n 钢笔".to_string(),
13364            3,
13365            NonZeroU32::new(4).unwrap()
13366        ),
13367        "这是什\n么 钢\n"
13368    );
13369}
13370
13371fn hunks_for_selections(
13372    multi_buffer_snapshot: &MultiBufferSnapshot,
13373    selections: &[Selection<Anchor>],
13374) -> Vec<MultiBufferDiffHunk> {
13375    let buffer_rows_for_selections = selections.iter().map(|selection| {
13376        let head = selection.head();
13377        let tail = selection.tail();
13378        let start = MultiBufferRow(tail.to_point(multi_buffer_snapshot).row);
13379        let end = MultiBufferRow(head.to_point(multi_buffer_snapshot).row);
13380        if start > end {
13381            end..start
13382        } else {
13383            start..end
13384        }
13385    });
13386
13387    hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
13388}
13389
13390pub fn hunks_for_rows(
13391    rows: impl Iterator<Item = Range<MultiBufferRow>>,
13392    multi_buffer_snapshot: &MultiBufferSnapshot,
13393) -> Vec<MultiBufferDiffHunk> {
13394    let mut hunks = Vec::new();
13395    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13396        HashMap::default();
13397    for selected_multi_buffer_rows in rows {
13398        let query_rows =
13399            selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
13400        for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
13401            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13402            // when the caret is just above or just below the deleted hunk.
13403            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13404            let related_to_selection = if allow_adjacent {
13405                hunk.row_range.overlaps(&query_rows)
13406                    || hunk.row_range.start == query_rows.end
13407                    || hunk.row_range.end == query_rows.start
13408            } else {
13409                // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
13410                // `hunk.row_range` is exclusive (e.g. [2..3] means 2nd row is selected)
13411                hunk.row_range.overlaps(&selected_multi_buffer_rows)
13412                    || selected_multi_buffer_rows.end == hunk.row_range.start
13413            };
13414            if related_to_selection {
13415                if !processed_buffer_rows
13416                    .entry(hunk.buffer_id)
13417                    .or_default()
13418                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13419                {
13420                    continue;
13421                }
13422                hunks.push(hunk);
13423            }
13424        }
13425    }
13426
13427    hunks
13428}
13429
13430pub trait CollaborationHub {
13431    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13432    fn user_participant_indices<'a>(
13433        &self,
13434        cx: &'a AppContext,
13435    ) -> &'a HashMap<u64, ParticipantIndex>;
13436    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13437}
13438
13439impl CollaborationHub for Model<Project> {
13440    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13441        self.read(cx).collaborators()
13442    }
13443
13444    fn user_participant_indices<'a>(
13445        &self,
13446        cx: &'a AppContext,
13447    ) -> &'a HashMap<u64, ParticipantIndex> {
13448        self.read(cx).user_store().read(cx).participant_indices()
13449    }
13450
13451    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13452        let this = self.read(cx);
13453        let user_ids = this.collaborators().values().map(|c| c.user_id);
13454        this.user_store().read_with(cx, |user_store, cx| {
13455            user_store.participant_names(user_ids, cx)
13456        })
13457    }
13458}
13459
13460pub trait SemanticsProvider {
13461    fn hover(
13462        &self,
13463        buffer: &Model<Buffer>,
13464        position: text::Anchor,
13465        cx: &mut AppContext,
13466    ) -> Option<Task<Vec<project::Hover>>>;
13467
13468    fn inlay_hints(
13469        &self,
13470        buffer_handle: Model<Buffer>,
13471        range: Range<text::Anchor>,
13472        cx: &mut AppContext,
13473    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13474
13475    fn resolve_inlay_hint(
13476        &self,
13477        hint: InlayHint,
13478        buffer_handle: Model<Buffer>,
13479        server_id: LanguageServerId,
13480        cx: &mut AppContext,
13481    ) -> Option<Task<anyhow::Result<InlayHint>>>;
13482
13483    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13484
13485    fn document_highlights(
13486        &self,
13487        buffer: &Model<Buffer>,
13488        position: text::Anchor,
13489        cx: &mut AppContext,
13490    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13491
13492    fn definitions(
13493        &self,
13494        buffer: &Model<Buffer>,
13495        position: text::Anchor,
13496        kind: GotoDefinitionKind,
13497        cx: &mut AppContext,
13498    ) -> Option<Task<Result<Vec<LocationLink>>>>;
13499
13500    fn range_for_rename(
13501        &self,
13502        buffer: &Model<Buffer>,
13503        position: text::Anchor,
13504        cx: &mut AppContext,
13505    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13506
13507    fn perform_rename(
13508        &self,
13509        buffer: &Model<Buffer>,
13510        position: text::Anchor,
13511        new_name: String,
13512        cx: &mut AppContext,
13513    ) -> Option<Task<Result<ProjectTransaction>>>;
13514}
13515
13516pub trait CompletionProvider {
13517    fn completions(
13518        &self,
13519        buffer: &Model<Buffer>,
13520        buffer_position: text::Anchor,
13521        trigger: CompletionContext,
13522        cx: &mut ViewContext<Editor>,
13523    ) -> Task<Result<Vec<Completion>>>;
13524
13525    fn resolve_completions(
13526        &self,
13527        buffer: Model<Buffer>,
13528        completion_indices: Vec<usize>,
13529        completions: Arc<RwLock<Box<[Completion]>>>,
13530        cx: &mut ViewContext<Editor>,
13531    ) -> Task<Result<bool>>;
13532
13533    fn apply_additional_edits_for_completion(
13534        &self,
13535        buffer: Model<Buffer>,
13536        completion: Completion,
13537        push_to_history: bool,
13538        cx: &mut ViewContext<Editor>,
13539    ) -> Task<Result<Option<language::Transaction>>>;
13540
13541    fn is_completion_trigger(
13542        &self,
13543        buffer: &Model<Buffer>,
13544        position: language::Anchor,
13545        text: &str,
13546        trigger_in_words: bool,
13547        cx: &mut ViewContext<Editor>,
13548    ) -> bool;
13549
13550    fn sort_completions(&self) -> bool {
13551        true
13552    }
13553}
13554
13555pub trait CodeActionProvider {
13556    fn code_actions(
13557        &self,
13558        buffer: &Model<Buffer>,
13559        range: Range<text::Anchor>,
13560        cx: &mut WindowContext,
13561    ) -> Task<Result<Vec<CodeAction>>>;
13562
13563    fn apply_code_action(
13564        &self,
13565        buffer_handle: Model<Buffer>,
13566        action: CodeAction,
13567        excerpt_id: ExcerptId,
13568        push_to_history: bool,
13569        cx: &mut WindowContext,
13570    ) -> Task<Result<ProjectTransaction>>;
13571}
13572
13573impl CodeActionProvider for Model<Project> {
13574    fn code_actions(
13575        &self,
13576        buffer: &Model<Buffer>,
13577        range: Range<text::Anchor>,
13578        cx: &mut WindowContext,
13579    ) -> Task<Result<Vec<CodeAction>>> {
13580        self.update(cx, |project, cx| project.code_actions(buffer, range, cx))
13581    }
13582
13583    fn apply_code_action(
13584        &self,
13585        buffer_handle: Model<Buffer>,
13586        action: CodeAction,
13587        _excerpt_id: ExcerptId,
13588        push_to_history: bool,
13589        cx: &mut WindowContext,
13590    ) -> Task<Result<ProjectTransaction>> {
13591        self.update(cx, |project, cx| {
13592            project.apply_code_action(buffer_handle, action, push_to_history, cx)
13593        })
13594    }
13595}
13596
13597fn snippet_completions(
13598    project: &Project,
13599    buffer: &Model<Buffer>,
13600    buffer_position: text::Anchor,
13601    cx: &mut AppContext,
13602) -> Vec<Completion> {
13603    let language = buffer.read(cx).language_at(buffer_position);
13604    let language_name = language.as_ref().map(|language| language.lsp_id());
13605    let snippet_store = project.snippets().read(cx);
13606    let snippets = snippet_store.snippets_for(language_name, cx);
13607
13608    if snippets.is_empty() {
13609        return vec![];
13610    }
13611    let snapshot = buffer.read(cx).text_snapshot();
13612    let chars = snapshot.reversed_chars_for_range(text::Anchor::MIN..buffer_position);
13613
13614    let scope = language.map(|language| language.default_scope());
13615    let classifier = CharClassifier::new(scope).for_completion(true);
13616    let mut last_word = chars
13617        .take_while(|c| classifier.is_word(*c))
13618        .collect::<String>();
13619    last_word = last_word.chars().rev().collect();
13620    let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13621    let to_lsp = |point: &text::Anchor| {
13622        let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13623        point_to_lsp(end)
13624    };
13625    let lsp_end = to_lsp(&buffer_position);
13626    snippets
13627        .into_iter()
13628        .filter_map(|snippet| {
13629            let matching_prefix = snippet
13630                .prefix
13631                .iter()
13632                .find(|prefix| prefix.starts_with(&last_word))?;
13633            let start = as_offset - last_word.len();
13634            let start = snapshot.anchor_before(start);
13635            let range = start..buffer_position;
13636            let lsp_start = to_lsp(&start);
13637            let lsp_range = lsp::Range {
13638                start: lsp_start,
13639                end: lsp_end,
13640            };
13641            Some(Completion {
13642                old_range: range,
13643                new_text: snippet.body.clone(),
13644                label: CodeLabel {
13645                    text: matching_prefix.clone(),
13646                    runs: vec![],
13647                    filter_range: 0..matching_prefix.len(),
13648                },
13649                server_id: LanguageServerId(usize::MAX),
13650                documentation: snippet.description.clone().map(Documentation::SingleLine),
13651                lsp_completion: lsp::CompletionItem {
13652                    label: snippet.prefix.first().unwrap().clone(),
13653                    kind: Some(CompletionItemKind::SNIPPET),
13654                    label_details: snippet.description.as_ref().map(|description| {
13655                        lsp::CompletionItemLabelDetails {
13656                            detail: Some(description.clone()),
13657                            description: None,
13658                        }
13659                    }),
13660                    insert_text_format: Some(InsertTextFormat::SNIPPET),
13661                    text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13662                        lsp::InsertReplaceEdit {
13663                            new_text: snippet.body.clone(),
13664                            insert: lsp_range,
13665                            replace: lsp_range,
13666                        },
13667                    )),
13668                    filter_text: Some(snippet.body.clone()),
13669                    sort_text: Some(char::MAX.to_string()),
13670                    ..Default::default()
13671                },
13672                confirm: None,
13673            })
13674        })
13675        .collect()
13676}
13677
13678impl CompletionProvider for Model<Project> {
13679    fn completions(
13680        &self,
13681        buffer: &Model<Buffer>,
13682        buffer_position: text::Anchor,
13683        options: CompletionContext,
13684        cx: &mut ViewContext<Editor>,
13685    ) -> Task<Result<Vec<Completion>>> {
13686        self.update(cx, |project, cx| {
13687            let snippets = snippet_completions(project, buffer, buffer_position, cx);
13688            let project_completions = project.completions(buffer, buffer_position, options, cx);
13689            cx.background_executor().spawn(async move {
13690                let mut completions = project_completions.await?;
13691                //let snippets = snippets.into_iter().;
13692                completions.extend(snippets);
13693                Ok(completions)
13694            })
13695        })
13696    }
13697
13698    fn resolve_completions(
13699        &self,
13700        buffer: Model<Buffer>,
13701        completion_indices: Vec<usize>,
13702        completions: Arc<RwLock<Box<[Completion]>>>,
13703        cx: &mut ViewContext<Editor>,
13704    ) -> Task<Result<bool>> {
13705        self.update(cx, |project, cx| {
13706            project.resolve_completions(buffer, completion_indices, completions, cx)
13707        })
13708    }
13709
13710    fn apply_additional_edits_for_completion(
13711        &self,
13712        buffer: Model<Buffer>,
13713        completion: Completion,
13714        push_to_history: bool,
13715        cx: &mut ViewContext<Editor>,
13716    ) -> Task<Result<Option<language::Transaction>>> {
13717        self.update(cx, |project, cx| {
13718            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13719        })
13720    }
13721
13722    fn is_completion_trigger(
13723        &self,
13724        buffer: &Model<Buffer>,
13725        position: language::Anchor,
13726        text: &str,
13727        trigger_in_words: bool,
13728        cx: &mut ViewContext<Editor>,
13729    ) -> bool {
13730        if !EditorSettings::get_global(cx).show_completions_on_input {
13731            return false;
13732        }
13733
13734        let mut chars = text.chars();
13735        let char = if let Some(char) = chars.next() {
13736            char
13737        } else {
13738            return false;
13739        };
13740        if chars.next().is_some() {
13741            return false;
13742        }
13743
13744        let buffer = buffer.read(cx);
13745        let classifier = buffer
13746            .snapshot()
13747            .char_classifier_at(position)
13748            .for_completion(true);
13749        if trigger_in_words && classifier.is_word(char) {
13750            return true;
13751        }
13752
13753        buffer
13754            .completion_triggers()
13755            .iter()
13756            .any(|string| string == text)
13757    }
13758}
13759
13760impl SemanticsProvider for Model<Project> {
13761    fn hover(
13762        &self,
13763        buffer: &Model<Buffer>,
13764        position: text::Anchor,
13765        cx: &mut AppContext,
13766    ) -> Option<Task<Vec<project::Hover>>> {
13767        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13768    }
13769
13770    fn document_highlights(
13771        &self,
13772        buffer: &Model<Buffer>,
13773        position: text::Anchor,
13774        cx: &mut AppContext,
13775    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13776        Some(self.update(cx, |project, cx| {
13777            project.document_highlights(buffer, position, cx)
13778        }))
13779    }
13780
13781    fn definitions(
13782        &self,
13783        buffer: &Model<Buffer>,
13784        position: text::Anchor,
13785        kind: GotoDefinitionKind,
13786        cx: &mut AppContext,
13787    ) -> Option<Task<Result<Vec<LocationLink>>>> {
13788        Some(self.update(cx, |project, cx| match kind {
13789            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13790            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13791            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13792            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13793        }))
13794    }
13795
13796    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13797        // TODO: make this work for remote projects
13798        self.read(cx)
13799            .language_servers_for_buffer(buffer.read(cx), cx)
13800            .any(
13801                |(_, server)| match server.capabilities().inlay_hint_provider {
13802                    Some(lsp::OneOf::Left(enabled)) => enabled,
13803                    Some(lsp::OneOf::Right(_)) => true,
13804                    None => false,
13805                },
13806            )
13807    }
13808
13809    fn inlay_hints(
13810        &self,
13811        buffer_handle: Model<Buffer>,
13812        range: Range<text::Anchor>,
13813        cx: &mut AppContext,
13814    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13815        Some(self.update(cx, |project, cx| {
13816            project.inlay_hints(buffer_handle, range, cx)
13817        }))
13818    }
13819
13820    fn resolve_inlay_hint(
13821        &self,
13822        hint: InlayHint,
13823        buffer_handle: Model<Buffer>,
13824        server_id: LanguageServerId,
13825        cx: &mut AppContext,
13826    ) -> Option<Task<anyhow::Result<InlayHint>>> {
13827        Some(self.update(cx, |project, cx| {
13828            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13829        }))
13830    }
13831
13832    fn range_for_rename(
13833        &self,
13834        buffer: &Model<Buffer>,
13835        position: text::Anchor,
13836        cx: &mut AppContext,
13837    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13838        Some(self.update(cx, |project, cx| {
13839            project.prepare_rename(buffer.clone(), position, cx)
13840        }))
13841    }
13842
13843    fn perform_rename(
13844        &self,
13845        buffer: &Model<Buffer>,
13846        position: text::Anchor,
13847        new_name: String,
13848        cx: &mut AppContext,
13849    ) -> Option<Task<Result<ProjectTransaction>>> {
13850        Some(self.update(cx, |project, cx| {
13851            project.perform_rename(buffer.clone(), position, new_name, cx)
13852        }))
13853    }
13854}
13855
13856fn inlay_hint_settings(
13857    location: Anchor,
13858    snapshot: &MultiBufferSnapshot,
13859    cx: &mut ViewContext<'_, Editor>,
13860) -> InlayHintSettings {
13861    let file = snapshot.file_at(location);
13862    let language = snapshot.language_at(location).map(|l| l.name());
13863    language_settings(language, file, cx).inlay_hints
13864}
13865
13866fn consume_contiguous_rows(
13867    contiguous_row_selections: &mut Vec<Selection<Point>>,
13868    selection: &Selection<Point>,
13869    display_map: &DisplaySnapshot,
13870    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
13871) -> (MultiBufferRow, MultiBufferRow) {
13872    contiguous_row_selections.push(selection.clone());
13873    let start_row = MultiBufferRow(selection.start.row);
13874    let mut end_row = ending_row(selection, display_map);
13875
13876    while let Some(next_selection) = selections.peek() {
13877        if next_selection.start.row <= end_row.0 {
13878            end_row = ending_row(next_selection, display_map);
13879            contiguous_row_selections.push(selections.next().unwrap().clone());
13880        } else {
13881            break;
13882        }
13883    }
13884    (start_row, end_row)
13885}
13886
13887fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13888    if next_selection.end.column > 0 || next_selection.is_empty() {
13889        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13890    } else {
13891        MultiBufferRow(next_selection.end.row)
13892    }
13893}
13894
13895impl EditorSnapshot {
13896    pub fn remote_selections_in_range<'a>(
13897        &'a self,
13898        range: &'a Range<Anchor>,
13899        collaboration_hub: &dyn CollaborationHub,
13900        cx: &'a AppContext,
13901    ) -> impl 'a + Iterator<Item = RemoteSelection> {
13902        let participant_names = collaboration_hub.user_names(cx);
13903        let participant_indices = collaboration_hub.user_participant_indices(cx);
13904        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
13905        let collaborators_by_replica_id = collaborators_by_peer_id
13906            .iter()
13907            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
13908            .collect::<HashMap<_, _>>();
13909        self.buffer_snapshot
13910            .selections_in_range(range, false)
13911            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
13912                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
13913                let participant_index = participant_indices.get(&collaborator.user_id).copied();
13914                let user_name = participant_names.get(&collaborator.user_id).cloned();
13915                Some(RemoteSelection {
13916                    replica_id,
13917                    selection,
13918                    cursor_shape,
13919                    line_mode,
13920                    participant_index,
13921                    peer_id: collaborator.peer_id,
13922                    user_name,
13923                })
13924            })
13925    }
13926
13927    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
13928        self.display_snapshot.buffer_snapshot.language_at(position)
13929    }
13930
13931    pub fn is_focused(&self) -> bool {
13932        self.is_focused
13933    }
13934
13935    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
13936        self.placeholder_text.as_ref()
13937    }
13938
13939    pub fn scroll_position(&self) -> gpui::Point<f32> {
13940        self.scroll_anchor.scroll_position(&self.display_snapshot)
13941    }
13942
13943    fn gutter_dimensions(
13944        &self,
13945        font_id: FontId,
13946        font_size: Pixels,
13947        em_width: Pixels,
13948        em_advance: Pixels,
13949        max_line_number_width: Pixels,
13950        cx: &AppContext,
13951    ) -> GutterDimensions {
13952        if !self.show_gutter {
13953            return GutterDimensions::default();
13954        }
13955        let descent = cx.text_system().descent(font_id, font_size);
13956
13957        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
13958            matches!(
13959                ProjectSettings::get_global(cx).git.git_gutter,
13960                Some(GitGutterSetting::TrackedFiles)
13961            )
13962        });
13963        let gutter_settings = EditorSettings::get_global(cx).gutter;
13964        let show_line_numbers = self
13965            .show_line_numbers
13966            .unwrap_or(gutter_settings.line_numbers);
13967        let line_gutter_width = if show_line_numbers {
13968            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
13969            let min_width_for_number_on_gutter = em_advance * 4.0;
13970            max_line_number_width.max(min_width_for_number_on_gutter)
13971        } else {
13972            0.0.into()
13973        };
13974
13975        let show_code_actions = self
13976            .show_code_actions
13977            .unwrap_or(gutter_settings.code_actions);
13978
13979        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
13980
13981        let git_blame_entries_width =
13982            self.git_blame_gutter_max_author_length
13983                .map(|max_author_length| {
13984                    // Length of the author name, but also space for the commit hash,
13985                    // the spacing and the timestamp.
13986                    let max_char_count = max_author_length
13987                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
13988                        + 7 // length of commit sha
13989                        + 14 // length of max relative timestamp ("60 minutes ago")
13990                        + 4; // gaps and margins
13991
13992                    em_advance * max_char_count
13993                });
13994
13995        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
13996        left_padding += if show_code_actions || show_runnables {
13997            em_width * 3.0
13998        } else if show_git_gutter && show_line_numbers {
13999            em_width * 2.0
14000        } else if show_git_gutter || show_line_numbers {
14001            em_width
14002        } else {
14003            px(0.)
14004        };
14005
14006        let right_padding = if gutter_settings.folds && show_line_numbers {
14007            em_width * 4.0
14008        } else if gutter_settings.folds {
14009            em_width * 3.0
14010        } else if show_line_numbers {
14011            em_width
14012        } else {
14013            px(0.)
14014        };
14015
14016        GutterDimensions {
14017            left_padding,
14018            right_padding,
14019            width: line_gutter_width + left_padding + right_padding,
14020            margin: -descent,
14021            git_blame_entries_width,
14022        }
14023    }
14024
14025    pub fn render_fold_toggle(
14026        &self,
14027        buffer_row: MultiBufferRow,
14028        row_contains_cursor: bool,
14029        editor: View<Editor>,
14030        cx: &mut WindowContext,
14031    ) -> Option<AnyElement> {
14032        let folded = self.is_line_folded(buffer_row);
14033
14034        if let Some(crease) = self
14035            .crease_snapshot
14036            .query_row(buffer_row, &self.buffer_snapshot)
14037        {
14038            let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14039                if folded {
14040                    editor.update(cx, |editor, cx| {
14041                        editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14042                    });
14043                } else {
14044                    editor.update(cx, |editor, cx| {
14045                        editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14046                    });
14047                }
14048            });
14049
14050            Some((crease.render_toggle)(
14051                buffer_row,
14052                folded,
14053                toggle_callback,
14054                cx,
14055            ))
14056        } else if folded
14057            || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
14058        {
14059            Some(
14060                Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
14061                    .selected(folded)
14062                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14063                        if folded {
14064                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
14065                        } else {
14066                            this.fold_at(&FoldAt { buffer_row }, cx);
14067                        }
14068                    }))
14069                    .into_any_element(),
14070            )
14071        } else {
14072            None
14073        }
14074    }
14075
14076    pub fn render_crease_trailer(
14077        &self,
14078        buffer_row: MultiBufferRow,
14079        cx: &mut WindowContext,
14080    ) -> Option<AnyElement> {
14081        let folded = self.is_line_folded(buffer_row);
14082        let crease = self
14083            .crease_snapshot
14084            .query_row(buffer_row, &self.buffer_snapshot)?;
14085        Some((crease.render_trailer)(buffer_row, folded, cx))
14086    }
14087}
14088
14089impl Deref for EditorSnapshot {
14090    type Target = DisplaySnapshot;
14091
14092    fn deref(&self) -> &Self::Target {
14093        &self.display_snapshot
14094    }
14095}
14096
14097#[derive(Clone, Debug, PartialEq, Eq)]
14098pub enum EditorEvent {
14099    InputIgnored {
14100        text: Arc<str>,
14101    },
14102    InputHandled {
14103        utf16_range_to_replace: Option<Range<isize>>,
14104        text: Arc<str>,
14105    },
14106    ExcerptsAdded {
14107        buffer: Model<Buffer>,
14108        predecessor: ExcerptId,
14109        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14110    },
14111    ExcerptsRemoved {
14112        ids: Vec<ExcerptId>,
14113    },
14114    ExcerptsEdited {
14115        ids: Vec<ExcerptId>,
14116    },
14117    ExcerptsExpanded {
14118        ids: Vec<ExcerptId>,
14119    },
14120    BufferEdited,
14121    Edited {
14122        transaction_id: clock::Lamport,
14123    },
14124    Reparsed(BufferId),
14125    Focused,
14126    FocusedIn,
14127    Blurred,
14128    DirtyChanged,
14129    Saved,
14130    TitleChanged,
14131    DiffBaseChanged,
14132    SelectionsChanged {
14133        local: bool,
14134    },
14135    ScrollPositionChanged {
14136        local: bool,
14137        autoscroll: bool,
14138    },
14139    Closed,
14140    TransactionUndone {
14141        transaction_id: clock::Lamport,
14142    },
14143    TransactionBegun {
14144        transaction_id: clock::Lamport,
14145    },
14146    Reloaded,
14147    CursorShapeChanged,
14148}
14149
14150impl EventEmitter<EditorEvent> for Editor {}
14151
14152impl FocusableView for Editor {
14153    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14154        self.focus_handle.clone()
14155    }
14156}
14157
14158impl Render for Editor {
14159    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14160        let settings = ThemeSettings::get_global(cx);
14161
14162        let mut text_style = match self.mode {
14163            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14164                color: cx.theme().colors().editor_foreground,
14165                font_family: settings.ui_font.family.clone(),
14166                font_features: settings.ui_font.features.clone(),
14167                font_fallbacks: settings.ui_font.fallbacks.clone(),
14168                font_size: rems(0.875).into(),
14169                font_weight: settings.ui_font.weight,
14170                line_height: relative(settings.buffer_line_height.value()),
14171                ..Default::default()
14172            },
14173            EditorMode::Full => TextStyle {
14174                color: cx.theme().colors().editor_foreground,
14175                font_family: settings.buffer_font.family.clone(),
14176                font_features: settings.buffer_font.features.clone(),
14177                font_fallbacks: settings.buffer_font.fallbacks.clone(),
14178                font_size: settings.buffer_font_size(cx).into(),
14179                font_weight: settings.buffer_font.weight,
14180                line_height: relative(settings.buffer_line_height.value()),
14181                ..Default::default()
14182            },
14183        };
14184        if let Some(text_style_refinement) = &self.text_style_refinement {
14185            text_style.refine(text_style_refinement)
14186        }
14187
14188        let background = match self.mode {
14189            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14190            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14191            EditorMode::Full => cx.theme().colors().editor_background,
14192        };
14193
14194        EditorElement::new(
14195            cx.view(),
14196            EditorStyle {
14197                background,
14198                local_player: cx.theme().players().local(),
14199                text: text_style,
14200                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14201                syntax: cx.theme().syntax().clone(),
14202                status: cx.theme().status().clone(),
14203                inlay_hints_style: make_inlay_hints_style(cx),
14204                suggestions_style: HighlightStyle {
14205                    color: Some(cx.theme().status().predictive),
14206                    ..HighlightStyle::default()
14207                },
14208                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14209            },
14210        )
14211    }
14212}
14213
14214impl ViewInputHandler for Editor {
14215    fn text_for_range(
14216        &mut self,
14217        range_utf16: Range<usize>,
14218        cx: &mut ViewContext<Self>,
14219    ) -> Option<String> {
14220        Some(
14221            self.buffer
14222                .read(cx)
14223                .read(cx)
14224                .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
14225                .collect(),
14226        )
14227    }
14228
14229    fn selected_text_range(
14230        &mut self,
14231        ignore_disabled_input: bool,
14232        cx: &mut ViewContext<Self>,
14233    ) -> Option<UTF16Selection> {
14234        // Prevent the IME menu from appearing when holding down an alphabetic key
14235        // while input is disabled.
14236        if !ignore_disabled_input && !self.input_enabled {
14237            return None;
14238        }
14239
14240        let selection = self.selections.newest::<OffsetUtf16>(cx);
14241        let range = selection.range();
14242
14243        Some(UTF16Selection {
14244            range: range.start.0..range.end.0,
14245            reversed: selection.reversed,
14246        })
14247    }
14248
14249    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14250        let snapshot = self.buffer.read(cx).read(cx);
14251        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14252        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14253    }
14254
14255    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14256        self.clear_highlights::<InputComposition>(cx);
14257        self.ime_transaction.take();
14258    }
14259
14260    fn replace_text_in_range(
14261        &mut self,
14262        range_utf16: Option<Range<usize>>,
14263        text: &str,
14264        cx: &mut ViewContext<Self>,
14265    ) {
14266        if !self.input_enabled {
14267            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14268            return;
14269        }
14270
14271        self.transact(cx, |this, cx| {
14272            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14273                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14274                Some(this.selection_replacement_ranges(range_utf16, cx))
14275            } else {
14276                this.marked_text_ranges(cx)
14277            };
14278
14279            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14280                let newest_selection_id = this.selections.newest_anchor().id;
14281                this.selections
14282                    .all::<OffsetUtf16>(cx)
14283                    .iter()
14284                    .zip(ranges_to_replace.iter())
14285                    .find_map(|(selection, range)| {
14286                        if selection.id == newest_selection_id {
14287                            Some(
14288                                (range.start.0 as isize - selection.head().0 as isize)
14289                                    ..(range.end.0 as isize - selection.head().0 as isize),
14290                            )
14291                        } else {
14292                            None
14293                        }
14294                    })
14295            });
14296
14297            cx.emit(EditorEvent::InputHandled {
14298                utf16_range_to_replace: range_to_replace,
14299                text: text.into(),
14300            });
14301
14302            if let Some(new_selected_ranges) = new_selected_ranges {
14303                this.change_selections(None, cx, |selections| {
14304                    selections.select_ranges(new_selected_ranges)
14305                });
14306                this.backspace(&Default::default(), cx);
14307            }
14308
14309            this.handle_input(text, cx);
14310        });
14311
14312        if let Some(transaction) = self.ime_transaction {
14313            self.buffer.update(cx, |buffer, cx| {
14314                buffer.group_until_transaction(transaction, cx);
14315            });
14316        }
14317
14318        self.unmark_text(cx);
14319    }
14320
14321    fn replace_and_mark_text_in_range(
14322        &mut self,
14323        range_utf16: Option<Range<usize>>,
14324        text: &str,
14325        new_selected_range_utf16: Option<Range<usize>>,
14326        cx: &mut ViewContext<Self>,
14327    ) {
14328        if !self.input_enabled {
14329            return;
14330        }
14331
14332        let transaction = self.transact(cx, |this, cx| {
14333            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14334                let snapshot = this.buffer.read(cx).read(cx);
14335                if let Some(relative_range_utf16) = range_utf16.as_ref() {
14336                    for marked_range in &mut marked_ranges {
14337                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14338                        marked_range.start.0 += relative_range_utf16.start;
14339                        marked_range.start =
14340                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14341                        marked_range.end =
14342                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14343                    }
14344                }
14345                Some(marked_ranges)
14346            } else if let Some(range_utf16) = range_utf16 {
14347                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14348                Some(this.selection_replacement_ranges(range_utf16, cx))
14349            } else {
14350                None
14351            };
14352
14353            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14354                let newest_selection_id = this.selections.newest_anchor().id;
14355                this.selections
14356                    .all::<OffsetUtf16>(cx)
14357                    .iter()
14358                    .zip(ranges_to_replace.iter())
14359                    .find_map(|(selection, range)| {
14360                        if selection.id == newest_selection_id {
14361                            Some(
14362                                (range.start.0 as isize - selection.head().0 as isize)
14363                                    ..(range.end.0 as isize - selection.head().0 as isize),
14364                            )
14365                        } else {
14366                            None
14367                        }
14368                    })
14369            });
14370
14371            cx.emit(EditorEvent::InputHandled {
14372                utf16_range_to_replace: range_to_replace,
14373                text: text.into(),
14374            });
14375
14376            if let Some(ranges) = ranges_to_replace {
14377                this.change_selections(None, cx, |s| s.select_ranges(ranges));
14378            }
14379
14380            let marked_ranges = {
14381                let snapshot = this.buffer.read(cx).read(cx);
14382                this.selections
14383                    .disjoint_anchors()
14384                    .iter()
14385                    .map(|selection| {
14386                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14387                    })
14388                    .collect::<Vec<_>>()
14389            };
14390
14391            if text.is_empty() {
14392                this.unmark_text(cx);
14393            } else {
14394                this.highlight_text::<InputComposition>(
14395                    marked_ranges.clone(),
14396                    HighlightStyle {
14397                        underline: Some(UnderlineStyle {
14398                            thickness: px(1.),
14399                            color: None,
14400                            wavy: false,
14401                        }),
14402                        ..Default::default()
14403                    },
14404                    cx,
14405                );
14406            }
14407
14408            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14409            let use_autoclose = this.use_autoclose;
14410            let use_auto_surround = this.use_auto_surround;
14411            this.set_use_autoclose(false);
14412            this.set_use_auto_surround(false);
14413            this.handle_input(text, cx);
14414            this.set_use_autoclose(use_autoclose);
14415            this.set_use_auto_surround(use_auto_surround);
14416
14417            if let Some(new_selected_range) = new_selected_range_utf16 {
14418                let snapshot = this.buffer.read(cx).read(cx);
14419                let new_selected_ranges = marked_ranges
14420                    .into_iter()
14421                    .map(|marked_range| {
14422                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14423                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14424                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14425                        snapshot.clip_offset_utf16(new_start, Bias::Left)
14426                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14427                    })
14428                    .collect::<Vec<_>>();
14429
14430                drop(snapshot);
14431                this.change_selections(None, cx, |selections| {
14432                    selections.select_ranges(new_selected_ranges)
14433                });
14434            }
14435        });
14436
14437        self.ime_transaction = self.ime_transaction.or(transaction);
14438        if let Some(transaction) = self.ime_transaction {
14439            self.buffer.update(cx, |buffer, cx| {
14440                buffer.group_until_transaction(transaction, cx);
14441            });
14442        }
14443
14444        if self.text_highlights::<InputComposition>(cx).is_none() {
14445            self.ime_transaction.take();
14446        }
14447    }
14448
14449    fn bounds_for_range(
14450        &mut self,
14451        range_utf16: Range<usize>,
14452        element_bounds: gpui::Bounds<Pixels>,
14453        cx: &mut ViewContext<Self>,
14454    ) -> Option<gpui::Bounds<Pixels>> {
14455        let text_layout_details = self.text_layout_details(cx);
14456        let style = &text_layout_details.editor_style;
14457        let font_id = cx.text_system().resolve_font(&style.text.font());
14458        let font_size = style.text.font_size.to_pixels(cx.rem_size());
14459        let line_height = style.text.line_height_in_pixels(cx.rem_size());
14460
14461        let em_width = cx
14462            .text_system()
14463            .typographic_bounds(font_id, font_size, 'm')
14464            .unwrap()
14465            .size
14466            .width;
14467
14468        let snapshot = self.snapshot(cx);
14469        let scroll_position = snapshot.scroll_position();
14470        let scroll_left = scroll_position.x * em_width;
14471
14472        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14473        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14474            + self.gutter_dimensions.width;
14475        let y = line_height * (start.row().as_f32() - scroll_position.y);
14476
14477        Some(Bounds {
14478            origin: element_bounds.origin + point(x, y),
14479            size: size(em_width, line_height),
14480        })
14481    }
14482}
14483
14484trait SelectionExt {
14485    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14486    fn spanned_rows(
14487        &self,
14488        include_end_if_at_line_start: bool,
14489        map: &DisplaySnapshot,
14490    ) -> Range<MultiBufferRow>;
14491}
14492
14493impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14494    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14495        let start = self
14496            .start
14497            .to_point(&map.buffer_snapshot)
14498            .to_display_point(map);
14499        let end = self
14500            .end
14501            .to_point(&map.buffer_snapshot)
14502            .to_display_point(map);
14503        if self.reversed {
14504            end..start
14505        } else {
14506            start..end
14507        }
14508    }
14509
14510    fn spanned_rows(
14511        &self,
14512        include_end_if_at_line_start: bool,
14513        map: &DisplaySnapshot,
14514    ) -> Range<MultiBufferRow> {
14515        let start = self.start.to_point(&map.buffer_snapshot);
14516        let mut end = self.end.to_point(&map.buffer_snapshot);
14517        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14518            end.row -= 1;
14519        }
14520
14521        let buffer_start = map.prev_line_boundary(start).0;
14522        let buffer_end = map.next_line_boundary(end).0;
14523        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14524    }
14525}
14526
14527impl<T: InvalidationRegion> InvalidationStack<T> {
14528    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14529    where
14530        S: Clone + ToOffset,
14531    {
14532        while let Some(region) = self.last() {
14533            let all_selections_inside_invalidation_ranges =
14534                if selections.len() == region.ranges().len() {
14535                    selections
14536                        .iter()
14537                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14538                        .all(|(selection, invalidation_range)| {
14539                            let head = selection.head().to_offset(buffer);
14540                            invalidation_range.start <= head && invalidation_range.end >= head
14541                        })
14542                } else {
14543                    false
14544                };
14545
14546            if all_selections_inside_invalidation_ranges {
14547                break;
14548            } else {
14549                self.pop();
14550            }
14551        }
14552    }
14553}
14554
14555impl<T> Default for InvalidationStack<T> {
14556    fn default() -> Self {
14557        Self(Default::default())
14558    }
14559}
14560
14561impl<T> Deref for InvalidationStack<T> {
14562    type Target = Vec<T>;
14563
14564    fn deref(&self) -> &Self::Target {
14565        &self.0
14566    }
14567}
14568
14569impl<T> DerefMut for InvalidationStack<T> {
14570    fn deref_mut(&mut self) -> &mut Self::Target {
14571        &mut self.0
14572    }
14573}
14574
14575impl InvalidationRegion for SnippetState {
14576    fn ranges(&self) -> &[Range<Anchor>] {
14577        &self.ranges[self.active_index]
14578    }
14579}
14580
14581pub fn diagnostic_block_renderer(
14582    diagnostic: Diagnostic,
14583    max_message_rows: Option<u8>,
14584    allow_closing: bool,
14585    _is_valid: bool,
14586) -> RenderBlock {
14587    let (text_without_backticks, code_ranges) =
14588        highlight_diagnostic_message(&diagnostic, max_message_rows);
14589
14590    Box::new(move |cx: &mut BlockContext| {
14591        let group_id: SharedString = cx.block_id.to_string().into();
14592
14593        let mut text_style = cx.text_style().clone();
14594        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14595        let theme_settings = ThemeSettings::get_global(cx);
14596        text_style.font_family = theme_settings.buffer_font.family.clone();
14597        text_style.font_style = theme_settings.buffer_font.style;
14598        text_style.font_features = theme_settings.buffer_font.features.clone();
14599        text_style.font_weight = theme_settings.buffer_font.weight;
14600
14601        let multi_line_diagnostic = diagnostic.message.contains('\n');
14602
14603        let buttons = |diagnostic: &Diagnostic| {
14604            if multi_line_diagnostic {
14605                v_flex()
14606            } else {
14607                h_flex()
14608            }
14609            .when(allow_closing, |div| {
14610                div.children(diagnostic.is_primary.then(|| {
14611                    IconButton::new("close-block", IconName::XCircle)
14612                        .icon_color(Color::Muted)
14613                        .size(ButtonSize::Compact)
14614                        .style(ButtonStyle::Transparent)
14615                        .visible_on_hover(group_id.clone())
14616                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14617                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14618                }))
14619            })
14620            .child(
14621                IconButton::new("copy-block", IconName::Copy)
14622                    .icon_color(Color::Muted)
14623                    .size(ButtonSize::Compact)
14624                    .style(ButtonStyle::Transparent)
14625                    .visible_on_hover(group_id.clone())
14626                    .on_click({
14627                        let message = diagnostic.message.clone();
14628                        move |_click, cx| {
14629                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14630                        }
14631                    })
14632                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14633            )
14634        };
14635
14636        let icon_size = buttons(&diagnostic)
14637            .into_any_element()
14638            .layout_as_root(AvailableSpace::min_size(), cx);
14639
14640        h_flex()
14641            .id(cx.block_id)
14642            .group(group_id.clone())
14643            .relative()
14644            .size_full()
14645            .pl(cx.gutter_dimensions.width)
14646            .w(cx.max_width - cx.gutter_dimensions.full_width())
14647            .child(
14648                div()
14649                    .flex()
14650                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14651                    .flex_shrink(),
14652            )
14653            .child(buttons(&diagnostic))
14654            .child(div().flex().flex_shrink_0().child(
14655                StyledText::new(text_without_backticks.clone()).with_highlights(
14656                    &text_style,
14657                    code_ranges.iter().map(|range| {
14658                        (
14659                            range.clone(),
14660                            HighlightStyle {
14661                                font_weight: Some(FontWeight::BOLD),
14662                                ..Default::default()
14663                            },
14664                        )
14665                    }),
14666                ),
14667            ))
14668            .into_any_element()
14669    })
14670}
14671
14672pub fn highlight_diagnostic_message(
14673    diagnostic: &Diagnostic,
14674    mut max_message_rows: Option<u8>,
14675) -> (SharedString, Vec<Range<usize>>) {
14676    let mut text_without_backticks = String::new();
14677    let mut code_ranges = Vec::new();
14678
14679    if let Some(source) = &diagnostic.source {
14680        text_without_backticks.push_str(source);
14681        code_ranges.push(0..source.len());
14682        text_without_backticks.push_str(": ");
14683    }
14684
14685    let mut prev_offset = 0;
14686    let mut in_code_block = false;
14687    let has_row_limit = max_message_rows.is_some();
14688    let mut newline_indices = diagnostic
14689        .message
14690        .match_indices('\n')
14691        .filter(|_| has_row_limit)
14692        .map(|(ix, _)| ix)
14693        .fuse()
14694        .peekable();
14695
14696    for (quote_ix, _) in diagnostic
14697        .message
14698        .match_indices('`')
14699        .chain([(diagnostic.message.len(), "")])
14700    {
14701        let mut first_newline_ix = None;
14702        let mut last_newline_ix = None;
14703        while let Some(newline_ix) = newline_indices.peek() {
14704            if *newline_ix < quote_ix {
14705                if first_newline_ix.is_none() {
14706                    first_newline_ix = Some(*newline_ix);
14707                }
14708                last_newline_ix = Some(*newline_ix);
14709
14710                if let Some(rows_left) = &mut max_message_rows {
14711                    if *rows_left == 0 {
14712                        break;
14713                    } else {
14714                        *rows_left -= 1;
14715                    }
14716                }
14717                let _ = newline_indices.next();
14718            } else {
14719                break;
14720            }
14721        }
14722        let prev_len = text_without_backticks.len();
14723        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14724        text_without_backticks.push_str(new_text);
14725        if in_code_block {
14726            code_ranges.push(prev_len..text_without_backticks.len());
14727        }
14728        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14729        in_code_block = !in_code_block;
14730        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14731            text_without_backticks.push_str("...");
14732            break;
14733        }
14734    }
14735
14736    (text_without_backticks.into(), code_ranges)
14737}
14738
14739fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14740    match severity {
14741        DiagnosticSeverity::ERROR => colors.error,
14742        DiagnosticSeverity::WARNING => colors.warning,
14743        DiagnosticSeverity::INFORMATION => colors.info,
14744        DiagnosticSeverity::HINT => colors.info,
14745        _ => colors.ignored,
14746    }
14747}
14748
14749pub fn styled_runs_for_code_label<'a>(
14750    label: &'a CodeLabel,
14751    syntax_theme: &'a theme::SyntaxTheme,
14752) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14753    let fade_out = HighlightStyle {
14754        fade_out: Some(0.35),
14755        ..Default::default()
14756    };
14757
14758    let mut prev_end = label.filter_range.end;
14759    label
14760        .runs
14761        .iter()
14762        .enumerate()
14763        .flat_map(move |(ix, (range, highlight_id))| {
14764            let style = if let Some(style) = highlight_id.style(syntax_theme) {
14765                style
14766            } else {
14767                return Default::default();
14768            };
14769            let mut muted_style = style;
14770            muted_style.highlight(fade_out);
14771
14772            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14773            if range.start >= label.filter_range.end {
14774                if range.start > prev_end {
14775                    runs.push((prev_end..range.start, fade_out));
14776                }
14777                runs.push((range.clone(), muted_style));
14778            } else if range.end <= label.filter_range.end {
14779                runs.push((range.clone(), style));
14780            } else {
14781                runs.push((range.start..label.filter_range.end, style));
14782                runs.push((label.filter_range.end..range.end, muted_style));
14783            }
14784            prev_end = cmp::max(prev_end, range.end);
14785
14786            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14787                runs.push((prev_end..label.text.len(), fade_out));
14788            }
14789
14790            runs
14791        })
14792}
14793
14794pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14795    let mut prev_index = 0;
14796    let mut prev_codepoint: Option<char> = None;
14797    text.char_indices()
14798        .chain([(text.len(), '\0')])
14799        .filter_map(move |(index, codepoint)| {
14800            let prev_codepoint = prev_codepoint.replace(codepoint)?;
14801            let is_boundary = index == text.len()
14802                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14803                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14804            if is_boundary {
14805                let chunk = &text[prev_index..index];
14806                prev_index = index;
14807                Some(chunk)
14808            } else {
14809                None
14810            }
14811        })
14812}
14813
14814pub trait RangeToAnchorExt: Sized {
14815    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14816
14817    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14818        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14819        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14820    }
14821}
14822
14823impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14824    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14825        let start_offset = self.start.to_offset(snapshot);
14826        let end_offset = self.end.to_offset(snapshot);
14827        if start_offset == end_offset {
14828            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14829        } else {
14830            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14831        }
14832    }
14833}
14834
14835pub trait RowExt {
14836    fn as_f32(&self) -> f32;
14837
14838    fn next_row(&self) -> Self;
14839
14840    fn previous_row(&self) -> Self;
14841
14842    fn minus(&self, other: Self) -> u32;
14843}
14844
14845impl RowExt for DisplayRow {
14846    fn as_f32(&self) -> f32 {
14847        self.0 as f32
14848    }
14849
14850    fn next_row(&self) -> Self {
14851        Self(self.0 + 1)
14852    }
14853
14854    fn previous_row(&self) -> Self {
14855        Self(self.0.saturating_sub(1))
14856    }
14857
14858    fn minus(&self, other: Self) -> u32 {
14859        self.0 - other.0
14860    }
14861}
14862
14863impl RowExt for MultiBufferRow {
14864    fn as_f32(&self) -> f32 {
14865        self.0 as f32
14866    }
14867
14868    fn next_row(&self) -> Self {
14869        Self(self.0 + 1)
14870    }
14871
14872    fn previous_row(&self) -> Self {
14873        Self(self.0.saturating_sub(1))
14874    }
14875
14876    fn minus(&self, other: Self) -> u32 {
14877        self.0 - other.0
14878    }
14879}
14880
14881trait RowRangeExt {
14882    type Row;
14883
14884    fn len(&self) -> usize;
14885
14886    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
14887}
14888
14889impl RowRangeExt for Range<MultiBufferRow> {
14890    type Row = MultiBufferRow;
14891
14892    fn len(&self) -> usize {
14893        (self.end.0 - self.start.0) as usize
14894    }
14895
14896    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
14897        (self.start.0..self.end.0).map(MultiBufferRow)
14898    }
14899}
14900
14901impl RowRangeExt for Range<DisplayRow> {
14902    type Row = DisplayRow;
14903
14904    fn len(&self) -> usize {
14905        (self.end.0 - self.start.0) as usize
14906    }
14907
14908    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
14909        (self.start.0..self.end.0).map(DisplayRow)
14910    }
14911}
14912
14913fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
14914    if hunk.diff_base_byte_range.is_empty() {
14915        DiffHunkStatus::Added
14916    } else if hunk.row_range.is_empty() {
14917        DiffHunkStatus::Removed
14918    } else {
14919        DiffHunkStatus::Modified
14920    }
14921}
14922
14923/// If select range has more than one line, we
14924/// just point the cursor to range.start.
14925fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
14926    if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
14927        range
14928    } else {
14929        range.start..range.start
14930    }
14931}