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, MouseButton, PaintQuad, ParentElement, Pixels, Render, SharedString,
   79    Size, StrikethroughStyle, Styled, StyledText, Subscription, Task, TextStyle,
   80    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 task::{ResolvedTask, TaskTemplate, TaskVariables};
  107
  108use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  109pub use lsp::CompletionContext;
  110use lsp::{
  111    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  112    LanguageServerId,
  113};
  114use mouse_context_menu::MouseContextMenu;
  115use movement::TextLayoutDetails;
  116pub use multi_buffer::{
  117    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
  118    ToPoint,
  119};
  120use multi_buffer::{
  121    ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
  122};
  123use ordered_float::OrderedFloat;
  124use parking_lot::{Mutex, RwLock};
  125use project::{
  126    lsp_store::{FormatTarget, FormatTrigger},
  127    project_settings::{GitGutterSetting, ProjectSettings},
  128    CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Item, Location,
  129    LocationLink, Project, ProjectPath, ProjectTransaction, TaskSourceKind,
  130};
  131use rand::prelude::*;
  132use rpc::{proto::*, ErrorExt};
  133use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  134use selections_collection::{resolve_multiple, MutableSelectionsCollection, SelectionsCollection};
  135use serde::{Deserialize, Serialize};
  136use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  137use smallvec::SmallVec;
  138use snippet::Snippet;
  139use std::{
  140    any::TypeId,
  141    borrow::Cow,
  142    cell::RefCell,
  143    cmp::{self, Ordering, Reverse},
  144    mem,
  145    num::NonZeroU32,
  146    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  147    path::{Path, PathBuf},
  148    rc::Rc,
  149    sync::Arc,
  150    time::{Duration, Instant},
  151};
  152pub use sum_tree::Bias;
  153use sum_tree::TreeMap;
  154use text::{BufferId, OffsetUtf16, Rope};
  155use theme::{
  156    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  157    ThemeColors, ThemeSettings,
  158};
  159use ui::{
  160    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
  161    ListItem, Popover, PopoverMenuHandle, Tooltip,
  162};
  163use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  164use workspace::item::{ItemHandle, PreviewTabsSettings};
  165use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
  166use workspace::{
  167    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  168};
  169use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  170
  171use crate::hover_links::find_url;
  172use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  173
  174pub const FILE_HEADER_HEIGHT: u32 = 2;
  175pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  176pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  177pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  178const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  179const MAX_LINE_LEN: usize = 1024;
  180const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  181const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  182pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  183#[doc(hidden)]
  184pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  185#[doc(hidden)]
  186pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
  187
  188pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  189pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  190
  191pub fn render_parsed_markdown(
  192    element_id: impl Into<ElementId>,
  193    parsed: &language::ParsedMarkdown,
  194    editor_style: &EditorStyle,
  195    workspace: Option<WeakView<Workspace>>,
  196    cx: &mut WindowContext,
  197) -> InteractiveText {
  198    let code_span_background_color = cx
  199        .theme()
  200        .colors()
  201        .editor_document_highlight_read_background;
  202
  203    let highlights = gpui::combine_highlights(
  204        parsed.highlights.iter().filter_map(|(range, highlight)| {
  205            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  206            Some((range.clone(), highlight))
  207        }),
  208        parsed
  209            .regions
  210            .iter()
  211            .zip(&parsed.region_ranges)
  212            .filter_map(|(region, range)| {
  213                if region.code {
  214                    Some((
  215                        range.clone(),
  216                        HighlightStyle {
  217                            background_color: Some(code_span_background_color),
  218                            ..Default::default()
  219                        },
  220                    ))
  221                } else {
  222                    None
  223                }
  224            }),
  225    );
  226
  227    let mut links = Vec::new();
  228    let mut link_ranges = Vec::new();
  229    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  230        if let Some(link) = region.link.clone() {
  231            links.push(link);
  232            link_ranges.push(range.clone());
  233        }
  234    }
  235
  236    InteractiveText::new(
  237        element_id,
  238        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  239    )
  240    .on_click(link_ranges, move |clicked_range_ix, cx| {
  241        match &links[clicked_range_ix] {
  242            markdown::Link::Web { url } => cx.open_url(url),
  243            markdown::Link::Path { path } => {
  244                if let Some(workspace) = &workspace {
  245                    _ = workspace.update(cx, |workspace, cx| {
  246                        workspace.open_abs_path(path.clone(), false, cx).detach();
  247                    });
  248                }
  249            }
  250        }
  251    })
  252}
  253
  254#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  255pub(crate) enum InlayId {
  256    Suggestion(usize),
  257    Hint(usize),
  258}
  259
  260impl InlayId {
  261    fn id(&self) -> usize {
  262        match self {
  263            Self::Suggestion(id) => *id,
  264            Self::Hint(id) => *id,
  265        }
  266    }
  267}
  268
  269enum DiffRowHighlight {}
  270enum DocumentHighlightRead {}
  271enum DocumentHighlightWrite {}
  272enum InputComposition {}
  273
  274#[derive(Copy, Clone, PartialEq, Eq)]
  275pub enum Direction {
  276    Prev,
  277    Next,
  278}
  279
  280#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  281pub enum Navigated {
  282    Yes,
  283    No,
  284}
  285
  286impl Navigated {
  287    pub fn from_bool(yes: bool) -> Navigated {
  288        if yes {
  289            Navigated::Yes
  290        } else {
  291            Navigated::No
  292        }
  293    }
  294}
  295
  296pub fn init_settings(cx: &mut AppContext) {
  297    EditorSettings::register(cx);
  298}
  299
  300pub fn init(cx: &mut AppContext) {
  301    init_settings(cx);
  302
  303    workspace::register_project_item::<Editor>(cx);
  304    workspace::FollowableViewRegistry::register::<Editor>(cx);
  305    workspace::register_serializable_item::<Editor>(cx);
  306
  307    cx.observe_new_views(
  308        |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
  309            workspace.register_action(Editor::new_file);
  310            workspace.register_action(Editor::new_file_vertical);
  311            workspace.register_action(Editor::new_file_horizontal);
  312        },
  313    )
  314    .detach();
  315
  316    cx.on_action(move |_: &workspace::NewFile, cx| {
  317        let app_state = workspace::AppState::global(cx);
  318        if let Some(app_state) = app_state.upgrade() {
  319            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  320                Editor::new_file(workspace, &Default::default(), cx)
  321            })
  322            .detach();
  323        }
  324    });
  325    cx.on_action(move |_: &workspace::NewWindow, cx| {
  326        let app_state = workspace::AppState::global(cx);
  327        if let Some(app_state) = app_state.upgrade() {
  328            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  329                Editor::new_file(workspace, &Default::default(), cx)
  330            })
  331            .detach();
  332        }
  333    });
  334}
  335
  336pub struct SearchWithinRange;
  337
  338trait InvalidationRegion {
  339    fn ranges(&self) -> &[Range<Anchor>];
  340}
  341
  342#[derive(Clone, Debug, PartialEq)]
  343pub enum SelectPhase {
  344    Begin {
  345        position: DisplayPoint,
  346        add: bool,
  347        click_count: usize,
  348    },
  349    BeginColumnar {
  350        position: DisplayPoint,
  351        reset: bool,
  352        goal_column: u32,
  353    },
  354    Extend {
  355        position: DisplayPoint,
  356        click_count: usize,
  357    },
  358    Update {
  359        position: DisplayPoint,
  360        goal_column: u32,
  361        scroll_delta: gpui::Point<f32>,
  362    },
  363    End,
  364}
  365
  366#[derive(Clone, Debug)]
  367pub enum SelectMode {
  368    Character,
  369    Word(Range<Anchor>),
  370    Line(Range<Anchor>),
  371    All,
  372}
  373
  374#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  375pub enum EditorMode {
  376    SingleLine { auto_width: bool },
  377    AutoHeight { max_lines: usize },
  378    Full,
  379}
  380
  381#[derive(Copy, Clone, Debug)]
  382pub enum SoftWrap {
  383    /// Prefer not to wrap at all.
  384    ///
  385    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  386    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  387    GitDiff,
  388    /// Prefer a single line generally, unless an overly long line is encountered.
  389    None,
  390    /// Soft wrap lines that exceed the editor width.
  391    EditorWidth,
  392    /// Soft wrap lines at the preferred line length.
  393    Column(u32),
  394    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  395    Bounded(u32),
  396}
  397
  398#[derive(Clone)]
  399pub struct EditorStyle {
  400    pub background: Hsla,
  401    pub local_player: PlayerColor,
  402    pub text: TextStyle,
  403    pub scrollbar_width: Pixels,
  404    pub syntax: Arc<SyntaxTheme>,
  405    pub status: StatusColors,
  406    pub inlay_hints_style: HighlightStyle,
  407    pub suggestions_style: HighlightStyle,
  408    pub unnecessary_code_fade: f32,
  409}
  410
  411impl Default for EditorStyle {
  412    fn default() -> Self {
  413        Self {
  414            background: Hsla::default(),
  415            local_player: PlayerColor::default(),
  416            text: TextStyle::default(),
  417            scrollbar_width: Pixels::default(),
  418            syntax: Default::default(),
  419            // HACK: Status colors don't have a real default.
  420            // We should look into removing the status colors from the editor
  421            // style and retrieve them directly from the theme.
  422            status: StatusColors::dark(),
  423            inlay_hints_style: HighlightStyle::default(),
  424            suggestions_style: HighlightStyle::default(),
  425            unnecessary_code_fade: Default::default(),
  426        }
  427    }
  428}
  429
  430pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
  431    let show_background = language_settings::language_settings(None, None, cx)
  432        .inlay_hints
  433        .show_background;
  434
  435    HighlightStyle {
  436        color: Some(cx.theme().status().hint),
  437        background_color: show_background.then(|| cx.theme().status().hint_background),
  438        ..HighlightStyle::default()
  439    }
  440}
  441
  442type CompletionId = usize;
  443
  444#[derive(Clone, Debug)]
  445struct CompletionState {
  446    // render_inlay_ids represents the inlay hints that are inserted
  447    // for rendering the inline completions. They may be discontinuous
  448    // in the event that the completion provider returns some intersection
  449    // with the existing content.
  450    render_inlay_ids: Vec<InlayId>,
  451    // text is the resulting rope that is inserted when the user accepts a completion.
  452    text: Rope,
  453    // position is the position of the cursor when the completion was triggered.
  454    position: multi_buffer::Anchor,
  455    // delete_range is the range of text that this completion state covers.
  456    // if the completion is accepted, this range should be deleted.
  457    delete_range: Option<Range<multi_buffer::Anchor>>,
  458}
  459
  460#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  461struct EditorActionId(usize);
  462
  463impl EditorActionId {
  464    pub fn post_inc(&mut self) -> Self {
  465        let answer = self.0;
  466
  467        *self = Self(answer + 1);
  468
  469        Self(answer)
  470    }
  471}
  472
  473// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  474// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  475
  476type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  477type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
  478
  479#[derive(Default)]
  480struct ScrollbarMarkerState {
  481    scrollbar_size: Size<Pixels>,
  482    dirty: bool,
  483    markers: Arc<[PaintQuad]>,
  484    pending_refresh: Option<Task<Result<()>>>,
  485}
  486
  487impl ScrollbarMarkerState {
  488    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  489        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  490    }
  491}
  492
  493#[derive(Clone, Debug)]
  494struct RunnableTasks {
  495    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  496    offset: MultiBufferOffset,
  497    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  498    column: u32,
  499    // Values of all named captures, including those starting with '_'
  500    extra_variables: HashMap<String, String>,
  501    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  502    context_range: Range<BufferOffset>,
  503}
  504
  505impl RunnableTasks {
  506    fn resolve<'a>(
  507        &'a self,
  508        cx: &'a task::TaskContext,
  509    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  510        self.templates.iter().filter_map(|(kind, template)| {
  511            template
  512                .resolve_task(&kind.to_id_base(), cx)
  513                .map(|task| (kind.clone(), task))
  514        })
  515    }
  516}
  517
  518#[derive(Clone)]
  519struct ResolvedTasks {
  520    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  521    position: Anchor,
  522}
  523#[derive(Copy, Clone, Debug)]
  524struct MultiBufferOffset(usize);
  525#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  526struct BufferOffset(usize);
  527
  528// Addons allow storing per-editor state in other crates (e.g. Vim)
  529pub trait Addon: 'static {
  530    fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
  531
  532    fn to_any(&self) -> &dyn std::any::Any;
  533}
  534
  535/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
  536///
  537/// See the [module level documentation](self) for more information.
  538pub struct Editor {
  539    focus_handle: FocusHandle,
  540    last_focused_descendant: Option<WeakFocusHandle>,
  541    /// The text buffer being edited
  542    buffer: Model<MultiBuffer>,
  543    /// Map of how text in the buffer should be displayed.
  544    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  545    pub display_map: Model<DisplayMap>,
  546    pub selections: SelectionsCollection,
  547    pub scroll_manager: ScrollManager,
  548    /// When inline assist editors are linked, they all render cursors because
  549    /// typing enters text into each of them, even the ones that aren't focused.
  550    pub(crate) show_cursor_when_unfocused: bool,
  551    columnar_selection_tail: Option<Anchor>,
  552    add_selections_state: Option<AddSelectionsState>,
  553    select_next_state: Option<SelectNextState>,
  554    select_prev_state: Option<SelectNextState>,
  555    selection_history: SelectionHistory,
  556    autoclose_regions: Vec<AutocloseRegion>,
  557    snippet_stack: InvalidationStack<SnippetState>,
  558    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  559    ime_transaction: Option<TransactionId>,
  560    active_diagnostics: Option<ActiveDiagnosticGroup>,
  561    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  562
  563    project: Option<Model<Project>>,
  564    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  565    completion_provider: Option<Box<dyn CompletionProvider>>,
  566    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  567    blink_manager: Model<BlinkManager>,
  568    show_cursor_names: bool,
  569    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  570    pub show_local_selections: bool,
  571    mode: EditorMode,
  572    show_breadcrumbs: bool,
  573    show_gutter: bool,
  574    show_line_numbers: Option<bool>,
  575    use_relative_line_numbers: Option<bool>,
  576    show_git_diff_gutter: Option<bool>,
  577    show_code_actions: Option<bool>,
  578    show_runnables: Option<bool>,
  579    show_wrap_guides: Option<bool>,
  580    show_indent_guides: Option<bool>,
  581    placeholder_text: Option<Arc<str>>,
  582    highlight_order: usize,
  583    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  584    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  585    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  586    scrollbar_marker_state: ScrollbarMarkerState,
  587    active_indent_guides_state: ActiveIndentGuidesState,
  588    nav_history: Option<ItemNavHistory>,
  589    context_menu: RwLock<Option<ContextMenu>>,
  590    mouse_context_menu: Option<MouseContextMenu>,
  591    hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
  592    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  593    signature_help_state: SignatureHelpState,
  594    auto_signature_help: Option<bool>,
  595    find_all_references_task_sources: Vec<Anchor>,
  596    next_completion_id: CompletionId,
  597    completion_documentation_pre_resolve_debounce: DebouncedDelay,
  598    available_code_actions: Option<(Location, Arc<[AvailableCodeAction]>)>,
  599    code_actions_task: Option<Task<Result<()>>>,
  600    document_highlights_task: Option<Task<()>>,
  601    linked_editing_range_task: Option<Task<Option<()>>>,
  602    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  603    pending_rename: Option<RenameState>,
  604    searchable: bool,
  605    cursor_shape: CursorShape,
  606    current_line_highlight: Option<CurrentLineHighlight>,
  607    collapse_matches: bool,
  608    autoindent_mode: Option<AutoindentMode>,
  609    workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
  610    input_enabled: bool,
  611    use_modal_editing: bool,
  612    read_only: bool,
  613    leader_peer_id: Option<PeerId>,
  614    remote_id: Option<ViewId>,
  615    hover_state: HoverState,
  616    gutter_hovered: bool,
  617    hovered_link_state: Option<HoveredLinkState>,
  618    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  619    code_action_providers: Vec<Arc<dyn CodeActionProvider>>,
  620    active_inline_completion: Option<CompletionState>,
  621    // enable_inline_completions is a switch that Vim can use to disable
  622    // inline completions based on its mode.
  623    enable_inline_completions: bool,
  624    show_inline_completions_override: Option<bool>,
  625    inlay_hint_cache: InlayHintCache,
  626    expanded_hunks: ExpandedHunks,
  627    next_inlay_id: usize,
  628    _subscriptions: Vec<Subscription>,
  629    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  630    gutter_dimensions: GutterDimensions,
  631    style: Option<EditorStyle>,
  632    text_style_refinement: Option<TextStyleRefinement>,
  633    next_editor_action_id: EditorActionId,
  634    editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
  635    use_autoclose: bool,
  636    use_auto_surround: bool,
  637    auto_replace_emoji_shortcode: bool,
  638    show_git_blame_gutter: bool,
  639    show_git_blame_inline: bool,
  640    show_git_blame_inline_delay_task: Option<Task<()>>,
  641    git_blame_inline_enabled: bool,
  642    serialize_dirty_buffers: bool,
  643    show_selection_menu: Option<bool>,
  644    blame: Option<Model<GitBlame>>,
  645    blame_subscription: Option<Subscription>,
  646    custom_context_menu: Option<
  647        Box<
  648            dyn 'static
  649                + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
  650        >,
  651    >,
  652    last_bounds: Option<Bounds<Pixels>>,
  653    expect_bounds_change: Option<Bounds<Pixels>>,
  654    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  655    tasks_update_task: Option<Task<()>>,
  656    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  657    breadcrumb_header: Option<String>,
  658    focused_block: Option<FocusedBlock>,
  659    next_scroll_position: NextScrollCursorCenterTopBottom,
  660    addons: HashMap<TypeId, Box<dyn Addon>>,
  661    _scroll_cursor_center_top_bottom_task: Task<()>,
  662}
  663
  664#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  665enum NextScrollCursorCenterTopBottom {
  666    #[default]
  667    Center,
  668    Top,
  669    Bottom,
  670}
  671
  672impl NextScrollCursorCenterTopBottom {
  673    fn next(&self) -> Self {
  674        match self {
  675            Self::Center => Self::Top,
  676            Self::Top => Self::Bottom,
  677            Self::Bottom => Self::Center,
  678        }
  679    }
  680}
  681
  682#[derive(Clone)]
  683pub struct EditorSnapshot {
  684    pub mode: EditorMode,
  685    show_gutter: bool,
  686    show_line_numbers: Option<bool>,
  687    show_git_diff_gutter: Option<bool>,
  688    show_code_actions: Option<bool>,
  689    show_runnables: Option<bool>,
  690    git_blame_gutter_max_author_length: Option<usize>,
  691    pub display_snapshot: DisplaySnapshot,
  692    pub placeholder_text: Option<Arc<str>>,
  693    is_focused: bool,
  694    scroll_anchor: ScrollAnchor,
  695    ongoing_scroll: OngoingScroll,
  696    current_line_highlight: CurrentLineHighlight,
  697    gutter_hovered: bool,
  698}
  699
  700const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  701
  702#[derive(Default, Debug, Clone, Copy)]
  703pub struct GutterDimensions {
  704    pub left_padding: Pixels,
  705    pub right_padding: Pixels,
  706    pub width: Pixels,
  707    pub margin: Pixels,
  708    pub git_blame_entries_width: Option<Pixels>,
  709}
  710
  711impl GutterDimensions {
  712    /// The full width of the space taken up by the gutter.
  713    pub fn full_width(&self) -> Pixels {
  714        self.margin + self.width
  715    }
  716
  717    /// The width of the space reserved for the fold indicators,
  718    /// use alongside 'justify_end' and `gutter_width` to
  719    /// right align content with the line numbers
  720    pub fn fold_area_width(&self) -> Pixels {
  721        self.margin + self.right_padding
  722    }
  723}
  724
  725#[derive(Debug)]
  726pub struct RemoteSelection {
  727    pub replica_id: ReplicaId,
  728    pub selection: Selection<Anchor>,
  729    pub cursor_shape: CursorShape,
  730    pub peer_id: PeerId,
  731    pub line_mode: bool,
  732    pub participant_index: Option<ParticipantIndex>,
  733    pub user_name: Option<SharedString>,
  734}
  735
  736#[derive(Clone, Debug)]
  737struct SelectionHistoryEntry {
  738    selections: Arc<[Selection<Anchor>]>,
  739    select_next_state: Option<SelectNextState>,
  740    select_prev_state: Option<SelectNextState>,
  741    add_selections_state: Option<AddSelectionsState>,
  742}
  743
  744enum SelectionHistoryMode {
  745    Normal,
  746    Undoing,
  747    Redoing,
  748}
  749
  750#[derive(Clone, PartialEq, Eq, Hash)]
  751struct HoveredCursor {
  752    replica_id: u16,
  753    selection_id: usize,
  754}
  755
  756impl Default for SelectionHistoryMode {
  757    fn default() -> Self {
  758        Self::Normal
  759    }
  760}
  761
  762#[derive(Default)]
  763struct SelectionHistory {
  764    #[allow(clippy::type_complexity)]
  765    selections_by_transaction:
  766        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  767    mode: SelectionHistoryMode,
  768    undo_stack: VecDeque<SelectionHistoryEntry>,
  769    redo_stack: VecDeque<SelectionHistoryEntry>,
  770}
  771
  772impl SelectionHistory {
  773    fn insert_transaction(
  774        &mut self,
  775        transaction_id: TransactionId,
  776        selections: Arc<[Selection<Anchor>]>,
  777    ) {
  778        self.selections_by_transaction
  779            .insert(transaction_id, (selections, None));
  780    }
  781
  782    #[allow(clippy::type_complexity)]
  783    fn transaction(
  784        &self,
  785        transaction_id: TransactionId,
  786    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  787        self.selections_by_transaction.get(&transaction_id)
  788    }
  789
  790    #[allow(clippy::type_complexity)]
  791    fn transaction_mut(
  792        &mut self,
  793        transaction_id: TransactionId,
  794    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  795        self.selections_by_transaction.get_mut(&transaction_id)
  796    }
  797
  798    fn push(&mut self, entry: SelectionHistoryEntry) {
  799        if !entry.selections.is_empty() {
  800            match self.mode {
  801                SelectionHistoryMode::Normal => {
  802                    self.push_undo(entry);
  803                    self.redo_stack.clear();
  804                }
  805                SelectionHistoryMode::Undoing => self.push_redo(entry),
  806                SelectionHistoryMode::Redoing => self.push_undo(entry),
  807            }
  808        }
  809    }
  810
  811    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  812        if self
  813            .undo_stack
  814            .back()
  815            .map_or(true, |e| e.selections != entry.selections)
  816        {
  817            self.undo_stack.push_back(entry);
  818            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  819                self.undo_stack.pop_front();
  820            }
  821        }
  822    }
  823
  824    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  825        if self
  826            .redo_stack
  827            .back()
  828            .map_or(true, |e| e.selections != entry.selections)
  829        {
  830            self.redo_stack.push_back(entry);
  831            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  832                self.redo_stack.pop_front();
  833            }
  834        }
  835    }
  836}
  837
  838struct RowHighlight {
  839    index: usize,
  840    range: Range<Anchor>,
  841    color: Hsla,
  842    should_autoscroll: bool,
  843}
  844
  845#[derive(Clone, Debug)]
  846struct AddSelectionsState {
  847    above: bool,
  848    stack: Vec<usize>,
  849}
  850
  851#[derive(Clone)]
  852struct SelectNextState {
  853    query: AhoCorasick,
  854    wordwise: bool,
  855    done: bool,
  856}
  857
  858impl std::fmt::Debug for SelectNextState {
  859    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  860        f.debug_struct(std::any::type_name::<Self>())
  861            .field("wordwise", &self.wordwise)
  862            .field("done", &self.done)
  863            .finish()
  864    }
  865}
  866
  867#[derive(Debug)]
  868struct AutocloseRegion {
  869    selection_id: usize,
  870    range: Range<Anchor>,
  871    pair: BracketPair,
  872}
  873
  874#[derive(Debug)]
  875struct SnippetState {
  876    ranges: Vec<Vec<Range<Anchor>>>,
  877    active_index: usize,
  878}
  879
  880#[doc(hidden)]
  881pub struct RenameState {
  882    pub range: Range<Anchor>,
  883    pub old_name: Arc<str>,
  884    pub editor: View<Editor>,
  885    block_id: CustomBlockId,
  886}
  887
  888struct InvalidationStack<T>(Vec<T>);
  889
  890struct RegisteredInlineCompletionProvider {
  891    provider: Arc<dyn InlineCompletionProviderHandle>,
  892    _subscription: Subscription,
  893}
  894
  895enum ContextMenu {
  896    Completions(CompletionsMenu),
  897    CodeActions(CodeActionsMenu),
  898}
  899
  900impl ContextMenu {
  901    fn select_first(
  902        &mut self,
  903        provider: Option<&dyn CompletionProvider>,
  904        cx: &mut ViewContext<Editor>,
  905    ) -> bool {
  906        if self.visible() {
  907            match self {
  908                ContextMenu::Completions(menu) => menu.select_first(provider, cx),
  909                ContextMenu::CodeActions(menu) => menu.select_first(cx),
  910            }
  911            true
  912        } else {
  913            false
  914        }
  915    }
  916
  917    fn select_prev(
  918        &mut self,
  919        provider: Option<&dyn CompletionProvider>,
  920        cx: &mut ViewContext<Editor>,
  921    ) -> bool {
  922        if self.visible() {
  923            match self {
  924                ContextMenu::Completions(menu) => menu.select_prev(provider, cx),
  925                ContextMenu::CodeActions(menu) => menu.select_prev(cx),
  926            }
  927            true
  928        } else {
  929            false
  930        }
  931    }
  932
  933    fn select_next(
  934        &mut self,
  935        provider: Option<&dyn CompletionProvider>,
  936        cx: &mut ViewContext<Editor>,
  937    ) -> bool {
  938        if self.visible() {
  939            match self {
  940                ContextMenu::Completions(menu) => menu.select_next(provider, cx),
  941                ContextMenu::CodeActions(menu) => menu.select_next(cx),
  942            }
  943            true
  944        } else {
  945            false
  946        }
  947    }
  948
  949    fn select_last(
  950        &mut self,
  951        provider: Option<&dyn CompletionProvider>,
  952        cx: &mut ViewContext<Editor>,
  953    ) -> bool {
  954        if self.visible() {
  955            match self {
  956                ContextMenu::Completions(menu) => menu.select_last(provider, cx),
  957                ContextMenu::CodeActions(menu) => menu.select_last(cx),
  958            }
  959            true
  960        } else {
  961            false
  962        }
  963    }
  964
  965    fn visible(&self) -> bool {
  966        match self {
  967            ContextMenu::Completions(menu) => menu.visible(),
  968            ContextMenu::CodeActions(menu) => menu.visible(),
  969        }
  970    }
  971
  972    fn render(
  973        &self,
  974        cursor_position: DisplayPoint,
  975        style: &EditorStyle,
  976        max_height: Pixels,
  977        workspace: Option<WeakView<Workspace>>,
  978        cx: &mut ViewContext<Editor>,
  979    ) -> (ContextMenuOrigin, AnyElement) {
  980        match self {
  981            ContextMenu::Completions(menu) => (
  982                ContextMenuOrigin::EditorPoint(cursor_position),
  983                menu.render(style, max_height, workspace, cx),
  984            ),
  985            ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
  986        }
  987    }
  988}
  989
  990enum ContextMenuOrigin {
  991    EditorPoint(DisplayPoint),
  992    GutterIndicator(DisplayRow),
  993}
  994
  995#[derive(Clone)]
  996struct CompletionsMenu {
  997    id: CompletionId,
  998    sort_completions: bool,
  999    initial_position: Anchor,
 1000    buffer: Model<Buffer>,
 1001    completions: Arc<RwLock<Box<[Completion]>>>,
 1002    match_candidates: Arc<[StringMatchCandidate]>,
 1003    matches: Arc<[StringMatch]>,
 1004    selected_item: usize,
 1005    scroll_handle: UniformListScrollHandle,
 1006    selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
 1007}
 1008
 1009impl CompletionsMenu {
 1010    fn select_first(
 1011        &mut self,
 1012        provider: Option<&dyn CompletionProvider>,
 1013        cx: &mut ViewContext<Editor>,
 1014    ) {
 1015        self.selected_item = 0;
 1016        self.scroll_handle.scroll_to_item(self.selected_item);
 1017        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1018        cx.notify();
 1019    }
 1020
 1021    fn select_prev(
 1022        &mut self,
 1023        provider: Option<&dyn CompletionProvider>,
 1024        cx: &mut ViewContext<Editor>,
 1025    ) {
 1026        if self.selected_item > 0 {
 1027            self.selected_item -= 1;
 1028        } else {
 1029            self.selected_item = self.matches.len() - 1;
 1030        }
 1031        self.scroll_handle.scroll_to_item(self.selected_item);
 1032        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1033        cx.notify();
 1034    }
 1035
 1036    fn select_next(
 1037        &mut self,
 1038        provider: Option<&dyn CompletionProvider>,
 1039        cx: &mut ViewContext<Editor>,
 1040    ) {
 1041        if self.selected_item + 1 < self.matches.len() {
 1042            self.selected_item += 1;
 1043        } else {
 1044            self.selected_item = 0;
 1045        }
 1046        self.scroll_handle.scroll_to_item(self.selected_item);
 1047        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1048        cx.notify();
 1049    }
 1050
 1051    fn select_last(
 1052        &mut self,
 1053        provider: Option<&dyn CompletionProvider>,
 1054        cx: &mut ViewContext<Editor>,
 1055    ) {
 1056        self.selected_item = self.matches.len() - 1;
 1057        self.scroll_handle.scroll_to_item(self.selected_item);
 1058        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1059        cx.notify();
 1060    }
 1061
 1062    fn pre_resolve_completion_documentation(
 1063        buffer: Model<Buffer>,
 1064        completions: Arc<RwLock<Box<[Completion]>>>,
 1065        matches: Arc<[StringMatch]>,
 1066        editor: &Editor,
 1067        cx: &mut ViewContext<Editor>,
 1068    ) -> Task<()> {
 1069        let settings = EditorSettings::get_global(cx);
 1070        if !settings.show_completion_documentation {
 1071            return Task::ready(());
 1072        }
 1073
 1074        let Some(provider) = editor.completion_provider.as_ref() else {
 1075            return Task::ready(());
 1076        };
 1077
 1078        let resolve_task = provider.resolve_completions(
 1079            buffer,
 1080            matches.iter().map(|m| m.candidate_id).collect(),
 1081            completions.clone(),
 1082            cx,
 1083        );
 1084
 1085        cx.spawn(move |this, mut cx| async move {
 1086            if let Some(true) = resolve_task.await.log_err() {
 1087                this.update(&mut cx, |_, cx| cx.notify()).ok();
 1088            }
 1089        })
 1090    }
 1091
 1092    fn attempt_resolve_selected_completion_documentation(
 1093        &mut self,
 1094        provider: Option<&dyn CompletionProvider>,
 1095        cx: &mut ViewContext<Editor>,
 1096    ) {
 1097        let settings = EditorSettings::get_global(cx);
 1098        if !settings.show_completion_documentation {
 1099            return;
 1100        }
 1101
 1102        let completion_index = self.matches[self.selected_item].candidate_id;
 1103        let Some(provider) = provider else {
 1104            return;
 1105        };
 1106
 1107        let resolve_task = provider.resolve_completions(
 1108            self.buffer.clone(),
 1109            vec![completion_index],
 1110            self.completions.clone(),
 1111            cx,
 1112        );
 1113
 1114        let delay_ms =
 1115            EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
 1116        let delay = Duration::from_millis(delay_ms);
 1117
 1118        self.selected_completion_documentation_resolve_debounce
 1119            .lock()
 1120            .fire_new(delay, cx, |_, cx| {
 1121                cx.spawn(move |this, mut cx| async move {
 1122                    if let Some(true) = resolve_task.await.log_err() {
 1123                        this.update(&mut cx, |_, cx| cx.notify()).ok();
 1124                    }
 1125                })
 1126            });
 1127    }
 1128
 1129    fn visible(&self) -> bool {
 1130        !self.matches.is_empty()
 1131    }
 1132
 1133    fn render(
 1134        &self,
 1135        style: &EditorStyle,
 1136        max_height: Pixels,
 1137        workspace: Option<WeakView<Workspace>>,
 1138        cx: &mut ViewContext<Editor>,
 1139    ) -> AnyElement {
 1140        let settings = EditorSettings::get_global(cx);
 1141        let show_completion_documentation = settings.show_completion_documentation;
 1142
 1143        let widest_completion_ix = self
 1144            .matches
 1145            .iter()
 1146            .enumerate()
 1147            .max_by_key(|(_, mat)| {
 1148                let completions = self.completions.read();
 1149                let completion = &completions[mat.candidate_id];
 1150                let documentation = &completion.documentation;
 1151
 1152                let mut len = completion.label.text.chars().count();
 1153                if let Some(Documentation::SingleLine(text)) = documentation {
 1154                    if show_completion_documentation {
 1155                        len += text.chars().count();
 1156                    }
 1157                }
 1158
 1159                len
 1160            })
 1161            .map(|(ix, _)| ix);
 1162
 1163        let completions = self.completions.clone();
 1164        let matches = self.matches.clone();
 1165        let selected_item = self.selected_item;
 1166        let style = style.clone();
 1167
 1168        let multiline_docs = if show_completion_documentation {
 1169            let mat = &self.matches[selected_item];
 1170            let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
 1171                Some(Documentation::MultiLinePlainText(text)) => {
 1172                    Some(div().child(SharedString::from(text.clone())))
 1173                }
 1174                Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
 1175                    Some(div().child(render_parsed_markdown(
 1176                        "completions_markdown",
 1177                        parsed,
 1178                        &style,
 1179                        workspace,
 1180                        cx,
 1181                    )))
 1182                }
 1183                _ => None,
 1184            };
 1185            multiline_docs.map(|div| {
 1186                div.id("multiline_docs")
 1187                    .max_h(max_height)
 1188                    .flex_1()
 1189                    .px_1p5()
 1190                    .py_1()
 1191                    .min_w(px(260.))
 1192                    .max_w(px(640.))
 1193                    .w(px(500.))
 1194                    .overflow_y_scroll()
 1195                    .occlude()
 1196            })
 1197        } else {
 1198            None
 1199        };
 1200
 1201        let list = uniform_list(
 1202            cx.view().clone(),
 1203            "completions",
 1204            matches.len(),
 1205            move |_editor, range, cx| {
 1206                let start_ix = range.start;
 1207                let completions_guard = completions.read();
 1208
 1209                matches[range]
 1210                    .iter()
 1211                    .enumerate()
 1212                    .map(|(ix, mat)| {
 1213                        let item_ix = start_ix + ix;
 1214                        let candidate_id = mat.candidate_id;
 1215                        let completion = &completions_guard[candidate_id];
 1216
 1217                        let documentation = if show_completion_documentation {
 1218                            &completion.documentation
 1219                        } else {
 1220                            &None
 1221                        };
 1222
 1223                        let highlights = gpui::combine_highlights(
 1224                            mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
 1225                            styled_runs_for_code_label(&completion.label, &style.syntax).map(
 1226                                |(range, mut highlight)| {
 1227                                    // Ignore font weight for syntax highlighting, as we'll use it
 1228                                    // for fuzzy matches.
 1229                                    highlight.font_weight = None;
 1230
 1231                                    if completion.lsp_completion.deprecated.unwrap_or(false) {
 1232                                        highlight.strikethrough = Some(StrikethroughStyle {
 1233                                            thickness: 1.0.into(),
 1234                                            ..Default::default()
 1235                                        });
 1236                                        highlight.color = Some(cx.theme().colors().text_muted);
 1237                                    }
 1238
 1239                                    (range, highlight)
 1240                                },
 1241                            ),
 1242                        );
 1243                        let completion_label = StyledText::new(completion.label.text.clone())
 1244                            .with_highlights(&style.text, highlights);
 1245                        let documentation_label =
 1246                            if let Some(Documentation::SingleLine(text)) = documentation {
 1247                                if text.trim().is_empty() {
 1248                                    None
 1249                                } else {
 1250                                    Some(
 1251                                        Label::new(text.clone())
 1252                                            .ml_4()
 1253                                            .size(LabelSize::Small)
 1254                                            .color(Color::Muted),
 1255                                    )
 1256                                }
 1257                            } else {
 1258                                None
 1259                            };
 1260
 1261                        let color_swatch = completion
 1262                            .color()
 1263                            .map(|color| div().size_4().bg(color).rounded_sm());
 1264
 1265                        div().min_w(px(220.)).max_w(px(540.)).child(
 1266                            ListItem::new(mat.candidate_id)
 1267                                .inset(true)
 1268                                .selected(item_ix == selected_item)
 1269                                .on_click(cx.listener(move |editor, _event, cx| {
 1270                                    cx.stop_propagation();
 1271                                    if let Some(task) = editor.confirm_completion(
 1272                                        &ConfirmCompletion {
 1273                                            item_ix: Some(item_ix),
 1274                                        },
 1275                                        cx,
 1276                                    ) {
 1277                                        task.detach_and_log_err(cx)
 1278                                    }
 1279                                }))
 1280                                .start_slot::<Div>(color_swatch)
 1281                                .child(h_flex().overflow_hidden().child(completion_label))
 1282                                .end_slot::<Label>(documentation_label),
 1283                        )
 1284                    })
 1285                    .collect()
 1286            },
 1287        )
 1288        .occlude()
 1289        .max_h(max_height)
 1290        .track_scroll(self.scroll_handle.clone())
 1291        .with_width_from_item(widest_completion_ix)
 1292        .with_sizing_behavior(ListSizingBehavior::Infer);
 1293
 1294        Popover::new()
 1295            .child(list)
 1296            .when_some(multiline_docs, |popover, multiline_docs| {
 1297                popover.aside(multiline_docs)
 1298            })
 1299            .into_any_element()
 1300    }
 1301
 1302    pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
 1303        let mut matches = if let Some(query) = query {
 1304            fuzzy::match_strings(
 1305                &self.match_candidates,
 1306                query,
 1307                query.chars().any(|c| c.is_uppercase()),
 1308                100,
 1309                &Default::default(),
 1310                executor,
 1311            )
 1312            .await
 1313        } else {
 1314            self.match_candidates
 1315                .iter()
 1316                .enumerate()
 1317                .map(|(candidate_id, candidate)| StringMatch {
 1318                    candidate_id,
 1319                    score: Default::default(),
 1320                    positions: Default::default(),
 1321                    string: candidate.string.clone(),
 1322                })
 1323                .collect()
 1324        };
 1325
 1326        // Remove all candidates where the query's start does not match the start of any word in the candidate
 1327        if let Some(query) = query {
 1328            if let Some(query_start) = query.chars().next() {
 1329                matches.retain(|string_match| {
 1330                    split_words(&string_match.string).any(|word| {
 1331                        // Check that the first codepoint of the word as lowercase matches the first
 1332                        // codepoint of the query as lowercase
 1333                        word.chars()
 1334                            .flat_map(|codepoint| codepoint.to_lowercase())
 1335                            .zip(query_start.to_lowercase())
 1336                            .all(|(word_cp, query_cp)| word_cp == query_cp)
 1337                    })
 1338                });
 1339            }
 1340        }
 1341
 1342        let completions = self.completions.read();
 1343        if self.sort_completions {
 1344            matches.sort_unstable_by_key(|mat| {
 1345                // We do want to strike a balance here between what the language server tells us
 1346                // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
 1347                // `Creat` and there is a local variable called `CreateComponent`).
 1348                // So what we do is: we bucket all matches into two buckets
 1349                // - Strong matches
 1350                // - Weak matches
 1351                // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
 1352                // and the Weak matches are the rest.
 1353                //
 1354                // For the strong matches, we sort by the language-servers score first and for the weak
 1355                // matches, we prefer our fuzzy finder first.
 1356                //
 1357                // The thinking behind that: it's useless to take the sort_text the language-server gives
 1358                // us into account when it's obviously a bad match.
 1359
 1360                #[derive(PartialEq, Eq, PartialOrd, Ord)]
 1361                enum MatchScore<'a> {
 1362                    Strong {
 1363                        sort_text: Option<&'a str>,
 1364                        score: Reverse<OrderedFloat<f64>>,
 1365                        sort_key: (usize, &'a str),
 1366                    },
 1367                    Weak {
 1368                        score: Reverse<OrderedFloat<f64>>,
 1369                        sort_text: Option<&'a str>,
 1370                        sort_key: (usize, &'a str),
 1371                    },
 1372                }
 1373
 1374                let completion = &completions[mat.candidate_id];
 1375                let sort_key = completion.sort_key();
 1376                let sort_text = completion.lsp_completion.sort_text.as_deref();
 1377                let score = Reverse(OrderedFloat(mat.score));
 1378
 1379                if mat.score >= 0.2 {
 1380                    MatchScore::Strong {
 1381                        sort_text,
 1382                        score,
 1383                        sort_key,
 1384                    }
 1385                } else {
 1386                    MatchScore::Weak {
 1387                        score,
 1388                        sort_text,
 1389                        sort_key,
 1390                    }
 1391                }
 1392            });
 1393        }
 1394
 1395        for mat in &mut matches {
 1396            let completion = &completions[mat.candidate_id];
 1397            mat.string.clone_from(&completion.label.text);
 1398            for position in &mut mat.positions {
 1399                *position += completion.label.filter_range.start;
 1400            }
 1401        }
 1402        drop(completions);
 1403
 1404        self.matches = matches.into();
 1405        self.selected_item = 0;
 1406    }
 1407}
 1408
 1409struct AvailableCodeAction {
 1410    excerpt_id: ExcerptId,
 1411    action: CodeAction,
 1412    provider: Arc<dyn CodeActionProvider>,
 1413}
 1414
 1415#[derive(Clone)]
 1416struct CodeActionContents {
 1417    tasks: Option<Arc<ResolvedTasks>>,
 1418    actions: Option<Arc<[AvailableCodeAction]>>,
 1419}
 1420
 1421impl CodeActionContents {
 1422    fn len(&self) -> usize {
 1423        match (&self.tasks, &self.actions) {
 1424            (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
 1425            (Some(tasks), None) => tasks.templates.len(),
 1426            (None, Some(actions)) => actions.len(),
 1427            (None, None) => 0,
 1428        }
 1429    }
 1430
 1431    fn is_empty(&self) -> bool {
 1432        match (&self.tasks, &self.actions) {
 1433            (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
 1434            (Some(tasks), None) => tasks.templates.is_empty(),
 1435            (None, Some(actions)) => actions.is_empty(),
 1436            (None, None) => true,
 1437        }
 1438    }
 1439
 1440    fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
 1441        self.tasks
 1442            .iter()
 1443            .flat_map(|tasks| {
 1444                tasks
 1445                    .templates
 1446                    .iter()
 1447                    .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
 1448            })
 1449            .chain(self.actions.iter().flat_map(|actions| {
 1450                actions.iter().map(|available| CodeActionsItem::CodeAction {
 1451                    excerpt_id: available.excerpt_id,
 1452                    action: available.action.clone(),
 1453                    provider: available.provider.clone(),
 1454                })
 1455            }))
 1456    }
 1457    fn get(&self, index: usize) -> Option<CodeActionsItem> {
 1458        match (&self.tasks, &self.actions) {
 1459            (Some(tasks), Some(actions)) => {
 1460                if index < tasks.templates.len() {
 1461                    tasks
 1462                        .templates
 1463                        .get(index)
 1464                        .cloned()
 1465                        .map(|(kind, task)| CodeActionsItem::Task(kind, task))
 1466                } else {
 1467                    actions.get(index - tasks.templates.len()).map(|available| {
 1468                        CodeActionsItem::CodeAction {
 1469                            excerpt_id: available.excerpt_id,
 1470                            action: available.action.clone(),
 1471                            provider: available.provider.clone(),
 1472                        }
 1473                    })
 1474                }
 1475            }
 1476            (Some(tasks), None) => tasks
 1477                .templates
 1478                .get(index)
 1479                .cloned()
 1480                .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
 1481            (None, Some(actions)) => {
 1482                actions
 1483                    .get(index)
 1484                    .map(|available| CodeActionsItem::CodeAction {
 1485                        excerpt_id: available.excerpt_id,
 1486                        action: available.action.clone(),
 1487                        provider: available.provider.clone(),
 1488                    })
 1489            }
 1490            (None, None) => None,
 1491        }
 1492    }
 1493}
 1494
 1495#[allow(clippy::large_enum_variant)]
 1496#[derive(Clone)]
 1497enum CodeActionsItem {
 1498    Task(TaskSourceKind, ResolvedTask),
 1499    CodeAction {
 1500        excerpt_id: ExcerptId,
 1501        action: CodeAction,
 1502        provider: Arc<dyn CodeActionProvider>,
 1503    },
 1504}
 1505
 1506impl CodeActionsItem {
 1507    fn as_task(&self) -> Option<&ResolvedTask> {
 1508        let Self::Task(_, task) = self else {
 1509            return None;
 1510        };
 1511        Some(task)
 1512    }
 1513    fn as_code_action(&self) -> Option<&CodeAction> {
 1514        let Self::CodeAction { action, .. } = self else {
 1515            return None;
 1516        };
 1517        Some(action)
 1518    }
 1519    fn label(&self) -> String {
 1520        match self {
 1521            Self::CodeAction { action, .. } => action.lsp_action.title.clone(),
 1522            Self::Task(_, task) => task.resolved_label.clone(),
 1523        }
 1524    }
 1525}
 1526
 1527struct CodeActionsMenu {
 1528    actions: CodeActionContents,
 1529    buffer: Model<Buffer>,
 1530    selected_item: usize,
 1531    scroll_handle: UniformListScrollHandle,
 1532    deployed_from_indicator: Option<DisplayRow>,
 1533}
 1534
 1535impl CodeActionsMenu {
 1536    fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
 1537        self.selected_item = 0;
 1538        self.scroll_handle.scroll_to_item(self.selected_item);
 1539        cx.notify()
 1540    }
 1541
 1542    fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
 1543        if self.selected_item > 0 {
 1544            self.selected_item -= 1;
 1545        } else {
 1546            self.selected_item = self.actions.len() - 1;
 1547        }
 1548        self.scroll_handle.scroll_to_item(self.selected_item);
 1549        cx.notify();
 1550    }
 1551
 1552    fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
 1553        if self.selected_item + 1 < self.actions.len() {
 1554            self.selected_item += 1;
 1555        } else {
 1556            self.selected_item = 0;
 1557        }
 1558        self.scroll_handle.scroll_to_item(self.selected_item);
 1559        cx.notify();
 1560    }
 1561
 1562    fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
 1563        self.selected_item = self.actions.len() - 1;
 1564        self.scroll_handle.scroll_to_item(self.selected_item);
 1565        cx.notify()
 1566    }
 1567
 1568    fn visible(&self) -> bool {
 1569        !self.actions.is_empty()
 1570    }
 1571
 1572    fn render(
 1573        &self,
 1574        cursor_position: DisplayPoint,
 1575        _style: &EditorStyle,
 1576        max_height: Pixels,
 1577        cx: &mut ViewContext<Editor>,
 1578    ) -> (ContextMenuOrigin, AnyElement) {
 1579        let actions = self.actions.clone();
 1580        let selected_item = self.selected_item;
 1581        let element = uniform_list(
 1582            cx.view().clone(),
 1583            "code_actions_menu",
 1584            self.actions.len(),
 1585            move |_this, range, cx| {
 1586                actions
 1587                    .iter()
 1588                    .skip(range.start)
 1589                    .take(range.end - range.start)
 1590                    .enumerate()
 1591                    .map(|(ix, action)| {
 1592                        let item_ix = range.start + ix;
 1593                        let selected = selected_item == item_ix;
 1594                        let colors = cx.theme().colors();
 1595                        div()
 1596                            .px_1()
 1597                            .rounded_md()
 1598                            .text_color(colors.text)
 1599                            .when(selected, |style| {
 1600                                style
 1601                                    .bg(colors.element_active)
 1602                                    .text_color(colors.text_accent)
 1603                            })
 1604                            .hover(|style| {
 1605                                style
 1606                                    .bg(colors.element_hover)
 1607                                    .text_color(colors.text_accent)
 1608                            })
 1609                            .whitespace_nowrap()
 1610                            .when_some(action.as_code_action(), |this, action| {
 1611                                this.on_mouse_down(
 1612                                    MouseButton::Left,
 1613                                    cx.listener(move |editor, _, cx| {
 1614                                        cx.stop_propagation();
 1615                                        if let Some(task) = editor.confirm_code_action(
 1616                                            &ConfirmCodeAction {
 1617                                                item_ix: Some(item_ix),
 1618                                            },
 1619                                            cx,
 1620                                        ) {
 1621                                            task.detach_and_log_err(cx)
 1622                                        }
 1623                                    }),
 1624                                )
 1625                                // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
 1626                                .child(SharedString::from(action.lsp_action.title.clone()))
 1627                            })
 1628                            .when_some(action.as_task(), |this, task| {
 1629                                this.on_mouse_down(
 1630                                    MouseButton::Left,
 1631                                    cx.listener(move |editor, _, cx| {
 1632                                        cx.stop_propagation();
 1633                                        if let Some(task) = editor.confirm_code_action(
 1634                                            &ConfirmCodeAction {
 1635                                                item_ix: Some(item_ix),
 1636                                            },
 1637                                            cx,
 1638                                        ) {
 1639                                            task.detach_and_log_err(cx)
 1640                                        }
 1641                                    }),
 1642                                )
 1643                                .child(SharedString::from(task.resolved_label.clone()))
 1644                            })
 1645                    })
 1646                    .collect()
 1647            },
 1648        )
 1649        .elevation_1(cx)
 1650        .p_1()
 1651        .max_h(max_height)
 1652        .occlude()
 1653        .track_scroll(self.scroll_handle.clone())
 1654        .with_width_from_item(
 1655            self.actions
 1656                .iter()
 1657                .enumerate()
 1658                .max_by_key(|(_, action)| match action {
 1659                    CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
 1660                    CodeActionsItem::CodeAction { action, .. } => {
 1661                        action.lsp_action.title.chars().count()
 1662                    }
 1663                })
 1664                .map(|(ix, _)| ix),
 1665        )
 1666        .with_sizing_behavior(ListSizingBehavior::Infer)
 1667        .into_any_element();
 1668
 1669        let cursor_position = if let Some(row) = self.deployed_from_indicator {
 1670            ContextMenuOrigin::GutterIndicator(row)
 1671        } else {
 1672            ContextMenuOrigin::EditorPoint(cursor_position)
 1673        };
 1674
 1675        (cursor_position, element)
 1676    }
 1677}
 1678
 1679#[derive(Debug)]
 1680struct ActiveDiagnosticGroup {
 1681    primary_range: Range<Anchor>,
 1682    primary_message: String,
 1683    group_id: usize,
 1684    blocks: HashMap<CustomBlockId, Diagnostic>,
 1685    is_valid: bool,
 1686}
 1687
 1688#[derive(Serialize, Deserialize, Clone, Debug)]
 1689pub struct ClipboardSelection {
 1690    pub len: usize,
 1691    pub is_entire_line: bool,
 1692    pub first_line_indent: u32,
 1693}
 1694
 1695#[derive(Debug)]
 1696pub(crate) struct NavigationData {
 1697    cursor_anchor: Anchor,
 1698    cursor_position: Point,
 1699    scroll_anchor: ScrollAnchor,
 1700    scroll_top_row: u32,
 1701}
 1702
 1703#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1704pub enum GotoDefinitionKind {
 1705    Symbol,
 1706    Declaration,
 1707    Type,
 1708    Implementation,
 1709}
 1710
 1711#[derive(Debug, Clone)]
 1712enum InlayHintRefreshReason {
 1713    Toggle(bool),
 1714    SettingsChange(InlayHintSettings),
 1715    NewLinesShown,
 1716    BufferEdited(HashSet<Arc<Language>>),
 1717    RefreshRequested,
 1718    ExcerptsRemoved(Vec<ExcerptId>),
 1719}
 1720
 1721impl InlayHintRefreshReason {
 1722    fn description(&self) -> &'static str {
 1723        match self {
 1724            Self::Toggle(_) => "toggle",
 1725            Self::SettingsChange(_) => "settings change",
 1726            Self::NewLinesShown => "new lines shown",
 1727            Self::BufferEdited(_) => "buffer edited",
 1728            Self::RefreshRequested => "refresh requested",
 1729            Self::ExcerptsRemoved(_) => "excerpts removed",
 1730        }
 1731    }
 1732}
 1733
 1734pub(crate) struct FocusedBlock {
 1735    id: BlockId,
 1736    focus_handle: WeakFocusHandle,
 1737}
 1738
 1739impl Editor {
 1740    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
 1741        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1742        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1743        Self::new(
 1744            EditorMode::SingleLine { auto_width: false },
 1745            buffer,
 1746            None,
 1747            false,
 1748            cx,
 1749        )
 1750    }
 1751
 1752    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
 1753        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1754        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1755        Self::new(EditorMode::Full, buffer, None, false, cx)
 1756    }
 1757
 1758    pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
 1759        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1760        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1761        Self::new(
 1762            EditorMode::SingleLine { auto_width: true },
 1763            buffer,
 1764            None,
 1765            false,
 1766            cx,
 1767        )
 1768    }
 1769
 1770    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
 1771        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1772        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1773        Self::new(
 1774            EditorMode::AutoHeight { max_lines },
 1775            buffer,
 1776            None,
 1777            false,
 1778            cx,
 1779        )
 1780    }
 1781
 1782    pub fn for_buffer(
 1783        buffer: Model<Buffer>,
 1784        project: Option<Model<Project>>,
 1785        cx: &mut ViewContext<Self>,
 1786    ) -> Self {
 1787        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1788        Self::new(EditorMode::Full, buffer, project, false, cx)
 1789    }
 1790
 1791    pub fn for_multibuffer(
 1792        buffer: Model<MultiBuffer>,
 1793        project: Option<Model<Project>>,
 1794        show_excerpt_controls: bool,
 1795        cx: &mut ViewContext<Self>,
 1796    ) -> Self {
 1797        Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
 1798    }
 1799
 1800    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 1801        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1802        let mut clone = Self::new(
 1803            self.mode,
 1804            self.buffer.clone(),
 1805            self.project.clone(),
 1806            show_excerpt_controls,
 1807            cx,
 1808        );
 1809        self.display_map.update(cx, |display_map, cx| {
 1810            let snapshot = display_map.snapshot(cx);
 1811            clone.display_map.update(cx, |display_map, cx| {
 1812                display_map.set_state(&snapshot, cx);
 1813            });
 1814        });
 1815        clone.selections.clone_state(&self.selections);
 1816        clone.scroll_manager.clone_state(&self.scroll_manager);
 1817        clone.searchable = self.searchable;
 1818        clone
 1819    }
 1820
 1821    pub fn new(
 1822        mode: EditorMode,
 1823        buffer: Model<MultiBuffer>,
 1824        project: Option<Model<Project>>,
 1825        show_excerpt_controls: bool,
 1826        cx: &mut ViewContext<Self>,
 1827    ) -> Self {
 1828        let style = cx.text_style();
 1829        let font_size = style.font_size.to_pixels(cx.rem_size());
 1830        let editor = cx.view().downgrade();
 1831        let fold_placeholder = FoldPlaceholder {
 1832            constrain_width: true,
 1833            render: Arc::new(move |fold_id, fold_range, cx| {
 1834                let editor = editor.clone();
 1835                div()
 1836                    .id(fold_id)
 1837                    .bg(cx.theme().colors().ghost_element_background)
 1838                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1839                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1840                    .rounded_sm()
 1841                    .size_full()
 1842                    .cursor_pointer()
 1843                    .child("")
 1844                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 1845                    .on_click(move |_, cx| {
 1846                        editor
 1847                            .update(cx, |editor, cx| {
 1848                                editor.unfold_ranges(
 1849                                    [fold_range.start..fold_range.end],
 1850                                    true,
 1851                                    false,
 1852                                    cx,
 1853                                );
 1854                                cx.stop_propagation();
 1855                            })
 1856                            .ok();
 1857                    })
 1858                    .into_any()
 1859            }),
 1860            merge_adjacent: true,
 1861        };
 1862        let display_map = cx.new_model(|cx| {
 1863            DisplayMap::new(
 1864                buffer.clone(),
 1865                style.font(),
 1866                font_size,
 1867                None,
 1868                show_excerpt_controls,
 1869                FILE_HEADER_HEIGHT,
 1870                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1871                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1872                fold_placeholder,
 1873                cx,
 1874            )
 1875        });
 1876
 1877        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1878
 1879        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1880
 1881        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1882            .then(|| language_settings::SoftWrap::None);
 1883
 1884        let mut project_subscriptions = Vec::new();
 1885        if mode == EditorMode::Full {
 1886            if let Some(project) = project.as_ref() {
 1887                if buffer.read(cx).is_singleton() {
 1888                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
 1889                        cx.emit(EditorEvent::TitleChanged);
 1890                    }));
 1891                }
 1892                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
 1893                    if let project::Event::RefreshInlayHints = event {
 1894                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1895                    } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1896                        if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1897                            let focus_handle = editor.focus_handle(cx);
 1898                            if focus_handle.is_focused(cx) {
 1899                                let snapshot = buffer.read(cx).snapshot();
 1900                                for (range, snippet) in snippet_edits {
 1901                                    let editor_range =
 1902                                        language::range_from_lsp(*range).to_offset(&snapshot);
 1903                                    editor
 1904                                        .insert_snippet(&[editor_range], snippet.clone(), cx)
 1905                                        .ok();
 1906                                }
 1907                            }
 1908                        }
 1909                    }
 1910                }));
 1911                if let Some(task_inventory) = project
 1912                    .read(cx)
 1913                    .task_store()
 1914                    .read(cx)
 1915                    .task_inventory()
 1916                    .cloned()
 1917                {
 1918                    project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
 1919                        editor.tasks_update_task = Some(editor.refresh_runnables(cx));
 1920                    }));
 1921                }
 1922            }
 1923        }
 1924
 1925        let inlay_hint_settings = inlay_hint_settings(
 1926            selections.newest_anchor().head(),
 1927            &buffer.read(cx).snapshot(cx),
 1928            cx,
 1929        );
 1930        let focus_handle = cx.focus_handle();
 1931        cx.on_focus(&focus_handle, Self::handle_focus).detach();
 1932        cx.on_focus_in(&focus_handle, Self::handle_focus_in)
 1933            .detach();
 1934        cx.on_focus_out(&focus_handle, Self::handle_focus_out)
 1935            .detach();
 1936        cx.on_blur(&focus_handle, Self::handle_blur).detach();
 1937
 1938        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1939            Some(false)
 1940        } else {
 1941            None
 1942        };
 1943
 1944        let mut code_action_providers = Vec::new();
 1945        if let Some(project) = project.clone() {
 1946            code_action_providers.push(Arc::new(project) as Arc<_>);
 1947        }
 1948
 1949        let mut this = Self {
 1950            focus_handle,
 1951            show_cursor_when_unfocused: false,
 1952            last_focused_descendant: None,
 1953            buffer: buffer.clone(),
 1954            display_map: display_map.clone(),
 1955            selections,
 1956            scroll_manager: ScrollManager::new(cx),
 1957            columnar_selection_tail: None,
 1958            add_selections_state: None,
 1959            select_next_state: None,
 1960            select_prev_state: None,
 1961            selection_history: Default::default(),
 1962            autoclose_regions: Default::default(),
 1963            snippet_stack: Default::default(),
 1964            select_larger_syntax_node_stack: Vec::new(),
 1965            ime_transaction: Default::default(),
 1966            active_diagnostics: None,
 1967            soft_wrap_mode_override,
 1968            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1969            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1970            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1971            project,
 1972            blink_manager: blink_manager.clone(),
 1973            show_local_selections: true,
 1974            mode,
 1975            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1976            show_gutter: mode == EditorMode::Full,
 1977            show_line_numbers: None,
 1978            use_relative_line_numbers: None,
 1979            show_git_diff_gutter: None,
 1980            show_code_actions: None,
 1981            show_runnables: None,
 1982            show_wrap_guides: None,
 1983            show_indent_guides,
 1984            placeholder_text: None,
 1985            highlight_order: 0,
 1986            highlighted_rows: HashMap::default(),
 1987            background_highlights: Default::default(),
 1988            gutter_highlights: TreeMap::default(),
 1989            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1990            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1991            nav_history: None,
 1992            context_menu: RwLock::new(None),
 1993            mouse_context_menu: None,
 1994            hunk_controls_menu_handle: PopoverMenuHandle::default(),
 1995            completion_tasks: Default::default(),
 1996            signature_help_state: SignatureHelpState::default(),
 1997            auto_signature_help: None,
 1998            find_all_references_task_sources: Vec::new(),
 1999            next_completion_id: 0,
 2000            completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
 2001            next_inlay_id: 0,
 2002            code_action_providers,
 2003            available_code_actions: Default::default(),
 2004            code_actions_task: Default::default(),
 2005            document_highlights_task: Default::default(),
 2006            linked_editing_range_task: Default::default(),
 2007            pending_rename: Default::default(),
 2008            searchable: true,
 2009            cursor_shape: EditorSettings::get_global(cx)
 2010                .cursor_shape
 2011                .unwrap_or_default(),
 2012            current_line_highlight: None,
 2013            autoindent_mode: Some(AutoindentMode::EachLine),
 2014            collapse_matches: false,
 2015            workspace: None,
 2016            input_enabled: true,
 2017            use_modal_editing: mode == EditorMode::Full,
 2018            read_only: false,
 2019            use_autoclose: true,
 2020            use_auto_surround: true,
 2021            auto_replace_emoji_shortcode: false,
 2022            leader_peer_id: None,
 2023            remote_id: None,
 2024            hover_state: Default::default(),
 2025            hovered_link_state: Default::default(),
 2026            inline_completion_provider: None,
 2027            active_inline_completion: None,
 2028            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 2029            expanded_hunks: ExpandedHunks::default(),
 2030            gutter_hovered: false,
 2031            pixel_position_of_newest_cursor: None,
 2032            last_bounds: None,
 2033            expect_bounds_change: None,
 2034            gutter_dimensions: GutterDimensions::default(),
 2035            style: None,
 2036            show_cursor_names: false,
 2037            hovered_cursors: Default::default(),
 2038            next_editor_action_id: EditorActionId::default(),
 2039            editor_actions: Rc::default(),
 2040            show_inline_completions_override: None,
 2041            enable_inline_completions: true,
 2042            custom_context_menu: None,
 2043            show_git_blame_gutter: false,
 2044            show_git_blame_inline: false,
 2045            show_selection_menu: None,
 2046            show_git_blame_inline_delay_task: None,
 2047            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 2048            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 2049                .session
 2050                .restore_unsaved_buffers,
 2051            blame: None,
 2052            blame_subscription: None,
 2053            tasks: Default::default(),
 2054            _subscriptions: vec![
 2055                cx.observe(&buffer, Self::on_buffer_changed),
 2056                cx.subscribe(&buffer, Self::on_buffer_event),
 2057                cx.observe(&display_map, Self::on_display_map_changed),
 2058                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 2059                cx.observe_global::<SettingsStore>(Self::settings_changed),
 2060                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 2061                cx.observe_window_activation(|editor, cx| {
 2062                    let active = cx.is_window_active();
 2063                    editor.blink_manager.update(cx, |blink_manager, cx| {
 2064                        if active {
 2065                            blink_manager.enable(cx);
 2066                        } else {
 2067                            blink_manager.disable(cx);
 2068                        }
 2069                    });
 2070                }),
 2071            ],
 2072            tasks_update_task: None,
 2073            linked_edit_ranges: Default::default(),
 2074            previous_search_ranges: None,
 2075            breadcrumb_header: None,
 2076            focused_block: None,
 2077            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 2078            addons: HashMap::default(),
 2079            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 2080            text_style_refinement: None,
 2081        };
 2082        this.tasks_update_task = Some(this.refresh_runnables(cx));
 2083        this._subscriptions.extend(project_subscriptions);
 2084
 2085        this.end_selection(cx);
 2086        this.scroll_manager.show_scrollbar(cx);
 2087
 2088        if mode == EditorMode::Full {
 2089            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 2090            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 2091
 2092            if this.git_blame_inline_enabled {
 2093                this.git_blame_inline_enabled = true;
 2094                this.start_git_blame_inline(false, cx);
 2095            }
 2096        }
 2097
 2098        this.report_editor_event("open", None, cx);
 2099        this
 2100    }
 2101
 2102    pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
 2103        self.mouse_context_menu
 2104            .as_ref()
 2105            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
 2106    }
 2107
 2108    fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
 2109        let mut key_context = KeyContext::new_with_defaults();
 2110        key_context.add("Editor");
 2111        let mode = match self.mode {
 2112            EditorMode::SingleLine { .. } => "single_line",
 2113            EditorMode::AutoHeight { .. } => "auto_height",
 2114            EditorMode::Full => "full",
 2115        };
 2116
 2117        if EditorSettings::jupyter_enabled(cx) {
 2118            key_context.add("jupyter");
 2119        }
 2120
 2121        key_context.set("mode", mode);
 2122        if self.pending_rename.is_some() {
 2123            key_context.add("renaming");
 2124        }
 2125        if self.context_menu_visible() {
 2126            match self.context_menu.read().as_ref() {
 2127                Some(ContextMenu::Completions(_)) => {
 2128                    key_context.add("menu");
 2129                    key_context.add("showing_completions")
 2130                }
 2131                Some(ContextMenu::CodeActions(_)) => {
 2132                    key_context.add("menu");
 2133                    key_context.add("showing_code_actions")
 2134                }
 2135                None => {}
 2136            }
 2137        }
 2138
 2139        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 2140        if !self.focus_handle(cx).contains_focused(cx)
 2141            || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
 2142        {
 2143            for addon in self.addons.values() {
 2144                addon.extend_key_context(&mut key_context, cx)
 2145            }
 2146        }
 2147
 2148        if let Some(extension) = self
 2149            .buffer
 2150            .read(cx)
 2151            .as_singleton()
 2152            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 2153        {
 2154            key_context.set("extension", extension.to_string());
 2155        }
 2156
 2157        if self.has_active_inline_completion(cx) {
 2158            key_context.add("copilot_suggestion");
 2159            key_context.add("inline_completion");
 2160        }
 2161
 2162        key_context
 2163    }
 2164
 2165    pub fn new_file(
 2166        workspace: &mut Workspace,
 2167        _: &workspace::NewFile,
 2168        cx: &mut ViewContext<Workspace>,
 2169    ) {
 2170        Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
 2171            "Failed to create buffer",
 2172            cx,
 2173            |e, _| match e.error_code() {
 2174                ErrorCode::RemoteUpgradeRequired => Some(format!(
 2175                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2176                e.error_tag("required").unwrap_or("the latest version")
 2177            )),
 2178                _ => None,
 2179            },
 2180        );
 2181    }
 2182
 2183    pub fn new_in_workspace(
 2184        workspace: &mut Workspace,
 2185        cx: &mut ViewContext<Workspace>,
 2186    ) -> Task<Result<View<Editor>>> {
 2187        let project = workspace.project().clone();
 2188        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2189
 2190        cx.spawn(|workspace, mut cx| async move {
 2191            let buffer = create.await?;
 2192            workspace.update(&mut cx, |workspace, cx| {
 2193                let editor =
 2194                    cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
 2195                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 2196                editor
 2197            })
 2198        })
 2199    }
 2200
 2201    fn new_file_vertical(
 2202        workspace: &mut Workspace,
 2203        _: &workspace::NewFileSplitVertical,
 2204        cx: &mut ViewContext<Workspace>,
 2205    ) {
 2206        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
 2207    }
 2208
 2209    fn new_file_horizontal(
 2210        workspace: &mut Workspace,
 2211        _: &workspace::NewFileSplitHorizontal,
 2212        cx: &mut ViewContext<Workspace>,
 2213    ) {
 2214        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
 2215    }
 2216
 2217    fn new_file_in_direction(
 2218        workspace: &mut Workspace,
 2219        direction: SplitDirection,
 2220        cx: &mut ViewContext<Workspace>,
 2221    ) {
 2222        let project = workspace.project().clone();
 2223        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2224
 2225        cx.spawn(|workspace, mut cx| async move {
 2226            let buffer = create.await?;
 2227            workspace.update(&mut cx, move |workspace, cx| {
 2228                workspace.split_item(
 2229                    direction,
 2230                    Box::new(
 2231                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 2232                    ),
 2233                    cx,
 2234                )
 2235            })?;
 2236            anyhow::Ok(())
 2237        })
 2238        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 2239            ErrorCode::RemoteUpgradeRequired => Some(format!(
 2240                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2241                e.error_tag("required").unwrap_or("the latest version")
 2242            )),
 2243            _ => None,
 2244        });
 2245    }
 2246
 2247    pub fn leader_peer_id(&self) -> Option<PeerId> {
 2248        self.leader_peer_id
 2249    }
 2250
 2251    pub fn buffer(&self) -> &Model<MultiBuffer> {
 2252        &self.buffer
 2253    }
 2254
 2255    pub fn workspace(&self) -> Option<View<Workspace>> {
 2256        self.workspace.as_ref()?.0.upgrade()
 2257    }
 2258
 2259    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
 2260        self.buffer().read(cx).title(cx)
 2261    }
 2262
 2263    pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
 2264        let git_blame_gutter_max_author_length = self
 2265            .render_git_blame_gutter(cx)
 2266            .then(|| {
 2267                if let Some(blame) = self.blame.as_ref() {
 2268                    let max_author_length =
 2269                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 2270                    Some(max_author_length)
 2271                } else {
 2272                    None
 2273                }
 2274            })
 2275            .flatten();
 2276
 2277        EditorSnapshot {
 2278            mode: self.mode,
 2279            show_gutter: self.show_gutter,
 2280            show_line_numbers: self.show_line_numbers,
 2281            show_git_diff_gutter: self.show_git_diff_gutter,
 2282            show_code_actions: self.show_code_actions,
 2283            show_runnables: self.show_runnables,
 2284            git_blame_gutter_max_author_length,
 2285            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 2286            scroll_anchor: self.scroll_manager.anchor(),
 2287            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 2288            placeholder_text: self.placeholder_text.clone(),
 2289            is_focused: self.focus_handle.is_focused(cx),
 2290            current_line_highlight: self
 2291                .current_line_highlight
 2292                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 2293            gutter_hovered: self.gutter_hovered,
 2294        }
 2295    }
 2296
 2297    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
 2298        self.buffer.read(cx).language_at(point, cx)
 2299    }
 2300
 2301    pub fn file_at<T: ToOffset>(
 2302        &self,
 2303        point: T,
 2304        cx: &AppContext,
 2305    ) -> Option<Arc<dyn language::File>> {
 2306        self.buffer.read(cx).read(cx).file_at(point).cloned()
 2307    }
 2308
 2309    pub fn active_excerpt(
 2310        &self,
 2311        cx: &AppContext,
 2312    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
 2313        self.buffer
 2314            .read(cx)
 2315            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 2316    }
 2317
 2318    pub fn mode(&self) -> EditorMode {
 2319        self.mode
 2320    }
 2321
 2322    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 2323        self.collaboration_hub.as_deref()
 2324    }
 2325
 2326    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 2327        self.collaboration_hub = Some(hub);
 2328    }
 2329
 2330    pub fn set_custom_context_menu(
 2331        &mut self,
 2332        f: impl 'static
 2333            + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
 2334    ) {
 2335        self.custom_context_menu = Some(Box::new(f))
 2336    }
 2337
 2338    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 2339        self.completion_provider = provider;
 2340    }
 2341
 2342    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 2343        self.semantics_provider.clone()
 2344    }
 2345
 2346    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 2347        self.semantics_provider = provider;
 2348    }
 2349
 2350    pub fn set_inline_completion_provider<T>(
 2351        &mut self,
 2352        provider: Option<Model<T>>,
 2353        cx: &mut ViewContext<Self>,
 2354    ) where
 2355        T: InlineCompletionProvider,
 2356    {
 2357        self.inline_completion_provider =
 2358            provider.map(|provider| RegisteredInlineCompletionProvider {
 2359                _subscription: cx.observe(&provider, |this, _, cx| {
 2360                    if this.focus_handle.is_focused(cx) {
 2361                        this.update_visible_inline_completion(cx);
 2362                    }
 2363                }),
 2364                provider: Arc::new(provider),
 2365            });
 2366        self.refresh_inline_completion(false, false, cx);
 2367    }
 2368
 2369    pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
 2370        self.placeholder_text.as_deref()
 2371    }
 2372
 2373    pub fn set_placeholder_text(
 2374        &mut self,
 2375        placeholder_text: impl Into<Arc<str>>,
 2376        cx: &mut ViewContext<Self>,
 2377    ) {
 2378        let placeholder_text = Some(placeholder_text.into());
 2379        if self.placeholder_text != placeholder_text {
 2380            self.placeholder_text = placeholder_text;
 2381            cx.notify();
 2382        }
 2383    }
 2384
 2385    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
 2386        self.cursor_shape = cursor_shape;
 2387
 2388        // Disrupt blink for immediate user feedback that the cursor shape has changed
 2389        self.blink_manager.update(cx, BlinkManager::show_cursor);
 2390
 2391        cx.notify();
 2392    }
 2393
 2394    pub fn set_current_line_highlight(
 2395        &mut self,
 2396        current_line_highlight: Option<CurrentLineHighlight>,
 2397    ) {
 2398        self.current_line_highlight = current_line_highlight;
 2399    }
 2400
 2401    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 2402        self.collapse_matches = collapse_matches;
 2403    }
 2404
 2405    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 2406        if self.collapse_matches {
 2407            return range.start..range.start;
 2408        }
 2409        range.clone()
 2410    }
 2411
 2412    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
 2413        if self.display_map.read(cx).clip_at_line_ends != clip {
 2414            self.display_map
 2415                .update(cx, |map, _| map.clip_at_line_ends = clip);
 2416        }
 2417    }
 2418
 2419    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 2420        self.input_enabled = input_enabled;
 2421    }
 2422
 2423    pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
 2424        self.enable_inline_completions = enabled;
 2425    }
 2426
 2427    pub fn set_autoindent(&mut self, autoindent: bool) {
 2428        if autoindent {
 2429            self.autoindent_mode = Some(AutoindentMode::EachLine);
 2430        } else {
 2431            self.autoindent_mode = None;
 2432        }
 2433    }
 2434
 2435    pub fn read_only(&self, cx: &AppContext) -> bool {
 2436        self.read_only || self.buffer.read(cx).read_only()
 2437    }
 2438
 2439    pub fn set_read_only(&mut self, read_only: bool) {
 2440        self.read_only = read_only;
 2441    }
 2442
 2443    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 2444        self.use_autoclose = autoclose;
 2445    }
 2446
 2447    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 2448        self.use_auto_surround = auto_surround;
 2449    }
 2450
 2451    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 2452        self.auto_replace_emoji_shortcode = auto_replace;
 2453    }
 2454
 2455    pub fn toggle_inline_completions(
 2456        &mut self,
 2457        _: &ToggleInlineCompletions,
 2458        cx: &mut ViewContext<Self>,
 2459    ) {
 2460        if self.show_inline_completions_override.is_some() {
 2461            self.set_show_inline_completions(None, cx);
 2462        } else {
 2463            let cursor = self.selections.newest_anchor().head();
 2464            if let Some((buffer, cursor_buffer_position)) =
 2465                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 2466            {
 2467                let show_inline_completions =
 2468                    !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
 2469                self.set_show_inline_completions(Some(show_inline_completions), cx);
 2470            }
 2471        }
 2472    }
 2473
 2474    pub fn set_show_inline_completions(
 2475        &mut self,
 2476        show_inline_completions: Option<bool>,
 2477        cx: &mut ViewContext<Self>,
 2478    ) {
 2479        self.show_inline_completions_override = show_inline_completions;
 2480        self.refresh_inline_completion(false, true, cx);
 2481    }
 2482
 2483    fn should_show_inline_completions(
 2484        &self,
 2485        buffer: &Model<Buffer>,
 2486        buffer_position: language::Anchor,
 2487        cx: &AppContext,
 2488    ) -> bool {
 2489        if let Some(provider) = self.inline_completion_provider() {
 2490            if let Some(show_inline_completions) = self.show_inline_completions_override {
 2491                show_inline_completions
 2492            } else {
 2493                self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
 2494            }
 2495        } else {
 2496            false
 2497        }
 2498    }
 2499
 2500    pub fn set_use_modal_editing(&mut self, to: bool) {
 2501        self.use_modal_editing = to;
 2502    }
 2503
 2504    pub fn use_modal_editing(&self) -> bool {
 2505        self.use_modal_editing
 2506    }
 2507
 2508    fn selections_did_change(
 2509        &mut self,
 2510        local: bool,
 2511        old_cursor_position: &Anchor,
 2512        show_completions: bool,
 2513        cx: &mut ViewContext<Self>,
 2514    ) {
 2515        cx.invalidate_character_coordinates();
 2516
 2517        // Copy selections to primary selection buffer
 2518        #[cfg(target_os = "linux")]
 2519        if local {
 2520            let selections = self.selections.all::<usize>(cx);
 2521            let buffer_handle = self.buffer.read(cx).read(cx);
 2522
 2523            let mut text = String::new();
 2524            for (index, selection) in selections.iter().enumerate() {
 2525                let text_for_selection = buffer_handle
 2526                    .text_for_range(selection.start..selection.end)
 2527                    .collect::<String>();
 2528
 2529                text.push_str(&text_for_selection);
 2530                if index != selections.len() - 1 {
 2531                    text.push('\n');
 2532                }
 2533            }
 2534
 2535            if !text.is_empty() {
 2536                cx.write_to_primary(ClipboardItem::new_string(text));
 2537            }
 2538        }
 2539
 2540        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
 2541            self.buffer.update(cx, |buffer, cx| {
 2542                buffer.set_active_selections(
 2543                    &self.selections.disjoint_anchors(),
 2544                    self.selections.line_mode,
 2545                    self.cursor_shape,
 2546                    cx,
 2547                )
 2548            });
 2549        }
 2550        let display_map = self
 2551            .display_map
 2552            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2553        let buffer = &display_map.buffer_snapshot;
 2554        self.add_selections_state = None;
 2555        self.select_next_state = None;
 2556        self.select_prev_state = None;
 2557        self.select_larger_syntax_node_stack.clear();
 2558        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2559        self.snippet_stack
 2560            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2561        self.take_rename(false, cx);
 2562
 2563        let new_cursor_position = self.selections.newest_anchor().head();
 2564
 2565        self.push_to_nav_history(
 2566            *old_cursor_position,
 2567            Some(new_cursor_position.to_point(buffer)),
 2568            cx,
 2569        );
 2570
 2571        if local {
 2572            let new_cursor_position = self.selections.newest_anchor().head();
 2573            let mut context_menu = self.context_menu.write();
 2574            let completion_menu = match context_menu.as_ref() {
 2575                Some(ContextMenu::Completions(menu)) => Some(menu),
 2576
 2577                _ => {
 2578                    *context_menu = None;
 2579                    None
 2580                }
 2581            };
 2582
 2583            if let Some(completion_menu) = completion_menu {
 2584                let cursor_position = new_cursor_position.to_offset(buffer);
 2585                let (word_range, kind) =
 2586                    buffer.surrounding_word(completion_menu.initial_position, true);
 2587                if kind == Some(CharKind::Word)
 2588                    && word_range.to_inclusive().contains(&cursor_position)
 2589                {
 2590                    let mut completion_menu = completion_menu.clone();
 2591                    drop(context_menu);
 2592
 2593                    let query = Self::completion_query(buffer, cursor_position);
 2594                    cx.spawn(move |this, mut cx| async move {
 2595                        completion_menu
 2596                            .filter(query.as_deref(), cx.background_executor().clone())
 2597                            .await;
 2598
 2599                        this.update(&mut cx, |this, cx| {
 2600                            let mut context_menu = this.context_menu.write();
 2601                            let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
 2602                                return;
 2603                            };
 2604
 2605                            if menu.id > completion_menu.id {
 2606                                return;
 2607                            }
 2608
 2609                            *context_menu = Some(ContextMenu::Completions(completion_menu));
 2610                            drop(context_menu);
 2611                            cx.notify();
 2612                        })
 2613                    })
 2614                    .detach();
 2615
 2616                    if show_completions {
 2617                        self.show_completions(&ShowCompletions { trigger: None }, cx);
 2618                    }
 2619                } else {
 2620                    drop(context_menu);
 2621                    self.hide_context_menu(cx);
 2622                }
 2623            } else {
 2624                drop(context_menu);
 2625            }
 2626
 2627            hide_hover(self, cx);
 2628
 2629            if old_cursor_position.to_display_point(&display_map).row()
 2630                != new_cursor_position.to_display_point(&display_map).row()
 2631            {
 2632                self.available_code_actions.take();
 2633            }
 2634            self.refresh_code_actions(cx);
 2635            self.refresh_document_highlights(cx);
 2636            refresh_matching_bracket_highlights(self, cx);
 2637            self.discard_inline_completion(false, cx);
 2638            linked_editing_ranges::refresh_linked_ranges(self, cx);
 2639            if self.git_blame_inline_enabled {
 2640                self.start_inline_blame_timer(cx);
 2641            }
 2642        }
 2643
 2644        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2645        cx.emit(EditorEvent::SelectionsChanged { local });
 2646
 2647        if self.selections.disjoint_anchors().len() == 1 {
 2648            cx.emit(SearchEvent::ActiveMatchChanged)
 2649        }
 2650        cx.notify();
 2651    }
 2652
 2653    pub fn change_selections<R>(
 2654        &mut self,
 2655        autoscroll: Option<Autoscroll>,
 2656        cx: &mut ViewContext<Self>,
 2657        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2658    ) -> R {
 2659        self.change_selections_inner(autoscroll, true, cx, change)
 2660    }
 2661
 2662    pub fn change_selections_inner<R>(
 2663        &mut self,
 2664        autoscroll: Option<Autoscroll>,
 2665        request_completions: bool,
 2666        cx: &mut ViewContext<Self>,
 2667        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2668    ) -> R {
 2669        let old_cursor_position = self.selections.newest_anchor().head();
 2670        self.push_to_selection_history();
 2671
 2672        let (changed, result) = self.selections.change_with(cx, change);
 2673
 2674        if changed {
 2675            if let Some(autoscroll) = autoscroll {
 2676                self.request_autoscroll(autoscroll, cx);
 2677            }
 2678            self.selections_did_change(true, &old_cursor_position, request_completions, cx);
 2679
 2680            if self.should_open_signature_help_automatically(
 2681                &old_cursor_position,
 2682                self.signature_help_state.backspace_pressed(),
 2683                cx,
 2684            ) {
 2685                self.show_signature_help(&ShowSignatureHelp, cx);
 2686            }
 2687            self.signature_help_state.set_backspace_pressed(false);
 2688        }
 2689
 2690        result
 2691    }
 2692
 2693    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2694    where
 2695        I: IntoIterator<Item = (Range<S>, T)>,
 2696        S: ToOffset,
 2697        T: Into<Arc<str>>,
 2698    {
 2699        if self.read_only(cx) {
 2700            return;
 2701        }
 2702
 2703        self.buffer
 2704            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2705    }
 2706
 2707    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2708    where
 2709        I: IntoIterator<Item = (Range<S>, T)>,
 2710        S: ToOffset,
 2711        T: Into<Arc<str>>,
 2712    {
 2713        if self.read_only(cx) {
 2714            return;
 2715        }
 2716
 2717        self.buffer.update(cx, |buffer, cx| {
 2718            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2719        });
 2720    }
 2721
 2722    pub fn edit_with_block_indent<I, S, T>(
 2723        &mut self,
 2724        edits: I,
 2725        original_indent_columns: Vec<u32>,
 2726        cx: &mut ViewContext<Self>,
 2727    ) where
 2728        I: IntoIterator<Item = (Range<S>, T)>,
 2729        S: ToOffset,
 2730        T: Into<Arc<str>>,
 2731    {
 2732        if self.read_only(cx) {
 2733            return;
 2734        }
 2735
 2736        self.buffer.update(cx, |buffer, cx| {
 2737            buffer.edit(
 2738                edits,
 2739                Some(AutoindentMode::Block {
 2740                    original_indent_columns,
 2741                }),
 2742                cx,
 2743            )
 2744        });
 2745    }
 2746
 2747    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
 2748        self.hide_context_menu(cx);
 2749
 2750        match phase {
 2751            SelectPhase::Begin {
 2752                position,
 2753                add,
 2754                click_count,
 2755            } => self.begin_selection(position, add, click_count, cx),
 2756            SelectPhase::BeginColumnar {
 2757                position,
 2758                goal_column,
 2759                reset,
 2760            } => self.begin_columnar_selection(position, goal_column, reset, cx),
 2761            SelectPhase::Extend {
 2762                position,
 2763                click_count,
 2764            } => self.extend_selection(position, click_count, cx),
 2765            SelectPhase::Update {
 2766                position,
 2767                goal_column,
 2768                scroll_delta,
 2769            } => self.update_selection(position, goal_column, scroll_delta, cx),
 2770            SelectPhase::End => self.end_selection(cx),
 2771        }
 2772    }
 2773
 2774    fn extend_selection(
 2775        &mut self,
 2776        position: DisplayPoint,
 2777        click_count: usize,
 2778        cx: &mut ViewContext<Self>,
 2779    ) {
 2780        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2781        let tail = self.selections.newest::<usize>(cx).tail();
 2782        self.begin_selection(position, false, click_count, cx);
 2783
 2784        let position = position.to_offset(&display_map, Bias::Left);
 2785        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2786
 2787        let mut pending_selection = self
 2788            .selections
 2789            .pending_anchor()
 2790            .expect("extend_selection not called with pending selection");
 2791        if position >= tail {
 2792            pending_selection.start = tail_anchor;
 2793        } else {
 2794            pending_selection.end = tail_anchor;
 2795            pending_selection.reversed = true;
 2796        }
 2797
 2798        let mut pending_mode = self.selections.pending_mode().unwrap();
 2799        match &mut pending_mode {
 2800            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2801            _ => {}
 2802        }
 2803
 2804        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 2805            s.set_pending(pending_selection, pending_mode)
 2806        });
 2807    }
 2808
 2809    fn begin_selection(
 2810        &mut self,
 2811        position: DisplayPoint,
 2812        add: bool,
 2813        click_count: usize,
 2814        cx: &mut ViewContext<Self>,
 2815    ) {
 2816        if !self.focus_handle.is_focused(cx) {
 2817            self.last_focused_descendant = None;
 2818            cx.focus(&self.focus_handle);
 2819        }
 2820
 2821        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2822        let buffer = &display_map.buffer_snapshot;
 2823        let newest_selection = self.selections.newest_anchor().clone();
 2824        let position = display_map.clip_point(position, Bias::Left);
 2825
 2826        let start;
 2827        let end;
 2828        let mode;
 2829        let auto_scroll;
 2830        match click_count {
 2831            1 => {
 2832                start = buffer.anchor_before(position.to_point(&display_map));
 2833                end = start;
 2834                mode = SelectMode::Character;
 2835                auto_scroll = true;
 2836            }
 2837            2 => {
 2838                let range = movement::surrounding_word(&display_map, position);
 2839                start = buffer.anchor_before(range.start.to_point(&display_map));
 2840                end = buffer.anchor_before(range.end.to_point(&display_map));
 2841                mode = SelectMode::Word(start..end);
 2842                auto_scroll = true;
 2843            }
 2844            3 => {
 2845                let position = display_map
 2846                    .clip_point(position, Bias::Left)
 2847                    .to_point(&display_map);
 2848                let line_start = display_map.prev_line_boundary(position).0;
 2849                let next_line_start = buffer.clip_point(
 2850                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2851                    Bias::Left,
 2852                );
 2853                start = buffer.anchor_before(line_start);
 2854                end = buffer.anchor_before(next_line_start);
 2855                mode = SelectMode::Line(start..end);
 2856                auto_scroll = true;
 2857            }
 2858            _ => {
 2859                start = buffer.anchor_before(0);
 2860                end = buffer.anchor_before(buffer.len());
 2861                mode = SelectMode::All;
 2862                auto_scroll = false;
 2863            }
 2864        }
 2865
 2866        let point_to_delete: Option<usize> = {
 2867            let selected_points: Vec<Selection<Point>> =
 2868                self.selections.disjoint_in_range(start..end, cx);
 2869
 2870            if !add || click_count > 1 {
 2871                None
 2872            } else if !selected_points.is_empty() {
 2873                Some(selected_points[0].id)
 2874            } else {
 2875                let clicked_point_already_selected =
 2876                    self.selections.disjoint.iter().find(|selection| {
 2877                        selection.start.to_point(buffer) == start.to_point(buffer)
 2878                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2879                    });
 2880
 2881                clicked_point_already_selected.map(|selection| selection.id)
 2882            }
 2883        };
 2884
 2885        let selections_count = self.selections.count();
 2886
 2887        self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
 2888            if let Some(point_to_delete) = point_to_delete {
 2889                s.delete(point_to_delete);
 2890
 2891                if selections_count == 1 {
 2892                    s.set_pending_anchor_range(start..end, mode);
 2893                }
 2894            } else {
 2895                if !add {
 2896                    s.clear_disjoint();
 2897                } else if click_count > 1 {
 2898                    s.delete(newest_selection.id)
 2899                }
 2900
 2901                s.set_pending_anchor_range(start..end, mode);
 2902            }
 2903        });
 2904    }
 2905
 2906    fn begin_columnar_selection(
 2907        &mut self,
 2908        position: DisplayPoint,
 2909        goal_column: u32,
 2910        reset: bool,
 2911        cx: &mut ViewContext<Self>,
 2912    ) {
 2913        if !self.focus_handle.is_focused(cx) {
 2914            self.last_focused_descendant = None;
 2915            cx.focus(&self.focus_handle);
 2916        }
 2917
 2918        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2919
 2920        if reset {
 2921            let pointer_position = display_map
 2922                .buffer_snapshot
 2923                .anchor_before(position.to_point(&display_map));
 2924
 2925            self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 2926                s.clear_disjoint();
 2927                s.set_pending_anchor_range(
 2928                    pointer_position..pointer_position,
 2929                    SelectMode::Character,
 2930                );
 2931            });
 2932        }
 2933
 2934        let tail = self.selections.newest::<Point>(cx).tail();
 2935        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2936
 2937        if !reset {
 2938            self.select_columns(
 2939                tail.to_display_point(&display_map),
 2940                position,
 2941                goal_column,
 2942                &display_map,
 2943                cx,
 2944            );
 2945        }
 2946    }
 2947
 2948    fn update_selection(
 2949        &mut self,
 2950        position: DisplayPoint,
 2951        goal_column: u32,
 2952        scroll_delta: gpui::Point<f32>,
 2953        cx: &mut ViewContext<Self>,
 2954    ) {
 2955        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2956
 2957        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2958            let tail = tail.to_display_point(&display_map);
 2959            self.select_columns(tail, position, goal_column, &display_map, cx);
 2960        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2961            let buffer = self.buffer.read(cx).snapshot(cx);
 2962            let head;
 2963            let tail;
 2964            let mode = self.selections.pending_mode().unwrap();
 2965            match &mode {
 2966                SelectMode::Character => {
 2967                    head = position.to_point(&display_map);
 2968                    tail = pending.tail().to_point(&buffer);
 2969                }
 2970                SelectMode::Word(original_range) => {
 2971                    let original_display_range = original_range.start.to_display_point(&display_map)
 2972                        ..original_range.end.to_display_point(&display_map);
 2973                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2974                        ..original_display_range.end.to_point(&display_map);
 2975                    if movement::is_inside_word(&display_map, position)
 2976                        || original_display_range.contains(&position)
 2977                    {
 2978                        let word_range = movement::surrounding_word(&display_map, position);
 2979                        if word_range.start < original_display_range.start {
 2980                            head = word_range.start.to_point(&display_map);
 2981                        } else {
 2982                            head = word_range.end.to_point(&display_map);
 2983                        }
 2984                    } else {
 2985                        head = position.to_point(&display_map);
 2986                    }
 2987
 2988                    if head <= original_buffer_range.start {
 2989                        tail = original_buffer_range.end;
 2990                    } else {
 2991                        tail = original_buffer_range.start;
 2992                    }
 2993                }
 2994                SelectMode::Line(original_range) => {
 2995                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2996
 2997                    let position = display_map
 2998                        .clip_point(position, Bias::Left)
 2999                        .to_point(&display_map);
 3000                    let line_start = display_map.prev_line_boundary(position).0;
 3001                    let next_line_start = buffer.clip_point(
 3002                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 3003                        Bias::Left,
 3004                    );
 3005
 3006                    if line_start < original_range.start {
 3007                        head = line_start
 3008                    } else {
 3009                        head = next_line_start
 3010                    }
 3011
 3012                    if head <= original_range.start {
 3013                        tail = original_range.end;
 3014                    } else {
 3015                        tail = original_range.start;
 3016                    }
 3017                }
 3018                SelectMode::All => {
 3019                    return;
 3020                }
 3021            };
 3022
 3023            if head < tail {
 3024                pending.start = buffer.anchor_before(head);
 3025                pending.end = buffer.anchor_before(tail);
 3026                pending.reversed = true;
 3027            } else {
 3028                pending.start = buffer.anchor_before(tail);
 3029                pending.end = buffer.anchor_before(head);
 3030                pending.reversed = false;
 3031            }
 3032
 3033            self.change_selections(None, cx, |s| {
 3034                s.set_pending(pending, mode);
 3035            });
 3036        } else {
 3037            log::error!("update_selection dispatched with no pending selection");
 3038            return;
 3039        }
 3040
 3041        self.apply_scroll_delta(scroll_delta, cx);
 3042        cx.notify();
 3043    }
 3044
 3045    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 3046        self.columnar_selection_tail.take();
 3047        if self.selections.pending_anchor().is_some() {
 3048            let selections = self.selections.all::<usize>(cx);
 3049            self.change_selections(None, cx, |s| {
 3050                s.select(selections);
 3051                s.clear_pending();
 3052            });
 3053        }
 3054    }
 3055
 3056    fn select_columns(
 3057        &mut self,
 3058        tail: DisplayPoint,
 3059        head: DisplayPoint,
 3060        goal_column: u32,
 3061        display_map: &DisplaySnapshot,
 3062        cx: &mut ViewContext<Self>,
 3063    ) {
 3064        let start_row = cmp::min(tail.row(), head.row());
 3065        let end_row = cmp::max(tail.row(), head.row());
 3066        let start_column = cmp::min(tail.column(), goal_column);
 3067        let end_column = cmp::max(tail.column(), goal_column);
 3068        let reversed = start_column < tail.column();
 3069
 3070        let selection_ranges = (start_row.0..=end_row.0)
 3071            .map(DisplayRow)
 3072            .filter_map(|row| {
 3073                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 3074                    let start = display_map
 3075                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 3076                        .to_point(display_map);
 3077                    let end = display_map
 3078                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 3079                        .to_point(display_map);
 3080                    if reversed {
 3081                        Some(end..start)
 3082                    } else {
 3083                        Some(start..end)
 3084                    }
 3085                } else {
 3086                    None
 3087                }
 3088            })
 3089            .collect::<Vec<_>>();
 3090
 3091        self.change_selections(None, cx, |s| {
 3092            s.select_ranges(selection_ranges);
 3093        });
 3094        cx.notify();
 3095    }
 3096
 3097    pub fn has_pending_nonempty_selection(&self) -> bool {
 3098        let pending_nonempty_selection = match self.selections.pending_anchor() {
 3099            Some(Selection { start, end, .. }) => start != end,
 3100            None => false,
 3101        };
 3102
 3103        pending_nonempty_selection
 3104            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 3105    }
 3106
 3107    pub fn has_pending_selection(&self) -> bool {
 3108        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 3109    }
 3110
 3111    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 3112        if self.clear_expanded_diff_hunks(cx) {
 3113            cx.notify();
 3114            return;
 3115        }
 3116        if self.dismiss_menus_and_popups(true, cx) {
 3117            return;
 3118        }
 3119
 3120        if self.mode == EditorMode::Full
 3121            && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
 3122        {
 3123            return;
 3124        }
 3125
 3126        cx.propagate();
 3127    }
 3128
 3129    pub fn dismiss_menus_and_popups(
 3130        &mut self,
 3131        should_report_inline_completion_event: bool,
 3132        cx: &mut ViewContext<Self>,
 3133    ) -> bool {
 3134        if self.take_rename(false, cx).is_some() {
 3135            return true;
 3136        }
 3137
 3138        if hide_hover(self, cx) {
 3139            return true;
 3140        }
 3141
 3142        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 3143            return true;
 3144        }
 3145
 3146        if self.hide_context_menu(cx).is_some() {
 3147            return true;
 3148        }
 3149
 3150        if self.mouse_context_menu.take().is_some() {
 3151            return true;
 3152        }
 3153
 3154        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 3155            return true;
 3156        }
 3157
 3158        if self.snippet_stack.pop().is_some() {
 3159            return true;
 3160        }
 3161
 3162        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 3163            self.dismiss_diagnostics(cx);
 3164            return true;
 3165        }
 3166
 3167        false
 3168    }
 3169
 3170    fn linked_editing_ranges_for(
 3171        &self,
 3172        selection: Range<text::Anchor>,
 3173        cx: &AppContext,
 3174    ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
 3175        if self.linked_edit_ranges.is_empty() {
 3176            return None;
 3177        }
 3178        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 3179            selection.end.buffer_id.and_then(|end_buffer_id| {
 3180                if selection.start.buffer_id != Some(end_buffer_id) {
 3181                    return None;
 3182                }
 3183                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 3184                let snapshot = buffer.read(cx).snapshot();
 3185                self.linked_edit_ranges
 3186                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 3187                    .map(|ranges| (ranges, snapshot, buffer))
 3188            })?;
 3189        use text::ToOffset as TO;
 3190        // find offset from the start of current range to current cursor position
 3191        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 3192
 3193        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 3194        let start_difference = start_offset - start_byte_offset;
 3195        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 3196        let end_difference = end_offset - start_byte_offset;
 3197        // Current range has associated linked ranges.
 3198        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3199        for range in linked_ranges.iter() {
 3200            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 3201            let end_offset = start_offset + end_difference;
 3202            let start_offset = start_offset + start_difference;
 3203            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 3204                continue;
 3205            }
 3206            if self.selections.disjoint_anchor_ranges().iter().any(|s| {
 3207                if s.start.buffer_id != selection.start.buffer_id
 3208                    || s.end.buffer_id != selection.end.buffer_id
 3209                {
 3210                    return false;
 3211                }
 3212                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 3213                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 3214            }) {
 3215                continue;
 3216            }
 3217            let start = buffer_snapshot.anchor_after(start_offset);
 3218            let end = buffer_snapshot.anchor_after(end_offset);
 3219            linked_edits
 3220                .entry(buffer.clone())
 3221                .or_default()
 3222                .push(start..end);
 3223        }
 3224        Some(linked_edits)
 3225    }
 3226
 3227    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3228        let text: Arc<str> = text.into();
 3229
 3230        if self.read_only(cx) {
 3231            return;
 3232        }
 3233
 3234        let selections = self.selections.all_adjusted(cx);
 3235        let mut bracket_inserted = false;
 3236        let mut edits = Vec::new();
 3237        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3238        let mut new_selections = Vec::with_capacity(selections.len());
 3239        let mut new_autoclose_regions = Vec::new();
 3240        let snapshot = self.buffer.read(cx).read(cx);
 3241
 3242        for (selection, autoclose_region) in
 3243            self.selections_with_autoclose_regions(selections, &snapshot)
 3244        {
 3245            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 3246                // Determine if the inserted text matches the opening or closing
 3247                // bracket of any of this language's bracket pairs.
 3248                let mut bracket_pair = None;
 3249                let mut is_bracket_pair_start = false;
 3250                let mut is_bracket_pair_end = false;
 3251                if !text.is_empty() {
 3252                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 3253                    //  and they are removing the character that triggered IME popup.
 3254                    for (pair, enabled) in scope.brackets() {
 3255                        if !pair.close && !pair.surround {
 3256                            continue;
 3257                        }
 3258
 3259                        if enabled && pair.start.ends_with(text.as_ref()) {
 3260                            let prefix_len = pair.start.len() - text.len();
 3261                            let preceding_text_matches_prefix = prefix_len == 0
 3262                                || (selection.start.column >= (prefix_len as u32)
 3263                                    && snapshot.contains_str_at(
 3264                                        Point::new(
 3265                                            selection.start.row,
 3266                                            selection.start.column - (prefix_len as u32),
 3267                                        ),
 3268                                        &pair.start[..prefix_len],
 3269                                    ));
 3270                            if preceding_text_matches_prefix {
 3271                                bracket_pair = Some(pair.clone());
 3272                                is_bracket_pair_start = true;
 3273                                break;
 3274                            }
 3275                        }
 3276                        if pair.end.as_str() == text.as_ref() {
 3277                            bracket_pair = Some(pair.clone());
 3278                            is_bracket_pair_end = true;
 3279                            break;
 3280                        }
 3281                    }
 3282                }
 3283
 3284                if let Some(bracket_pair) = bracket_pair {
 3285                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 3286                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 3287                    let auto_surround =
 3288                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 3289                    if selection.is_empty() {
 3290                        if is_bracket_pair_start {
 3291                            // If the inserted text is a suffix of an opening bracket and the
 3292                            // selection is preceded by the rest of the opening bracket, then
 3293                            // insert the closing bracket.
 3294                            let following_text_allows_autoclose = snapshot
 3295                                .chars_at(selection.start)
 3296                                .next()
 3297                                .map_or(true, |c| scope.should_autoclose_before(c));
 3298
 3299                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 3300                                && bracket_pair.start.len() == 1
 3301                            {
 3302                                let target = bracket_pair.start.chars().next().unwrap();
 3303                                let current_line_count = snapshot
 3304                                    .reversed_chars_at(selection.start)
 3305                                    .take_while(|&c| c != '\n')
 3306                                    .filter(|&c| c == target)
 3307                                    .count();
 3308                                current_line_count % 2 == 1
 3309                            } else {
 3310                                false
 3311                            };
 3312
 3313                            if autoclose
 3314                                && bracket_pair.close
 3315                                && following_text_allows_autoclose
 3316                                && !is_closing_quote
 3317                            {
 3318                                let anchor = snapshot.anchor_before(selection.end);
 3319                                new_selections.push((selection.map(|_| anchor), text.len()));
 3320                                new_autoclose_regions.push((
 3321                                    anchor,
 3322                                    text.len(),
 3323                                    selection.id,
 3324                                    bracket_pair.clone(),
 3325                                ));
 3326                                edits.push((
 3327                                    selection.range(),
 3328                                    format!("{}{}", text, bracket_pair.end).into(),
 3329                                ));
 3330                                bracket_inserted = true;
 3331                                continue;
 3332                            }
 3333                        }
 3334
 3335                        if let Some(region) = autoclose_region {
 3336                            // If the selection is followed by an auto-inserted closing bracket,
 3337                            // then don't insert that closing bracket again; just move the selection
 3338                            // past the closing bracket.
 3339                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3340                                && text.as_ref() == region.pair.end.as_str();
 3341                            if should_skip {
 3342                                let anchor = snapshot.anchor_after(selection.end);
 3343                                new_selections
 3344                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3345                                continue;
 3346                            }
 3347                        }
 3348
 3349                        let always_treat_brackets_as_autoclosed = snapshot
 3350                            .settings_at(selection.start, cx)
 3351                            .always_treat_brackets_as_autoclosed;
 3352                        if always_treat_brackets_as_autoclosed
 3353                            && is_bracket_pair_end
 3354                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3355                        {
 3356                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3357                            // and the inserted text is a closing bracket and the selection is followed
 3358                            // by the closing bracket then move the selection past the closing bracket.
 3359                            let anchor = snapshot.anchor_after(selection.end);
 3360                            new_selections.push((selection.map(|_| anchor), text.len()));
 3361                            continue;
 3362                        }
 3363                    }
 3364                    // If an opening bracket is 1 character long and is typed while
 3365                    // text is selected, then surround that text with the bracket pair.
 3366                    else if auto_surround
 3367                        && bracket_pair.surround
 3368                        && is_bracket_pair_start
 3369                        && bracket_pair.start.chars().count() == 1
 3370                    {
 3371                        edits.push((selection.start..selection.start, text.clone()));
 3372                        edits.push((
 3373                            selection.end..selection.end,
 3374                            bracket_pair.end.as_str().into(),
 3375                        ));
 3376                        bracket_inserted = true;
 3377                        new_selections.push((
 3378                            Selection {
 3379                                id: selection.id,
 3380                                start: snapshot.anchor_after(selection.start),
 3381                                end: snapshot.anchor_before(selection.end),
 3382                                reversed: selection.reversed,
 3383                                goal: selection.goal,
 3384                            },
 3385                            0,
 3386                        ));
 3387                        continue;
 3388                    }
 3389                }
 3390            }
 3391
 3392            if self.auto_replace_emoji_shortcode
 3393                && selection.is_empty()
 3394                && text.as_ref().ends_with(':')
 3395            {
 3396                if let Some(possible_emoji_short_code) =
 3397                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3398                {
 3399                    if !possible_emoji_short_code.is_empty() {
 3400                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3401                            let emoji_shortcode_start = Point::new(
 3402                                selection.start.row,
 3403                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3404                            );
 3405
 3406                            // Remove shortcode from buffer
 3407                            edits.push((
 3408                                emoji_shortcode_start..selection.start,
 3409                                "".to_string().into(),
 3410                            ));
 3411                            new_selections.push((
 3412                                Selection {
 3413                                    id: selection.id,
 3414                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3415                                    end: snapshot.anchor_before(selection.start),
 3416                                    reversed: selection.reversed,
 3417                                    goal: selection.goal,
 3418                                },
 3419                                0,
 3420                            ));
 3421
 3422                            // Insert emoji
 3423                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3424                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3425                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3426
 3427                            continue;
 3428                        }
 3429                    }
 3430                }
 3431            }
 3432
 3433            // If not handling any auto-close operation, then just replace the selected
 3434            // text with the given input and move the selection to the end of the
 3435            // newly inserted text.
 3436            let anchor = snapshot.anchor_after(selection.end);
 3437            if !self.linked_edit_ranges.is_empty() {
 3438                let start_anchor = snapshot.anchor_before(selection.start);
 3439
 3440                let is_word_char = text.chars().next().map_or(true, |char| {
 3441                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3442                    classifier.is_word(char)
 3443                });
 3444
 3445                if is_word_char {
 3446                    if let Some(ranges) = self
 3447                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3448                    {
 3449                        for (buffer, edits) in ranges {
 3450                            linked_edits
 3451                                .entry(buffer.clone())
 3452                                .or_default()
 3453                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3454                        }
 3455                    }
 3456                }
 3457            }
 3458
 3459            new_selections.push((selection.map(|_| anchor), 0));
 3460            edits.push((selection.start..selection.end, text.clone()));
 3461        }
 3462
 3463        drop(snapshot);
 3464
 3465        self.transact(cx, |this, cx| {
 3466            this.buffer.update(cx, |buffer, cx| {
 3467                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3468            });
 3469            for (buffer, edits) in linked_edits {
 3470                buffer.update(cx, |buffer, cx| {
 3471                    let snapshot = buffer.snapshot();
 3472                    let edits = edits
 3473                        .into_iter()
 3474                        .map(|(range, text)| {
 3475                            use text::ToPoint as TP;
 3476                            let end_point = TP::to_point(&range.end, &snapshot);
 3477                            let start_point = TP::to_point(&range.start, &snapshot);
 3478                            (start_point..end_point, text)
 3479                        })
 3480                        .sorted_by_key(|(range, _)| range.start)
 3481                        .collect::<Vec<_>>();
 3482                    buffer.edit(edits, None, cx);
 3483                })
 3484            }
 3485            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3486            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3487            let snapshot = this.buffer.read(cx).read(cx);
 3488            let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
 3489                .zip(new_selection_deltas)
 3490                .map(|(selection, delta)| Selection {
 3491                    id: selection.id,
 3492                    start: selection.start + delta,
 3493                    end: selection.end + delta,
 3494                    reversed: selection.reversed,
 3495                    goal: SelectionGoal::None,
 3496                })
 3497                .collect::<Vec<_>>();
 3498
 3499            let mut i = 0;
 3500            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3501                let position = position.to_offset(&snapshot) + delta;
 3502                let start = snapshot.anchor_before(position);
 3503                let end = snapshot.anchor_after(position);
 3504                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3505                    match existing_state.range.start.cmp(&start, &snapshot) {
 3506                        Ordering::Less => i += 1,
 3507                        Ordering::Greater => break,
 3508                        Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
 3509                            Ordering::Less => i += 1,
 3510                            Ordering::Equal => break,
 3511                            Ordering::Greater => break,
 3512                        },
 3513                    }
 3514                }
 3515                this.autoclose_regions.insert(
 3516                    i,
 3517                    AutocloseRegion {
 3518                        selection_id,
 3519                        range: start..end,
 3520                        pair,
 3521                    },
 3522                );
 3523            }
 3524
 3525            drop(snapshot);
 3526            let had_active_inline_completion = this.has_active_inline_completion(cx);
 3527            this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
 3528                s.select(new_selections)
 3529            });
 3530
 3531            if !bracket_inserted {
 3532                if let Some(on_type_format_task) =
 3533                    this.trigger_on_type_formatting(text.to_string(), cx)
 3534                {
 3535                    on_type_format_task.detach_and_log_err(cx);
 3536                }
 3537            }
 3538
 3539            let editor_settings = EditorSettings::get_global(cx);
 3540            if bracket_inserted
 3541                && (editor_settings.auto_signature_help
 3542                    || editor_settings.show_signature_help_after_edits)
 3543            {
 3544                this.show_signature_help(&ShowSignatureHelp, cx);
 3545            }
 3546
 3547            let trigger_in_words = !had_active_inline_completion;
 3548            this.trigger_completion_on_input(&text, trigger_in_words, cx);
 3549            linked_editing_ranges::refresh_linked_ranges(this, cx);
 3550            this.refresh_inline_completion(true, false, cx);
 3551        });
 3552    }
 3553
 3554    fn find_possible_emoji_shortcode_at_position(
 3555        snapshot: &MultiBufferSnapshot,
 3556        position: Point,
 3557    ) -> Option<String> {
 3558        let mut chars = Vec::new();
 3559        let mut found_colon = false;
 3560        for char in snapshot.reversed_chars_at(position).take(100) {
 3561            // Found a possible emoji shortcode in the middle of the buffer
 3562            if found_colon {
 3563                if char.is_whitespace() {
 3564                    chars.reverse();
 3565                    return Some(chars.iter().collect());
 3566                }
 3567                // If the previous character is not a whitespace, we are in the middle of a word
 3568                // and we only want to complete the shortcode if the word is made up of other emojis
 3569                let mut containing_word = String::new();
 3570                for ch in snapshot
 3571                    .reversed_chars_at(position)
 3572                    .skip(chars.len() + 1)
 3573                    .take(100)
 3574                {
 3575                    if ch.is_whitespace() {
 3576                        break;
 3577                    }
 3578                    containing_word.push(ch);
 3579                }
 3580                let containing_word = containing_word.chars().rev().collect::<String>();
 3581                if util::word_consists_of_emojis(containing_word.as_str()) {
 3582                    chars.reverse();
 3583                    return Some(chars.iter().collect());
 3584                }
 3585            }
 3586
 3587            if char.is_whitespace() || !char.is_ascii() {
 3588                return None;
 3589            }
 3590            if char == ':' {
 3591                found_colon = true;
 3592            } else {
 3593                chars.push(char);
 3594            }
 3595        }
 3596        // Found a possible emoji shortcode at the beginning of the buffer
 3597        chars.reverse();
 3598        Some(chars.iter().collect())
 3599    }
 3600
 3601    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 3602        self.transact(cx, |this, cx| {
 3603            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3604                let selections = this.selections.all::<usize>(cx);
 3605                let multi_buffer = this.buffer.read(cx);
 3606                let buffer = multi_buffer.snapshot(cx);
 3607                selections
 3608                    .iter()
 3609                    .map(|selection| {
 3610                        let start_point = selection.start.to_point(&buffer);
 3611                        let mut indent =
 3612                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3613                        indent.len = cmp::min(indent.len, start_point.column);
 3614                        let start = selection.start;
 3615                        let end = selection.end;
 3616                        let selection_is_empty = start == end;
 3617                        let language_scope = buffer.language_scope_at(start);
 3618                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3619                            &language_scope
 3620                        {
 3621                            let leading_whitespace_len = buffer
 3622                                .reversed_chars_at(start)
 3623                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3624                                .map(|c| c.len_utf8())
 3625                                .sum::<usize>();
 3626
 3627                            let trailing_whitespace_len = buffer
 3628                                .chars_at(end)
 3629                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3630                                .map(|c| c.len_utf8())
 3631                                .sum::<usize>();
 3632
 3633                            let insert_extra_newline =
 3634                                language.brackets().any(|(pair, enabled)| {
 3635                                    let pair_start = pair.start.trim_end();
 3636                                    let pair_end = pair.end.trim_start();
 3637
 3638                                    enabled
 3639                                        && pair.newline
 3640                                        && buffer.contains_str_at(
 3641                                            end + trailing_whitespace_len,
 3642                                            pair_end,
 3643                                        )
 3644                                        && buffer.contains_str_at(
 3645                                            (start - leading_whitespace_len)
 3646                                                .saturating_sub(pair_start.len()),
 3647                                            pair_start,
 3648                                        )
 3649                                });
 3650
 3651                            // Comment extension on newline is allowed only for cursor selections
 3652                            let comment_delimiter = maybe!({
 3653                                if !selection_is_empty {
 3654                                    return None;
 3655                                }
 3656
 3657                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3658                                    return None;
 3659                                }
 3660
 3661                                let delimiters = language.line_comment_prefixes();
 3662                                let max_len_of_delimiter =
 3663                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3664                                let (snapshot, range) =
 3665                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3666
 3667                                let mut index_of_first_non_whitespace = 0;
 3668                                let comment_candidate = snapshot
 3669                                    .chars_for_range(range)
 3670                                    .skip_while(|c| {
 3671                                        let should_skip = c.is_whitespace();
 3672                                        if should_skip {
 3673                                            index_of_first_non_whitespace += 1;
 3674                                        }
 3675                                        should_skip
 3676                                    })
 3677                                    .take(max_len_of_delimiter)
 3678                                    .collect::<String>();
 3679                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3680                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3681                                })?;
 3682                                let cursor_is_placed_after_comment_marker =
 3683                                    index_of_first_non_whitespace + comment_prefix.len()
 3684                                        <= start_point.column as usize;
 3685                                if cursor_is_placed_after_comment_marker {
 3686                                    Some(comment_prefix.clone())
 3687                                } else {
 3688                                    None
 3689                                }
 3690                            });
 3691                            (comment_delimiter, insert_extra_newline)
 3692                        } else {
 3693                            (None, false)
 3694                        };
 3695
 3696                        let capacity_for_delimiter = comment_delimiter
 3697                            .as_deref()
 3698                            .map(str::len)
 3699                            .unwrap_or_default();
 3700                        let mut new_text =
 3701                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3702                        new_text.push('\n');
 3703                        new_text.extend(indent.chars());
 3704                        if let Some(delimiter) = &comment_delimiter {
 3705                            new_text.push_str(delimiter);
 3706                        }
 3707                        if insert_extra_newline {
 3708                            new_text = new_text.repeat(2);
 3709                        }
 3710
 3711                        let anchor = buffer.anchor_after(end);
 3712                        let new_selection = selection.map(|_| anchor);
 3713                        (
 3714                            (start..end, new_text),
 3715                            (insert_extra_newline, new_selection),
 3716                        )
 3717                    })
 3718                    .unzip()
 3719            };
 3720
 3721            this.edit_with_autoindent(edits, cx);
 3722            let buffer = this.buffer.read(cx).snapshot(cx);
 3723            let new_selections = selection_fixup_info
 3724                .into_iter()
 3725                .map(|(extra_newline_inserted, new_selection)| {
 3726                    let mut cursor = new_selection.end.to_point(&buffer);
 3727                    if extra_newline_inserted {
 3728                        cursor.row -= 1;
 3729                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3730                    }
 3731                    new_selection.map(|_| cursor)
 3732                })
 3733                .collect();
 3734
 3735            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3736            this.refresh_inline_completion(true, false, cx);
 3737        });
 3738    }
 3739
 3740    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3741        let buffer = self.buffer.read(cx);
 3742        let snapshot = buffer.snapshot(cx);
 3743
 3744        let mut edits = Vec::new();
 3745        let mut rows = Vec::new();
 3746
 3747        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3748            let cursor = selection.head();
 3749            let row = cursor.row;
 3750
 3751            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3752
 3753            let newline = "\n".to_string();
 3754            edits.push((start_of_line..start_of_line, newline));
 3755
 3756            rows.push(row + rows_inserted as u32);
 3757        }
 3758
 3759        self.transact(cx, |editor, cx| {
 3760            editor.edit(edits, cx);
 3761
 3762            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3763                let mut index = 0;
 3764                s.move_cursors_with(|map, _, _| {
 3765                    let row = rows[index];
 3766                    index += 1;
 3767
 3768                    let point = Point::new(row, 0);
 3769                    let boundary = map.next_line_boundary(point).1;
 3770                    let clipped = map.clip_point(boundary, Bias::Left);
 3771
 3772                    (clipped, SelectionGoal::None)
 3773                });
 3774            });
 3775
 3776            let mut indent_edits = Vec::new();
 3777            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3778            for row in rows {
 3779                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3780                for (row, indent) in indents {
 3781                    if indent.len == 0 {
 3782                        continue;
 3783                    }
 3784
 3785                    let text = match indent.kind {
 3786                        IndentKind::Space => " ".repeat(indent.len as usize),
 3787                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3788                    };
 3789                    let point = Point::new(row.0, 0);
 3790                    indent_edits.push((point..point, text));
 3791                }
 3792            }
 3793            editor.edit(indent_edits, cx);
 3794        });
 3795    }
 3796
 3797    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3798        let buffer = self.buffer.read(cx);
 3799        let snapshot = buffer.snapshot(cx);
 3800
 3801        let mut edits = Vec::new();
 3802        let mut rows = Vec::new();
 3803        let mut rows_inserted = 0;
 3804
 3805        for selection in self.selections.all_adjusted(cx) {
 3806            let cursor = selection.head();
 3807            let row = cursor.row;
 3808
 3809            let point = Point::new(row + 1, 0);
 3810            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3811
 3812            let newline = "\n".to_string();
 3813            edits.push((start_of_line..start_of_line, newline));
 3814
 3815            rows_inserted += 1;
 3816            rows.push(row + rows_inserted);
 3817        }
 3818
 3819        self.transact(cx, |editor, cx| {
 3820            editor.edit(edits, cx);
 3821
 3822            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3823                let mut index = 0;
 3824                s.move_cursors_with(|map, _, _| {
 3825                    let row = rows[index];
 3826                    index += 1;
 3827
 3828                    let point = Point::new(row, 0);
 3829                    let boundary = map.next_line_boundary(point).1;
 3830                    let clipped = map.clip_point(boundary, Bias::Left);
 3831
 3832                    (clipped, SelectionGoal::None)
 3833                });
 3834            });
 3835
 3836            let mut indent_edits = Vec::new();
 3837            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3838            for row in rows {
 3839                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3840                for (row, indent) in indents {
 3841                    if indent.len == 0 {
 3842                        continue;
 3843                    }
 3844
 3845                    let text = match indent.kind {
 3846                        IndentKind::Space => " ".repeat(indent.len as usize),
 3847                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3848                    };
 3849                    let point = Point::new(row.0, 0);
 3850                    indent_edits.push((point..point, text));
 3851                }
 3852            }
 3853            editor.edit(indent_edits, cx);
 3854        });
 3855    }
 3856
 3857    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3858        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3859            original_indent_columns: Vec::new(),
 3860        });
 3861        self.insert_with_autoindent_mode(text, autoindent, cx);
 3862    }
 3863
 3864    fn insert_with_autoindent_mode(
 3865        &mut self,
 3866        text: &str,
 3867        autoindent_mode: Option<AutoindentMode>,
 3868        cx: &mut ViewContext<Self>,
 3869    ) {
 3870        if self.read_only(cx) {
 3871            return;
 3872        }
 3873
 3874        let text: Arc<str> = text.into();
 3875        self.transact(cx, |this, cx| {
 3876            let old_selections = this.selections.all_adjusted(cx);
 3877            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3878                let anchors = {
 3879                    let snapshot = buffer.read(cx);
 3880                    old_selections
 3881                        .iter()
 3882                        .map(|s| {
 3883                            let anchor = snapshot.anchor_after(s.head());
 3884                            s.map(|_| anchor)
 3885                        })
 3886                        .collect::<Vec<_>>()
 3887                };
 3888                buffer.edit(
 3889                    old_selections
 3890                        .iter()
 3891                        .map(|s| (s.start..s.end, text.clone())),
 3892                    autoindent_mode,
 3893                    cx,
 3894                );
 3895                anchors
 3896            });
 3897
 3898            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3899                s.select_anchors(selection_anchors);
 3900            })
 3901        });
 3902    }
 3903
 3904    fn trigger_completion_on_input(
 3905        &mut self,
 3906        text: &str,
 3907        trigger_in_words: bool,
 3908        cx: &mut ViewContext<Self>,
 3909    ) {
 3910        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3911            self.show_completions(
 3912                &ShowCompletions {
 3913                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3914                },
 3915                cx,
 3916            );
 3917        } else {
 3918            self.hide_context_menu(cx);
 3919        }
 3920    }
 3921
 3922    fn is_completion_trigger(
 3923        &self,
 3924        text: &str,
 3925        trigger_in_words: bool,
 3926        cx: &mut ViewContext<Self>,
 3927    ) -> bool {
 3928        let position = self.selections.newest_anchor().head();
 3929        let multibuffer = self.buffer.read(cx);
 3930        let Some(buffer) = position
 3931            .buffer_id
 3932            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3933        else {
 3934            return false;
 3935        };
 3936
 3937        if let Some(completion_provider) = &self.completion_provider {
 3938            completion_provider.is_completion_trigger(
 3939                &buffer,
 3940                position.text_anchor,
 3941                text,
 3942                trigger_in_words,
 3943                cx,
 3944            )
 3945        } else {
 3946            false
 3947        }
 3948    }
 3949
 3950    /// If any empty selections is touching the start of its innermost containing autoclose
 3951    /// region, expand it to select the brackets.
 3952    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 3953        let selections = self.selections.all::<usize>(cx);
 3954        let buffer = self.buffer.read(cx).read(cx);
 3955        let new_selections = self
 3956            .selections_with_autoclose_regions(selections, &buffer)
 3957            .map(|(mut selection, region)| {
 3958                if !selection.is_empty() {
 3959                    return selection;
 3960                }
 3961
 3962                if let Some(region) = region {
 3963                    let mut range = region.range.to_offset(&buffer);
 3964                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3965                        range.start -= region.pair.start.len();
 3966                        if buffer.contains_str_at(range.start, &region.pair.start)
 3967                            && buffer.contains_str_at(range.end, &region.pair.end)
 3968                        {
 3969                            range.end += region.pair.end.len();
 3970                            selection.start = range.start;
 3971                            selection.end = range.end;
 3972
 3973                            return selection;
 3974                        }
 3975                    }
 3976                }
 3977
 3978                let always_treat_brackets_as_autoclosed = buffer
 3979                    .settings_at(selection.start, cx)
 3980                    .always_treat_brackets_as_autoclosed;
 3981
 3982                if !always_treat_brackets_as_autoclosed {
 3983                    return selection;
 3984                }
 3985
 3986                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3987                    for (pair, enabled) in scope.brackets() {
 3988                        if !enabled || !pair.close {
 3989                            continue;
 3990                        }
 3991
 3992                        if buffer.contains_str_at(selection.start, &pair.end) {
 3993                            let pair_start_len = pair.start.len();
 3994                            if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
 3995                            {
 3996                                selection.start -= pair_start_len;
 3997                                selection.end += pair.end.len();
 3998
 3999                                return selection;
 4000                            }
 4001                        }
 4002                    }
 4003                }
 4004
 4005                selection
 4006            })
 4007            .collect();
 4008
 4009        drop(buffer);
 4010        self.change_selections(None, cx, |selections| selections.select(new_selections));
 4011    }
 4012
 4013    /// Iterate the given selections, and for each one, find the smallest surrounding
 4014    /// autoclose region. This uses the ordering of the selections and the autoclose
 4015    /// regions to avoid repeated comparisons.
 4016    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 4017        &'a self,
 4018        selections: impl IntoIterator<Item = Selection<D>>,
 4019        buffer: &'a MultiBufferSnapshot,
 4020    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 4021        let mut i = 0;
 4022        let mut regions = self.autoclose_regions.as_slice();
 4023        selections.into_iter().map(move |selection| {
 4024            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 4025
 4026            let mut enclosing = None;
 4027            while let Some(pair_state) = regions.get(i) {
 4028                if pair_state.range.end.to_offset(buffer) < range.start {
 4029                    regions = &regions[i + 1..];
 4030                    i = 0;
 4031                } else if pair_state.range.start.to_offset(buffer) > range.end {
 4032                    break;
 4033                } else {
 4034                    if pair_state.selection_id == selection.id {
 4035                        enclosing = Some(pair_state);
 4036                    }
 4037                    i += 1;
 4038                }
 4039            }
 4040
 4041            (selection.clone(), enclosing)
 4042        })
 4043    }
 4044
 4045    /// Remove any autoclose regions that no longer contain their selection.
 4046    fn invalidate_autoclose_regions(
 4047        &mut self,
 4048        mut selections: &[Selection<Anchor>],
 4049        buffer: &MultiBufferSnapshot,
 4050    ) {
 4051        self.autoclose_regions.retain(|state| {
 4052            let mut i = 0;
 4053            while let Some(selection) = selections.get(i) {
 4054                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 4055                    selections = &selections[1..];
 4056                    continue;
 4057                }
 4058                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 4059                    break;
 4060                }
 4061                if selection.id == state.selection_id {
 4062                    return true;
 4063                } else {
 4064                    i += 1;
 4065                }
 4066            }
 4067            false
 4068        });
 4069    }
 4070
 4071    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 4072        let offset = position.to_offset(buffer);
 4073        let (word_range, kind) = buffer.surrounding_word(offset, true);
 4074        if offset > word_range.start && kind == Some(CharKind::Word) {
 4075            Some(
 4076                buffer
 4077                    .text_for_range(word_range.start..offset)
 4078                    .collect::<String>(),
 4079            )
 4080        } else {
 4081            None
 4082        }
 4083    }
 4084
 4085    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 4086        self.refresh_inlay_hints(
 4087            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 4088            cx,
 4089        );
 4090    }
 4091
 4092    pub fn inlay_hints_enabled(&self) -> bool {
 4093        self.inlay_hint_cache.enabled
 4094    }
 4095
 4096    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 4097        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 4098            return;
 4099        }
 4100
 4101        let reason_description = reason.description();
 4102        let ignore_debounce = matches!(
 4103            reason,
 4104            InlayHintRefreshReason::SettingsChange(_)
 4105                | InlayHintRefreshReason::Toggle(_)
 4106                | InlayHintRefreshReason::ExcerptsRemoved(_)
 4107        );
 4108        let (invalidate_cache, required_languages) = match reason {
 4109            InlayHintRefreshReason::Toggle(enabled) => {
 4110                self.inlay_hint_cache.enabled = enabled;
 4111                if enabled {
 4112                    (InvalidationStrategy::RefreshRequested, None)
 4113                } else {
 4114                    self.inlay_hint_cache.clear();
 4115                    self.splice_inlays(
 4116                        self.visible_inlay_hints(cx)
 4117                            .iter()
 4118                            .map(|inlay| inlay.id)
 4119                            .collect(),
 4120                        Vec::new(),
 4121                        cx,
 4122                    );
 4123                    return;
 4124                }
 4125            }
 4126            InlayHintRefreshReason::SettingsChange(new_settings) => {
 4127                match self.inlay_hint_cache.update_settings(
 4128                    &self.buffer,
 4129                    new_settings,
 4130                    self.visible_inlay_hints(cx),
 4131                    cx,
 4132                ) {
 4133                    ControlFlow::Break(Some(InlaySplice {
 4134                        to_remove,
 4135                        to_insert,
 4136                    })) => {
 4137                        self.splice_inlays(to_remove, to_insert, cx);
 4138                        return;
 4139                    }
 4140                    ControlFlow::Break(None) => return,
 4141                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 4142                }
 4143            }
 4144            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 4145                if let Some(InlaySplice {
 4146                    to_remove,
 4147                    to_insert,
 4148                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 4149                {
 4150                    self.splice_inlays(to_remove, to_insert, cx);
 4151                }
 4152                return;
 4153            }
 4154            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 4155            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 4156                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 4157            }
 4158            InlayHintRefreshReason::RefreshRequested => {
 4159                (InvalidationStrategy::RefreshRequested, None)
 4160            }
 4161        };
 4162
 4163        if let Some(InlaySplice {
 4164            to_remove,
 4165            to_insert,
 4166        }) = self.inlay_hint_cache.spawn_hint_refresh(
 4167            reason_description,
 4168            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 4169            invalidate_cache,
 4170            ignore_debounce,
 4171            cx,
 4172        ) {
 4173            self.splice_inlays(to_remove, to_insert, cx);
 4174        }
 4175    }
 4176
 4177    fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
 4178        self.display_map
 4179            .read(cx)
 4180            .current_inlays()
 4181            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 4182            .cloned()
 4183            .collect()
 4184    }
 4185
 4186    pub fn excerpts_for_inlay_hints_query(
 4187        &self,
 4188        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 4189        cx: &mut ViewContext<Editor>,
 4190    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 4191        let Some(project) = self.project.as_ref() else {
 4192            return HashMap::default();
 4193        };
 4194        let project = project.read(cx);
 4195        let multi_buffer = self.buffer().read(cx);
 4196        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 4197        let multi_buffer_visible_start = self
 4198            .scroll_manager
 4199            .anchor()
 4200            .anchor
 4201            .to_point(&multi_buffer_snapshot);
 4202        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 4203            multi_buffer_visible_start
 4204                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 4205            Bias::Left,
 4206        );
 4207        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 4208        multi_buffer
 4209            .range_to_buffer_ranges(multi_buffer_visible_range, cx)
 4210            .into_iter()
 4211            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 4212            .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
 4213                let buffer = buffer_handle.read(cx);
 4214                let buffer_file = project::File::from_dyn(buffer.file())?;
 4215                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 4216                let worktree_entry = buffer_worktree
 4217                    .read(cx)
 4218                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 4219                if worktree_entry.is_ignored {
 4220                    return None;
 4221                }
 4222
 4223                let language = buffer.language()?;
 4224                if let Some(restrict_to_languages) = restrict_to_languages {
 4225                    if !restrict_to_languages.contains(language) {
 4226                        return None;
 4227                    }
 4228                }
 4229                Some((
 4230                    excerpt_id,
 4231                    (
 4232                        buffer_handle,
 4233                        buffer.version().clone(),
 4234                        excerpt_visible_range,
 4235                    ),
 4236                ))
 4237            })
 4238            .collect()
 4239    }
 4240
 4241    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 4242        TextLayoutDetails {
 4243            text_system: cx.text_system().clone(),
 4244            editor_style: self.style.clone().unwrap(),
 4245            rem_size: cx.rem_size(),
 4246            scroll_anchor: self.scroll_manager.anchor(),
 4247            visible_rows: self.visible_line_count(),
 4248            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 4249        }
 4250    }
 4251
 4252    fn splice_inlays(
 4253        &self,
 4254        to_remove: Vec<InlayId>,
 4255        to_insert: Vec<Inlay>,
 4256        cx: &mut ViewContext<Self>,
 4257    ) {
 4258        self.display_map.update(cx, |display_map, cx| {
 4259            display_map.splice_inlays(to_remove, to_insert, cx);
 4260        });
 4261        cx.notify();
 4262    }
 4263
 4264    fn trigger_on_type_formatting(
 4265        &self,
 4266        input: String,
 4267        cx: &mut ViewContext<Self>,
 4268    ) -> Option<Task<Result<()>>> {
 4269        if input.len() != 1 {
 4270            return None;
 4271        }
 4272
 4273        let project = self.project.as_ref()?;
 4274        let position = self.selections.newest_anchor().head();
 4275        let (buffer, buffer_position) = self
 4276            .buffer
 4277            .read(cx)
 4278            .text_anchor_for_position(position, cx)?;
 4279
 4280        let settings = language_settings::language_settings(
 4281            buffer
 4282                .read(cx)
 4283                .language_at(buffer_position)
 4284                .map(|l| l.name()),
 4285            buffer.read(cx).file(),
 4286            cx,
 4287        );
 4288        if !settings.use_on_type_format {
 4289            return None;
 4290        }
 4291
 4292        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 4293        // hence we do LSP request & edit on host side only — add formats to host's history.
 4294        let push_to_lsp_host_history = true;
 4295        // If this is not the host, append its history with new edits.
 4296        let push_to_client_history = project.read(cx).is_via_collab();
 4297
 4298        let on_type_formatting = project.update(cx, |project, cx| {
 4299            project.on_type_format(
 4300                buffer.clone(),
 4301                buffer_position,
 4302                input,
 4303                push_to_lsp_host_history,
 4304                cx,
 4305            )
 4306        });
 4307        Some(cx.spawn(|editor, mut cx| async move {
 4308            if let Some(transaction) = on_type_formatting.await? {
 4309                if push_to_client_history {
 4310                    buffer
 4311                        .update(&mut cx, |buffer, _| {
 4312                            buffer.push_transaction(transaction, Instant::now());
 4313                        })
 4314                        .ok();
 4315                }
 4316                editor.update(&mut cx, |editor, cx| {
 4317                    editor.refresh_document_highlights(cx);
 4318                })?;
 4319            }
 4320            Ok(())
 4321        }))
 4322    }
 4323
 4324    pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
 4325        if self.pending_rename.is_some() {
 4326            return;
 4327        }
 4328
 4329        let Some(provider) = self.completion_provider.as_ref() else {
 4330            return;
 4331        };
 4332
 4333        let position = self.selections.newest_anchor().head();
 4334        let (buffer, buffer_position) =
 4335            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4336                output
 4337            } else {
 4338                return;
 4339            };
 4340
 4341        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4342        let is_followup_invoke = {
 4343            let context_menu_state = self.context_menu.read();
 4344            matches!(
 4345                context_menu_state.deref(),
 4346                Some(ContextMenu::Completions(_))
 4347            )
 4348        };
 4349        let trigger_kind = match (&options.trigger, is_followup_invoke) {
 4350            (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
 4351            (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4352                CompletionTriggerKind::TRIGGER_CHARACTER
 4353            }
 4354
 4355            _ => CompletionTriggerKind::INVOKED,
 4356        };
 4357        let completion_context = CompletionContext {
 4358            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 4359                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4360                    Some(String::from(trigger))
 4361                } else {
 4362                    None
 4363                }
 4364            }),
 4365            trigger_kind,
 4366        };
 4367        let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
 4368        let sort_completions = provider.sort_completions();
 4369
 4370        let id = post_inc(&mut self.next_completion_id);
 4371        let task = cx.spawn(|this, mut cx| {
 4372            async move {
 4373                this.update(&mut cx, |this, _| {
 4374                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4375                })?;
 4376                let completions = completions.await.log_err();
 4377                let menu = if let Some(completions) = completions {
 4378                    let mut menu = CompletionsMenu {
 4379                        id,
 4380                        sort_completions,
 4381                        initial_position: position,
 4382                        match_candidates: completions
 4383                            .iter()
 4384                            .enumerate()
 4385                            .map(|(id, completion)| {
 4386                                StringMatchCandidate::new(
 4387                                    id,
 4388                                    completion.label.text[completion.label.filter_range.clone()]
 4389                                        .into(),
 4390                                )
 4391                            })
 4392                            .collect(),
 4393                        buffer: buffer.clone(),
 4394                        completions: Arc::new(RwLock::new(completions.into())),
 4395                        matches: Vec::new().into(),
 4396                        selected_item: 0,
 4397                        scroll_handle: UniformListScrollHandle::new(),
 4398                        selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
 4399                            DebouncedDelay::new(),
 4400                        )),
 4401                    };
 4402                    menu.filter(query.as_deref(), cx.background_executor().clone())
 4403                        .await;
 4404
 4405                    if menu.matches.is_empty() {
 4406                        None
 4407                    } else {
 4408                        this.update(&mut cx, |editor, cx| {
 4409                            let completions = menu.completions.clone();
 4410                            let matches = menu.matches.clone();
 4411
 4412                            let delay_ms = EditorSettings::get_global(cx)
 4413                                .completion_documentation_secondary_query_debounce;
 4414                            let delay = Duration::from_millis(delay_ms);
 4415                            editor
 4416                                .completion_documentation_pre_resolve_debounce
 4417                                .fire_new(delay, cx, |editor, cx| {
 4418                                    CompletionsMenu::pre_resolve_completion_documentation(
 4419                                        buffer,
 4420                                        completions,
 4421                                        matches,
 4422                                        editor,
 4423                                        cx,
 4424                                    )
 4425                                });
 4426                        })
 4427                        .ok();
 4428                        Some(menu)
 4429                    }
 4430                } else {
 4431                    None
 4432                };
 4433
 4434                this.update(&mut cx, |this, cx| {
 4435                    let mut context_menu = this.context_menu.write();
 4436                    match context_menu.as_ref() {
 4437                        None => {}
 4438
 4439                        Some(ContextMenu::Completions(prev_menu)) => {
 4440                            if prev_menu.id > id {
 4441                                return;
 4442                            }
 4443                        }
 4444
 4445                        _ => return,
 4446                    }
 4447
 4448                    if this.focus_handle.is_focused(cx) && menu.is_some() {
 4449                        let menu = menu.unwrap();
 4450                        *context_menu = Some(ContextMenu::Completions(menu));
 4451                        drop(context_menu);
 4452                        this.discard_inline_completion(false, cx);
 4453                        cx.notify();
 4454                    } else if this.completion_tasks.len() <= 1 {
 4455                        // If there are no more completion tasks and the last menu was
 4456                        // empty, we should hide it. If it was already hidden, we should
 4457                        // also show the copilot completion when available.
 4458                        drop(context_menu);
 4459                        if this.hide_context_menu(cx).is_none() {
 4460                            this.update_visible_inline_completion(cx);
 4461                        }
 4462                    }
 4463                })?;
 4464
 4465                Ok::<_, anyhow::Error>(())
 4466            }
 4467            .log_err()
 4468        });
 4469
 4470        self.completion_tasks.push((id, task));
 4471    }
 4472
 4473    pub fn confirm_completion(
 4474        &mut self,
 4475        action: &ConfirmCompletion,
 4476        cx: &mut ViewContext<Self>,
 4477    ) -> Option<Task<Result<()>>> {
 4478        self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
 4479    }
 4480
 4481    pub fn compose_completion(
 4482        &mut self,
 4483        action: &ComposeCompletion,
 4484        cx: &mut ViewContext<Self>,
 4485    ) -> Option<Task<Result<()>>> {
 4486        self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
 4487    }
 4488
 4489    fn do_completion(
 4490        &mut self,
 4491        item_ix: Option<usize>,
 4492        intent: CompletionIntent,
 4493        cx: &mut ViewContext<Editor>,
 4494    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 4495        use language::ToOffset as _;
 4496
 4497        let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 4498            menu
 4499        } else {
 4500            return None;
 4501        };
 4502
 4503        let mat = completions_menu
 4504            .matches
 4505            .get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4506        let buffer_handle = completions_menu.buffer;
 4507        let completions = completions_menu.completions.read();
 4508        let completion = completions.get(mat.candidate_id)?;
 4509        cx.stop_propagation();
 4510
 4511        let snippet;
 4512        let text;
 4513
 4514        if completion.is_snippet() {
 4515            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4516            text = snippet.as_ref().unwrap().text.clone();
 4517        } else {
 4518            snippet = None;
 4519            text = completion.new_text.clone();
 4520        };
 4521        let selections = self.selections.all::<usize>(cx);
 4522        let buffer = buffer_handle.read(cx);
 4523        let old_range = completion.old_range.to_offset(buffer);
 4524        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4525
 4526        let newest_selection = self.selections.newest_anchor();
 4527        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4528            return None;
 4529        }
 4530
 4531        let lookbehind = newest_selection
 4532            .start
 4533            .text_anchor
 4534            .to_offset(buffer)
 4535            .saturating_sub(old_range.start);
 4536        let lookahead = old_range
 4537            .end
 4538            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4539        let mut common_prefix_len = old_text
 4540            .bytes()
 4541            .zip(text.bytes())
 4542            .take_while(|(a, b)| a == b)
 4543            .count();
 4544
 4545        let snapshot = self.buffer.read(cx).snapshot(cx);
 4546        let mut range_to_replace: Option<Range<isize>> = None;
 4547        let mut ranges = Vec::new();
 4548        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4549        for selection in &selections {
 4550            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4551                let start = selection.start.saturating_sub(lookbehind);
 4552                let end = selection.end + lookahead;
 4553                if selection.id == newest_selection.id {
 4554                    range_to_replace = Some(
 4555                        ((start + common_prefix_len) as isize - selection.start as isize)
 4556                            ..(end as isize - selection.start as isize),
 4557                    );
 4558                }
 4559                ranges.push(start + common_prefix_len..end);
 4560            } else {
 4561                common_prefix_len = 0;
 4562                ranges.clear();
 4563                ranges.extend(selections.iter().map(|s| {
 4564                    if s.id == newest_selection.id {
 4565                        range_to_replace = Some(
 4566                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4567                                - selection.start as isize
 4568                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4569                                    - selection.start as isize,
 4570                        );
 4571                        old_range.clone()
 4572                    } else {
 4573                        s.start..s.end
 4574                    }
 4575                }));
 4576                break;
 4577            }
 4578            if !self.linked_edit_ranges.is_empty() {
 4579                let start_anchor = snapshot.anchor_before(selection.head());
 4580                let end_anchor = snapshot.anchor_after(selection.tail());
 4581                if let Some(ranges) = self
 4582                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4583                {
 4584                    for (buffer, edits) in ranges {
 4585                        linked_edits.entry(buffer.clone()).or_default().extend(
 4586                            edits
 4587                                .into_iter()
 4588                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4589                        );
 4590                    }
 4591                }
 4592            }
 4593        }
 4594        let text = &text[common_prefix_len..];
 4595
 4596        cx.emit(EditorEvent::InputHandled {
 4597            utf16_range_to_replace: range_to_replace,
 4598            text: text.into(),
 4599        });
 4600
 4601        self.transact(cx, |this, cx| {
 4602            if let Some(mut snippet) = snippet {
 4603                snippet.text = text.to_string();
 4604                for tabstop in snippet.tabstops.iter_mut().flatten() {
 4605                    tabstop.start -= common_prefix_len as isize;
 4606                    tabstop.end -= common_prefix_len as isize;
 4607                }
 4608
 4609                this.insert_snippet(&ranges, snippet, cx).log_err();
 4610            } else {
 4611                this.buffer.update(cx, |buffer, cx| {
 4612                    buffer.edit(
 4613                        ranges.iter().map(|range| (range.clone(), text)),
 4614                        this.autoindent_mode.clone(),
 4615                        cx,
 4616                    );
 4617                });
 4618            }
 4619            for (buffer, edits) in linked_edits {
 4620                buffer.update(cx, |buffer, cx| {
 4621                    let snapshot = buffer.snapshot();
 4622                    let edits = edits
 4623                        .into_iter()
 4624                        .map(|(range, text)| {
 4625                            use text::ToPoint as TP;
 4626                            let end_point = TP::to_point(&range.end, &snapshot);
 4627                            let start_point = TP::to_point(&range.start, &snapshot);
 4628                            (start_point..end_point, text)
 4629                        })
 4630                        .sorted_by_key(|(range, _)| range.start)
 4631                        .collect::<Vec<_>>();
 4632                    buffer.edit(edits, None, cx);
 4633                })
 4634            }
 4635
 4636            this.refresh_inline_completion(true, false, cx);
 4637        });
 4638
 4639        let show_new_completions_on_confirm = completion
 4640            .confirm
 4641            .as_ref()
 4642            .map_or(false, |confirm| confirm(intent, cx));
 4643        if show_new_completions_on_confirm {
 4644            self.show_completions(&ShowCompletions { trigger: None }, cx);
 4645        }
 4646
 4647        let provider = self.completion_provider.as_ref()?;
 4648        let apply_edits = provider.apply_additional_edits_for_completion(
 4649            buffer_handle,
 4650            completion.clone(),
 4651            true,
 4652            cx,
 4653        );
 4654
 4655        let editor_settings = EditorSettings::get_global(cx);
 4656        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4657            // After the code completion is finished, users often want to know what signatures are needed.
 4658            // so we should automatically call signature_help
 4659            self.show_signature_help(&ShowSignatureHelp, cx);
 4660        }
 4661
 4662        Some(cx.foreground_executor().spawn(async move {
 4663            apply_edits.await?;
 4664            Ok(())
 4665        }))
 4666    }
 4667
 4668    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 4669        let mut context_menu = self.context_menu.write();
 4670        if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4671            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4672                // Toggle if we're selecting the same one
 4673                *context_menu = None;
 4674                cx.notify();
 4675                return;
 4676            } else {
 4677                // Otherwise, clear it and start a new one
 4678                *context_menu = None;
 4679                cx.notify();
 4680            }
 4681        }
 4682        drop(context_menu);
 4683        let snapshot = self.snapshot(cx);
 4684        let deployed_from_indicator = action.deployed_from_indicator;
 4685        let mut task = self.code_actions_task.take();
 4686        let action = action.clone();
 4687        cx.spawn(|editor, mut cx| async move {
 4688            while let Some(prev_task) = task {
 4689                prev_task.await.log_err();
 4690                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4691            }
 4692
 4693            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 4694                if editor.focus_handle.is_focused(cx) {
 4695                    let multibuffer_point = action
 4696                        .deployed_from_indicator
 4697                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4698                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4699                    let (buffer, buffer_row) = snapshot
 4700                        .buffer_snapshot
 4701                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4702                        .and_then(|(buffer_snapshot, range)| {
 4703                            editor
 4704                                .buffer
 4705                                .read(cx)
 4706                                .buffer(buffer_snapshot.remote_id())
 4707                                .map(|buffer| (buffer, range.start.row))
 4708                        })?;
 4709                    let (_, code_actions) = editor
 4710                        .available_code_actions
 4711                        .clone()
 4712                        .and_then(|(location, code_actions)| {
 4713                            let snapshot = location.buffer.read(cx).snapshot();
 4714                            let point_range = location.range.to_point(&snapshot);
 4715                            let point_range = point_range.start.row..=point_range.end.row;
 4716                            if point_range.contains(&buffer_row) {
 4717                                Some((location, code_actions))
 4718                            } else {
 4719                                None
 4720                            }
 4721                        })
 4722                        .unzip();
 4723                    let buffer_id = buffer.read(cx).remote_id();
 4724                    let tasks = editor
 4725                        .tasks
 4726                        .get(&(buffer_id, buffer_row))
 4727                        .map(|t| Arc::new(t.to_owned()));
 4728                    if tasks.is_none() && code_actions.is_none() {
 4729                        return None;
 4730                    }
 4731
 4732                    editor.completion_tasks.clear();
 4733                    editor.discard_inline_completion(false, cx);
 4734                    let task_context =
 4735                        tasks
 4736                            .as_ref()
 4737                            .zip(editor.project.clone())
 4738                            .map(|(tasks, project)| {
 4739                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4740                            });
 4741
 4742                    Some(cx.spawn(|editor, mut cx| async move {
 4743                        let task_context = match task_context {
 4744                            Some(task_context) => task_context.await,
 4745                            None => None,
 4746                        };
 4747                        let resolved_tasks =
 4748                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4749                                Arc::new(ResolvedTasks {
 4750                                    templates: tasks.resolve(&task_context).collect(),
 4751                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4752                                        multibuffer_point.row,
 4753                                        tasks.column,
 4754                                    )),
 4755                                })
 4756                            });
 4757                        let spawn_straight_away = resolved_tasks
 4758                            .as_ref()
 4759                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4760                            && code_actions
 4761                                .as_ref()
 4762                                .map_or(true, |actions| actions.is_empty());
 4763                        if let Ok(task) = editor.update(&mut cx, |editor, cx| {
 4764                            *editor.context_menu.write() =
 4765                                Some(ContextMenu::CodeActions(CodeActionsMenu {
 4766                                    buffer,
 4767                                    actions: CodeActionContents {
 4768                                        tasks: resolved_tasks,
 4769                                        actions: code_actions,
 4770                                    },
 4771                                    selected_item: Default::default(),
 4772                                    scroll_handle: UniformListScrollHandle::default(),
 4773                                    deployed_from_indicator,
 4774                                }));
 4775                            if spawn_straight_away {
 4776                                if let Some(task) = editor.confirm_code_action(
 4777                                    &ConfirmCodeAction { item_ix: Some(0) },
 4778                                    cx,
 4779                                ) {
 4780                                    cx.notify();
 4781                                    return task;
 4782                                }
 4783                            }
 4784                            cx.notify();
 4785                            Task::ready(Ok(()))
 4786                        }) {
 4787                            task.await
 4788                        } else {
 4789                            Ok(())
 4790                        }
 4791                    }))
 4792                } else {
 4793                    Some(Task::ready(Ok(())))
 4794                }
 4795            })?;
 4796            if let Some(task) = spawned_test_task {
 4797                task.await?;
 4798            }
 4799
 4800            Ok::<_, anyhow::Error>(())
 4801        })
 4802        .detach_and_log_err(cx);
 4803    }
 4804
 4805    pub fn confirm_code_action(
 4806        &mut self,
 4807        action: &ConfirmCodeAction,
 4808        cx: &mut ViewContext<Self>,
 4809    ) -> Option<Task<Result<()>>> {
 4810        let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4811            menu
 4812        } else {
 4813            return None;
 4814        };
 4815        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4816        let action = actions_menu.actions.get(action_ix)?;
 4817        let title = action.label();
 4818        let buffer = actions_menu.buffer;
 4819        let workspace = self.workspace()?;
 4820
 4821        match action {
 4822            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4823                workspace.update(cx, |workspace, cx| {
 4824                    workspace::tasks::schedule_resolved_task(
 4825                        workspace,
 4826                        task_source_kind,
 4827                        resolved_task,
 4828                        false,
 4829                        cx,
 4830                    );
 4831
 4832                    Some(Task::ready(Ok(())))
 4833                })
 4834            }
 4835            CodeActionsItem::CodeAction {
 4836                excerpt_id,
 4837                action,
 4838                provider,
 4839            } => {
 4840                let apply_code_action =
 4841                    provider.apply_code_action(buffer, action, excerpt_id, true, cx);
 4842                let workspace = workspace.downgrade();
 4843                Some(cx.spawn(|editor, cx| async move {
 4844                    let project_transaction = apply_code_action.await?;
 4845                    Self::open_project_transaction(
 4846                        &editor,
 4847                        workspace,
 4848                        project_transaction,
 4849                        title,
 4850                        cx,
 4851                    )
 4852                    .await
 4853                }))
 4854            }
 4855        }
 4856    }
 4857
 4858    pub async fn open_project_transaction(
 4859        this: &WeakView<Editor>,
 4860        workspace: WeakView<Workspace>,
 4861        transaction: ProjectTransaction,
 4862        title: String,
 4863        mut cx: AsyncWindowContext,
 4864    ) -> Result<()> {
 4865        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4866        cx.update(|cx| {
 4867            entries.sort_unstable_by_key(|(buffer, _)| {
 4868                buffer.read(cx).file().map(|f| f.path().clone())
 4869            });
 4870        })?;
 4871
 4872        // If the project transaction's edits are all contained within this editor, then
 4873        // avoid opening a new editor to display them.
 4874
 4875        if let Some((buffer, transaction)) = entries.first() {
 4876            if entries.len() == 1 {
 4877                let excerpt = this.update(&mut cx, |editor, cx| {
 4878                    editor
 4879                        .buffer()
 4880                        .read(cx)
 4881                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4882                })?;
 4883                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4884                    if excerpted_buffer == *buffer {
 4885                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4886                            let excerpt_range = excerpt_range.to_offset(buffer);
 4887                            buffer
 4888                                .edited_ranges_for_transaction::<usize>(transaction)
 4889                                .all(|range| {
 4890                                    excerpt_range.start <= range.start
 4891                                        && excerpt_range.end >= range.end
 4892                                })
 4893                        })?;
 4894
 4895                        if all_edits_within_excerpt {
 4896                            return Ok(());
 4897                        }
 4898                    }
 4899                }
 4900            }
 4901        } else {
 4902            return Ok(());
 4903        }
 4904
 4905        let mut ranges_to_highlight = Vec::new();
 4906        let excerpt_buffer = cx.new_model(|cx| {
 4907            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4908            for (buffer_handle, transaction) in &entries {
 4909                let buffer = buffer_handle.read(cx);
 4910                ranges_to_highlight.extend(
 4911                    multibuffer.push_excerpts_with_context_lines(
 4912                        buffer_handle.clone(),
 4913                        buffer
 4914                            .edited_ranges_for_transaction::<usize>(transaction)
 4915                            .collect(),
 4916                        DEFAULT_MULTIBUFFER_CONTEXT,
 4917                        cx,
 4918                    ),
 4919                );
 4920            }
 4921            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4922            multibuffer
 4923        })?;
 4924
 4925        workspace.update(&mut cx, |workspace, cx| {
 4926            let project = workspace.project().clone();
 4927            let editor =
 4928                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 4929            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 4930            editor.update(cx, |editor, cx| {
 4931                editor.highlight_background::<Self>(
 4932                    &ranges_to_highlight,
 4933                    |theme| theme.editor_highlighted_line_background,
 4934                    cx,
 4935                );
 4936            });
 4937        })?;
 4938
 4939        Ok(())
 4940    }
 4941
 4942    pub fn clear_code_action_providers(&mut self) {
 4943        self.code_action_providers.clear();
 4944        self.available_code_actions.take();
 4945    }
 4946
 4947    pub fn push_code_action_provider(
 4948        &mut self,
 4949        provider: Arc<dyn CodeActionProvider>,
 4950        cx: &mut ViewContext<Self>,
 4951    ) {
 4952        self.code_action_providers.push(provider);
 4953        self.refresh_code_actions(cx);
 4954    }
 4955
 4956    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4957        let buffer = self.buffer.read(cx);
 4958        let newest_selection = self.selections.newest_anchor().clone();
 4959        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4960        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4961        if start_buffer != end_buffer {
 4962            return None;
 4963        }
 4964
 4965        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 4966            cx.background_executor()
 4967                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4968                .await;
 4969
 4970            let (providers, tasks) = this.update(&mut cx, |this, cx| {
 4971                let providers = this.code_action_providers.clone();
 4972                let tasks = this
 4973                    .code_action_providers
 4974                    .iter()
 4975                    .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
 4976                    .collect::<Vec<_>>();
 4977                (providers, tasks)
 4978            })?;
 4979
 4980            let mut actions = Vec::new();
 4981            for (provider, provider_actions) in
 4982                providers.into_iter().zip(future::join_all(tasks).await)
 4983            {
 4984                if let Some(provider_actions) = provider_actions.log_err() {
 4985                    actions.extend(provider_actions.into_iter().map(|action| {
 4986                        AvailableCodeAction {
 4987                            excerpt_id: newest_selection.start.excerpt_id,
 4988                            action,
 4989                            provider: provider.clone(),
 4990                        }
 4991                    }));
 4992                }
 4993            }
 4994
 4995            this.update(&mut cx, |this, cx| {
 4996                this.available_code_actions = if actions.is_empty() {
 4997                    None
 4998                } else {
 4999                    Some((
 5000                        Location {
 5001                            buffer: start_buffer,
 5002                            range: start..end,
 5003                        },
 5004                        actions.into(),
 5005                    ))
 5006                };
 5007                cx.notify();
 5008            })
 5009        }));
 5010        None
 5011    }
 5012
 5013    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 5014        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 5015            self.show_git_blame_inline = false;
 5016
 5017            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 5018                cx.background_executor().timer(delay).await;
 5019
 5020                this.update(&mut cx, |this, cx| {
 5021                    this.show_git_blame_inline = true;
 5022                    cx.notify();
 5023                })
 5024                .log_err();
 5025            }));
 5026        }
 5027    }
 5028
 5029    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 5030        if self.pending_rename.is_some() {
 5031            return None;
 5032        }
 5033
 5034        let provider = self.semantics_provider.clone()?;
 5035        let buffer = self.buffer.read(cx);
 5036        let newest_selection = self.selections.newest_anchor().clone();
 5037        let cursor_position = newest_selection.head();
 5038        let (cursor_buffer, cursor_buffer_position) =
 5039            buffer.text_anchor_for_position(cursor_position, cx)?;
 5040        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 5041        if cursor_buffer != tail_buffer {
 5042            return None;
 5043        }
 5044
 5045        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 5046            cx.background_executor()
 5047                .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
 5048                .await;
 5049
 5050            let highlights = if let Some(highlights) = cx
 5051                .update(|cx| {
 5052                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 5053                })
 5054                .ok()
 5055                .flatten()
 5056            {
 5057                highlights.await.log_err()
 5058            } else {
 5059                None
 5060            };
 5061
 5062            if let Some(highlights) = highlights {
 5063                this.update(&mut cx, |this, cx| {
 5064                    if this.pending_rename.is_some() {
 5065                        return;
 5066                    }
 5067
 5068                    let buffer_id = cursor_position.buffer_id;
 5069                    let buffer = this.buffer.read(cx);
 5070                    if !buffer
 5071                        .text_anchor_for_position(cursor_position, cx)
 5072                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 5073                    {
 5074                        return;
 5075                    }
 5076
 5077                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 5078                    let mut write_ranges = Vec::new();
 5079                    let mut read_ranges = Vec::new();
 5080                    for highlight in highlights {
 5081                        for (excerpt_id, excerpt_range) in
 5082                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 5083                        {
 5084                            let start = highlight
 5085                                .range
 5086                                .start
 5087                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 5088                            let end = highlight
 5089                                .range
 5090                                .end
 5091                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 5092                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 5093                                continue;
 5094                            }
 5095
 5096                            let range = Anchor {
 5097                                buffer_id,
 5098                                excerpt_id,
 5099                                text_anchor: start,
 5100                            }..Anchor {
 5101                                buffer_id,
 5102                                excerpt_id,
 5103                                text_anchor: end,
 5104                            };
 5105                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 5106                                write_ranges.push(range);
 5107                            } else {
 5108                                read_ranges.push(range);
 5109                            }
 5110                        }
 5111                    }
 5112
 5113                    this.highlight_background::<DocumentHighlightRead>(
 5114                        &read_ranges,
 5115                        |theme| theme.editor_document_highlight_read_background,
 5116                        cx,
 5117                    );
 5118                    this.highlight_background::<DocumentHighlightWrite>(
 5119                        &write_ranges,
 5120                        |theme| theme.editor_document_highlight_write_background,
 5121                        cx,
 5122                    );
 5123                    cx.notify();
 5124                })
 5125                .log_err();
 5126            }
 5127        }));
 5128        None
 5129    }
 5130
 5131    pub fn refresh_inline_completion(
 5132        &mut self,
 5133        debounce: bool,
 5134        user_requested: bool,
 5135        cx: &mut ViewContext<Self>,
 5136    ) -> Option<()> {
 5137        let provider = self.inline_completion_provider()?;
 5138        let cursor = self.selections.newest_anchor().head();
 5139        let (buffer, cursor_buffer_position) =
 5140            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5141
 5142        if !user_requested
 5143            && (!self.enable_inline_completions
 5144                || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx))
 5145        {
 5146            self.discard_inline_completion(false, cx);
 5147            return None;
 5148        }
 5149
 5150        self.update_visible_inline_completion(cx);
 5151        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 5152        Some(())
 5153    }
 5154
 5155    fn cycle_inline_completion(
 5156        &mut self,
 5157        direction: Direction,
 5158        cx: &mut ViewContext<Self>,
 5159    ) -> Option<()> {
 5160        let provider = self.inline_completion_provider()?;
 5161        let cursor = self.selections.newest_anchor().head();
 5162        let (buffer, cursor_buffer_position) =
 5163            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5164        if !self.enable_inline_completions
 5165            || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 5166        {
 5167            return None;
 5168        }
 5169
 5170        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5171        self.update_visible_inline_completion(cx);
 5172
 5173        Some(())
 5174    }
 5175
 5176    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 5177        if !self.has_active_inline_completion(cx) {
 5178            self.refresh_inline_completion(false, true, cx);
 5179            return;
 5180        }
 5181
 5182        self.update_visible_inline_completion(cx);
 5183    }
 5184
 5185    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 5186        self.show_cursor_names(cx);
 5187    }
 5188
 5189    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 5190        self.show_cursor_names = true;
 5191        cx.notify();
 5192        cx.spawn(|this, mut cx| async move {
 5193            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5194            this.update(&mut cx, |this, cx| {
 5195                this.show_cursor_names = false;
 5196                cx.notify()
 5197            })
 5198            .ok()
 5199        })
 5200        .detach();
 5201    }
 5202
 5203    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 5204        if self.has_active_inline_completion(cx) {
 5205            self.cycle_inline_completion(Direction::Next, cx);
 5206        } else {
 5207            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5208            if is_copilot_disabled {
 5209                cx.propagate();
 5210            }
 5211        }
 5212    }
 5213
 5214    pub fn previous_inline_completion(
 5215        &mut self,
 5216        _: &PreviousInlineCompletion,
 5217        cx: &mut ViewContext<Self>,
 5218    ) {
 5219        if self.has_active_inline_completion(cx) {
 5220            self.cycle_inline_completion(Direction::Prev, cx);
 5221        } else {
 5222            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5223            if is_copilot_disabled {
 5224                cx.propagate();
 5225            }
 5226        }
 5227    }
 5228
 5229    pub fn accept_inline_completion(
 5230        &mut self,
 5231        _: &AcceptInlineCompletion,
 5232        cx: &mut ViewContext<Self>,
 5233    ) {
 5234        let Some(completion) = self.take_active_inline_completion(cx) else {
 5235            return;
 5236        };
 5237        if let Some(provider) = self.inline_completion_provider() {
 5238            provider.accept(cx);
 5239        }
 5240
 5241        cx.emit(EditorEvent::InputHandled {
 5242            utf16_range_to_replace: None,
 5243            text: completion.text.to_string().into(),
 5244        });
 5245
 5246        if let Some(range) = completion.delete_range {
 5247            self.change_selections(None, cx, |s| s.select_ranges([range]))
 5248        }
 5249        self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
 5250        self.refresh_inline_completion(true, true, cx);
 5251        cx.notify();
 5252    }
 5253
 5254    pub fn accept_partial_inline_completion(
 5255        &mut self,
 5256        _: &AcceptPartialInlineCompletion,
 5257        cx: &mut ViewContext<Self>,
 5258    ) {
 5259        if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
 5260            if let Some(completion) = self.take_active_inline_completion(cx) {
 5261                let mut partial_completion = completion
 5262                    .text
 5263                    .chars()
 5264                    .by_ref()
 5265                    .take_while(|c| c.is_alphabetic())
 5266                    .collect::<String>();
 5267                if partial_completion.is_empty() {
 5268                    partial_completion = completion
 5269                        .text
 5270                        .chars()
 5271                        .by_ref()
 5272                        .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5273                        .collect::<String>();
 5274                }
 5275
 5276                cx.emit(EditorEvent::InputHandled {
 5277                    utf16_range_to_replace: None,
 5278                    text: partial_completion.clone().into(),
 5279                });
 5280
 5281                if let Some(range) = completion.delete_range {
 5282                    self.change_selections(None, cx, |s| s.select_ranges([range]))
 5283                }
 5284                self.insert_with_autoindent_mode(&partial_completion, None, cx);
 5285
 5286                self.refresh_inline_completion(true, true, cx);
 5287                cx.notify();
 5288            }
 5289        }
 5290    }
 5291
 5292    fn discard_inline_completion(
 5293        &mut self,
 5294        should_report_inline_completion_event: bool,
 5295        cx: &mut ViewContext<Self>,
 5296    ) -> bool {
 5297        if let Some(provider) = self.inline_completion_provider() {
 5298            provider.discard(should_report_inline_completion_event, cx);
 5299        }
 5300
 5301        self.take_active_inline_completion(cx).is_some()
 5302    }
 5303
 5304    pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
 5305        if let Some(completion) = self.active_inline_completion.as_ref() {
 5306            let buffer = self.buffer.read(cx).read(cx);
 5307            completion.position.is_valid(&buffer)
 5308        } else {
 5309            false
 5310        }
 5311    }
 5312
 5313    fn take_active_inline_completion(
 5314        &mut self,
 5315        cx: &mut ViewContext<Self>,
 5316    ) -> Option<CompletionState> {
 5317        let completion = self.active_inline_completion.take()?;
 5318        let render_inlay_ids = completion.render_inlay_ids.clone();
 5319        self.display_map.update(cx, |map, cx| {
 5320            map.splice_inlays(render_inlay_ids, Default::default(), cx);
 5321        });
 5322        let buffer = self.buffer.read(cx).read(cx);
 5323
 5324        if completion.position.is_valid(&buffer) {
 5325            Some(completion)
 5326        } else {
 5327            None
 5328        }
 5329    }
 5330
 5331    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
 5332        let selection = self.selections.newest_anchor();
 5333        let cursor = selection.head();
 5334
 5335        let excerpt_id = cursor.excerpt_id;
 5336
 5337        if self.context_menu.read().is_none()
 5338            && self.completion_tasks.is_empty()
 5339            && selection.start == selection.end
 5340        {
 5341            if let Some(provider) = self.inline_completion_provider() {
 5342                if let Some((buffer, cursor_buffer_position)) =
 5343                    self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5344                {
 5345                    if let Some(proposal) =
 5346                        provider.active_completion_text(&buffer, cursor_buffer_position, cx)
 5347                    {
 5348                        let mut to_remove = Vec::new();
 5349                        if let Some(completion) = self.active_inline_completion.take() {
 5350                            to_remove.extend(completion.render_inlay_ids.iter());
 5351                        }
 5352
 5353                        let to_add = proposal
 5354                            .inlays
 5355                            .iter()
 5356                            .filter_map(|inlay| {
 5357                                let snapshot = self.buffer.read(cx).snapshot(cx);
 5358                                let id = post_inc(&mut self.next_inlay_id);
 5359                                match inlay {
 5360                                    InlayProposal::Hint(position, hint) => {
 5361                                        let position =
 5362                                            snapshot.anchor_in_excerpt(excerpt_id, *position)?;
 5363                                        Some(Inlay::hint(id, position, hint))
 5364                                    }
 5365                                    InlayProposal::Suggestion(position, text) => {
 5366                                        let position =
 5367                                            snapshot.anchor_in_excerpt(excerpt_id, *position)?;
 5368                                        Some(Inlay::suggestion(id, position, text.clone()))
 5369                                    }
 5370                                }
 5371                            })
 5372                            .collect_vec();
 5373
 5374                        self.active_inline_completion = Some(CompletionState {
 5375                            position: cursor,
 5376                            text: proposal.text,
 5377                            delete_range: proposal.delete_range.and_then(|range| {
 5378                                let snapshot = self.buffer.read(cx).snapshot(cx);
 5379                                let start = snapshot.anchor_in_excerpt(excerpt_id, range.start);
 5380                                let end = snapshot.anchor_in_excerpt(excerpt_id, range.end);
 5381                                Some(start?..end?)
 5382                            }),
 5383                            render_inlay_ids: to_add.iter().map(|i| i.id).collect(),
 5384                        });
 5385
 5386                        self.display_map
 5387                            .update(cx, move |map, cx| map.splice_inlays(to_remove, to_add, cx));
 5388
 5389                        cx.notify();
 5390                        return;
 5391                    }
 5392                }
 5393            }
 5394        }
 5395
 5396        self.discard_inline_completion(false, cx);
 5397    }
 5398
 5399    fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5400        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 5401    }
 5402
 5403    fn render_code_actions_indicator(
 5404        &self,
 5405        _style: &EditorStyle,
 5406        row: DisplayRow,
 5407        is_active: bool,
 5408        cx: &mut ViewContext<Self>,
 5409    ) -> Option<IconButton> {
 5410        if self.available_code_actions.is_some() {
 5411            Some(
 5412                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5413                    .shape(ui::IconButtonShape::Square)
 5414                    .icon_size(IconSize::XSmall)
 5415                    .icon_color(Color::Muted)
 5416                    .selected(is_active)
 5417                    .tooltip({
 5418                        let focus_handle = self.focus_handle.clone();
 5419                        move |cx| {
 5420                            Tooltip::for_action_in(
 5421                                "Toggle Code Actions",
 5422                                &ToggleCodeActions {
 5423                                    deployed_from_indicator: None,
 5424                                },
 5425                                &focus_handle,
 5426                                cx,
 5427                            )
 5428                        }
 5429                    })
 5430                    .on_click(cx.listener(move |editor, _e, cx| {
 5431                        editor.focus(cx);
 5432                        editor.toggle_code_actions(
 5433                            &ToggleCodeActions {
 5434                                deployed_from_indicator: Some(row),
 5435                            },
 5436                            cx,
 5437                        );
 5438                    })),
 5439            )
 5440        } else {
 5441            None
 5442        }
 5443    }
 5444
 5445    fn clear_tasks(&mut self) {
 5446        self.tasks.clear()
 5447    }
 5448
 5449    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5450        if self.tasks.insert(key, value).is_some() {
 5451            // This case should hopefully be rare, but just in case...
 5452            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5453        }
 5454    }
 5455
 5456    fn build_tasks_context(
 5457        project: &Model<Project>,
 5458        buffer: &Model<Buffer>,
 5459        buffer_row: u32,
 5460        tasks: &Arc<RunnableTasks>,
 5461        cx: &mut ViewContext<Self>,
 5462    ) -> Task<Option<task::TaskContext>> {
 5463        let position = Point::new(buffer_row, tasks.column);
 5464        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5465        let location = Location {
 5466            buffer: buffer.clone(),
 5467            range: range_start..range_start,
 5468        };
 5469        // Fill in the environmental variables from the tree-sitter captures
 5470        let mut captured_task_variables = TaskVariables::default();
 5471        for (capture_name, value) in tasks.extra_variables.clone() {
 5472            captured_task_variables.insert(
 5473                task::VariableName::Custom(capture_name.into()),
 5474                value.clone(),
 5475            );
 5476        }
 5477        project.update(cx, |project, cx| {
 5478            project.task_store().update(cx, |task_store, cx| {
 5479                task_store.task_context_for_location(captured_task_variables, location, cx)
 5480            })
 5481        })
 5482    }
 5483
 5484    pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
 5485        let Some((workspace, _)) = self.workspace.clone() else {
 5486            return;
 5487        };
 5488        let Some(project) = self.project.clone() else {
 5489            return;
 5490        };
 5491
 5492        // Try to find a closest, enclosing node using tree-sitter that has a
 5493        // task
 5494        let Some((buffer, buffer_row, tasks)) = self
 5495            .find_enclosing_node_task(cx)
 5496            // Or find the task that's closest in row-distance.
 5497            .or_else(|| self.find_closest_task(cx))
 5498        else {
 5499            return;
 5500        };
 5501
 5502        let reveal_strategy = action.reveal;
 5503        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5504        cx.spawn(|_, mut cx| async move {
 5505            let context = task_context.await?;
 5506            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5507
 5508            let resolved = resolved_task.resolved.as_mut()?;
 5509            resolved.reveal = reveal_strategy;
 5510
 5511            workspace
 5512                .update(&mut cx, |workspace, cx| {
 5513                    workspace::tasks::schedule_resolved_task(
 5514                        workspace,
 5515                        task_source_kind,
 5516                        resolved_task,
 5517                        false,
 5518                        cx,
 5519                    );
 5520                })
 5521                .ok()
 5522        })
 5523        .detach();
 5524    }
 5525
 5526    fn find_closest_task(
 5527        &mut self,
 5528        cx: &mut ViewContext<Self>,
 5529    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5530        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5531
 5532        let ((buffer_id, row), tasks) = self
 5533            .tasks
 5534            .iter()
 5535            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5536
 5537        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5538        let tasks = Arc::new(tasks.to_owned());
 5539        Some((buffer, *row, tasks))
 5540    }
 5541
 5542    fn find_enclosing_node_task(
 5543        &mut self,
 5544        cx: &mut ViewContext<Self>,
 5545    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5546        let snapshot = self.buffer.read(cx).snapshot(cx);
 5547        let offset = self.selections.newest::<usize>(cx).head();
 5548        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5549        let buffer_id = excerpt.buffer().remote_id();
 5550
 5551        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5552        let mut cursor = layer.node().walk();
 5553
 5554        while cursor.goto_first_child_for_byte(offset).is_some() {
 5555            if cursor.node().end_byte() == offset {
 5556                cursor.goto_next_sibling();
 5557            }
 5558        }
 5559
 5560        // Ascend to the smallest ancestor that contains the range and has a task.
 5561        loop {
 5562            let node = cursor.node();
 5563            let node_range = node.byte_range();
 5564            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5565
 5566            // Check if this node contains our offset
 5567            if node_range.start <= offset && node_range.end >= offset {
 5568                // If it contains offset, check for task
 5569                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5570                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5571                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5572                }
 5573            }
 5574
 5575            if !cursor.goto_parent() {
 5576                break;
 5577            }
 5578        }
 5579        None
 5580    }
 5581
 5582    fn render_run_indicator(
 5583        &self,
 5584        _style: &EditorStyle,
 5585        is_active: bool,
 5586        row: DisplayRow,
 5587        cx: &mut ViewContext<Self>,
 5588    ) -> IconButton {
 5589        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5590            .shape(ui::IconButtonShape::Square)
 5591            .icon_size(IconSize::XSmall)
 5592            .icon_color(Color::Muted)
 5593            .selected(is_active)
 5594            .on_click(cx.listener(move |editor, _e, cx| {
 5595                editor.focus(cx);
 5596                editor.toggle_code_actions(
 5597                    &ToggleCodeActions {
 5598                        deployed_from_indicator: Some(row),
 5599                    },
 5600                    cx,
 5601                );
 5602            }))
 5603    }
 5604
 5605    pub fn context_menu_visible(&self) -> bool {
 5606        self.context_menu
 5607            .read()
 5608            .as_ref()
 5609            .map_or(false, |menu| menu.visible())
 5610    }
 5611
 5612    fn render_context_menu(
 5613        &self,
 5614        cursor_position: DisplayPoint,
 5615        style: &EditorStyle,
 5616        max_height: Pixels,
 5617        cx: &mut ViewContext<Editor>,
 5618    ) -> Option<(ContextMenuOrigin, AnyElement)> {
 5619        self.context_menu.read().as_ref().map(|menu| {
 5620            menu.render(
 5621                cursor_position,
 5622                style,
 5623                max_height,
 5624                self.workspace.as_ref().map(|(w, _)| w.clone()),
 5625                cx,
 5626            )
 5627        })
 5628    }
 5629
 5630    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
 5631        cx.notify();
 5632        self.completion_tasks.clear();
 5633        let context_menu = self.context_menu.write().take();
 5634        if context_menu.is_some() {
 5635            self.update_visible_inline_completion(cx);
 5636        }
 5637        context_menu
 5638    }
 5639
 5640    pub fn insert_snippet(
 5641        &mut self,
 5642        insertion_ranges: &[Range<usize>],
 5643        snippet: Snippet,
 5644        cx: &mut ViewContext<Self>,
 5645    ) -> Result<()> {
 5646        struct Tabstop<T> {
 5647            is_end_tabstop: bool,
 5648            ranges: Vec<Range<T>>,
 5649        }
 5650
 5651        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5652            let snippet_text: Arc<str> = snippet.text.clone().into();
 5653            buffer.edit(
 5654                insertion_ranges
 5655                    .iter()
 5656                    .cloned()
 5657                    .map(|range| (range, snippet_text.clone())),
 5658                Some(AutoindentMode::EachLine),
 5659                cx,
 5660            );
 5661
 5662            let snapshot = &*buffer.read(cx);
 5663            let snippet = &snippet;
 5664            snippet
 5665                .tabstops
 5666                .iter()
 5667                .map(|tabstop| {
 5668                    let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
 5669                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5670                    });
 5671                    let mut tabstop_ranges = tabstop
 5672                        .iter()
 5673                        .flat_map(|tabstop_range| {
 5674                            let mut delta = 0_isize;
 5675                            insertion_ranges.iter().map(move |insertion_range| {
 5676                                let insertion_start = insertion_range.start as isize + delta;
 5677                                delta +=
 5678                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5679
 5680                                let start = ((insertion_start + tabstop_range.start) as usize)
 5681                                    .min(snapshot.len());
 5682                                let end = ((insertion_start + tabstop_range.end) as usize)
 5683                                    .min(snapshot.len());
 5684                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5685                            })
 5686                        })
 5687                        .collect::<Vec<_>>();
 5688                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5689
 5690                    Tabstop {
 5691                        is_end_tabstop,
 5692                        ranges: tabstop_ranges,
 5693                    }
 5694                })
 5695                .collect::<Vec<_>>()
 5696        });
 5697        if let Some(tabstop) = tabstops.first() {
 5698            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5699                s.select_ranges(tabstop.ranges.iter().cloned());
 5700            });
 5701
 5702            // If we're already at the last tabstop and it's at the end of the snippet,
 5703            // we're done, we don't need to keep the state around.
 5704            if !tabstop.is_end_tabstop {
 5705                let ranges = tabstops
 5706                    .into_iter()
 5707                    .map(|tabstop| tabstop.ranges)
 5708                    .collect::<Vec<_>>();
 5709                self.snippet_stack.push(SnippetState {
 5710                    active_index: 0,
 5711                    ranges,
 5712                });
 5713            }
 5714
 5715            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5716            if self.autoclose_regions.is_empty() {
 5717                let snapshot = self.buffer.read(cx).snapshot(cx);
 5718                for selection in &mut self.selections.all::<Point>(cx) {
 5719                    let selection_head = selection.head();
 5720                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5721                        continue;
 5722                    };
 5723
 5724                    let mut bracket_pair = None;
 5725                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5726                    let prev_chars = snapshot
 5727                        .reversed_chars_at(selection_head)
 5728                        .collect::<String>();
 5729                    for (pair, enabled) in scope.brackets() {
 5730                        if enabled
 5731                            && pair.close
 5732                            && prev_chars.starts_with(pair.start.as_str())
 5733                            && next_chars.starts_with(pair.end.as_str())
 5734                        {
 5735                            bracket_pair = Some(pair.clone());
 5736                            break;
 5737                        }
 5738                    }
 5739                    if let Some(pair) = bracket_pair {
 5740                        let start = snapshot.anchor_after(selection_head);
 5741                        let end = snapshot.anchor_after(selection_head);
 5742                        self.autoclose_regions.push(AutocloseRegion {
 5743                            selection_id: selection.id,
 5744                            range: start..end,
 5745                            pair,
 5746                        });
 5747                    }
 5748                }
 5749            }
 5750        }
 5751        Ok(())
 5752    }
 5753
 5754    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5755        self.move_to_snippet_tabstop(Bias::Right, cx)
 5756    }
 5757
 5758    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5759        self.move_to_snippet_tabstop(Bias::Left, cx)
 5760    }
 5761
 5762    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5763        if let Some(mut snippet) = self.snippet_stack.pop() {
 5764            match bias {
 5765                Bias::Left => {
 5766                    if snippet.active_index > 0 {
 5767                        snippet.active_index -= 1;
 5768                    } else {
 5769                        self.snippet_stack.push(snippet);
 5770                        return false;
 5771                    }
 5772                }
 5773                Bias::Right => {
 5774                    if snippet.active_index + 1 < snippet.ranges.len() {
 5775                        snippet.active_index += 1;
 5776                    } else {
 5777                        self.snippet_stack.push(snippet);
 5778                        return false;
 5779                    }
 5780                }
 5781            }
 5782            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5783                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5784                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5785                });
 5786                // If snippet state is not at the last tabstop, push it back on the stack
 5787                if snippet.active_index + 1 < snippet.ranges.len() {
 5788                    self.snippet_stack.push(snippet);
 5789                }
 5790                return true;
 5791            }
 5792        }
 5793
 5794        false
 5795    }
 5796
 5797    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 5798        self.transact(cx, |this, cx| {
 5799            this.select_all(&SelectAll, cx);
 5800            this.insert("", cx);
 5801        });
 5802    }
 5803
 5804    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 5805        self.transact(cx, |this, cx| {
 5806            this.select_autoclose_pair(cx);
 5807            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5808            if !this.linked_edit_ranges.is_empty() {
 5809                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5810                let snapshot = this.buffer.read(cx).snapshot(cx);
 5811
 5812                for selection in selections.iter() {
 5813                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5814                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 5815                    if selection_start.buffer_id != selection_end.buffer_id {
 5816                        continue;
 5817                    }
 5818                    if let Some(ranges) =
 5819                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 5820                    {
 5821                        for (buffer, entries) in ranges {
 5822                            linked_ranges.entry(buffer).or_default().extend(entries);
 5823                        }
 5824                    }
 5825                }
 5826            }
 5827
 5828            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 5829            if !this.selections.line_mode {
 5830                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 5831                for selection in &mut selections {
 5832                    if selection.is_empty() {
 5833                        let old_head = selection.head();
 5834                        let mut new_head =
 5835                            movement::left(&display_map, old_head.to_display_point(&display_map))
 5836                                .to_point(&display_map);
 5837                        if let Some((buffer, line_buffer_range)) = display_map
 5838                            .buffer_snapshot
 5839                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 5840                        {
 5841                            let indent_size =
 5842                                buffer.indent_size_for_line(line_buffer_range.start.row);
 5843                            let indent_len = match indent_size.kind {
 5844                                IndentKind::Space => {
 5845                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 5846                                }
 5847                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 5848                            };
 5849                            if old_head.column <= indent_size.len && old_head.column > 0 {
 5850                                let indent_len = indent_len.get();
 5851                                new_head = cmp::min(
 5852                                    new_head,
 5853                                    MultiBufferPoint::new(
 5854                                        old_head.row,
 5855                                        ((old_head.column - 1) / indent_len) * indent_len,
 5856                                    ),
 5857                                );
 5858                            }
 5859                        }
 5860
 5861                        selection.set_head(new_head, SelectionGoal::None);
 5862                    }
 5863                }
 5864            }
 5865
 5866            this.signature_help_state.set_backspace_pressed(true);
 5867            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5868            this.insert("", cx);
 5869            let empty_str: Arc<str> = Arc::from("");
 5870            for (buffer, edits) in linked_ranges {
 5871                let snapshot = buffer.read(cx).snapshot();
 5872                use text::ToPoint as TP;
 5873
 5874                let edits = edits
 5875                    .into_iter()
 5876                    .map(|range| {
 5877                        let end_point = TP::to_point(&range.end, &snapshot);
 5878                        let mut start_point = TP::to_point(&range.start, &snapshot);
 5879
 5880                        if end_point == start_point {
 5881                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 5882                                .saturating_sub(1);
 5883                            start_point = TP::to_point(&offset, &snapshot);
 5884                        };
 5885
 5886                        (start_point..end_point, empty_str.clone())
 5887                    })
 5888                    .sorted_by_key(|(range, _)| range.start)
 5889                    .collect::<Vec<_>>();
 5890                buffer.update(cx, |this, cx| {
 5891                    this.edit(edits, None, cx);
 5892                })
 5893            }
 5894            this.refresh_inline_completion(true, false, cx);
 5895            linked_editing_ranges::refresh_linked_ranges(this, cx);
 5896        });
 5897    }
 5898
 5899    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 5900        self.transact(cx, |this, cx| {
 5901            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5902                let line_mode = s.line_mode;
 5903                s.move_with(|map, selection| {
 5904                    if selection.is_empty() && !line_mode {
 5905                        let cursor = movement::right(map, selection.head());
 5906                        selection.end = cursor;
 5907                        selection.reversed = true;
 5908                        selection.goal = SelectionGoal::None;
 5909                    }
 5910                })
 5911            });
 5912            this.insert("", cx);
 5913            this.refresh_inline_completion(true, false, cx);
 5914        });
 5915    }
 5916
 5917    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 5918        if self.move_to_prev_snippet_tabstop(cx) {
 5919            return;
 5920        }
 5921
 5922        self.outdent(&Outdent, cx);
 5923    }
 5924
 5925    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 5926        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 5927            return;
 5928        }
 5929
 5930        let mut selections = self.selections.all_adjusted(cx);
 5931        let buffer = self.buffer.read(cx);
 5932        let snapshot = buffer.snapshot(cx);
 5933        let rows_iter = selections.iter().map(|s| s.head().row);
 5934        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 5935
 5936        let mut edits = Vec::new();
 5937        let mut prev_edited_row = 0;
 5938        let mut row_delta = 0;
 5939        for selection in &mut selections {
 5940            if selection.start.row != prev_edited_row {
 5941                row_delta = 0;
 5942            }
 5943            prev_edited_row = selection.end.row;
 5944
 5945            // If the selection is non-empty, then increase the indentation of the selected lines.
 5946            if !selection.is_empty() {
 5947                row_delta =
 5948                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5949                continue;
 5950            }
 5951
 5952            // If the selection is empty and the cursor is in the leading whitespace before the
 5953            // suggested indentation, then auto-indent the line.
 5954            let cursor = selection.head();
 5955            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 5956            if let Some(suggested_indent) =
 5957                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 5958            {
 5959                if cursor.column < suggested_indent.len
 5960                    && cursor.column <= current_indent.len
 5961                    && current_indent.len <= suggested_indent.len
 5962                {
 5963                    selection.start = Point::new(cursor.row, suggested_indent.len);
 5964                    selection.end = selection.start;
 5965                    if row_delta == 0 {
 5966                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 5967                            cursor.row,
 5968                            current_indent,
 5969                            suggested_indent,
 5970                        ));
 5971                        row_delta = suggested_indent.len - current_indent.len;
 5972                    }
 5973                    continue;
 5974                }
 5975            }
 5976
 5977            // Otherwise, insert a hard or soft tab.
 5978            let settings = buffer.settings_at(cursor, cx);
 5979            let tab_size = if settings.hard_tabs {
 5980                IndentSize::tab()
 5981            } else {
 5982                let tab_size = settings.tab_size.get();
 5983                let char_column = snapshot
 5984                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 5985                    .flat_map(str::chars)
 5986                    .count()
 5987                    + row_delta as usize;
 5988                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 5989                IndentSize::spaces(chars_to_next_tab_stop)
 5990            };
 5991            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 5992            selection.end = selection.start;
 5993            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 5994            row_delta += tab_size.len;
 5995        }
 5996
 5997        self.transact(cx, |this, cx| {
 5998            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5999            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6000            this.refresh_inline_completion(true, false, cx);
 6001        });
 6002    }
 6003
 6004    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 6005        if self.read_only(cx) {
 6006            return;
 6007        }
 6008        let mut selections = self.selections.all::<Point>(cx);
 6009        let mut prev_edited_row = 0;
 6010        let mut row_delta = 0;
 6011        let mut edits = Vec::new();
 6012        let buffer = self.buffer.read(cx);
 6013        let snapshot = buffer.snapshot(cx);
 6014        for selection in &mut selections {
 6015            if selection.start.row != prev_edited_row {
 6016                row_delta = 0;
 6017            }
 6018            prev_edited_row = selection.end.row;
 6019
 6020            row_delta =
 6021                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6022        }
 6023
 6024        self.transact(cx, |this, cx| {
 6025            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6026            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6027        });
 6028    }
 6029
 6030    fn indent_selection(
 6031        buffer: &MultiBuffer,
 6032        snapshot: &MultiBufferSnapshot,
 6033        selection: &mut Selection<Point>,
 6034        edits: &mut Vec<(Range<Point>, String)>,
 6035        delta_for_start_row: u32,
 6036        cx: &AppContext,
 6037    ) -> u32 {
 6038        let settings = buffer.settings_at(selection.start, cx);
 6039        let tab_size = settings.tab_size.get();
 6040        let indent_kind = if settings.hard_tabs {
 6041            IndentKind::Tab
 6042        } else {
 6043            IndentKind::Space
 6044        };
 6045        let mut start_row = selection.start.row;
 6046        let mut end_row = selection.end.row + 1;
 6047
 6048        // If a selection ends at the beginning of a line, don't indent
 6049        // that last line.
 6050        if selection.end.column == 0 && selection.end.row > selection.start.row {
 6051            end_row -= 1;
 6052        }
 6053
 6054        // Avoid re-indenting a row that has already been indented by a
 6055        // previous selection, but still update this selection's column
 6056        // to reflect that indentation.
 6057        if delta_for_start_row > 0 {
 6058            start_row += 1;
 6059            selection.start.column += delta_for_start_row;
 6060            if selection.end.row == selection.start.row {
 6061                selection.end.column += delta_for_start_row;
 6062            }
 6063        }
 6064
 6065        let mut delta_for_end_row = 0;
 6066        let has_multiple_rows = start_row + 1 != end_row;
 6067        for row in start_row..end_row {
 6068            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 6069            let indent_delta = match (current_indent.kind, indent_kind) {
 6070                (IndentKind::Space, IndentKind::Space) => {
 6071                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 6072                    IndentSize::spaces(columns_to_next_tab_stop)
 6073                }
 6074                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 6075                (_, IndentKind::Tab) => IndentSize::tab(),
 6076            };
 6077
 6078            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 6079                0
 6080            } else {
 6081                selection.start.column
 6082            };
 6083            let row_start = Point::new(row, start);
 6084            edits.push((
 6085                row_start..row_start,
 6086                indent_delta.chars().collect::<String>(),
 6087            ));
 6088
 6089            // Update this selection's endpoints to reflect the indentation.
 6090            if row == selection.start.row {
 6091                selection.start.column += indent_delta.len;
 6092            }
 6093            if row == selection.end.row {
 6094                selection.end.column += indent_delta.len;
 6095                delta_for_end_row = indent_delta.len;
 6096            }
 6097        }
 6098
 6099        if selection.start.row == selection.end.row {
 6100            delta_for_start_row + delta_for_end_row
 6101        } else {
 6102            delta_for_end_row
 6103        }
 6104    }
 6105
 6106    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 6107        if self.read_only(cx) {
 6108            return;
 6109        }
 6110        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6111        let selections = self.selections.all::<Point>(cx);
 6112        let mut deletion_ranges = Vec::new();
 6113        let mut last_outdent = None;
 6114        {
 6115            let buffer = self.buffer.read(cx);
 6116            let snapshot = buffer.snapshot(cx);
 6117            for selection in &selections {
 6118                let settings = buffer.settings_at(selection.start, cx);
 6119                let tab_size = settings.tab_size.get();
 6120                let mut rows = selection.spanned_rows(false, &display_map);
 6121
 6122                // Avoid re-outdenting a row that has already been outdented by a
 6123                // previous selection.
 6124                if let Some(last_row) = last_outdent {
 6125                    if last_row == rows.start {
 6126                        rows.start = rows.start.next_row();
 6127                    }
 6128                }
 6129                let has_multiple_rows = rows.len() > 1;
 6130                for row in rows.iter_rows() {
 6131                    let indent_size = snapshot.indent_size_for_line(row);
 6132                    if indent_size.len > 0 {
 6133                        let deletion_len = match indent_size.kind {
 6134                            IndentKind::Space => {
 6135                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 6136                                if columns_to_prev_tab_stop == 0 {
 6137                                    tab_size
 6138                                } else {
 6139                                    columns_to_prev_tab_stop
 6140                                }
 6141                            }
 6142                            IndentKind::Tab => 1,
 6143                        };
 6144                        let start = if has_multiple_rows
 6145                            || deletion_len > selection.start.column
 6146                            || indent_size.len < selection.start.column
 6147                        {
 6148                            0
 6149                        } else {
 6150                            selection.start.column - deletion_len
 6151                        };
 6152                        deletion_ranges.push(
 6153                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 6154                        );
 6155                        last_outdent = Some(row);
 6156                    }
 6157                }
 6158            }
 6159        }
 6160
 6161        self.transact(cx, |this, cx| {
 6162            this.buffer.update(cx, |buffer, cx| {
 6163                let empty_str: Arc<str> = Arc::default();
 6164                buffer.edit(
 6165                    deletion_ranges
 6166                        .into_iter()
 6167                        .map(|range| (range, empty_str.clone())),
 6168                    None,
 6169                    cx,
 6170                );
 6171            });
 6172            let selections = this.selections.all::<usize>(cx);
 6173            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6174        });
 6175    }
 6176
 6177    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 6178        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6179        let selections = self.selections.all::<Point>(cx);
 6180
 6181        let mut new_cursors = Vec::new();
 6182        let mut edit_ranges = Vec::new();
 6183        let mut selections = selections.iter().peekable();
 6184        while let Some(selection) = selections.next() {
 6185            let mut rows = selection.spanned_rows(false, &display_map);
 6186            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6187
 6188            // Accumulate contiguous regions of rows that we want to delete.
 6189            while let Some(next_selection) = selections.peek() {
 6190                let next_rows = next_selection.spanned_rows(false, &display_map);
 6191                if next_rows.start <= rows.end {
 6192                    rows.end = next_rows.end;
 6193                    selections.next().unwrap();
 6194                } else {
 6195                    break;
 6196                }
 6197            }
 6198
 6199            let buffer = &display_map.buffer_snapshot;
 6200            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6201            let edit_end;
 6202            let cursor_buffer_row;
 6203            if buffer.max_point().row >= rows.end.0 {
 6204                // If there's a line after the range, delete the \n from the end of the row range
 6205                // and position the cursor on the next line.
 6206                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6207                cursor_buffer_row = rows.end;
 6208            } else {
 6209                // If there isn't a line after the range, delete the \n from the line before the
 6210                // start of the row range and position the cursor there.
 6211                edit_start = edit_start.saturating_sub(1);
 6212                edit_end = buffer.len();
 6213                cursor_buffer_row = rows.start.previous_row();
 6214            }
 6215
 6216            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6217            *cursor.column_mut() =
 6218                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6219
 6220            new_cursors.push((
 6221                selection.id,
 6222                buffer.anchor_after(cursor.to_point(&display_map)),
 6223            ));
 6224            edit_ranges.push(edit_start..edit_end);
 6225        }
 6226
 6227        self.transact(cx, |this, cx| {
 6228            let buffer = this.buffer.update(cx, |buffer, cx| {
 6229                let empty_str: Arc<str> = Arc::default();
 6230                buffer.edit(
 6231                    edit_ranges
 6232                        .into_iter()
 6233                        .map(|range| (range, empty_str.clone())),
 6234                    None,
 6235                    cx,
 6236                );
 6237                buffer.snapshot(cx)
 6238            });
 6239            let new_selections = new_cursors
 6240                .into_iter()
 6241                .map(|(id, cursor)| {
 6242                    let cursor = cursor.to_point(&buffer);
 6243                    Selection {
 6244                        id,
 6245                        start: cursor,
 6246                        end: cursor,
 6247                        reversed: false,
 6248                        goal: SelectionGoal::None,
 6249                    }
 6250                })
 6251                .collect();
 6252
 6253            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6254                s.select(new_selections);
 6255            });
 6256        });
 6257    }
 6258
 6259    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 6260        if self.read_only(cx) {
 6261            return;
 6262        }
 6263        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6264        for selection in self.selections.all::<Point>(cx) {
 6265            let start = MultiBufferRow(selection.start.row);
 6266            let end = if selection.start.row == selection.end.row {
 6267                MultiBufferRow(selection.start.row + 1)
 6268            } else {
 6269                MultiBufferRow(selection.end.row)
 6270            };
 6271
 6272            if let Some(last_row_range) = row_ranges.last_mut() {
 6273                if start <= last_row_range.end {
 6274                    last_row_range.end = end;
 6275                    continue;
 6276                }
 6277            }
 6278            row_ranges.push(start..end);
 6279        }
 6280
 6281        let snapshot = self.buffer.read(cx).snapshot(cx);
 6282        let mut cursor_positions = Vec::new();
 6283        for row_range in &row_ranges {
 6284            let anchor = snapshot.anchor_before(Point::new(
 6285                row_range.end.previous_row().0,
 6286                snapshot.line_len(row_range.end.previous_row()),
 6287            ));
 6288            cursor_positions.push(anchor..anchor);
 6289        }
 6290
 6291        self.transact(cx, |this, cx| {
 6292            for row_range in row_ranges.into_iter().rev() {
 6293                for row in row_range.iter_rows().rev() {
 6294                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6295                    let next_line_row = row.next_row();
 6296                    let indent = snapshot.indent_size_for_line(next_line_row);
 6297                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 6298
 6299                    let replace = if snapshot.line_len(next_line_row) > indent.len {
 6300                        " "
 6301                    } else {
 6302                        ""
 6303                    };
 6304
 6305                    this.buffer.update(cx, |buffer, cx| {
 6306                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6307                    });
 6308                }
 6309            }
 6310
 6311            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6312                s.select_anchor_ranges(cursor_positions)
 6313            });
 6314        });
 6315    }
 6316
 6317    pub fn sort_lines_case_sensitive(
 6318        &mut self,
 6319        _: &SortLinesCaseSensitive,
 6320        cx: &mut ViewContext<Self>,
 6321    ) {
 6322        self.manipulate_lines(cx, |lines| lines.sort())
 6323    }
 6324
 6325    pub fn sort_lines_case_insensitive(
 6326        &mut self,
 6327        _: &SortLinesCaseInsensitive,
 6328        cx: &mut ViewContext<Self>,
 6329    ) {
 6330        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 6331    }
 6332
 6333    pub fn unique_lines_case_insensitive(
 6334        &mut self,
 6335        _: &UniqueLinesCaseInsensitive,
 6336        cx: &mut ViewContext<Self>,
 6337    ) {
 6338        self.manipulate_lines(cx, |lines| {
 6339            let mut seen = HashSet::default();
 6340            lines.retain(|line| seen.insert(line.to_lowercase()));
 6341        })
 6342    }
 6343
 6344    pub fn unique_lines_case_sensitive(
 6345        &mut self,
 6346        _: &UniqueLinesCaseSensitive,
 6347        cx: &mut ViewContext<Self>,
 6348    ) {
 6349        self.manipulate_lines(cx, |lines| {
 6350            let mut seen = HashSet::default();
 6351            lines.retain(|line| seen.insert(*line));
 6352        })
 6353    }
 6354
 6355    pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
 6356        let mut revert_changes = HashMap::default();
 6357        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 6358        for hunk in hunks_for_rows(
 6359            Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
 6360            &multi_buffer_snapshot,
 6361        ) {
 6362            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 6363        }
 6364        if !revert_changes.is_empty() {
 6365            self.transact(cx, |editor, cx| {
 6366                editor.revert(revert_changes, cx);
 6367            });
 6368        }
 6369    }
 6370
 6371    pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
 6372        let Some(project) = self.project.clone() else {
 6373            return;
 6374        };
 6375        self.reload(project, cx).detach_and_notify_err(cx);
 6376    }
 6377
 6378    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 6379        let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
 6380        if !revert_changes.is_empty() {
 6381            self.transact(cx, |editor, cx| {
 6382                editor.revert(revert_changes, cx);
 6383            });
 6384        }
 6385    }
 6386
 6387    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 6388        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6389            let project_path = buffer.read(cx).project_path(cx)?;
 6390            let project = self.project.as_ref()?.read(cx);
 6391            let entry = project.entry_for_path(&project_path, cx)?;
 6392            let parent = match &entry.canonical_path {
 6393                Some(canonical_path) => canonical_path.to_path_buf(),
 6394                None => project.absolute_path(&project_path, cx)?,
 6395            }
 6396            .parent()?
 6397            .to_path_buf();
 6398            Some(parent)
 6399        }) {
 6400            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 6401        }
 6402    }
 6403
 6404    fn gather_revert_changes(
 6405        &mut self,
 6406        selections: &[Selection<Anchor>],
 6407        cx: &mut ViewContext<'_, Editor>,
 6408    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 6409        let mut revert_changes = HashMap::default();
 6410        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 6411        for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
 6412            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 6413        }
 6414        revert_changes
 6415    }
 6416
 6417    pub fn prepare_revert_change(
 6418        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6419        multi_buffer: &Model<MultiBuffer>,
 6420        hunk: &MultiBufferDiffHunk,
 6421        cx: &AppContext,
 6422    ) -> Option<()> {
 6423        let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
 6424        let buffer = buffer.read(cx);
 6425        let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
 6426        let buffer_snapshot = buffer.snapshot();
 6427        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6428        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6429            probe
 6430                .0
 6431                .start
 6432                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6433                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6434        }) {
 6435            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6436            Some(())
 6437        } else {
 6438            None
 6439        }
 6440    }
 6441
 6442    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 6443        self.manipulate_lines(cx, |lines| lines.reverse())
 6444    }
 6445
 6446    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 6447        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 6448    }
 6449
 6450    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6451    where
 6452        Fn: FnMut(&mut Vec<&str>),
 6453    {
 6454        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6455        let buffer = self.buffer.read(cx).snapshot(cx);
 6456
 6457        let mut edits = Vec::new();
 6458
 6459        let selections = self.selections.all::<Point>(cx);
 6460        let mut selections = selections.iter().peekable();
 6461        let mut contiguous_row_selections = Vec::new();
 6462        let mut new_selections = Vec::new();
 6463        let mut added_lines = 0;
 6464        let mut removed_lines = 0;
 6465
 6466        while let Some(selection) = selections.next() {
 6467            let (start_row, end_row) = consume_contiguous_rows(
 6468                &mut contiguous_row_selections,
 6469                selection,
 6470                &display_map,
 6471                &mut selections,
 6472            );
 6473
 6474            let start_point = Point::new(start_row.0, 0);
 6475            let end_point = Point::new(
 6476                end_row.previous_row().0,
 6477                buffer.line_len(end_row.previous_row()),
 6478            );
 6479            let text = buffer
 6480                .text_for_range(start_point..end_point)
 6481                .collect::<String>();
 6482
 6483            let mut lines = text.split('\n').collect_vec();
 6484
 6485            let lines_before = lines.len();
 6486            callback(&mut lines);
 6487            let lines_after = lines.len();
 6488
 6489            edits.push((start_point..end_point, lines.join("\n")));
 6490
 6491            // Selections must change based on added and removed line count
 6492            let start_row =
 6493                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6494            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6495            new_selections.push(Selection {
 6496                id: selection.id,
 6497                start: start_row,
 6498                end: end_row,
 6499                goal: SelectionGoal::None,
 6500                reversed: selection.reversed,
 6501            });
 6502
 6503            if lines_after > lines_before {
 6504                added_lines += lines_after - lines_before;
 6505            } else if lines_before > lines_after {
 6506                removed_lines += lines_before - lines_after;
 6507            }
 6508        }
 6509
 6510        self.transact(cx, |this, cx| {
 6511            let buffer = this.buffer.update(cx, |buffer, cx| {
 6512                buffer.edit(edits, None, cx);
 6513                buffer.snapshot(cx)
 6514            });
 6515
 6516            // Recalculate offsets on newly edited buffer
 6517            let new_selections = new_selections
 6518                .iter()
 6519                .map(|s| {
 6520                    let start_point = Point::new(s.start.0, 0);
 6521                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6522                    Selection {
 6523                        id: s.id,
 6524                        start: buffer.point_to_offset(start_point),
 6525                        end: buffer.point_to_offset(end_point),
 6526                        goal: s.goal,
 6527                        reversed: s.reversed,
 6528                    }
 6529                })
 6530                .collect();
 6531
 6532            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6533                s.select(new_selections);
 6534            });
 6535
 6536            this.request_autoscroll(Autoscroll::fit(), cx);
 6537        });
 6538    }
 6539
 6540    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 6541        self.manipulate_text(cx, |text| text.to_uppercase())
 6542    }
 6543
 6544    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 6545        self.manipulate_text(cx, |text| text.to_lowercase())
 6546    }
 6547
 6548    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 6549        self.manipulate_text(cx, |text| {
 6550            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6551            // https://github.com/rutrum/convert-case/issues/16
 6552            text.split('\n')
 6553                .map(|line| line.to_case(Case::Title))
 6554                .join("\n")
 6555        })
 6556    }
 6557
 6558    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6559        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6560    }
 6561
 6562    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6563        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6564    }
 6565
 6566    pub fn convert_to_upper_camel_case(
 6567        &mut self,
 6568        _: &ConvertToUpperCamelCase,
 6569        cx: &mut ViewContext<Self>,
 6570    ) {
 6571        self.manipulate_text(cx, |text| {
 6572            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6573            // https://github.com/rutrum/convert-case/issues/16
 6574            text.split('\n')
 6575                .map(|line| line.to_case(Case::UpperCamel))
 6576                .join("\n")
 6577        })
 6578    }
 6579
 6580    pub fn convert_to_lower_camel_case(
 6581        &mut self,
 6582        _: &ConvertToLowerCamelCase,
 6583        cx: &mut ViewContext<Self>,
 6584    ) {
 6585        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6586    }
 6587
 6588    pub fn convert_to_opposite_case(
 6589        &mut self,
 6590        _: &ConvertToOppositeCase,
 6591        cx: &mut ViewContext<Self>,
 6592    ) {
 6593        self.manipulate_text(cx, |text| {
 6594            text.chars()
 6595                .fold(String::with_capacity(text.len()), |mut t, c| {
 6596                    if c.is_uppercase() {
 6597                        t.extend(c.to_lowercase());
 6598                    } else {
 6599                        t.extend(c.to_uppercase());
 6600                    }
 6601                    t
 6602                })
 6603        })
 6604    }
 6605
 6606    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6607    where
 6608        Fn: FnMut(&str) -> String,
 6609    {
 6610        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6611        let buffer = self.buffer.read(cx).snapshot(cx);
 6612
 6613        let mut new_selections = Vec::new();
 6614        let mut edits = Vec::new();
 6615        let mut selection_adjustment = 0i32;
 6616
 6617        for selection in self.selections.all::<usize>(cx) {
 6618            let selection_is_empty = selection.is_empty();
 6619
 6620            let (start, end) = if selection_is_empty {
 6621                let word_range = movement::surrounding_word(
 6622                    &display_map,
 6623                    selection.start.to_display_point(&display_map),
 6624                );
 6625                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6626                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6627                (start, end)
 6628            } else {
 6629                (selection.start, selection.end)
 6630            };
 6631
 6632            let text = buffer.text_for_range(start..end).collect::<String>();
 6633            let old_length = text.len() as i32;
 6634            let text = callback(&text);
 6635
 6636            new_selections.push(Selection {
 6637                start: (start as i32 - selection_adjustment) as usize,
 6638                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6639                goal: SelectionGoal::None,
 6640                ..selection
 6641            });
 6642
 6643            selection_adjustment += old_length - text.len() as i32;
 6644
 6645            edits.push((start..end, text));
 6646        }
 6647
 6648        self.transact(cx, |this, cx| {
 6649            this.buffer.update(cx, |buffer, cx| {
 6650                buffer.edit(edits, None, cx);
 6651            });
 6652
 6653            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6654                s.select(new_selections);
 6655            });
 6656
 6657            this.request_autoscroll(Autoscroll::fit(), cx);
 6658        });
 6659    }
 6660
 6661    pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
 6662        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6663        let buffer = &display_map.buffer_snapshot;
 6664        let selections = self.selections.all::<Point>(cx);
 6665
 6666        let mut edits = Vec::new();
 6667        let mut selections_iter = selections.iter().peekable();
 6668        while let Some(selection) = selections_iter.next() {
 6669            // Avoid duplicating the same lines twice.
 6670            let mut rows = selection.spanned_rows(false, &display_map);
 6671
 6672            while let Some(next_selection) = selections_iter.peek() {
 6673                let next_rows = next_selection.spanned_rows(false, &display_map);
 6674                if next_rows.start < rows.end {
 6675                    rows.end = next_rows.end;
 6676                    selections_iter.next().unwrap();
 6677                } else {
 6678                    break;
 6679                }
 6680            }
 6681
 6682            // Copy the text from the selected row region and splice it either at the start
 6683            // or end of the region.
 6684            let start = Point::new(rows.start.0, 0);
 6685            let end = Point::new(
 6686                rows.end.previous_row().0,
 6687                buffer.line_len(rows.end.previous_row()),
 6688            );
 6689            let text = buffer
 6690                .text_for_range(start..end)
 6691                .chain(Some("\n"))
 6692                .collect::<String>();
 6693            let insert_location = if upwards {
 6694                Point::new(rows.end.0, 0)
 6695            } else {
 6696                start
 6697            };
 6698            edits.push((insert_location..insert_location, text));
 6699        }
 6700
 6701        self.transact(cx, |this, cx| {
 6702            this.buffer.update(cx, |buffer, cx| {
 6703                buffer.edit(edits, None, cx);
 6704            });
 6705
 6706            this.request_autoscroll(Autoscroll::fit(), cx);
 6707        });
 6708    }
 6709
 6710    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6711        self.duplicate_line(true, cx);
 6712    }
 6713
 6714    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6715        self.duplicate_line(false, cx);
 6716    }
 6717
 6718    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6719        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6720        let buffer = self.buffer.read(cx).snapshot(cx);
 6721
 6722        let mut edits = Vec::new();
 6723        let mut unfold_ranges = Vec::new();
 6724        let mut refold_ranges = Vec::new();
 6725
 6726        let selections = self.selections.all::<Point>(cx);
 6727        let mut selections = selections.iter().peekable();
 6728        let mut contiguous_row_selections = Vec::new();
 6729        let mut new_selections = Vec::new();
 6730
 6731        while let Some(selection) = selections.next() {
 6732            // Find all the selections that span a contiguous row range
 6733            let (start_row, end_row) = consume_contiguous_rows(
 6734                &mut contiguous_row_selections,
 6735                selection,
 6736                &display_map,
 6737                &mut selections,
 6738            );
 6739
 6740            // Move the text spanned by the row range to be before the line preceding the row range
 6741            if start_row.0 > 0 {
 6742                let range_to_move = Point::new(
 6743                    start_row.previous_row().0,
 6744                    buffer.line_len(start_row.previous_row()),
 6745                )
 6746                    ..Point::new(
 6747                        end_row.previous_row().0,
 6748                        buffer.line_len(end_row.previous_row()),
 6749                    );
 6750                let insertion_point = display_map
 6751                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6752                    .0;
 6753
 6754                // Don't move lines across excerpts
 6755                if buffer
 6756                    .excerpt_boundaries_in_range((
 6757                        Bound::Excluded(insertion_point),
 6758                        Bound::Included(range_to_move.end),
 6759                    ))
 6760                    .next()
 6761                    .is_none()
 6762                {
 6763                    let text = buffer
 6764                        .text_for_range(range_to_move.clone())
 6765                        .flat_map(|s| s.chars())
 6766                        .skip(1)
 6767                        .chain(['\n'])
 6768                        .collect::<String>();
 6769
 6770                    edits.push((
 6771                        buffer.anchor_after(range_to_move.start)
 6772                            ..buffer.anchor_before(range_to_move.end),
 6773                        String::new(),
 6774                    ));
 6775                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6776                    edits.push((insertion_anchor..insertion_anchor, text));
 6777
 6778                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6779
 6780                    // Move selections up
 6781                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6782                        |mut selection| {
 6783                            selection.start.row -= row_delta;
 6784                            selection.end.row -= row_delta;
 6785                            selection
 6786                        },
 6787                    ));
 6788
 6789                    // Move folds up
 6790                    unfold_ranges.push(range_to_move.clone());
 6791                    for fold in display_map.folds_in_range(
 6792                        buffer.anchor_before(range_to_move.start)
 6793                            ..buffer.anchor_after(range_to_move.end),
 6794                    ) {
 6795                        let mut start = fold.range.start.to_point(&buffer);
 6796                        let mut end = fold.range.end.to_point(&buffer);
 6797                        start.row -= row_delta;
 6798                        end.row -= row_delta;
 6799                        refold_ranges.push((start..end, fold.placeholder.clone()));
 6800                    }
 6801                }
 6802            }
 6803
 6804            // If we didn't move line(s), preserve the existing selections
 6805            new_selections.append(&mut contiguous_row_selections);
 6806        }
 6807
 6808        self.transact(cx, |this, cx| {
 6809            this.unfold_ranges(unfold_ranges, true, true, cx);
 6810            this.buffer.update(cx, |buffer, cx| {
 6811                for (range, text) in edits {
 6812                    buffer.edit([(range, text)], None, cx);
 6813                }
 6814            });
 6815            this.fold_ranges(refold_ranges, true, cx);
 6816            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6817                s.select(new_selections);
 6818            })
 6819        });
 6820    }
 6821
 6822    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 6823        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6824        let buffer = self.buffer.read(cx).snapshot(cx);
 6825
 6826        let mut edits = Vec::new();
 6827        let mut unfold_ranges = Vec::new();
 6828        let mut refold_ranges = Vec::new();
 6829
 6830        let selections = self.selections.all::<Point>(cx);
 6831        let mut selections = selections.iter().peekable();
 6832        let mut contiguous_row_selections = Vec::new();
 6833        let mut new_selections = Vec::new();
 6834
 6835        while let Some(selection) = selections.next() {
 6836            // Find all the selections that span a contiguous row range
 6837            let (start_row, end_row) = consume_contiguous_rows(
 6838                &mut contiguous_row_selections,
 6839                selection,
 6840                &display_map,
 6841                &mut selections,
 6842            );
 6843
 6844            // Move the text spanned by the row range to be after the last line of the row range
 6845            if end_row.0 <= buffer.max_point().row {
 6846                let range_to_move =
 6847                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 6848                let insertion_point = display_map
 6849                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 6850                    .0;
 6851
 6852                // Don't move lines across excerpt boundaries
 6853                if buffer
 6854                    .excerpt_boundaries_in_range((
 6855                        Bound::Excluded(range_to_move.start),
 6856                        Bound::Included(insertion_point),
 6857                    ))
 6858                    .next()
 6859                    .is_none()
 6860                {
 6861                    let mut text = String::from("\n");
 6862                    text.extend(buffer.text_for_range(range_to_move.clone()));
 6863                    text.pop(); // Drop trailing newline
 6864                    edits.push((
 6865                        buffer.anchor_after(range_to_move.start)
 6866                            ..buffer.anchor_before(range_to_move.end),
 6867                        String::new(),
 6868                    ));
 6869                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6870                    edits.push((insertion_anchor..insertion_anchor, text));
 6871
 6872                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 6873
 6874                    // Move selections down
 6875                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6876                        |mut selection| {
 6877                            selection.start.row += row_delta;
 6878                            selection.end.row += row_delta;
 6879                            selection
 6880                        },
 6881                    ));
 6882
 6883                    // Move folds down
 6884                    unfold_ranges.push(range_to_move.clone());
 6885                    for fold in display_map.folds_in_range(
 6886                        buffer.anchor_before(range_to_move.start)
 6887                            ..buffer.anchor_after(range_to_move.end),
 6888                    ) {
 6889                        let mut start = fold.range.start.to_point(&buffer);
 6890                        let mut end = fold.range.end.to_point(&buffer);
 6891                        start.row += row_delta;
 6892                        end.row += row_delta;
 6893                        refold_ranges.push((start..end, fold.placeholder.clone()));
 6894                    }
 6895                }
 6896            }
 6897
 6898            // If we didn't move line(s), preserve the existing selections
 6899            new_selections.append(&mut contiguous_row_selections);
 6900        }
 6901
 6902        self.transact(cx, |this, cx| {
 6903            this.unfold_ranges(unfold_ranges, true, true, cx);
 6904            this.buffer.update(cx, |buffer, cx| {
 6905                for (range, text) in edits {
 6906                    buffer.edit([(range, text)], None, cx);
 6907                }
 6908            });
 6909            this.fold_ranges(refold_ranges, true, cx);
 6910            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 6911        });
 6912    }
 6913
 6914    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 6915        let text_layout_details = &self.text_layout_details(cx);
 6916        self.transact(cx, |this, cx| {
 6917            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6918                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 6919                let line_mode = s.line_mode;
 6920                s.move_with(|display_map, selection| {
 6921                    if !selection.is_empty() || line_mode {
 6922                        return;
 6923                    }
 6924
 6925                    let mut head = selection.head();
 6926                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 6927                    if head.column() == display_map.line_len(head.row()) {
 6928                        transpose_offset = display_map
 6929                            .buffer_snapshot
 6930                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6931                    }
 6932
 6933                    if transpose_offset == 0 {
 6934                        return;
 6935                    }
 6936
 6937                    *head.column_mut() += 1;
 6938                    head = display_map.clip_point(head, Bias::Right);
 6939                    let goal = SelectionGoal::HorizontalPosition(
 6940                        display_map
 6941                            .x_for_display_point(head, text_layout_details)
 6942                            .into(),
 6943                    );
 6944                    selection.collapse_to(head, goal);
 6945
 6946                    let transpose_start = display_map
 6947                        .buffer_snapshot
 6948                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6949                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 6950                        let transpose_end = display_map
 6951                            .buffer_snapshot
 6952                            .clip_offset(transpose_offset + 1, Bias::Right);
 6953                        if let Some(ch) =
 6954                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 6955                        {
 6956                            edits.push((transpose_start..transpose_offset, String::new()));
 6957                            edits.push((transpose_end..transpose_end, ch.to_string()));
 6958                        }
 6959                    }
 6960                });
 6961                edits
 6962            });
 6963            this.buffer
 6964                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6965            let selections = this.selections.all::<usize>(cx);
 6966            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6967                s.select(selections);
 6968            });
 6969        });
 6970    }
 6971
 6972    pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
 6973        self.rewrap_impl(true, cx)
 6974    }
 6975
 6976    pub fn rewrap_impl(&mut self, only_text: bool, cx: &mut ViewContext<Self>) {
 6977        let buffer = self.buffer.read(cx).snapshot(cx);
 6978        let selections = self.selections.all::<Point>(cx);
 6979        let mut selections = selections.iter().peekable();
 6980
 6981        let mut edits = Vec::new();
 6982        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 6983
 6984        while let Some(selection) = selections.next() {
 6985            let mut start_row = selection.start.row;
 6986            let mut end_row = selection.end.row;
 6987
 6988            // Skip selections that overlap with a range that has already been rewrapped.
 6989            let selection_range = start_row..end_row;
 6990            if rewrapped_row_ranges
 6991                .iter()
 6992                .any(|range| range.overlaps(&selection_range))
 6993            {
 6994                continue;
 6995            }
 6996
 6997            let mut should_rewrap = !only_text;
 6998
 6999            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 7000                match language_scope.language_name().0.as_ref() {
 7001                    "Markdown" | "Plain Text" => {
 7002                        should_rewrap = true;
 7003                    }
 7004                    _ => {}
 7005                }
 7006            }
 7007
 7008            // Since not all lines in the selection may be at the same indent
 7009            // level, choose the indent size that is the most common between all
 7010            // of the lines.
 7011            //
 7012            // If there is a tie, we use the deepest indent.
 7013            let (indent_size, indent_end) = {
 7014                let mut indent_size_occurrences = HashMap::default();
 7015                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 7016
 7017                for row in start_row..=end_row {
 7018                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 7019                    rows_by_indent_size.entry(indent).or_default().push(row);
 7020                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 7021                }
 7022
 7023                let indent_size = indent_size_occurrences
 7024                    .into_iter()
 7025                    .max_by_key(|(indent, count)| (*count, indent.len))
 7026                    .map(|(indent, _)| indent)
 7027                    .unwrap_or_default();
 7028                let row = rows_by_indent_size[&indent_size][0];
 7029                let indent_end = Point::new(row, indent_size.len);
 7030
 7031                (indent_size, indent_end)
 7032            };
 7033
 7034            let mut line_prefix = indent_size.chars().collect::<String>();
 7035
 7036            if let Some(comment_prefix) =
 7037                buffer
 7038                    .language_scope_at(selection.head())
 7039                    .and_then(|language| {
 7040                        language
 7041                            .line_comment_prefixes()
 7042                            .iter()
 7043                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 7044                            .cloned()
 7045                    })
 7046            {
 7047                line_prefix.push_str(&comment_prefix);
 7048                should_rewrap = true;
 7049            }
 7050
 7051            if selection.is_empty() {
 7052                'expand_upwards: while start_row > 0 {
 7053                    let prev_row = start_row - 1;
 7054                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 7055                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 7056                    {
 7057                        start_row = prev_row;
 7058                    } else {
 7059                        break 'expand_upwards;
 7060                    }
 7061                }
 7062
 7063                'expand_downwards: while end_row < buffer.max_point().row {
 7064                    let next_row = end_row + 1;
 7065                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 7066                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 7067                    {
 7068                        end_row = next_row;
 7069                    } else {
 7070                        break 'expand_downwards;
 7071                    }
 7072                }
 7073            }
 7074
 7075            if !should_rewrap {
 7076                continue;
 7077            }
 7078
 7079            let start = Point::new(start_row, 0);
 7080            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 7081            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 7082            let Some(lines_without_prefixes) = selection_text
 7083                .lines()
 7084                .map(|line| {
 7085                    line.strip_prefix(&line_prefix)
 7086                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 7087                        .ok_or_else(|| {
 7088                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 7089                        })
 7090                })
 7091                .collect::<Result<Vec<_>, _>>()
 7092                .log_err()
 7093            else {
 7094                continue;
 7095            };
 7096
 7097            let unwrapped_text = lines_without_prefixes.join(" ");
 7098            let wrap_column = buffer
 7099                .settings_at(Point::new(start_row, 0), cx)
 7100                .preferred_line_length as usize;
 7101            let mut wrapped_text = String::new();
 7102            let mut current_line = line_prefix.clone();
 7103            for word in unwrapped_text.split_whitespace() {
 7104                if current_line.len() + word.len() >= wrap_column {
 7105                    wrapped_text.push_str(&current_line);
 7106                    wrapped_text.push('\n');
 7107                    current_line.truncate(line_prefix.len());
 7108                }
 7109
 7110                if current_line.len() > line_prefix.len() {
 7111                    current_line.push(' ');
 7112                }
 7113
 7114                current_line.push_str(word);
 7115            }
 7116
 7117            if !current_line.is_empty() {
 7118                wrapped_text.push_str(&current_line);
 7119            }
 7120
 7121            let diff = TextDiff::from_lines(&selection_text, &wrapped_text);
 7122            let mut offset = start.to_offset(&buffer);
 7123            let mut moved_since_edit = true;
 7124
 7125            for change in diff.iter_all_changes() {
 7126                let value = change.value();
 7127                match change.tag() {
 7128                    ChangeTag::Equal => {
 7129                        offset += value.len();
 7130                        moved_since_edit = true;
 7131                    }
 7132                    ChangeTag::Delete => {
 7133                        let start = buffer.anchor_after(offset);
 7134                        let end = buffer.anchor_before(offset + value.len());
 7135
 7136                        if moved_since_edit {
 7137                            edits.push((start..end, String::new()));
 7138                        } else {
 7139                            edits.last_mut().unwrap().0.end = end;
 7140                        }
 7141
 7142                        offset += value.len();
 7143                        moved_since_edit = false;
 7144                    }
 7145                    ChangeTag::Insert => {
 7146                        if moved_since_edit {
 7147                            let anchor = buffer.anchor_after(offset);
 7148                            edits.push((anchor..anchor, value.to_string()));
 7149                        } else {
 7150                            edits.last_mut().unwrap().1.push_str(value);
 7151                        }
 7152
 7153                        moved_since_edit = false;
 7154                    }
 7155                }
 7156            }
 7157
 7158            rewrapped_row_ranges.push(start_row..=end_row);
 7159        }
 7160
 7161        self.buffer
 7162            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7163    }
 7164
 7165    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 7166        let mut text = String::new();
 7167        let buffer = self.buffer.read(cx).snapshot(cx);
 7168        let mut selections = self.selections.all::<Point>(cx);
 7169        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7170        {
 7171            let max_point = buffer.max_point();
 7172            let mut is_first = true;
 7173            for selection in &mut selections {
 7174                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7175                if is_entire_line {
 7176                    selection.start = Point::new(selection.start.row, 0);
 7177                    if !selection.is_empty() && selection.end.column == 0 {
 7178                        selection.end = cmp::min(max_point, selection.end);
 7179                    } else {
 7180                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7181                    }
 7182                    selection.goal = SelectionGoal::None;
 7183                }
 7184                if is_first {
 7185                    is_first = false;
 7186                } else {
 7187                    text += "\n";
 7188                }
 7189                let mut len = 0;
 7190                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7191                    text.push_str(chunk);
 7192                    len += chunk.len();
 7193                }
 7194                clipboard_selections.push(ClipboardSelection {
 7195                    len,
 7196                    is_entire_line,
 7197                    first_line_indent: buffer
 7198                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7199                        .len,
 7200                });
 7201            }
 7202        }
 7203
 7204        self.transact(cx, |this, cx| {
 7205            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7206                s.select(selections);
 7207            });
 7208            this.insert("", cx);
 7209            cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7210                text,
 7211                clipboard_selections,
 7212            ));
 7213        });
 7214    }
 7215
 7216    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 7217        let selections = self.selections.all::<Point>(cx);
 7218        let buffer = self.buffer.read(cx).read(cx);
 7219        let mut text = String::new();
 7220
 7221        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7222        {
 7223            let max_point = buffer.max_point();
 7224            let mut is_first = true;
 7225            for selection in selections.iter() {
 7226                let mut start = selection.start;
 7227                let mut end = selection.end;
 7228                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7229                if is_entire_line {
 7230                    start = Point::new(start.row, 0);
 7231                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 7232                }
 7233                if is_first {
 7234                    is_first = false;
 7235                } else {
 7236                    text += "\n";
 7237                }
 7238                let mut len = 0;
 7239                for chunk in buffer.text_for_range(start..end) {
 7240                    text.push_str(chunk);
 7241                    len += chunk.len();
 7242                }
 7243                clipboard_selections.push(ClipboardSelection {
 7244                    len,
 7245                    is_entire_line,
 7246                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 7247                });
 7248            }
 7249        }
 7250
 7251        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7252            text,
 7253            clipboard_selections,
 7254        ));
 7255    }
 7256
 7257    pub fn do_paste(
 7258        &mut self,
 7259        text: &String,
 7260        clipboard_selections: Option<Vec<ClipboardSelection>>,
 7261        handle_entire_lines: bool,
 7262        cx: &mut ViewContext<Self>,
 7263    ) {
 7264        if self.read_only(cx) {
 7265            return;
 7266        }
 7267
 7268        let clipboard_text = Cow::Borrowed(text);
 7269
 7270        self.transact(cx, |this, cx| {
 7271            if let Some(mut clipboard_selections) = clipboard_selections {
 7272                let old_selections = this.selections.all::<usize>(cx);
 7273                let all_selections_were_entire_line =
 7274                    clipboard_selections.iter().all(|s| s.is_entire_line);
 7275                let first_selection_indent_column =
 7276                    clipboard_selections.first().map(|s| s.first_line_indent);
 7277                if clipboard_selections.len() != old_selections.len() {
 7278                    clipboard_selections.drain(..);
 7279                }
 7280
 7281                this.buffer.update(cx, |buffer, cx| {
 7282                    let snapshot = buffer.read(cx);
 7283                    let mut start_offset = 0;
 7284                    let mut edits = Vec::new();
 7285                    let mut original_indent_columns = Vec::new();
 7286                    for (ix, selection) in old_selections.iter().enumerate() {
 7287                        let to_insert;
 7288                        let entire_line;
 7289                        let original_indent_column;
 7290                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 7291                            let end_offset = start_offset + clipboard_selection.len;
 7292                            to_insert = &clipboard_text[start_offset..end_offset];
 7293                            entire_line = clipboard_selection.is_entire_line;
 7294                            start_offset = end_offset + 1;
 7295                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7296                        } else {
 7297                            to_insert = clipboard_text.as_str();
 7298                            entire_line = all_selections_were_entire_line;
 7299                            original_indent_column = first_selection_indent_column
 7300                        }
 7301
 7302                        // If the corresponding selection was empty when this slice of the
 7303                        // clipboard text was written, then the entire line containing the
 7304                        // selection was copied. If this selection is also currently empty,
 7305                        // then paste the line before the current line of the buffer.
 7306                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7307                            let column = selection.start.to_point(&snapshot).column as usize;
 7308                            let line_start = selection.start - column;
 7309                            line_start..line_start
 7310                        } else {
 7311                            selection.range()
 7312                        };
 7313
 7314                        edits.push((range, to_insert));
 7315                        original_indent_columns.extend(original_indent_column);
 7316                    }
 7317                    drop(snapshot);
 7318
 7319                    buffer.edit(
 7320                        edits,
 7321                        Some(AutoindentMode::Block {
 7322                            original_indent_columns,
 7323                        }),
 7324                        cx,
 7325                    );
 7326                });
 7327
 7328                let selections = this.selections.all::<usize>(cx);
 7329                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 7330            } else {
 7331                this.insert(&clipboard_text, cx);
 7332            }
 7333        });
 7334    }
 7335
 7336    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 7337        if let Some(item) = cx.read_from_clipboard() {
 7338            let entries = item.entries();
 7339
 7340            match entries.first() {
 7341                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7342                // of all the pasted entries.
 7343                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7344                    .do_paste(
 7345                        clipboard_string.text(),
 7346                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7347                        true,
 7348                        cx,
 7349                    ),
 7350                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
 7351            }
 7352        }
 7353    }
 7354
 7355    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 7356        if self.read_only(cx) {
 7357            return;
 7358        }
 7359
 7360        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7361            if let Some((selections, _)) =
 7362                self.selection_history.transaction(transaction_id).cloned()
 7363            {
 7364                self.change_selections(None, cx, |s| {
 7365                    s.select_anchors(selections.to_vec());
 7366                });
 7367            }
 7368            self.request_autoscroll(Autoscroll::fit(), cx);
 7369            self.unmark_text(cx);
 7370            self.refresh_inline_completion(true, false, cx);
 7371            cx.emit(EditorEvent::Edited { transaction_id });
 7372            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7373        }
 7374    }
 7375
 7376    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 7377        if self.read_only(cx) {
 7378            return;
 7379        }
 7380
 7381        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7382            if let Some((_, Some(selections))) =
 7383                self.selection_history.transaction(transaction_id).cloned()
 7384            {
 7385                self.change_selections(None, cx, |s| {
 7386                    s.select_anchors(selections.to_vec());
 7387                });
 7388            }
 7389            self.request_autoscroll(Autoscroll::fit(), cx);
 7390            self.unmark_text(cx);
 7391            self.refresh_inline_completion(true, false, cx);
 7392            cx.emit(EditorEvent::Edited { transaction_id });
 7393        }
 7394    }
 7395
 7396    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 7397        self.buffer
 7398            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7399    }
 7400
 7401    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 7402        self.buffer
 7403            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7404    }
 7405
 7406    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 7407        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7408            let line_mode = s.line_mode;
 7409            s.move_with(|map, selection| {
 7410                let cursor = if selection.is_empty() && !line_mode {
 7411                    movement::left(map, selection.start)
 7412                } else {
 7413                    selection.start
 7414                };
 7415                selection.collapse_to(cursor, SelectionGoal::None);
 7416            });
 7417        })
 7418    }
 7419
 7420    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 7421        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7422            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7423        })
 7424    }
 7425
 7426    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 7427        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7428            let line_mode = s.line_mode;
 7429            s.move_with(|map, selection| {
 7430                let cursor = if selection.is_empty() && !line_mode {
 7431                    movement::right(map, selection.end)
 7432                } else {
 7433                    selection.end
 7434                };
 7435                selection.collapse_to(cursor, SelectionGoal::None)
 7436            });
 7437        })
 7438    }
 7439
 7440    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 7441        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7442            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7443        })
 7444    }
 7445
 7446    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 7447        if self.take_rename(true, cx).is_some() {
 7448            return;
 7449        }
 7450
 7451        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7452            cx.propagate();
 7453            return;
 7454        }
 7455
 7456        let text_layout_details = &self.text_layout_details(cx);
 7457        let selection_count = self.selections.count();
 7458        let first_selection = self.selections.first_anchor();
 7459
 7460        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7461            let line_mode = s.line_mode;
 7462            s.move_with(|map, selection| {
 7463                if !selection.is_empty() && !line_mode {
 7464                    selection.goal = SelectionGoal::None;
 7465                }
 7466                let (cursor, goal) = movement::up(
 7467                    map,
 7468                    selection.start,
 7469                    selection.goal,
 7470                    false,
 7471                    text_layout_details,
 7472                );
 7473                selection.collapse_to(cursor, goal);
 7474            });
 7475        });
 7476
 7477        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7478        {
 7479            cx.propagate();
 7480        }
 7481    }
 7482
 7483    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 7484        if self.take_rename(true, cx).is_some() {
 7485            return;
 7486        }
 7487
 7488        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7489            cx.propagate();
 7490            return;
 7491        }
 7492
 7493        let text_layout_details = &self.text_layout_details(cx);
 7494
 7495        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7496            let line_mode = s.line_mode;
 7497            s.move_with(|map, selection| {
 7498                if !selection.is_empty() && !line_mode {
 7499                    selection.goal = SelectionGoal::None;
 7500                }
 7501                let (cursor, goal) = movement::up_by_rows(
 7502                    map,
 7503                    selection.start,
 7504                    action.lines,
 7505                    selection.goal,
 7506                    false,
 7507                    text_layout_details,
 7508                );
 7509                selection.collapse_to(cursor, goal);
 7510            });
 7511        })
 7512    }
 7513
 7514    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 7515        if self.take_rename(true, cx).is_some() {
 7516            return;
 7517        }
 7518
 7519        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7520            cx.propagate();
 7521            return;
 7522        }
 7523
 7524        let text_layout_details = &self.text_layout_details(cx);
 7525
 7526        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7527            let line_mode = s.line_mode;
 7528            s.move_with(|map, selection| {
 7529                if !selection.is_empty() && !line_mode {
 7530                    selection.goal = SelectionGoal::None;
 7531                }
 7532                let (cursor, goal) = movement::down_by_rows(
 7533                    map,
 7534                    selection.start,
 7535                    action.lines,
 7536                    selection.goal,
 7537                    false,
 7538                    text_layout_details,
 7539                );
 7540                selection.collapse_to(cursor, goal);
 7541            });
 7542        })
 7543    }
 7544
 7545    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 7546        let text_layout_details = &self.text_layout_details(cx);
 7547        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7548            s.move_heads_with(|map, head, goal| {
 7549                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7550            })
 7551        })
 7552    }
 7553
 7554    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 7555        let text_layout_details = &self.text_layout_details(cx);
 7556        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7557            s.move_heads_with(|map, head, goal| {
 7558                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7559            })
 7560        })
 7561    }
 7562
 7563    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 7564        let Some(row_count) = self.visible_row_count() else {
 7565            return;
 7566        };
 7567
 7568        let text_layout_details = &self.text_layout_details(cx);
 7569
 7570        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7571            s.move_heads_with(|map, head, goal| {
 7572                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7573            })
 7574        })
 7575    }
 7576
 7577    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 7578        if self.take_rename(true, cx).is_some() {
 7579            return;
 7580        }
 7581
 7582        if self
 7583            .context_menu
 7584            .write()
 7585            .as_mut()
 7586            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 7587            .unwrap_or(false)
 7588        {
 7589            return;
 7590        }
 7591
 7592        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7593            cx.propagate();
 7594            return;
 7595        }
 7596
 7597        let Some(row_count) = self.visible_row_count() else {
 7598            return;
 7599        };
 7600
 7601        let autoscroll = if action.center_cursor {
 7602            Autoscroll::center()
 7603        } else {
 7604            Autoscroll::fit()
 7605        };
 7606
 7607        let text_layout_details = &self.text_layout_details(cx);
 7608
 7609        self.change_selections(Some(autoscroll), cx, |s| {
 7610            let line_mode = s.line_mode;
 7611            s.move_with(|map, selection| {
 7612                if !selection.is_empty() && !line_mode {
 7613                    selection.goal = SelectionGoal::None;
 7614                }
 7615                let (cursor, goal) = movement::up_by_rows(
 7616                    map,
 7617                    selection.end,
 7618                    row_count,
 7619                    selection.goal,
 7620                    false,
 7621                    text_layout_details,
 7622                );
 7623                selection.collapse_to(cursor, goal);
 7624            });
 7625        });
 7626    }
 7627
 7628    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 7629        let text_layout_details = &self.text_layout_details(cx);
 7630        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7631            s.move_heads_with(|map, head, goal| {
 7632                movement::up(map, head, goal, false, text_layout_details)
 7633            })
 7634        })
 7635    }
 7636
 7637    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 7638        self.take_rename(true, cx);
 7639
 7640        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7641            cx.propagate();
 7642            return;
 7643        }
 7644
 7645        let text_layout_details = &self.text_layout_details(cx);
 7646        let selection_count = self.selections.count();
 7647        let first_selection = self.selections.first_anchor();
 7648
 7649        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7650            let line_mode = s.line_mode;
 7651            s.move_with(|map, selection| {
 7652                if !selection.is_empty() && !line_mode {
 7653                    selection.goal = SelectionGoal::None;
 7654                }
 7655                let (cursor, goal) = movement::down(
 7656                    map,
 7657                    selection.end,
 7658                    selection.goal,
 7659                    false,
 7660                    text_layout_details,
 7661                );
 7662                selection.collapse_to(cursor, goal);
 7663            });
 7664        });
 7665
 7666        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7667        {
 7668            cx.propagate();
 7669        }
 7670    }
 7671
 7672    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 7673        let Some(row_count) = self.visible_row_count() else {
 7674            return;
 7675        };
 7676
 7677        let text_layout_details = &self.text_layout_details(cx);
 7678
 7679        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7680            s.move_heads_with(|map, head, goal| {
 7681                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 7682            })
 7683        })
 7684    }
 7685
 7686    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 7687        if self.take_rename(true, cx).is_some() {
 7688            return;
 7689        }
 7690
 7691        if self
 7692            .context_menu
 7693            .write()
 7694            .as_mut()
 7695            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 7696            .unwrap_or(false)
 7697        {
 7698            return;
 7699        }
 7700
 7701        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7702            cx.propagate();
 7703            return;
 7704        }
 7705
 7706        let Some(row_count) = self.visible_row_count() else {
 7707            return;
 7708        };
 7709
 7710        let autoscroll = if action.center_cursor {
 7711            Autoscroll::center()
 7712        } else {
 7713            Autoscroll::fit()
 7714        };
 7715
 7716        let text_layout_details = &self.text_layout_details(cx);
 7717        self.change_selections(Some(autoscroll), cx, |s| {
 7718            let line_mode = s.line_mode;
 7719            s.move_with(|map, selection| {
 7720                if !selection.is_empty() && !line_mode {
 7721                    selection.goal = SelectionGoal::None;
 7722                }
 7723                let (cursor, goal) = movement::down_by_rows(
 7724                    map,
 7725                    selection.end,
 7726                    row_count,
 7727                    selection.goal,
 7728                    false,
 7729                    text_layout_details,
 7730                );
 7731                selection.collapse_to(cursor, goal);
 7732            });
 7733        });
 7734    }
 7735
 7736    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 7737        let text_layout_details = &self.text_layout_details(cx);
 7738        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7739            s.move_heads_with(|map, head, goal| {
 7740                movement::down(map, head, goal, false, text_layout_details)
 7741            })
 7742        });
 7743    }
 7744
 7745    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 7746        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7747            context_menu.select_first(self.completion_provider.as_deref(), cx);
 7748        }
 7749    }
 7750
 7751    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 7752        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7753            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 7754        }
 7755    }
 7756
 7757    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7758        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7759            context_menu.select_next(self.completion_provider.as_deref(), cx);
 7760        }
 7761    }
 7762
 7763    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 7764        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7765            context_menu.select_last(self.completion_provider.as_deref(), cx);
 7766        }
 7767    }
 7768
 7769    pub fn move_to_previous_word_start(
 7770        &mut self,
 7771        _: &MoveToPreviousWordStart,
 7772        cx: &mut ViewContext<Self>,
 7773    ) {
 7774        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7775            s.move_cursors_with(|map, head, _| {
 7776                (
 7777                    movement::previous_word_start(map, head),
 7778                    SelectionGoal::None,
 7779                )
 7780            });
 7781        })
 7782    }
 7783
 7784    pub fn move_to_previous_subword_start(
 7785        &mut self,
 7786        _: &MoveToPreviousSubwordStart,
 7787        cx: &mut ViewContext<Self>,
 7788    ) {
 7789        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7790            s.move_cursors_with(|map, head, _| {
 7791                (
 7792                    movement::previous_subword_start(map, head),
 7793                    SelectionGoal::None,
 7794                )
 7795            });
 7796        })
 7797    }
 7798
 7799    pub fn select_to_previous_word_start(
 7800        &mut self,
 7801        _: &SelectToPreviousWordStart,
 7802        cx: &mut ViewContext<Self>,
 7803    ) {
 7804        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7805            s.move_heads_with(|map, head, _| {
 7806                (
 7807                    movement::previous_word_start(map, head),
 7808                    SelectionGoal::None,
 7809                )
 7810            });
 7811        })
 7812    }
 7813
 7814    pub fn select_to_previous_subword_start(
 7815        &mut self,
 7816        _: &SelectToPreviousSubwordStart,
 7817        cx: &mut ViewContext<Self>,
 7818    ) {
 7819        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7820            s.move_heads_with(|map, head, _| {
 7821                (
 7822                    movement::previous_subword_start(map, head),
 7823                    SelectionGoal::None,
 7824                )
 7825            });
 7826        })
 7827    }
 7828
 7829    pub fn delete_to_previous_word_start(
 7830        &mut self,
 7831        action: &DeleteToPreviousWordStart,
 7832        cx: &mut ViewContext<Self>,
 7833    ) {
 7834        self.transact(cx, |this, cx| {
 7835            this.select_autoclose_pair(cx);
 7836            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7837                let line_mode = s.line_mode;
 7838                s.move_with(|map, selection| {
 7839                    if selection.is_empty() && !line_mode {
 7840                        let cursor = if action.ignore_newlines {
 7841                            movement::previous_word_start(map, selection.head())
 7842                        } else {
 7843                            movement::previous_word_start_or_newline(map, selection.head())
 7844                        };
 7845                        selection.set_head(cursor, SelectionGoal::None);
 7846                    }
 7847                });
 7848            });
 7849            this.insert("", cx);
 7850        });
 7851    }
 7852
 7853    pub fn delete_to_previous_subword_start(
 7854        &mut self,
 7855        _: &DeleteToPreviousSubwordStart,
 7856        cx: &mut ViewContext<Self>,
 7857    ) {
 7858        self.transact(cx, |this, cx| {
 7859            this.select_autoclose_pair(cx);
 7860            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7861                let line_mode = s.line_mode;
 7862                s.move_with(|map, selection| {
 7863                    if selection.is_empty() && !line_mode {
 7864                        let cursor = movement::previous_subword_start(map, selection.head());
 7865                        selection.set_head(cursor, SelectionGoal::None);
 7866                    }
 7867                });
 7868            });
 7869            this.insert("", cx);
 7870        });
 7871    }
 7872
 7873    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 7874        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7875            s.move_cursors_with(|map, head, _| {
 7876                (movement::next_word_end(map, head), SelectionGoal::None)
 7877            });
 7878        })
 7879    }
 7880
 7881    pub fn move_to_next_subword_end(
 7882        &mut self,
 7883        _: &MoveToNextSubwordEnd,
 7884        cx: &mut ViewContext<Self>,
 7885    ) {
 7886        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7887            s.move_cursors_with(|map, head, _| {
 7888                (movement::next_subword_end(map, head), SelectionGoal::None)
 7889            });
 7890        })
 7891    }
 7892
 7893    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 7894        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7895            s.move_heads_with(|map, head, _| {
 7896                (movement::next_word_end(map, head), SelectionGoal::None)
 7897            });
 7898        })
 7899    }
 7900
 7901    pub fn select_to_next_subword_end(
 7902        &mut self,
 7903        _: &SelectToNextSubwordEnd,
 7904        cx: &mut ViewContext<Self>,
 7905    ) {
 7906        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7907            s.move_heads_with(|map, head, _| {
 7908                (movement::next_subword_end(map, head), SelectionGoal::None)
 7909            });
 7910        })
 7911    }
 7912
 7913    pub fn delete_to_next_word_end(
 7914        &mut self,
 7915        action: &DeleteToNextWordEnd,
 7916        cx: &mut ViewContext<Self>,
 7917    ) {
 7918        self.transact(cx, |this, cx| {
 7919            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7920                let line_mode = s.line_mode;
 7921                s.move_with(|map, selection| {
 7922                    if selection.is_empty() && !line_mode {
 7923                        let cursor = if action.ignore_newlines {
 7924                            movement::next_word_end(map, selection.head())
 7925                        } else {
 7926                            movement::next_word_end_or_newline(map, selection.head())
 7927                        };
 7928                        selection.set_head(cursor, SelectionGoal::None);
 7929                    }
 7930                });
 7931            });
 7932            this.insert("", cx);
 7933        });
 7934    }
 7935
 7936    pub fn delete_to_next_subword_end(
 7937        &mut self,
 7938        _: &DeleteToNextSubwordEnd,
 7939        cx: &mut ViewContext<Self>,
 7940    ) {
 7941        self.transact(cx, |this, cx| {
 7942            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7943                s.move_with(|map, selection| {
 7944                    if selection.is_empty() {
 7945                        let cursor = movement::next_subword_end(map, selection.head());
 7946                        selection.set_head(cursor, SelectionGoal::None);
 7947                    }
 7948                });
 7949            });
 7950            this.insert("", cx);
 7951        });
 7952    }
 7953
 7954    pub fn move_to_beginning_of_line(
 7955        &mut self,
 7956        action: &MoveToBeginningOfLine,
 7957        cx: &mut ViewContext<Self>,
 7958    ) {
 7959        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7960            s.move_cursors_with(|map, head, _| {
 7961                (
 7962                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7963                    SelectionGoal::None,
 7964                )
 7965            });
 7966        })
 7967    }
 7968
 7969    pub fn select_to_beginning_of_line(
 7970        &mut self,
 7971        action: &SelectToBeginningOfLine,
 7972        cx: &mut ViewContext<Self>,
 7973    ) {
 7974        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7975            s.move_heads_with(|map, head, _| {
 7976                (
 7977                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7978                    SelectionGoal::None,
 7979                )
 7980            });
 7981        });
 7982    }
 7983
 7984    pub fn delete_to_beginning_of_line(
 7985        &mut self,
 7986        _: &DeleteToBeginningOfLine,
 7987        cx: &mut ViewContext<Self>,
 7988    ) {
 7989        self.transact(cx, |this, cx| {
 7990            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7991                s.move_with(|_, selection| {
 7992                    selection.reversed = true;
 7993                });
 7994            });
 7995
 7996            this.select_to_beginning_of_line(
 7997                &SelectToBeginningOfLine {
 7998                    stop_at_soft_wraps: false,
 7999                },
 8000                cx,
 8001            );
 8002            this.backspace(&Backspace, cx);
 8003        });
 8004    }
 8005
 8006    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 8007        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8008            s.move_cursors_with(|map, head, _| {
 8009                (
 8010                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8011                    SelectionGoal::None,
 8012                )
 8013            });
 8014        })
 8015    }
 8016
 8017    pub fn select_to_end_of_line(
 8018        &mut self,
 8019        action: &SelectToEndOfLine,
 8020        cx: &mut ViewContext<Self>,
 8021    ) {
 8022        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8023            s.move_heads_with(|map, head, _| {
 8024                (
 8025                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8026                    SelectionGoal::None,
 8027                )
 8028            });
 8029        })
 8030    }
 8031
 8032    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 8033        self.transact(cx, |this, cx| {
 8034            this.select_to_end_of_line(
 8035                &SelectToEndOfLine {
 8036                    stop_at_soft_wraps: false,
 8037                },
 8038                cx,
 8039            );
 8040            this.delete(&Delete, cx);
 8041        });
 8042    }
 8043
 8044    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 8045        self.transact(cx, |this, cx| {
 8046            this.select_to_end_of_line(
 8047                &SelectToEndOfLine {
 8048                    stop_at_soft_wraps: false,
 8049                },
 8050                cx,
 8051            );
 8052            this.cut(&Cut, cx);
 8053        });
 8054    }
 8055
 8056    pub fn move_to_start_of_paragraph(
 8057        &mut self,
 8058        _: &MoveToStartOfParagraph,
 8059        cx: &mut ViewContext<Self>,
 8060    ) {
 8061        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8062            cx.propagate();
 8063            return;
 8064        }
 8065
 8066        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8067            s.move_with(|map, selection| {
 8068                selection.collapse_to(
 8069                    movement::start_of_paragraph(map, selection.head(), 1),
 8070                    SelectionGoal::None,
 8071                )
 8072            });
 8073        })
 8074    }
 8075
 8076    pub fn move_to_end_of_paragraph(
 8077        &mut self,
 8078        _: &MoveToEndOfParagraph,
 8079        cx: &mut ViewContext<Self>,
 8080    ) {
 8081        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8082            cx.propagate();
 8083            return;
 8084        }
 8085
 8086        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8087            s.move_with(|map, selection| {
 8088                selection.collapse_to(
 8089                    movement::end_of_paragraph(map, selection.head(), 1),
 8090                    SelectionGoal::None,
 8091                )
 8092            });
 8093        })
 8094    }
 8095
 8096    pub fn select_to_start_of_paragraph(
 8097        &mut self,
 8098        _: &SelectToStartOfParagraph,
 8099        cx: &mut ViewContext<Self>,
 8100    ) {
 8101        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8102            cx.propagate();
 8103            return;
 8104        }
 8105
 8106        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8107            s.move_heads_with(|map, head, _| {
 8108                (
 8109                    movement::start_of_paragraph(map, head, 1),
 8110                    SelectionGoal::None,
 8111                )
 8112            });
 8113        })
 8114    }
 8115
 8116    pub fn select_to_end_of_paragraph(
 8117        &mut self,
 8118        _: &SelectToEndOfParagraph,
 8119        cx: &mut ViewContext<Self>,
 8120    ) {
 8121        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8122            cx.propagate();
 8123            return;
 8124        }
 8125
 8126        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8127            s.move_heads_with(|map, head, _| {
 8128                (
 8129                    movement::end_of_paragraph(map, head, 1),
 8130                    SelectionGoal::None,
 8131                )
 8132            });
 8133        })
 8134    }
 8135
 8136    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 8137        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8138            cx.propagate();
 8139            return;
 8140        }
 8141
 8142        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8143            s.select_ranges(vec![0..0]);
 8144        });
 8145    }
 8146
 8147    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 8148        let mut selection = self.selections.last::<Point>(cx);
 8149        selection.set_head(Point::zero(), SelectionGoal::None);
 8150
 8151        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8152            s.select(vec![selection]);
 8153        });
 8154    }
 8155
 8156    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 8157        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8158            cx.propagate();
 8159            return;
 8160        }
 8161
 8162        let cursor = self.buffer.read(cx).read(cx).len();
 8163        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8164            s.select_ranges(vec![cursor..cursor])
 8165        });
 8166    }
 8167
 8168    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 8169        self.nav_history = nav_history;
 8170    }
 8171
 8172    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 8173        self.nav_history.as_ref()
 8174    }
 8175
 8176    fn push_to_nav_history(
 8177        &mut self,
 8178        cursor_anchor: Anchor,
 8179        new_position: Option<Point>,
 8180        cx: &mut ViewContext<Self>,
 8181    ) {
 8182        if let Some(nav_history) = self.nav_history.as_mut() {
 8183            let buffer = self.buffer.read(cx).read(cx);
 8184            let cursor_position = cursor_anchor.to_point(&buffer);
 8185            let scroll_state = self.scroll_manager.anchor();
 8186            let scroll_top_row = scroll_state.top_row(&buffer);
 8187            drop(buffer);
 8188
 8189            if let Some(new_position) = new_position {
 8190                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 8191                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 8192                    return;
 8193                }
 8194            }
 8195
 8196            nav_history.push(
 8197                Some(NavigationData {
 8198                    cursor_anchor,
 8199                    cursor_position,
 8200                    scroll_anchor: scroll_state,
 8201                    scroll_top_row,
 8202                }),
 8203                cx,
 8204            );
 8205        }
 8206    }
 8207
 8208    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 8209        let buffer = self.buffer.read(cx).snapshot(cx);
 8210        let mut selection = self.selections.first::<usize>(cx);
 8211        selection.set_head(buffer.len(), SelectionGoal::None);
 8212        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8213            s.select(vec![selection]);
 8214        });
 8215    }
 8216
 8217    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 8218        let end = self.buffer.read(cx).read(cx).len();
 8219        self.change_selections(None, cx, |s| {
 8220            s.select_ranges(vec![0..end]);
 8221        });
 8222    }
 8223
 8224    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 8225        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8226        let mut selections = self.selections.all::<Point>(cx);
 8227        let max_point = display_map.buffer_snapshot.max_point();
 8228        for selection in &mut selections {
 8229            let rows = selection.spanned_rows(true, &display_map);
 8230            selection.start = Point::new(rows.start.0, 0);
 8231            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 8232            selection.reversed = false;
 8233        }
 8234        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8235            s.select(selections);
 8236        });
 8237    }
 8238
 8239    pub fn split_selection_into_lines(
 8240        &mut self,
 8241        _: &SplitSelectionIntoLines,
 8242        cx: &mut ViewContext<Self>,
 8243    ) {
 8244        let mut to_unfold = Vec::new();
 8245        let mut new_selection_ranges = Vec::new();
 8246        {
 8247            let selections = self.selections.all::<Point>(cx);
 8248            let buffer = self.buffer.read(cx).read(cx);
 8249            for selection in selections {
 8250                for row in selection.start.row..selection.end.row {
 8251                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 8252                    new_selection_ranges.push(cursor..cursor);
 8253                }
 8254                new_selection_ranges.push(selection.end..selection.end);
 8255                to_unfold.push(selection.start..selection.end);
 8256            }
 8257        }
 8258        self.unfold_ranges(to_unfold, true, true, cx);
 8259        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8260            s.select_ranges(new_selection_ranges);
 8261        });
 8262    }
 8263
 8264    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 8265        self.add_selection(true, cx);
 8266    }
 8267
 8268    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 8269        self.add_selection(false, cx);
 8270    }
 8271
 8272    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 8273        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8274        let mut selections = self.selections.all::<Point>(cx);
 8275        let text_layout_details = self.text_layout_details(cx);
 8276        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 8277            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 8278            let range = oldest_selection.display_range(&display_map).sorted();
 8279
 8280            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 8281            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 8282            let positions = start_x.min(end_x)..start_x.max(end_x);
 8283
 8284            selections.clear();
 8285            let mut stack = Vec::new();
 8286            for row in range.start.row().0..=range.end.row().0 {
 8287                if let Some(selection) = self.selections.build_columnar_selection(
 8288                    &display_map,
 8289                    DisplayRow(row),
 8290                    &positions,
 8291                    oldest_selection.reversed,
 8292                    &text_layout_details,
 8293                ) {
 8294                    stack.push(selection.id);
 8295                    selections.push(selection);
 8296                }
 8297            }
 8298
 8299            if above {
 8300                stack.reverse();
 8301            }
 8302
 8303            AddSelectionsState { above, stack }
 8304        });
 8305
 8306        let last_added_selection = *state.stack.last().unwrap();
 8307        let mut new_selections = Vec::new();
 8308        if above == state.above {
 8309            let end_row = if above {
 8310                DisplayRow(0)
 8311            } else {
 8312                display_map.max_point().row()
 8313            };
 8314
 8315            'outer: for selection in selections {
 8316                if selection.id == last_added_selection {
 8317                    let range = selection.display_range(&display_map).sorted();
 8318                    debug_assert_eq!(range.start.row(), range.end.row());
 8319                    let mut row = range.start.row();
 8320                    let positions =
 8321                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 8322                            px(start)..px(end)
 8323                        } else {
 8324                            let start_x =
 8325                                display_map.x_for_display_point(range.start, &text_layout_details);
 8326                            let end_x =
 8327                                display_map.x_for_display_point(range.end, &text_layout_details);
 8328                            start_x.min(end_x)..start_x.max(end_x)
 8329                        };
 8330
 8331                    while row != end_row {
 8332                        if above {
 8333                            row.0 -= 1;
 8334                        } else {
 8335                            row.0 += 1;
 8336                        }
 8337
 8338                        if let Some(new_selection) = self.selections.build_columnar_selection(
 8339                            &display_map,
 8340                            row,
 8341                            &positions,
 8342                            selection.reversed,
 8343                            &text_layout_details,
 8344                        ) {
 8345                            state.stack.push(new_selection.id);
 8346                            if above {
 8347                                new_selections.push(new_selection);
 8348                                new_selections.push(selection);
 8349                            } else {
 8350                                new_selections.push(selection);
 8351                                new_selections.push(new_selection);
 8352                            }
 8353
 8354                            continue 'outer;
 8355                        }
 8356                    }
 8357                }
 8358
 8359                new_selections.push(selection);
 8360            }
 8361        } else {
 8362            new_selections = selections;
 8363            new_selections.retain(|s| s.id != last_added_selection);
 8364            state.stack.pop();
 8365        }
 8366
 8367        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8368            s.select(new_selections);
 8369        });
 8370        if state.stack.len() > 1 {
 8371            self.add_selections_state = Some(state);
 8372        }
 8373    }
 8374
 8375    pub fn select_next_match_internal(
 8376        &mut self,
 8377        display_map: &DisplaySnapshot,
 8378        replace_newest: bool,
 8379        autoscroll: Option<Autoscroll>,
 8380        cx: &mut ViewContext<Self>,
 8381    ) -> Result<()> {
 8382        fn select_next_match_ranges(
 8383            this: &mut Editor,
 8384            range: Range<usize>,
 8385            replace_newest: bool,
 8386            auto_scroll: Option<Autoscroll>,
 8387            cx: &mut ViewContext<Editor>,
 8388        ) {
 8389            this.unfold_ranges([range.clone()], false, true, cx);
 8390            this.change_selections(auto_scroll, cx, |s| {
 8391                if replace_newest {
 8392                    s.delete(s.newest_anchor().id);
 8393                }
 8394                s.insert_range(range.clone());
 8395            });
 8396        }
 8397
 8398        let buffer = &display_map.buffer_snapshot;
 8399        let mut selections = self.selections.all::<usize>(cx);
 8400        if let Some(mut select_next_state) = self.select_next_state.take() {
 8401            let query = &select_next_state.query;
 8402            if !select_next_state.done {
 8403                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8404                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8405                let mut next_selected_range = None;
 8406
 8407                let bytes_after_last_selection =
 8408                    buffer.bytes_in_range(last_selection.end..buffer.len());
 8409                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 8410                let query_matches = query
 8411                    .stream_find_iter(bytes_after_last_selection)
 8412                    .map(|result| (last_selection.end, result))
 8413                    .chain(
 8414                        query
 8415                            .stream_find_iter(bytes_before_first_selection)
 8416                            .map(|result| (0, result)),
 8417                    );
 8418
 8419                for (start_offset, query_match) in query_matches {
 8420                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8421                    let offset_range =
 8422                        start_offset + query_match.start()..start_offset + query_match.end();
 8423                    let display_range = offset_range.start.to_display_point(display_map)
 8424                        ..offset_range.end.to_display_point(display_map);
 8425
 8426                    if !select_next_state.wordwise
 8427                        || (!movement::is_inside_word(display_map, display_range.start)
 8428                            && !movement::is_inside_word(display_map, display_range.end))
 8429                    {
 8430                        // TODO: This is n^2, because we might check all the selections
 8431                        if !selections
 8432                            .iter()
 8433                            .any(|selection| selection.range().overlaps(&offset_range))
 8434                        {
 8435                            next_selected_range = Some(offset_range);
 8436                            break;
 8437                        }
 8438                    }
 8439                }
 8440
 8441                if let Some(next_selected_range) = next_selected_range {
 8442                    select_next_match_ranges(
 8443                        self,
 8444                        next_selected_range,
 8445                        replace_newest,
 8446                        autoscroll,
 8447                        cx,
 8448                    );
 8449                } else {
 8450                    select_next_state.done = true;
 8451                }
 8452            }
 8453
 8454            self.select_next_state = Some(select_next_state);
 8455        } else {
 8456            let mut only_carets = true;
 8457            let mut same_text_selected = true;
 8458            let mut selected_text = None;
 8459
 8460            let mut selections_iter = selections.iter().peekable();
 8461            while let Some(selection) = selections_iter.next() {
 8462                if selection.start != selection.end {
 8463                    only_carets = false;
 8464                }
 8465
 8466                if same_text_selected {
 8467                    if selected_text.is_none() {
 8468                        selected_text =
 8469                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8470                    }
 8471
 8472                    if let Some(next_selection) = selections_iter.peek() {
 8473                        if next_selection.range().len() == selection.range().len() {
 8474                            let next_selected_text = buffer
 8475                                .text_for_range(next_selection.range())
 8476                                .collect::<String>();
 8477                            if Some(next_selected_text) != selected_text {
 8478                                same_text_selected = false;
 8479                                selected_text = None;
 8480                            }
 8481                        } else {
 8482                            same_text_selected = false;
 8483                            selected_text = None;
 8484                        }
 8485                    }
 8486                }
 8487            }
 8488
 8489            if only_carets {
 8490                for selection in &mut selections {
 8491                    let word_range = movement::surrounding_word(
 8492                        display_map,
 8493                        selection.start.to_display_point(display_map),
 8494                    );
 8495                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 8496                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 8497                    selection.goal = SelectionGoal::None;
 8498                    selection.reversed = false;
 8499                    select_next_match_ranges(
 8500                        self,
 8501                        selection.start..selection.end,
 8502                        replace_newest,
 8503                        autoscroll,
 8504                        cx,
 8505                    );
 8506                }
 8507
 8508                if selections.len() == 1 {
 8509                    let selection = selections
 8510                        .last()
 8511                        .expect("ensured that there's only one selection");
 8512                    let query = buffer
 8513                        .text_for_range(selection.start..selection.end)
 8514                        .collect::<String>();
 8515                    let is_empty = query.is_empty();
 8516                    let select_state = SelectNextState {
 8517                        query: AhoCorasick::new(&[query])?,
 8518                        wordwise: true,
 8519                        done: is_empty,
 8520                    };
 8521                    self.select_next_state = Some(select_state);
 8522                } else {
 8523                    self.select_next_state = None;
 8524                }
 8525            } else if let Some(selected_text) = selected_text {
 8526                self.select_next_state = Some(SelectNextState {
 8527                    query: AhoCorasick::new(&[selected_text])?,
 8528                    wordwise: false,
 8529                    done: false,
 8530                });
 8531                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 8532            }
 8533        }
 8534        Ok(())
 8535    }
 8536
 8537    pub fn select_all_matches(
 8538        &mut self,
 8539        _action: &SelectAllMatches,
 8540        cx: &mut ViewContext<Self>,
 8541    ) -> Result<()> {
 8542        self.push_to_selection_history();
 8543        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8544
 8545        self.select_next_match_internal(&display_map, false, None, cx)?;
 8546        let Some(select_next_state) = self.select_next_state.as_mut() else {
 8547            return Ok(());
 8548        };
 8549        if select_next_state.done {
 8550            return Ok(());
 8551        }
 8552
 8553        let mut new_selections = self.selections.all::<usize>(cx);
 8554
 8555        let buffer = &display_map.buffer_snapshot;
 8556        let query_matches = select_next_state
 8557            .query
 8558            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 8559
 8560        for query_match in query_matches {
 8561            let query_match = query_match.unwrap(); // can only fail due to I/O
 8562            let offset_range = query_match.start()..query_match.end();
 8563            let display_range = offset_range.start.to_display_point(&display_map)
 8564                ..offset_range.end.to_display_point(&display_map);
 8565
 8566            if !select_next_state.wordwise
 8567                || (!movement::is_inside_word(&display_map, display_range.start)
 8568                    && !movement::is_inside_word(&display_map, display_range.end))
 8569            {
 8570                self.selections.change_with(cx, |selections| {
 8571                    new_selections.push(Selection {
 8572                        id: selections.new_selection_id(),
 8573                        start: offset_range.start,
 8574                        end: offset_range.end,
 8575                        reversed: false,
 8576                        goal: SelectionGoal::None,
 8577                    });
 8578                });
 8579            }
 8580        }
 8581
 8582        new_selections.sort_by_key(|selection| selection.start);
 8583        let mut ix = 0;
 8584        while ix + 1 < new_selections.len() {
 8585            let current_selection = &new_selections[ix];
 8586            let next_selection = &new_selections[ix + 1];
 8587            if current_selection.range().overlaps(&next_selection.range()) {
 8588                if current_selection.id < next_selection.id {
 8589                    new_selections.remove(ix + 1);
 8590                } else {
 8591                    new_selections.remove(ix);
 8592                }
 8593            } else {
 8594                ix += 1;
 8595            }
 8596        }
 8597
 8598        select_next_state.done = true;
 8599        self.unfold_ranges(
 8600            new_selections.iter().map(|selection| selection.range()),
 8601            false,
 8602            false,
 8603            cx,
 8604        );
 8605        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 8606            selections.select(new_selections)
 8607        });
 8608
 8609        Ok(())
 8610    }
 8611
 8612    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 8613        self.push_to_selection_history();
 8614        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8615        self.select_next_match_internal(
 8616            &display_map,
 8617            action.replace_newest,
 8618            Some(Autoscroll::newest()),
 8619            cx,
 8620        )?;
 8621        Ok(())
 8622    }
 8623
 8624    pub fn select_previous(
 8625        &mut self,
 8626        action: &SelectPrevious,
 8627        cx: &mut ViewContext<Self>,
 8628    ) -> Result<()> {
 8629        self.push_to_selection_history();
 8630        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8631        let buffer = &display_map.buffer_snapshot;
 8632        let mut selections = self.selections.all::<usize>(cx);
 8633        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8634            let query = &select_prev_state.query;
 8635            if !select_prev_state.done {
 8636                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8637                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8638                let mut next_selected_range = None;
 8639                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8640                let bytes_before_last_selection =
 8641                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8642                let bytes_after_first_selection =
 8643                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8644                let query_matches = query
 8645                    .stream_find_iter(bytes_before_last_selection)
 8646                    .map(|result| (last_selection.start, result))
 8647                    .chain(
 8648                        query
 8649                            .stream_find_iter(bytes_after_first_selection)
 8650                            .map(|result| (buffer.len(), result)),
 8651                    );
 8652                for (end_offset, query_match) in query_matches {
 8653                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8654                    let offset_range =
 8655                        end_offset - query_match.end()..end_offset - query_match.start();
 8656                    let display_range = offset_range.start.to_display_point(&display_map)
 8657                        ..offset_range.end.to_display_point(&display_map);
 8658
 8659                    if !select_prev_state.wordwise
 8660                        || (!movement::is_inside_word(&display_map, display_range.start)
 8661                            && !movement::is_inside_word(&display_map, display_range.end))
 8662                    {
 8663                        next_selected_range = Some(offset_range);
 8664                        break;
 8665                    }
 8666                }
 8667
 8668                if let Some(next_selected_range) = next_selected_range {
 8669                    self.unfold_ranges([next_selected_range.clone()], false, true, cx);
 8670                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8671                        if action.replace_newest {
 8672                            s.delete(s.newest_anchor().id);
 8673                        }
 8674                        s.insert_range(next_selected_range);
 8675                    });
 8676                } else {
 8677                    select_prev_state.done = true;
 8678                }
 8679            }
 8680
 8681            self.select_prev_state = Some(select_prev_state);
 8682        } else {
 8683            let mut only_carets = true;
 8684            let mut same_text_selected = true;
 8685            let mut selected_text = None;
 8686
 8687            let mut selections_iter = selections.iter().peekable();
 8688            while let Some(selection) = selections_iter.next() {
 8689                if selection.start != selection.end {
 8690                    only_carets = false;
 8691                }
 8692
 8693                if same_text_selected {
 8694                    if selected_text.is_none() {
 8695                        selected_text =
 8696                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8697                    }
 8698
 8699                    if let Some(next_selection) = selections_iter.peek() {
 8700                        if next_selection.range().len() == selection.range().len() {
 8701                            let next_selected_text = buffer
 8702                                .text_for_range(next_selection.range())
 8703                                .collect::<String>();
 8704                            if Some(next_selected_text) != selected_text {
 8705                                same_text_selected = false;
 8706                                selected_text = None;
 8707                            }
 8708                        } else {
 8709                            same_text_selected = false;
 8710                            selected_text = None;
 8711                        }
 8712                    }
 8713                }
 8714            }
 8715
 8716            if only_carets {
 8717                for selection in &mut selections {
 8718                    let word_range = movement::surrounding_word(
 8719                        &display_map,
 8720                        selection.start.to_display_point(&display_map),
 8721                    );
 8722                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8723                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8724                    selection.goal = SelectionGoal::None;
 8725                    selection.reversed = false;
 8726                }
 8727                if selections.len() == 1 {
 8728                    let selection = selections
 8729                        .last()
 8730                        .expect("ensured that there's only one selection");
 8731                    let query = buffer
 8732                        .text_for_range(selection.start..selection.end)
 8733                        .collect::<String>();
 8734                    let is_empty = query.is_empty();
 8735                    let select_state = SelectNextState {
 8736                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8737                        wordwise: true,
 8738                        done: is_empty,
 8739                    };
 8740                    self.select_prev_state = Some(select_state);
 8741                } else {
 8742                    self.select_prev_state = None;
 8743                }
 8744
 8745                self.unfold_ranges(
 8746                    selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8747                    false,
 8748                    true,
 8749                    cx,
 8750                );
 8751                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8752                    s.select(selections);
 8753                });
 8754            } else if let Some(selected_text) = selected_text {
 8755                self.select_prev_state = Some(SelectNextState {
 8756                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8757                    wordwise: false,
 8758                    done: false,
 8759                });
 8760                self.select_previous(action, cx)?;
 8761            }
 8762        }
 8763        Ok(())
 8764    }
 8765
 8766    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 8767        let text_layout_details = &self.text_layout_details(cx);
 8768        self.transact(cx, |this, cx| {
 8769            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8770            let mut edits = Vec::new();
 8771            let mut selection_edit_ranges = Vec::new();
 8772            let mut last_toggled_row = None;
 8773            let snapshot = this.buffer.read(cx).read(cx);
 8774            let empty_str: Arc<str> = Arc::default();
 8775            let mut suffixes_inserted = Vec::new();
 8776            let ignore_indent = action.ignore_indent;
 8777
 8778            fn comment_prefix_range(
 8779                snapshot: &MultiBufferSnapshot,
 8780                row: MultiBufferRow,
 8781                comment_prefix: &str,
 8782                comment_prefix_whitespace: &str,
 8783                ignore_indent: bool,
 8784            ) -> Range<Point> {
 8785                let indent_size = if ignore_indent {
 8786                    0
 8787                } else {
 8788                    snapshot.indent_size_for_line(row).len
 8789                };
 8790
 8791                let start = Point::new(row.0, indent_size);
 8792
 8793                let mut line_bytes = snapshot
 8794                    .bytes_in_range(start..snapshot.max_point())
 8795                    .flatten()
 8796                    .copied();
 8797
 8798                // If this line currently begins with the line comment prefix, then record
 8799                // the range containing the prefix.
 8800                if line_bytes
 8801                    .by_ref()
 8802                    .take(comment_prefix.len())
 8803                    .eq(comment_prefix.bytes())
 8804                {
 8805                    // Include any whitespace that matches the comment prefix.
 8806                    let matching_whitespace_len = line_bytes
 8807                        .zip(comment_prefix_whitespace.bytes())
 8808                        .take_while(|(a, b)| a == b)
 8809                        .count() as u32;
 8810                    let end = Point::new(
 8811                        start.row,
 8812                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 8813                    );
 8814                    start..end
 8815                } else {
 8816                    start..start
 8817                }
 8818            }
 8819
 8820            fn comment_suffix_range(
 8821                snapshot: &MultiBufferSnapshot,
 8822                row: MultiBufferRow,
 8823                comment_suffix: &str,
 8824                comment_suffix_has_leading_space: bool,
 8825            ) -> Range<Point> {
 8826                let end = Point::new(row.0, snapshot.line_len(row));
 8827                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 8828
 8829                let mut line_end_bytes = snapshot
 8830                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 8831                    .flatten()
 8832                    .copied();
 8833
 8834                let leading_space_len = if suffix_start_column > 0
 8835                    && line_end_bytes.next() == Some(b' ')
 8836                    && comment_suffix_has_leading_space
 8837                {
 8838                    1
 8839                } else {
 8840                    0
 8841                };
 8842
 8843                // If this line currently begins with the line comment prefix, then record
 8844                // the range containing the prefix.
 8845                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 8846                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 8847                    start..end
 8848                } else {
 8849                    end..end
 8850                }
 8851            }
 8852
 8853            // TODO: Handle selections that cross excerpts
 8854            for selection in &mut selections {
 8855                let start_column = snapshot
 8856                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 8857                    .len;
 8858                let language = if let Some(language) =
 8859                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 8860                {
 8861                    language
 8862                } else {
 8863                    continue;
 8864                };
 8865
 8866                selection_edit_ranges.clear();
 8867
 8868                // If multiple selections contain a given row, avoid processing that
 8869                // row more than once.
 8870                let mut start_row = MultiBufferRow(selection.start.row);
 8871                if last_toggled_row == Some(start_row) {
 8872                    start_row = start_row.next_row();
 8873                }
 8874                let end_row =
 8875                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 8876                        MultiBufferRow(selection.end.row - 1)
 8877                    } else {
 8878                        MultiBufferRow(selection.end.row)
 8879                    };
 8880                last_toggled_row = Some(end_row);
 8881
 8882                if start_row > end_row {
 8883                    continue;
 8884                }
 8885
 8886                // If the language has line comments, toggle those.
 8887                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 8888
 8889                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 8890                if ignore_indent {
 8891                    full_comment_prefixes = full_comment_prefixes
 8892                        .into_iter()
 8893                        .map(|s| Arc::from(s.trim_end()))
 8894                        .collect();
 8895                }
 8896
 8897                if !full_comment_prefixes.is_empty() {
 8898                    let first_prefix = full_comment_prefixes
 8899                        .first()
 8900                        .expect("prefixes is non-empty");
 8901                    let prefix_trimmed_lengths = full_comment_prefixes
 8902                        .iter()
 8903                        .map(|p| p.trim_end_matches(' ').len())
 8904                        .collect::<SmallVec<[usize; 4]>>();
 8905
 8906                    let mut all_selection_lines_are_comments = true;
 8907
 8908                    for row in start_row.0..=end_row.0 {
 8909                        let row = MultiBufferRow(row);
 8910                        if start_row < end_row && snapshot.is_line_blank(row) {
 8911                            continue;
 8912                        }
 8913
 8914                        let prefix_range = full_comment_prefixes
 8915                            .iter()
 8916                            .zip(prefix_trimmed_lengths.iter().copied())
 8917                            .map(|(prefix, trimmed_prefix_len)| {
 8918                                comment_prefix_range(
 8919                                    snapshot.deref(),
 8920                                    row,
 8921                                    &prefix[..trimmed_prefix_len],
 8922                                    &prefix[trimmed_prefix_len..],
 8923                                    ignore_indent,
 8924                                )
 8925                            })
 8926                            .max_by_key(|range| range.end.column - range.start.column)
 8927                            .expect("prefixes is non-empty");
 8928
 8929                        if prefix_range.is_empty() {
 8930                            all_selection_lines_are_comments = false;
 8931                        }
 8932
 8933                        selection_edit_ranges.push(prefix_range);
 8934                    }
 8935
 8936                    if all_selection_lines_are_comments {
 8937                        edits.extend(
 8938                            selection_edit_ranges
 8939                                .iter()
 8940                                .cloned()
 8941                                .map(|range| (range, empty_str.clone())),
 8942                        );
 8943                    } else {
 8944                        let min_column = selection_edit_ranges
 8945                            .iter()
 8946                            .map(|range| range.start.column)
 8947                            .min()
 8948                            .unwrap_or(0);
 8949                        edits.extend(selection_edit_ranges.iter().map(|range| {
 8950                            let position = Point::new(range.start.row, min_column);
 8951                            (position..position, first_prefix.clone())
 8952                        }));
 8953                    }
 8954                } else if let Some((full_comment_prefix, comment_suffix)) =
 8955                    language.block_comment_delimiters()
 8956                {
 8957                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 8958                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 8959                    let prefix_range = comment_prefix_range(
 8960                        snapshot.deref(),
 8961                        start_row,
 8962                        comment_prefix,
 8963                        comment_prefix_whitespace,
 8964                        ignore_indent,
 8965                    );
 8966                    let suffix_range = comment_suffix_range(
 8967                        snapshot.deref(),
 8968                        end_row,
 8969                        comment_suffix.trim_start_matches(' '),
 8970                        comment_suffix.starts_with(' '),
 8971                    );
 8972
 8973                    if prefix_range.is_empty() || suffix_range.is_empty() {
 8974                        edits.push((
 8975                            prefix_range.start..prefix_range.start,
 8976                            full_comment_prefix.clone(),
 8977                        ));
 8978                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 8979                        suffixes_inserted.push((end_row, comment_suffix.len()));
 8980                    } else {
 8981                        edits.push((prefix_range, empty_str.clone()));
 8982                        edits.push((suffix_range, empty_str.clone()));
 8983                    }
 8984                } else {
 8985                    continue;
 8986                }
 8987            }
 8988
 8989            drop(snapshot);
 8990            this.buffer.update(cx, |buffer, cx| {
 8991                buffer.edit(edits, None, cx);
 8992            });
 8993
 8994            // Adjust selections so that they end before any comment suffixes that
 8995            // were inserted.
 8996            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 8997            let mut selections = this.selections.all::<Point>(cx);
 8998            let snapshot = this.buffer.read(cx).read(cx);
 8999            for selection in &mut selections {
 9000                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 9001                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 9002                        Ordering::Less => {
 9003                            suffixes_inserted.next();
 9004                            continue;
 9005                        }
 9006                        Ordering::Greater => break,
 9007                        Ordering::Equal => {
 9008                            if selection.end.column == snapshot.line_len(row) {
 9009                                if selection.is_empty() {
 9010                                    selection.start.column -= suffix_len as u32;
 9011                                }
 9012                                selection.end.column -= suffix_len as u32;
 9013                            }
 9014                            break;
 9015                        }
 9016                    }
 9017                }
 9018            }
 9019
 9020            drop(snapshot);
 9021            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 9022
 9023            let selections = this.selections.all::<Point>(cx);
 9024            let selections_on_single_row = selections.windows(2).all(|selections| {
 9025                selections[0].start.row == selections[1].start.row
 9026                    && selections[0].end.row == selections[1].end.row
 9027                    && selections[0].start.row == selections[0].end.row
 9028            });
 9029            let selections_selecting = selections
 9030                .iter()
 9031                .any(|selection| selection.start != selection.end);
 9032            let advance_downwards = action.advance_downwards
 9033                && selections_on_single_row
 9034                && !selections_selecting
 9035                && !matches!(this.mode, EditorMode::SingleLine { .. });
 9036
 9037            if advance_downwards {
 9038                let snapshot = this.buffer.read(cx).snapshot(cx);
 9039
 9040                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9041                    s.move_cursors_with(|display_snapshot, display_point, _| {
 9042                        let mut point = display_point.to_point(display_snapshot);
 9043                        point.row += 1;
 9044                        point = snapshot.clip_point(point, Bias::Left);
 9045                        let display_point = point.to_display_point(display_snapshot);
 9046                        let goal = SelectionGoal::HorizontalPosition(
 9047                            display_snapshot
 9048                                .x_for_display_point(display_point, text_layout_details)
 9049                                .into(),
 9050                        );
 9051                        (display_point, goal)
 9052                    })
 9053                });
 9054            }
 9055        });
 9056    }
 9057
 9058    pub fn select_enclosing_symbol(
 9059        &mut self,
 9060        _: &SelectEnclosingSymbol,
 9061        cx: &mut ViewContext<Self>,
 9062    ) {
 9063        let buffer = self.buffer.read(cx).snapshot(cx);
 9064        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9065
 9066        fn update_selection(
 9067            selection: &Selection<usize>,
 9068            buffer_snap: &MultiBufferSnapshot,
 9069        ) -> Option<Selection<usize>> {
 9070            let cursor = selection.head();
 9071            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 9072            for symbol in symbols.iter().rev() {
 9073                let start = symbol.range.start.to_offset(buffer_snap);
 9074                let end = symbol.range.end.to_offset(buffer_snap);
 9075                let new_range = start..end;
 9076                if start < selection.start || end > selection.end {
 9077                    return Some(Selection {
 9078                        id: selection.id,
 9079                        start: new_range.start,
 9080                        end: new_range.end,
 9081                        goal: SelectionGoal::None,
 9082                        reversed: selection.reversed,
 9083                    });
 9084                }
 9085            }
 9086            None
 9087        }
 9088
 9089        let mut selected_larger_symbol = false;
 9090        let new_selections = old_selections
 9091            .iter()
 9092            .map(|selection| match update_selection(selection, &buffer) {
 9093                Some(new_selection) => {
 9094                    if new_selection.range() != selection.range() {
 9095                        selected_larger_symbol = true;
 9096                    }
 9097                    new_selection
 9098                }
 9099                None => selection.clone(),
 9100            })
 9101            .collect::<Vec<_>>();
 9102
 9103        if selected_larger_symbol {
 9104            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9105                s.select(new_selections);
 9106            });
 9107        }
 9108    }
 9109
 9110    pub fn select_larger_syntax_node(
 9111        &mut self,
 9112        _: &SelectLargerSyntaxNode,
 9113        cx: &mut ViewContext<Self>,
 9114    ) {
 9115        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9116        let buffer = self.buffer.read(cx).snapshot(cx);
 9117        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9118
 9119        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9120        let mut selected_larger_node = false;
 9121        let new_selections = old_selections
 9122            .iter()
 9123            .map(|selection| {
 9124                let old_range = selection.start..selection.end;
 9125                let mut new_range = old_range.clone();
 9126                while let Some(containing_range) =
 9127                    buffer.range_for_syntax_ancestor(new_range.clone())
 9128                {
 9129                    new_range = containing_range;
 9130                    if !display_map.intersects_fold(new_range.start)
 9131                        && !display_map.intersects_fold(new_range.end)
 9132                    {
 9133                        break;
 9134                    }
 9135                }
 9136
 9137                selected_larger_node |= new_range != old_range;
 9138                Selection {
 9139                    id: selection.id,
 9140                    start: new_range.start,
 9141                    end: new_range.end,
 9142                    goal: SelectionGoal::None,
 9143                    reversed: selection.reversed,
 9144                }
 9145            })
 9146            .collect::<Vec<_>>();
 9147
 9148        if selected_larger_node {
 9149            stack.push(old_selections);
 9150            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9151                s.select(new_selections);
 9152            });
 9153        }
 9154        self.select_larger_syntax_node_stack = stack;
 9155    }
 9156
 9157    pub fn select_smaller_syntax_node(
 9158        &mut self,
 9159        _: &SelectSmallerSyntaxNode,
 9160        cx: &mut ViewContext<Self>,
 9161    ) {
 9162        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9163        if let Some(selections) = stack.pop() {
 9164            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9165                s.select(selections.to_vec());
 9166            });
 9167        }
 9168        self.select_larger_syntax_node_stack = stack;
 9169    }
 9170
 9171    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 9172        if !EditorSettings::get_global(cx).gutter.runnables {
 9173            self.clear_tasks();
 9174            return Task::ready(());
 9175        }
 9176        let project = self.project.clone();
 9177        cx.spawn(|this, mut cx| async move {
 9178            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 9179                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 9180            }) else {
 9181                return;
 9182            };
 9183
 9184            let Some(project) = project else {
 9185                return;
 9186            };
 9187
 9188            let hide_runnables = project
 9189                .update(&mut cx, |project, cx| {
 9190                    // Do not display any test indicators in non-dev server remote projects.
 9191                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 9192                })
 9193                .unwrap_or(true);
 9194            if hide_runnables {
 9195                return;
 9196            }
 9197            let new_rows =
 9198                cx.background_executor()
 9199                    .spawn({
 9200                        let snapshot = display_snapshot.clone();
 9201                        async move {
 9202                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 9203                        }
 9204                    })
 9205                    .await;
 9206            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 9207
 9208            this.update(&mut cx, |this, _| {
 9209                this.clear_tasks();
 9210                for (key, value) in rows {
 9211                    this.insert_tasks(key, value);
 9212                }
 9213            })
 9214            .ok();
 9215        })
 9216    }
 9217    fn fetch_runnable_ranges(
 9218        snapshot: &DisplaySnapshot,
 9219        range: Range<Anchor>,
 9220    ) -> Vec<language::RunnableRange> {
 9221        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 9222    }
 9223
 9224    fn runnable_rows(
 9225        project: Model<Project>,
 9226        snapshot: DisplaySnapshot,
 9227        runnable_ranges: Vec<RunnableRange>,
 9228        mut cx: AsyncWindowContext,
 9229    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 9230        runnable_ranges
 9231            .into_iter()
 9232            .filter_map(|mut runnable| {
 9233                let tasks = cx
 9234                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 9235                    .ok()?;
 9236                if tasks.is_empty() {
 9237                    return None;
 9238                }
 9239
 9240                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 9241
 9242                let row = snapshot
 9243                    .buffer_snapshot
 9244                    .buffer_line_for_row(MultiBufferRow(point.row))?
 9245                    .1
 9246                    .start
 9247                    .row;
 9248
 9249                let context_range =
 9250                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 9251                Some((
 9252                    (runnable.buffer_id, row),
 9253                    RunnableTasks {
 9254                        templates: tasks,
 9255                        offset: MultiBufferOffset(runnable.run_range.start),
 9256                        context_range,
 9257                        column: point.column,
 9258                        extra_variables: runnable.extra_captures,
 9259                    },
 9260                ))
 9261            })
 9262            .collect()
 9263    }
 9264
 9265    fn templates_with_tags(
 9266        project: &Model<Project>,
 9267        runnable: &mut Runnable,
 9268        cx: &WindowContext<'_>,
 9269    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 9270        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 9271            let (worktree_id, file) = project
 9272                .buffer_for_id(runnable.buffer, cx)
 9273                .and_then(|buffer| buffer.read(cx).file())
 9274                .map(|file| (file.worktree_id(cx), file.clone()))
 9275                .unzip();
 9276
 9277            (
 9278                project.task_store().read(cx).task_inventory().cloned(),
 9279                worktree_id,
 9280                file,
 9281            )
 9282        });
 9283
 9284        let tags = mem::take(&mut runnable.tags);
 9285        let mut tags: Vec<_> = tags
 9286            .into_iter()
 9287            .flat_map(|tag| {
 9288                let tag = tag.0.clone();
 9289                inventory
 9290                    .as_ref()
 9291                    .into_iter()
 9292                    .flat_map(|inventory| {
 9293                        inventory.read(cx).list_tasks(
 9294                            file.clone(),
 9295                            Some(runnable.language.clone()),
 9296                            worktree_id,
 9297                            cx,
 9298                        )
 9299                    })
 9300                    .filter(move |(_, template)| {
 9301                        template.tags.iter().any(|source_tag| source_tag == &tag)
 9302                    })
 9303            })
 9304            .sorted_by_key(|(kind, _)| kind.to_owned())
 9305            .collect();
 9306        if let Some((leading_tag_source, _)) = tags.first() {
 9307            // Strongest source wins; if we have worktree tag binding, prefer that to
 9308            // global and language bindings;
 9309            // if we have a global binding, prefer that to language binding.
 9310            let first_mismatch = tags
 9311                .iter()
 9312                .position(|(tag_source, _)| tag_source != leading_tag_source);
 9313            if let Some(index) = first_mismatch {
 9314                tags.truncate(index);
 9315            }
 9316        }
 9317
 9318        tags
 9319    }
 9320
 9321    pub fn move_to_enclosing_bracket(
 9322        &mut self,
 9323        _: &MoveToEnclosingBracket,
 9324        cx: &mut ViewContext<Self>,
 9325    ) {
 9326        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9327            s.move_offsets_with(|snapshot, selection| {
 9328                let Some(enclosing_bracket_ranges) =
 9329                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 9330                else {
 9331                    return;
 9332                };
 9333
 9334                let mut best_length = usize::MAX;
 9335                let mut best_inside = false;
 9336                let mut best_in_bracket_range = false;
 9337                let mut best_destination = None;
 9338                for (open, close) in enclosing_bracket_ranges {
 9339                    let close = close.to_inclusive();
 9340                    let length = close.end() - open.start;
 9341                    let inside = selection.start >= open.end && selection.end <= *close.start();
 9342                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 9343                        || close.contains(&selection.head());
 9344
 9345                    // If best is next to a bracket and current isn't, skip
 9346                    if !in_bracket_range && best_in_bracket_range {
 9347                        continue;
 9348                    }
 9349
 9350                    // Prefer smaller lengths unless best is inside and current isn't
 9351                    if length > best_length && (best_inside || !inside) {
 9352                        continue;
 9353                    }
 9354
 9355                    best_length = length;
 9356                    best_inside = inside;
 9357                    best_in_bracket_range = in_bracket_range;
 9358                    best_destination = Some(
 9359                        if close.contains(&selection.start) && close.contains(&selection.end) {
 9360                            if inside {
 9361                                open.end
 9362                            } else {
 9363                                open.start
 9364                            }
 9365                        } else if inside {
 9366                            *close.start()
 9367                        } else {
 9368                            *close.end()
 9369                        },
 9370                    );
 9371                }
 9372
 9373                if let Some(destination) = best_destination {
 9374                    selection.collapse_to(destination, SelectionGoal::None);
 9375                }
 9376            })
 9377        });
 9378    }
 9379
 9380    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 9381        self.end_selection(cx);
 9382        self.selection_history.mode = SelectionHistoryMode::Undoing;
 9383        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 9384            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9385            self.select_next_state = entry.select_next_state;
 9386            self.select_prev_state = entry.select_prev_state;
 9387            self.add_selections_state = entry.add_selections_state;
 9388            self.request_autoscroll(Autoscroll::newest(), cx);
 9389        }
 9390        self.selection_history.mode = SelectionHistoryMode::Normal;
 9391    }
 9392
 9393    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 9394        self.end_selection(cx);
 9395        self.selection_history.mode = SelectionHistoryMode::Redoing;
 9396        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 9397            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9398            self.select_next_state = entry.select_next_state;
 9399            self.select_prev_state = entry.select_prev_state;
 9400            self.add_selections_state = entry.add_selections_state;
 9401            self.request_autoscroll(Autoscroll::newest(), cx);
 9402        }
 9403        self.selection_history.mode = SelectionHistoryMode::Normal;
 9404    }
 9405
 9406    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 9407        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 9408    }
 9409
 9410    pub fn expand_excerpts_down(
 9411        &mut self,
 9412        action: &ExpandExcerptsDown,
 9413        cx: &mut ViewContext<Self>,
 9414    ) {
 9415        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 9416    }
 9417
 9418    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 9419        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 9420    }
 9421
 9422    pub fn expand_excerpts_for_direction(
 9423        &mut self,
 9424        lines: u32,
 9425        direction: ExpandExcerptDirection,
 9426        cx: &mut ViewContext<Self>,
 9427    ) {
 9428        let selections = self.selections.disjoint_anchors();
 9429
 9430        let lines = if lines == 0 {
 9431            EditorSettings::get_global(cx).expand_excerpt_lines
 9432        } else {
 9433            lines
 9434        };
 9435
 9436        self.buffer.update(cx, |buffer, cx| {
 9437            buffer.expand_excerpts(
 9438                selections
 9439                    .iter()
 9440                    .map(|selection| selection.head().excerpt_id)
 9441                    .dedup(),
 9442                lines,
 9443                direction,
 9444                cx,
 9445            )
 9446        })
 9447    }
 9448
 9449    pub fn expand_excerpt(
 9450        &mut self,
 9451        excerpt: ExcerptId,
 9452        direction: ExpandExcerptDirection,
 9453        cx: &mut ViewContext<Self>,
 9454    ) {
 9455        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 9456        self.buffer.update(cx, |buffer, cx| {
 9457            buffer.expand_excerpts([excerpt], lines, direction, cx)
 9458        })
 9459    }
 9460
 9461    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 9462        self.go_to_diagnostic_impl(Direction::Next, cx)
 9463    }
 9464
 9465    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 9466        self.go_to_diagnostic_impl(Direction::Prev, cx)
 9467    }
 9468
 9469    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 9470        let buffer = self.buffer.read(cx).snapshot(cx);
 9471        let selection = self.selections.newest::<usize>(cx);
 9472
 9473        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 9474        if direction == Direction::Next {
 9475            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 9476                let (group_id, jump_to) = popover.activation_info();
 9477                if self.activate_diagnostics(group_id, cx) {
 9478                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9479                        let mut new_selection = s.newest_anchor().clone();
 9480                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 9481                        s.select_anchors(vec![new_selection.clone()]);
 9482                    });
 9483                }
 9484                return;
 9485            }
 9486        }
 9487
 9488        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 9489            active_diagnostics
 9490                .primary_range
 9491                .to_offset(&buffer)
 9492                .to_inclusive()
 9493        });
 9494        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 9495            if active_primary_range.contains(&selection.head()) {
 9496                *active_primary_range.start()
 9497            } else {
 9498                selection.head()
 9499            }
 9500        } else {
 9501            selection.head()
 9502        };
 9503        let snapshot = self.snapshot(cx);
 9504        loop {
 9505            let diagnostics = if direction == Direction::Prev {
 9506                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 9507            } else {
 9508                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 9509            }
 9510            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 9511            let group = diagnostics
 9512                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 9513                // be sorted in a stable way
 9514                // skip until we are at current active diagnostic, if it exists
 9515                .skip_while(|entry| {
 9516                    (match direction {
 9517                        Direction::Prev => entry.range.start >= search_start,
 9518                        Direction::Next => entry.range.start <= search_start,
 9519                    }) && self
 9520                        .active_diagnostics
 9521                        .as_ref()
 9522                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 9523                })
 9524                .find_map(|entry| {
 9525                    if entry.diagnostic.is_primary
 9526                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 9527                        && !entry.range.is_empty()
 9528                        // if we match with the active diagnostic, skip it
 9529                        && Some(entry.diagnostic.group_id)
 9530                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 9531                    {
 9532                        Some((entry.range, entry.diagnostic.group_id))
 9533                    } else {
 9534                        None
 9535                    }
 9536                });
 9537
 9538            if let Some((primary_range, group_id)) = group {
 9539                if self.activate_diagnostics(group_id, cx) {
 9540                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9541                        s.select(vec![Selection {
 9542                            id: selection.id,
 9543                            start: primary_range.start,
 9544                            end: primary_range.start,
 9545                            reversed: false,
 9546                            goal: SelectionGoal::None,
 9547                        }]);
 9548                    });
 9549                }
 9550                break;
 9551            } else {
 9552                // Cycle around to the start of the buffer, potentially moving back to the start of
 9553                // the currently active diagnostic.
 9554                active_primary_range.take();
 9555                if direction == Direction::Prev {
 9556                    if search_start == buffer.len() {
 9557                        break;
 9558                    } else {
 9559                        search_start = buffer.len();
 9560                    }
 9561                } else if search_start == 0 {
 9562                    break;
 9563                } else {
 9564                    search_start = 0;
 9565                }
 9566            }
 9567        }
 9568    }
 9569
 9570    fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 9571        let snapshot = self
 9572            .display_map
 9573            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9574        let selection = self.selections.newest::<Point>(cx);
 9575        self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
 9576    }
 9577
 9578    fn go_to_hunk_after_position(
 9579        &mut self,
 9580        snapshot: &DisplaySnapshot,
 9581        position: Point,
 9582        cx: &mut ViewContext<'_, Editor>,
 9583    ) -> Option<MultiBufferDiffHunk> {
 9584        if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9585            snapshot,
 9586            position,
 9587            false,
 9588            snapshot
 9589                .buffer_snapshot
 9590                .git_diff_hunks_in_range(MultiBufferRow(position.row + 1)..MultiBufferRow::MAX),
 9591            cx,
 9592        ) {
 9593            return Some(hunk);
 9594        }
 9595
 9596        let wrapped_point = Point::zero();
 9597        self.go_to_next_hunk_in_direction(
 9598            snapshot,
 9599            wrapped_point,
 9600            true,
 9601            snapshot.buffer_snapshot.git_diff_hunks_in_range(
 9602                MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
 9603            ),
 9604            cx,
 9605        )
 9606    }
 9607
 9608    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 9609        let snapshot = self
 9610            .display_map
 9611            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9612        let selection = self.selections.newest::<Point>(cx);
 9613
 9614        self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
 9615    }
 9616
 9617    fn go_to_hunk_before_position(
 9618        &mut self,
 9619        snapshot: &DisplaySnapshot,
 9620        position: Point,
 9621        cx: &mut ViewContext<'_, Editor>,
 9622    ) -> Option<MultiBufferDiffHunk> {
 9623        if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9624            snapshot,
 9625            position,
 9626            false,
 9627            snapshot
 9628                .buffer_snapshot
 9629                .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(position.row)),
 9630            cx,
 9631        ) {
 9632            return Some(hunk);
 9633        }
 9634
 9635        let wrapped_point = snapshot.buffer_snapshot.max_point();
 9636        self.go_to_next_hunk_in_direction(
 9637            snapshot,
 9638            wrapped_point,
 9639            true,
 9640            snapshot
 9641                .buffer_snapshot
 9642                .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(wrapped_point.row)),
 9643            cx,
 9644        )
 9645    }
 9646
 9647    fn go_to_next_hunk_in_direction(
 9648        &mut self,
 9649        snapshot: &DisplaySnapshot,
 9650        initial_point: Point,
 9651        is_wrapped: bool,
 9652        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
 9653        cx: &mut ViewContext<Editor>,
 9654    ) -> Option<MultiBufferDiffHunk> {
 9655        let display_point = initial_point.to_display_point(snapshot);
 9656        let mut hunks = hunks
 9657            .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
 9658            .filter(|(display_hunk, _)| {
 9659                is_wrapped || !display_hunk.contains_display_row(display_point.row())
 9660            })
 9661            .dedup();
 9662
 9663        if let Some((display_hunk, hunk)) = hunks.next() {
 9664            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9665                let row = display_hunk.start_display_row();
 9666                let point = DisplayPoint::new(row, 0);
 9667                s.select_display_ranges([point..point]);
 9668            });
 9669
 9670            Some(hunk)
 9671        } else {
 9672            None
 9673        }
 9674    }
 9675
 9676    pub fn go_to_definition(
 9677        &mut self,
 9678        _: &GoToDefinition,
 9679        cx: &mut ViewContext<Self>,
 9680    ) -> Task<Result<Navigated>> {
 9681        let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
 9682        cx.spawn(|editor, mut cx| async move {
 9683            if definition.await? == Navigated::Yes {
 9684                return Ok(Navigated::Yes);
 9685            }
 9686            match editor.update(&mut cx, |editor, cx| {
 9687                editor.find_all_references(&FindAllReferences, cx)
 9688            })? {
 9689                Some(references) => references.await,
 9690                None => Ok(Navigated::No),
 9691            }
 9692        })
 9693    }
 9694
 9695    pub fn go_to_declaration(
 9696        &mut self,
 9697        _: &GoToDeclaration,
 9698        cx: &mut ViewContext<Self>,
 9699    ) -> Task<Result<Navigated>> {
 9700        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
 9701    }
 9702
 9703    pub fn go_to_declaration_split(
 9704        &mut self,
 9705        _: &GoToDeclaration,
 9706        cx: &mut ViewContext<Self>,
 9707    ) -> Task<Result<Navigated>> {
 9708        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
 9709    }
 9710
 9711    pub fn go_to_implementation(
 9712        &mut self,
 9713        _: &GoToImplementation,
 9714        cx: &mut ViewContext<Self>,
 9715    ) -> Task<Result<Navigated>> {
 9716        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 9717    }
 9718
 9719    pub fn go_to_implementation_split(
 9720        &mut self,
 9721        _: &GoToImplementationSplit,
 9722        cx: &mut ViewContext<Self>,
 9723    ) -> Task<Result<Navigated>> {
 9724        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 9725    }
 9726
 9727    pub fn go_to_type_definition(
 9728        &mut self,
 9729        _: &GoToTypeDefinition,
 9730        cx: &mut ViewContext<Self>,
 9731    ) -> Task<Result<Navigated>> {
 9732        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 9733    }
 9734
 9735    pub fn go_to_definition_split(
 9736        &mut self,
 9737        _: &GoToDefinitionSplit,
 9738        cx: &mut ViewContext<Self>,
 9739    ) -> Task<Result<Navigated>> {
 9740        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 9741    }
 9742
 9743    pub fn go_to_type_definition_split(
 9744        &mut self,
 9745        _: &GoToTypeDefinitionSplit,
 9746        cx: &mut ViewContext<Self>,
 9747    ) -> Task<Result<Navigated>> {
 9748        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 9749    }
 9750
 9751    fn go_to_definition_of_kind(
 9752        &mut self,
 9753        kind: GotoDefinitionKind,
 9754        split: bool,
 9755        cx: &mut ViewContext<Self>,
 9756    ) -> Task<Result<Navigated>> {
 9757        let Some(provider) = self.semantics_provider.clone() else {
 9758            return Task::ready(Ok(Navigated::No));
 9759        };
 9760        let head = self.selections.newest::<usize>(cx).head();
 9761        let buffer = self.buffer.read(cx);
 9762        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 9763            text_anchor
 9764        } else {
 9765            return Task::ready(Ok(Navigated::No));
 9766        };
 9767
 9768        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
 9769            return Task::ready(Ok(Navigated::No));
 9770        };
 9771
 9772        cx.spawn(|editor, mut cx| async move {
 9773            let definitions = definitions.await?;
 9774            let navigated = editor
 9775                .update(&mut cx, |editor, cx| {
 9776                    editor.navigate_to_hover_links(
 9777                        Some(kind),
 9778                        definitions
 9779                            .into_iter()
 9780                            .filter(|location| {
 9781                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 9782                            })
 9783                            .map(HoverLink::Text)
 9784                            .collect::<Vec<_>>(),
 9785                        split,
 9786                        cx,
 9787                    )
 9788                })?
 9789                .await?;
 9790            anyhow::Ok(navigated)
 9791        })
 9792    }
 9793
 9794    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 9795        let position = self.selections.newest_anchor().head();
 9796        let Some((buffer, buffer_position)) =
 9797            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9798        else {
 9799            return;
 9800        };
 9801
 9802        cx.spawn(|editor, mut cx| async move {
 9803            if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
 9804                editor.update(&mut cx, |_, cx| {
 9805                    cx.open_url(&url);
 9806                })
 9807            } else {
 9808                Ok(())
 9809            }
 9810        })
 9811        .detach();
 9812    }
 9813
 9814    pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
 9815        let Some(workspace) = self.workspace() else {
 9816            return;
 9817        };
 9818
 9819        let position = self.selections.newest_anchor().head();
 9820
 9821        let Some((buffer, buffer_position)) =
 9822            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9823        else {
 9824            return;
 9825        };
 9826
 9827        let project = self.project.clone();
 9828
 9829        cx.spawn(|_, mut cx| async move {
 9830            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
 9831
 9832            if let Some((_, path)) = result {
 9833                workspace
 9834                    .update(&mut cx, |workspace, cx| {
 9835                        workspace.open_resolved_path(path, cx)
 9836                    })?
 9837                    .await?;
 9838            }
 9839            anyhow::Ok(())
 9840        })
 9841        .detach();
 9842    }
 9843
 9844    pub(crate) fn navigate_to_hover_links(
 9845        &mut self,
 9846        kind: Option<GotoDefinitionKind>,
 9847        mut definitions: Vec<HoverLink>,
 9848        split: bool,
 9849        cx: &mut ViewContext<Editor>,
 9850    ) -> Task<Result<Navigated>> {
 9851        // If there is one definition, just open it directly
 9852        if definitions.len() == 1 {
 9853            let definition = definitions.pop().unwrap();
 9854
 9855            enum TargetTaskResult {
 9856                Location(Option<Location>),
 9857                AlreadyNavigated,
 9858            }
 9859
 9860            let target_task = match definition {
 9861                HoverLink::Text(link) => {
 9862                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
 9863                }
 9864                HoverLink::InlayHint(lsp_location, server_id) => {
 9865                    let computation = self.compute_target_location(lsp_location, server_id, cx);
 9866                    cx.background_executor().spawn(async move {
 9867                        let location = computation.await?;
 9868                        Ok(TargetTaskResult::Location(location))
 9869                    })
 9870                }
 9871                HoverLink::Url(url) => {
 9872                    cx.open_url(&url);
 9873                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
 9874                }
 9875                HoverLink::File(path) => {
 9876                    if let Some(workspace) = self.workspace() {
 9877                        cx.spawn(|_, mut cx| async move {
 9878                            workspace
 9879                                .update(&mut cx, |workspace, cx| {
 9880                                    workspace.open_resolved_path(path, cx)
 9881                                })?
 9882                                .await
 9883                                .map(|_| TargetTaskResult::AlreadyNavigated)
 9884                        })
 9885                    } else {
 9886                        Task::ready(Ok(TargetTaskResult::Location(None)))
 9887                    }
 9888                }
 9889            };
 9890            cx.spawn(|editor, mut cx| async move {
 9891                let target = match target_task.await.context("target resolution task")? {
 9892                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
 9893                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
 9894                    TargetTaskResult::Location(Some(target)) => target,
 9895                };
 9896
 9897                editor.update(&mut cx, |editor, cx| {
 9898                    let Some(workspace) = editor.workspace() else {
 9899                        return Navigated::No;
 9900                    };
 9901                    let pane = workspace.read(cx).active_pane().clone();
 9902
 9903                    let range = target.range.to_offset(target.buffer.read(cx));
 9904                    let range = editor.range_for_match(&range);
 9905
 9906                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 9907                        let buffer = target.buffer.read(cx);
 9908                        let range = check_multiline_range(buffer, range);
 9909                        editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9910                            s.select_ranges([range]);
 9911                        });
 9912                    } else {
 9913                        cx.window_context().defer(move |cx| {
 9914                            let target_editor: View<Self> =
 9915                                workspace.update(cx, |workspace, cx| {
 9916                                    let pane = if split {
 9917                                        workspace.adjacent_pane(cx)
 9918                                    } else {
 9919                                        workspace.active_pane().clone()
 9920                                    };
 9921
 9922                                    workspace.open_project_item(
 9923                                        pane,
 9924                                        target.buffer.clone(),
 9925                                        true,
 9926                                        true,
 9927                                        cx,
 9928                                    )
 9929                                });
 9930                            target_editor.update(cx, |target_editor, cx| {
 9931                                // When selecting a definition in a different buffer, disable the nav history
 9932                                // to avoid creating a history entry at the previous cursor location.
 9933                                pane.update(cx, |pane, _| pane.disable_history());
 9934                                let buffer = target.buffer.read(cx);
 9935                                let range = check_multiline_range(buffer, range);
 9936                                target_editor.change_selections(
 9937                                    Some(Autoscroll::focused()),
 9938                                    cx,
 9939                                    |s| {
 9940                                        s.select_ranges([range]);
 9941                                    },
 9942                                );
 9943                                pane.update(cx, |pane, _| pane.enable_history());
 9944                            });
 9945                        });
 9946                    }
 9947                    Navigated::Yes
 9948                })
 9949            })
 9950        } else if !definitions.is_empty() {
 9951            cx.spawn(|editor, mut cx| async move {
 9952                let (title, location_tasks, workspace) = editor
 9953                    .update(&mut cx, |editor, cx| {
 9954                        let tab_kind = match kind {
 9955                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 9956                            _ => "Definitions",
 9957                        };
 9958                        let title = definitions
 9959                            .iter()
 9960                            .find_map(|definition| match definition {
 9961                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 9962                                    let buffer = origin.buffer.read(cx);
 9963                                    format!(
 9964                                        "{} for {}",
 9965                                        tab_kind,
 9966                                        buffer
 9967                                            .text_for_range(origin.range.clone())
 9968                                            .collect::<String>()
 9969                                    )
 9970                                }),
 9971                                HoverLink::InlayHint(_, _) => None,
 9972                                HoverLink::Url(_) => None,
 9973                                HoverLink::File(_) => None,
 9974                            })
 9975                            .unwrap_or(tab_kind.to_string());
 9976                        let location_tasks = definitions
 9977                            .into_iter()
 9978                            .map(|definition| match definition {
 9979                                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 9980                                HoverLink::InlayHint(lsp_location, server_id) => {
 9981                                    editor.compute_target_location(lsp_location, server_id, cx)
 9982                                }
 9983                                HoverLink::Url(_) => Task::ready(Ok(None)),
 9984                                HoverLink::File(_) => Task::ready(Ok(None)),
 9985                            })
 9986                            .collect::<Vec<_>>();
 9987                        (title, location_tasks, editor.workspace().clone())
 9988                    })
 9989                    .context("location tasks preparation")?;
 9990
 9991                let locations = future::join_all(location_tasks)
 9992                    .await
 9993                    .into_iter()
 9994                    .filter_map(|location| location.transpose())
 9995                    .collect::<Result<_>>()
 9996                    .context("location tasks")?;
 9997
 9998                let Some(workspace) = workspace else {
 9999                    return Ok(Navigated::No);
10000                };
10001                let opened = workspace
10002                    .update(&mut cx, |workspace, cx| {
10003                        Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
10004                    })
10005                    .ok();
10006
10007                anyhow::Ok(Navigated::from_bool(opened.is_some()))
10008            })
10009        } else {
10010            Task::ready(Ok(Navigated::No))
10011        }
10012    }
10013
10014    fn compute_target_location(
10015        &self,
10016        lsp_location: lsp::Location,
10017        server_id: LanguageServerId,
10018        cx: &mut ViewContext<Self>,
10019    ) -> Task<anyhow::Result<Option<Location>>> {
10020        let Some(project) = self.project.clone() else {
10021            return Task::Ready(Some(Ok(None)));
10022        };
10023
10024        cx.spawn(move |editor, mut cx| async move {
10025            let location_task = editor.update(&mut cx, |_, cx| {
10026                project.update(cx, |project, cx| {
10027                    let language_server_name = project
10028                        .language_server_statuses(cx)
10029                        .find(|(id, _)| server_id == *id)
10030                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10031                    language_server_name.map(|language_server_name| {
10032                        project.open_local_buffer_via_lsp(
10033                            lsp_location.uri.clone(),
10034                            server_id,
10035                            language_server_name,
10036                            cx,
10037                        )
10038                    })
10039                })
10040            })?;
10041            let location = match location_task {
10042                Some(task) => Some({
10043                    let target_buffer_handle = task.await.context("open local buffer")?;
10044                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10045                        let target_start = target_buffer
10046                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10047                        let target_end = target_buffer
10048                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10049                        target_buffer.anchor_after(target_start)
10050                            ..target_buffer.anchor_before(target_end)
10051                    })?;
10052                    Location {
10053                        buffer: target_buffer_handle,
10054                        range,
10055                    }
10056                }),
10057                None => None,
10058            };
10059            Ok(location)
10060        })
10061    }
10062
10063    pub fn find_all_references(
10064        &mut self,
10065        _: &FindAllReferences,
10066        cx: &mut ViewContext<Self>,
10067    ) -> Option<Task<Result<Navigated>>> {
10068        let selection = self.selections.newest::<usize>(cx);
10069        let multi_buffer = self.buffer.read(cx);
10070        let head = selection.head();
10071
10072        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10073        let head_anchor = multi_buffer_snapshot.anchor_at(
10074            head,
10075            if head < selection.tail() {
10076                Bias::Right
10077            } else {
10078                Bias::Left
10079            },
10080        );
10081
10082        match self
10083            .find_all_references_task_sources
10084            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10085        {
10086            Ok(_) => {
10087                log::info!(
10088                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
10089                );
10090                return None;
10091            }
10092            Err(i) => {
10093                self.find_all_references_task_sources.insert(i, head_anchor);
10094            }
10095        }
10096
10097        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10098        let workspace = self.workspace()?;
10099        let project = workspace.read(cx).project().clone();
10100        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10101        Some(cx.spawn(|editor, mut cx| async move {
10102            let _cleanup = defer({
10103                let mut cx = cx.clone();
10104                move || {
10105                    let _ = editor.update(&mut cx, |editor, _| {
10106                        if let Ok(i) =
10107                            editor
10108                                .find_all_references_task_sources
10109                                .binary_search_by(|anchor| {
10110                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10111                                })
10112                        {
10113                            editor.find_all_references_task_sources.remove(i);
10114                        }
10115                    });
10116                }
10117            });
10118
10119            let locations = references.await?;
10120            if locations.is_empty() {
10121                return anyhow::Ok(Navigated::No);
10122            }
10123
10124            workspace.update(&mut cx, |workspace, cx| {
10125                let title = locations
10126                    .first()
10127                    .as_ref()
10128                    .map(|location| {
10129                        let buffer = location.buffer.read(cx);
10130                        format!(
10131                            "References to `{}`",
10132                            buffer
10133                                .text_for_range(location.range.clone())
10134                                .collect::<String>()
10135                        )
10136                    })
10137                    .unwrap();
10138                Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
10139                Navigated::Yes
10140            })
10141        }))
10142    }
10143
10144    /// Opens a multibuffer with the given project locations in it
10145    pub fn open_locations_in_multibuffer(
10146        workspace: &mut Workspace,
10147        mut locations: Vec<Location>,
10148        title: String,
10149        split: bool,
10150        cx: &mut ViewContext<Workspace>,
10151    ) {
10152        // If there are multiple definitions, open them in a multibuffer
10153        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10154        let mut locations = locations.into_iter().peekable();
10155        let mut ranges_to_highlight = Vec::new();
10156        let capability = workspace.project().read(cx).capability();
10157
10158        let excerpt_buffer = cx.new_model(|cx| {
10159            let mut multibuffer = MultiBuffer::new(capability);
10160            while let Some(location) = locations.next() {
10161                let buffer = location.buffer.read(cx);
10162                let mut ranges_for_buffer = Vec::new();
10163                let range = location.range.to_offset(buffer);
10164                ranges_for_buffer.push(range.clone());
10165
10166                while let Some(next_location) = locations.peek() {
10167                    if next_location.buffer == location.buffer {
10168                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
10169                        locations.next();
10170                    } else {
10171                        break;
10172                    }
10173                }
10174
10175                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10176                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
10177                    location.buffer.clone(),
10178                    ranges_for_buffer,
10179                    DEFAULT_MULTIBUFFER_CONTEXT,
10180                    cx,
10181                ))
10182            }
10183
10184            multibuffer.with_title(title)
10185        });
10186
10187        let editor = cx.new_view(|cx| {
10188            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
10189        });
10190        editor.update(cx, |editor, cx| {
10191            if let Some(first_range) = ranges_to_highlight.first() {
10192                editor.change_selections(None, cx, |selections| {
10193                    selections.clear_disjoint();
10194                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10195                });
10196            }
10197            editor.highlight_background::<Self>(
10198                &ranges_to_highlight,
10199                |theme| theme.editor_highlighted_line_background,
10200                cx,
10201            );
10202        });
10203
10204        let item = Box::new(editor);
10205        let item_id = item.item_id();
10206
10207        if split {
10208            workspace.split_item(SplitDirection::Right, item.clone(), cx);
10209        } else {
10210            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10211                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10212                    pane.close_current_preview_item(cx)
10213                } else {
10214                    None
10215                }
10216            });
10217            workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
10218        }
10219        workspace.active_pane().update(cx, |pane, cx| {
10220            pane.set_preview_item_id(Some(item_id), cx);
10221        });
10222    }
10223
10224    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10225        use language::ToOffset as _;
10226
10227        let provider = self.semantics_provider.clone()?;
10228        let selection = self.selections.newest_anchor().clone();
10229        let (cursor_buffer, cursor_buffer_position) = self
10230            .buffer
10231            .read(cx)
10232            .text_anchor_for_position(selection.head(), cx)?;
10233        let (tail_buffer, cursor_buffer_position_end) = self
10234            .buffer
10235            .read(cx)
10236            .text_anchor_for_position(selection.tail(), cx)?;
10237        if tail_buffer != cursor_buffer {
10238            return None;
10239        }
10240
10241        let snapshot = cursor_buffer.read(cx).snapshot();
10242        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10243        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10244        let prepare_rename = provider
10245            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10246            .unwrap_or_else(|| Task::ready(Ok(None)));
10247        drop(snapshot);
10248
10249        Some(cx.spawn(|this, mut cx| async move {
10250            let rename_range = if let Some(range) = prepare_rename.await? {
10251                Some(range)
10252            } else {
10253                this.update(&mut cx, |this, cx| {
10254                    let buffer = this.buffer.read(cx).snapshot(cx);
10255                    let mut buffer_highlights = this
10256                        .document_highlights_for_position(selection.head(), &buffer)
10257                        .filter(|highlight| {
10258                            highlight.start.excerpt_id == selection.head().excerpt_id
10259                                && highlight.end.excerpt_id == selection.head().excerpt_id
10260                        });
10261                    buffer_highlights
10262                        .next()
10263                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10264                })?
10265            };
10266            if let Some(rename_range) = rename_range {
10267                this.update(&mut cx, |this, cx| {
10268                    let snapshot = cursor_buffer.read(cx).snapshot();
10269                    let rename_buffer_range = rename_range.to_offset(&snapshot);
10270                    let cursor_offset_in_rename_range =
10271                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10272                    let cursor_offset_in_rename_range_end =
10273                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10274
10275                    this.take_rename(false, cx);
10276                    let buffer = this.buffer.read(cx).read(cx);
10277                    let cursor_offset = selection.head().to_offset(&buffer);
10278                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10279                    let rename_end = rename_start + rename_buffer_range.len();
10280                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10281                    let mut old_highlight_id = None;
10282                    let old_name: Arc<str> = buffer
10283                        .chunks(rename_start..rename_end, true)
10284                        .map(|chunk| {
10285                            if old_highlight_id.is_none() {
10286                                old_highlight_id = chunk.syntax_highlight_id;
10287                            }
10288                            chunk.text
10289                        })
10290                        .collect::<String>()
10291                        .into();
10292
10293                    drop(buffer);
10294
10295                    // Position the selection in the rename editor so that it matches the current selection.
10296                    this.show_local_selections = false;
10297                    let rename_editor = cx.new_view(|cx| {
10298                        let mut editor = Editor::single_line(cx);
10299                        editor.buffer.update(cx, |buffer, cx| {
10300                            buffer.edit([(0..0, old_name.clone())], None, cx)
10301                        });
10302                        let rename_selection_range = match cursor_offset_in_rename_range
10303                            .cmp(&cursor_offset_in_rename_range_end)
10304                        {
10305                            Ordering::Equal => {
10306                                editor.select_all(&SelectAll, cx);
10307                                return editor;
10308                            }
10309                            Ordering::Less => {
10310                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10311                            }
10312                            Ordering::Greater => {
10313                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10314                            }
10315                        };
10316                        if rename_selection_range.end > old_name.len() {
10317                            editor.select_all(&SelectAll, cx);
10318                        } else {
10319                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10320                                s.select_ranges([rename_selection_range]);
10321                            });
10322                        }
10323                        editor
10324                    });
10325                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10326                        if e == &EditorEvent::Focused {
10327                            cx.emit(EditorEvent::FocusedIn)
10328                        }
10329                    })
10330                    .detach();
10331
10332                    let write_highlights =
10333                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10334                    let read_highlights =
10335                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
10336                    let ranges = write_highlights
10337                        .iter()
10338                        .flat_map(|(_, ranges)| ranges.iter())
10339                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10340                        .cloned()
10341                        .collect();
10342
10343                    this.highlight_text::<Rename>(
10344                        ranges,
10345                        HighlightStyle {
10346                            fade_out: Some(0.6),
10347                            ..Default::default()
10348                        },
10349                        cx,
10350                    );
10351                    let rename_focus_handle = rename_editor.focus_handle(cx);
10352                    cx.focus(&rename_focus_handle);
10353                    let block_id = this.insert_blocks(
10354                        [BlockProperties {
10355                            style: BlockStyle::Flex,
10356                            placement: BlockPlacement::Below(range.start),
10357                            height: 1,
10358                            render: Box::new({
10359                                let rename_editor = rename_editor.clone();
10360                                move |cx: &mut BlockContext| {
10361                                    let mut text_style = cx.editor_style.text.clone();
10362                                    if let Some(highlight_style) = old_highlight_id
10363                                        .and_then(|h| h.style(&cx.editor_style.syntax))
10364                                    {
10365                                        text_style = text_style.highlight(highlight_style);
10366                                    }
10367                                    div()
10368                                        .pl(cx.anchor_x)
10369                                        .child(EditorElement::new(
10370                                            &rename_editor,
10371                                            EditorStyle {
10372                                                background: cx.theme().system().transparent,
10373                                                local_player: cx.editor_style.local_player,
10374                                                text: text_style,
10375                                                scrollbar_width: cx.editor_style.scrollbar_width,
10376                                                syntax: cx.editor_style.syntax.clone(),
10377                                                status: cx.editor_style.status.clone(),
10378                                                inlay_hints_style: HighlightStyle {
10379                                                    font_weight: Some(FontWeight::BOLD),
10380                                                    ..make_inlay_hints_style(cx)
10381                                                },
10382                                                suggestions_style: HighlightStyle {
10383                                                    color: Some(cx.theme().status().predictive),
10384                                                    ..HighlightStyle::default()
10385                                                },
10386                                                ..EditorStyle::default()
10387                                            },
10388                                        ))
10389                                        .into_any_element()
10390                                }
10391                            }),
10392                            priority: 0,
10393                        }],
10394                        Some(Autoscroll::fit()),
10395                        cx,
10396                    )[0];
10397                    this.pending_rename = Some(RenameState {
10398                        range,
10399                        old_name,
10400                        editor: rename_editor,
10401                        block_id,
10402                    });
10403                })?;
10404            }
10405
10406            Ok(())
10407        }))
10408    }
10409
10410    pub fn confirm_rename(
10411        &mut self,
10412        _: &ConfirmRename,
10413        cx: &mut ViewContext<Self>,
10414    ) -> Option<Task<Result<()>>> {
10415        let rename = self.take_rename(false, cx)?;
10416        let workspace = self.workspace()?.downgrade();
10417        let (buffer, start) = self
10418            .buffer
10419            .read(cx)
10420            .text_anchor_for_position(rename.range.start, cx)?;
10421        let (end_buffer, _) = self
10422            .buffer
10423            .read(cx)
10424            .text_anchor_for_position(rename.range.end, cx)?;
10425        if buffer != end_buffer {
10426            return None;
10427        }
10428
10429        let old_name = rename.old_name;
10430        let new_name = rename.editor.read(cx).text(cx);
10431
10432        let rename = self.semantics_provider.as_ref()?.perform_rename(
10433            &buffer,
10434            start,
10435            new_name.clone(),
10436            cx,
10437        )?;
10438
10439        Some(cx.spawn(|editor, mut cx| async move {
10440            let project_transaction = rename.await?;
10441            Self::open_project_transaction(
10442                &editor,
10443                workspace,
10444                project_transaction,
10445                format!("Rename: {}{}", old_name, new_name),
10446                cx.clone(),
10447            )
10448            .await?;
10449
10450            editor.update(&mut cx, |editor, cx| {
10451                editor.refresh_document_highlights(cx);
10452            })?;
10453            Ok(())
10454        }))
10455    }
10456
10457    fn take_rename(
10458        &mut self,
10459        moving_cursor: bool,
10460        cx: &mut ViewContext<Self>,
10461    ) -> Option<RenameState> {
10462        let rename = self.pending_rename.take()?;
10463        if rename.editor.focus_handle(cx).is_focused(cx) {
10464            cx.focus(&self.focus_handle);
10465        }
10466
10467        self.remove_blocks(
10468            [rename.block_id].into_iter().collect(),
10469            Some(Autoscroll::fit()),
10470            cx,
10471        );
10472        self.clear_highlights::<Rename>(cx);
10473        self.show_local_selections = true;
10474
10475        if moving_cursor {
10476            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10477                editor.selections.newest::<usize>(cx).head()
10478            });
10479
10480            // Update the selection to match the position of the selection inside
10481            // the rename editor.
10482            let snapshot = self.buffer.read(cx).read(cx);
10483            let rename_range = rename.range.to_offset(&snapshot);
10484            let cursor_in_editor = snapshot
10485                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10486                .min(rename_range.end);
10487            drop(snapshot);
10488
10489            self.change_selections(None, cx, |s| {
10490                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10491            });
10492        } else {
10493            self.refresh_document_highlights(cx);
10494        }
10495
10496        Some(rename)
10497    }
10498
10499    pub fn pending_rename(&self) -> Option<&RenameState> {
10500        self.pending_rename.as_ref()
10501    }
10502
10503    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10504        let project = match &self.project {
10505            Some(project) => project.clone(),
10506            None => return None,
10507        };
10508
10509        Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10510    }
10511
10512    fn format_selections(
10513        &mut self,
10514        _: &FormatSelections,
10515        cx: &mut ViewContext<Self>,
10516    ) -> Option<Task<Result<()>>> {
10517        let project = match &self.project {
10518            Some(project) => project.clone(),
10519            None => return None,
10520        };
10521
10522        let selections = self
10523            .selections
10524            .all_adjusted(cx)
10525            .into_iter()
10526            .filter(|s| !s.is_empty())
10527            .collect_vec();
10528
10529        Some(self.perform_format(
10530            project,
10531            FormatTrigger::Manual,
10532            FormatTarget::Ranges(selections),
10533            cx,
10534        ))
10535    }
10536
10537    fn perform_format(
10538        &mut self,
10539        project: Model<Project>,
10540        trigger: FormatTrigger,
10541        target: FormatTarget,
10542        cx: &mut ViewContext<Self>,
10543    ) -> Task<Result<()>> {
10544        let buffer = self.buffer().clone();
10545        let mut buffers = buffer.read(cx).all_buffers();
10546        if trigger == FormatTrigger::Save {
10547            buffers.retain(|buffer| buffer.read(cx).is_dirty());
10548        }
10549
10550        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10551        let format = project.update(cx, |project, cx| {
10552            project.format(buffers, true, trigger, target, cx)
10553        });
10554
10555        cx.spawn(|_, mut cx| async move {
10556            let transaction = futures::select_biased! {
10557                () = timeout => {
10558                    log::warn!("timed out waiting for formatting");
10559                    None
10560                }
10561                transaction = format.log_err().fuse() => transaction,
10562            };
10563
10564            buffer
10565                .update(&mut cx, |buffer, cx| {
10566                    if let Some(transaction) = transaction {
10567                        if !buffer.is_singleton() {
10568                            buffer.push_transaction(&transaction.0, cx);
10569                        }
10570                    }
10571
10572                    cx.notify();
10573                })
10574                .ok();
10575
10576            Ok(())
10577        })
10578    }
10579
10580    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10581        if let Some(project) = self.project.clone() {
10582            self.buffer.update(cx, |multi_buffer, cx| {
10583                project.update(cx, |project, cx| {
10584                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10585                });
10586            })
10587        }
10588    }
10589
10590    fn cancel_language_server_work(
10591        &mut self,
10592        _: &actions::CancelLanguageServerWork,
10593        cx: &mut ViewContext<Self>,
10594    ) {
10595        if let Some(project) = self.project.clone() {
10596            self.buffer.update(cx, |multi_buffer, cx| {
10597                project.update(cx, |project, cx| {
10598                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10599                });
10600            })
10601        }
10602    }
10603
10604    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10605        cx.show_character_palette();
10606    }
10607
10608    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10609        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10610            let buffer = self.buffer.read(cx).snapshot(cx);
10611            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10612            let is_valid = buffer
10613                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10614                .any(|entry| {
10615                    entry.diagnostic.is_primary
10616                        && !entry.range.is_empty()
10617                        && entry.range.start == primary_range_start
10618                        && entry.diagnostic.message == active_diagnostics.primary_message
10619                });
10620
10621            if is_valid != active_diagnostics.is_valid {
10622                active_diagnostics.is_valid = is_valid;
10623                let mut new_styles = HashMap::default();
10624                for (block_id, diagnostic) in &active_diagnostics.blocks {
10625                    new_styles.insert(
10626                        *block_id,
10627                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10628                    );
10629                }
10630                self.display_map.update(cx, |display_map, _cx| {
10631                    display_map.replace_blocks(new_styles)
10632                });
10633            }
10634        }
10635    }
10636
10637    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10638        self.dismiss_diagnostics(cx);
10639        let snapshot = self.snapshot(cx);
10640        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10641            let buffer = self.buffer.read(cx).snapshot(cx);
10642
10643            let mut primary_range = None;
10644            let mut primary_message = None;
10645            let mut group_end = Point::zero();
10646            let diagnostic_group = buffer
10647                .diagnostic_group::<MultiBufferPoint>(group_id)
10648                .filter_map(|entry| {
10649                    if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10650                        && (entry.range.start.row == entry.range.end.row
10651                            || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10652                    {
10653                        return None;
10654                    }
10655                    if entry.range.end > group_end {
10656                        group_end = entry.range.end;
10657                    }
10658                    if entry.diagnostic.is_primary {
10659                        primary_range = Some(entry.range.clone());
10660                        primary_message = Some(entry.diagnostic.message.clone());
10661                    }
10662                    Some(entry)
10663                })
10664                .collect::<Vec<_>>();
10665            let primary_range = primary_range?;
10666            let primary_message = primary_message?;
10667            let primary_range =
10668                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10669
10670            let blocks = display_map
10671                .insert_blocks(
10672                    diagnostic_group.iter().map(|entry| {
10673                        let diagnostic = entry.diagnostic.clone();
10674                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10675                        BlockProperties {
10676                            style: BlockStyle::Fixed,
10677                            placement: BlockPlacement::Below(
10678                                buffer.anchor_after(entry.range.start),
10679                            ),
10680                            height: message_height,
10681                            render: diagnostic_block_renderer(diagnostic, None, true, true),
10682                            priority: 0,
10683                        }
10684                    }),
10685                    cx,
10686                )
10687                .into_iter()
10688                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10689                .collect();
10690
10691            Some(ActiveDiagnosticGroup {
10692                primary_range,
10693                primary_message,
10694                group_id,
10695                blocks,
10696                is_valid: true,
10697            })
10698        });
10699        self.active_diagnostics.is_some()
10700    }
10701
10702    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10703        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10704            self.display_map.update(cx, |display_map, cx| {
10705                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10706            });
10707            cx.notify();
10708        }
10709    }
10710
10711    pub fn set_selections_from_remote(
10712        &mut self,
10713        selections: Vec<Selection<Anchor>>,
10714        pending_selection: Option<Selection<Anchor>>,
10715        cx: &mut ViewContext<Self>,
10716    ) {
10717        let old_cursor_position = self.selections.newest_anchor().head();
10718        self.selections.change_with(cx, |s| {
10719            s.select_anchors(selections);
10720            if let Some(pending_selection) = pending_selection {
10721                s.set_pending(pending_selection, SelectMode::Character);
10722            } else {
10723                s.clear_pending();
10724            }
10725        });
10726        self.selections_did_change(false, &old_cursor_position, true, cx);
10727    }
10728
10729    fn push_to_selection_history(&mut self) {
10730        self.selection_history.push(SelectionHistoryEntry {
10731            selections: self.selections.disjoint_anchors(),
10732            select_next_state: self.select_next_state.clone(),
10733            select_prev_state: self.select_prev_state.clone(),
10734            add_selections_state: self.add_selections_state.clone(),
10735        });
10736    }
10737
10738    pub fn transact(
10739        &mut self,
10740        cx: &mut ViewContext<Self>,
10741        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10742    ) -> Option<TransactionId> {
10743        self.start_transaction_at(Instant::now(), cx);
10744        update(self, cx);
10745        self.end_transaction_at(Instant::now(), cx)
10746    }
10747
10748    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10749        self.end_selection(cx);
10750        if let Some(tx_id) = self
10751            .buffer
10752            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10753        {
10754            self.selection_history
10755                .insert_transaction(tx_id, self.selections.disjoint_anchors());
10756            cx.emit(EditorEvent::TransactionBegun {
10757                transaction_id: tx_id,
10758            })
10759        }
10760    }
10761
10762    fn end_transaction_at(
10763        &mut self,
10764        now: Instant,
10765        cx: &mut ViewContext<Self>,
10766    ) -> Option<TransactionId> {
10767        if let Some(transaction_id) = self
10768            .buffer
10769            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10770        {
10771            if let Some((_, end_selections)) =
10772                self.selection_history.transaction_mut(transaction_id)
10773            {
10774                *end_selections = Some(self.selections.disjoint_anchors());
10775            } else {
10776                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10777            }
10778
10779            cx.emit(EditorEvent::Edited { transaction_id });
10780            Some(transaction_id)
10781        } else {
10782            None
10783        }
10784    }
10785
10786    pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10787        let selection = self.selections.newest::<Point>(cx);
10788
10789        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10790        let range = if selection.is_empty() {
10791            let point = selection.head().to_display_point(&display_map);
10792            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10793            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10794                .to_point(&display_map);
10795            start..end
10796        } else {
10797            selection.range()
10798        };
10799        if display_map.folds_in_range(range).next().is_some() {
10800            self.unfold_lines(&Default::default(), cx)
10801        } else {
10802            self.fold(&Default::default(), cx)
10803        }
10804    }
10805
10806    pub fn toggle_fold_recursive(
10807        &mut self,
10808        _: &actions::ToggleFoldRecursive,
10809        cx: &mut ViewContext<Self>,
10810    ) {
10811        let selection = self.selections.newest::<Point>(cx);
10812
10813        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10814        let range = if selection.is_empty() {
10815            let point = selection.head().to_display_point(&display_map);
10816            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10817            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10818                .to_point(&display_map);
10819            start..end
10820        } else {
10821            selection.range()
10822        };
10823        if display_map.folds_in_range(range).next().is_some() {
10824            self.unfold_recursive(&Default::default(), cx)
10825        } else {
10826            self.fold_recursive(&Default::default(), cx)
10827        }
10828    }
10829
10830    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10831        let mut fold_ranges = Vec::new();
10832        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10833        let selections = self.selections.all_adjusted(cx);
10834
10835        for selection in selections {
10836            let range = selection.range().sorted();
10837            let buffer_start_row = range.start.row;
10838
10839            if range.start.row != range.end.row {
10840                let mut found = false;
10841                let mut row = range.start.row;
10842                while row <= range.end.row {
10843                    if let Some((foldable_range, fold_text)) =
10844                        { display_map.foldable_range(MultiBufferRow(row)) }
10845                    {
10846                        found = true;
10847                        row = foldable_range.end.row + 1;
10848                        fold_ranges.push((foldable_range, fold_text));
10849                    } else {
10850                        row += 1
10851                    }
10852                }
10853                if found {
10854                    continue;
10855                }
10856            }
10857
10858            for row in (0..=range.start.row).rev() {
10859                if let Some((foldable_range, fold_text)) =
10860                    display_map.foldable_range(MultiBufferRow(row))
10861                {
10862                    if foldable_range.end.row >= buffer_start_row {
10863                        fold_ranges.push((foldable_range, fold_text));
10864                        if row <= range.start.row {
10865                            break;
10866                        }
10867                    }
10868                }
10869            }
10870        }
10871
10872        self.fold_ranges(fold_ranges, true, cx);
10873    }
10874
10875    fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10876        let fold_at_level = fold_at.level;
10877        let snapshot = self.buffer.read(cx).snapshot(cx);
10878        let mut fold_ranges = Vec::new();
10879        let mut stack = vec![(0, snapshot.max_buffer_row().0, 1)];
10880
10881        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10882            while start_row < end_row {
10883                match self.snapshot(cx).foldable_range(MultiBufferRow(start_row)) {
10884                    Some(foldable_range) => {
10885                        let nested_start_row = foldable_range.0.start.row + 1;
10886                        let nested_end_row = foldable_range.0.end.row;
10887
10888                        if current_level < fold_at_level {
10889                            stack.push((nested_start_row, nested_end_row, current_level + 1));
10890                        } else if current_level == fold_at_level {
10891                            fold_ranges.push(foldable_range);
10892                        }
10893
10894                        start_row = nested_end_row + 1;
10895                    }
10896                    None => start_row += 1,
10897                }
10898            }
10899        }
10900
10901        self.fold_ranges(fold_ranges, true, cx);
10902    }
10903
10904    pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10905        let mut fold_ranges = Vec::new();
10906        let snapshot = self.buffer.read(cx).snapshot(cx);
10907
10908        for row in 0..snapshot.max_buffer_row().0 {
10909            if let Some(foldable_range) = self.snapshot(cx).foldable_range(MultiBufferRow(row)) {
10910                fold_ranges.push(foldable_range);
10911            }
10912        }
10913
10914        self.fold_ranges(fold_ranges, true, cx);
10915    }
10916
10917    pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10918        let mut fold_ranges = Vec::new();
10919        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10920        let selections = self.selections.all_adjusted(cx);
10921
10922        for selection in selections {
10923            let range = selection.range().sorted();
10924            let buffer_start_row = range.start.row;
10925
10926            if range.start.row != range.end.row {
10927                let mut found = false;
10928                for row in range.start.row..=range.end.row {
10929                    if let Some((foldable_range, fold_text)) =
10930                        { display_map.foldable_range(MultiBufferRow(row)) }
10931                    {
10932                        found = true;
10933                        fold_ranges.push((foldable_range, fold_text));
10934                    }
10935                }
10936                if found {
10937                    continue;
10938                }
10939            }
10940
10941            for row in (0..=range.start.row).rev() {
10942                if let Some((foldable_range, fold_text)) =
10943                    display_map.foldable_range(MultiBufferRow(row))
10944                {
10945                    if foldable_range.end.row >= buffer_start_row {
10946                        fold_ranges.push((foldable_range, fold_text));
10947                    } else {
10948                        break;
10949                    }
10950                }
10951            }
10952        }
10953
10954        self.fold_ranges(fold_ranges, true, cx);
10955    }
10956
10957    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10958        let buffer_row = fold_at.buffer_row;
10959        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10960
10961        if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
10962            let autoscroll = self
10963                .selections
10964                .all::<Point>(cx)
10965                .iter()
10966                .any(|selection| fold_range.overlaps(&selection.range()));
10967
10968            self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
10969        }
10970    }
10971
10972    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10973        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10974        let buffer = &display_map.buffer_snapshot;
10975        let selections = self.selections.all::<Point>(cx);
10976        let ranges = selections
10977            .iter()
10978            .map(|s| {
10979                let range = s.display_range(&display_map).sorted();
10980                let mut start = range.start.to_point(&display_map);
10981                let mut end = range.end.to_point(&display_map);
10982                start.column = 0;
10983                end.column = buffer.line_len(MultiBufferRow(end.row));
10984                start..end
10985            })
10986            .collect::<Vec<_>>();
10987
10988        self.unfold_ranges(ranges, true, true, cx);
10989    }
10990
10991    pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10992        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10993        let selections = self.selections.all::<Point>(cx);
10994        let ranges = selections
10995            .iter()
10996            .map(|s| {
10997                let mut range = s.display_range(&display_map).sorted();
10998                *range.start.column_mut() = 0;
10999                *range.end.column_mut() = display_map.line_len(range.end.row());
11000                let start = range.start.to_point(&display_map);
11001                let end = range.end.to_point(&display_map);
11002                start..end
11003            })
11004            .collect::<Vec<_>>();
11005
11006        self.unfold_ranges(ranges, true, true, cx);
11007    }
11008
11009    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
11010        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11011
11012        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
11013            ..Point::new(
11014                unfold_at.buffer_row.0,
11015                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
11016            );
11017
11018        let autoscroll = self
11019            .selections
11020            .all::<Point>(cx)
11021            .iter()
11022            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
11023
11024        self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
11025    }
11026
11027    pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
11028        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11029        self.unfold_ranges(
11030            [Point::zero()..display_map.max_point().to_point(&display_map)],
11031            true,
11032            true,
11033            cx,
11034        );
11035    }
11036
11037    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
11038        let selections = self.selections.all::<Point>(cx);
11039        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11040        let line_mode = self.selections.line_mode;
11041        let ranges = selections.into_iter().map(|s| {
11042            if line_mode {
11043                let start = Point::new(s.start.row, 0);
11044                let end = Point::new(
11045                    s.end.row,
11046                    display_map
11047                        .buffer_snapshot
11048                        .line_len(MultiBufferRow(s.end.row)),
11049                );
11050                (start..end, display_map.fold_placeholder.clone())
11051            } else {
11052                (s.start..s.end, display_map.fold_placeholder.clone())
11053            }
11054        });
11055        self.fold_ranges(ranges, true, cx);
11056    }
11057
11058    pub fn fold_ranges<T: ToOffset + Clone>(
11059        &mut self,
11060        ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
11061        auto_scroll: bool,
11062        cx: &mut ViewContext<Self>,
11063    ) {
11064        let mut fold_ranges = Vec::new();
11065        let mut buffers_affected = HashMap::default();
11066        let multi_buffer = self.buffer().read(cx);
11067        for (fold_range, fold_text) in ranges {
11068            if let Some((_, buffer, _)) =
11069                multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
11070            {
11071                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
11072            };
11073            fold_ranges.push((fold_range, fold_text));
11074        }
11075
11076        let mut ranges = fold_ranges.into_iter().peekable();
11077        if ranges.peek().is_some() {
11078            self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
11079
11080            if auto_scroll {
11081                self.request_autoscroll(Autoscroll::fit(), cx);
11082            }
11083
11084            for buffer in buffers_affected.into_values() {
11085                self.sync_expanded_diff_hunks(buffer, cx);
11086            }
11087
11088            cx.notify();
11089
11090            if let Some(active_diagnostics) = self.active_diagnostics.take() {
11091                // Clear diagnostics block when folding a range that contains it.
11092                let snapshot = self.snapshot(cx);
11093                if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
11094                    drop(snapshot);
11095                    self.active_diagnostics = Some(active_diagnostics);
11096                    self.dismiss_diagnostics(cx);
11097                } else {
11098                    self.active_diagnostics = Some(active_diagnostics);
11099                }
11100            }
11101
11102            self.scrollbar_marker_state.dirty = true;
11103        }
11104    }
11105
11106    pub fn unfold_ranges<T: ToOffset + Clone>(
11107        &mut self,
11108        ranges: impl IntoIterator<Item = Range<T>>,
11109        inclusive: bool,
11110        auto_scroll: bool,
11111        cx: &mut ViewContext<Self>,
11112    ) {
11113        let mut unfold_ranges = Vec::new();
11114        let mut buffers_affected = HashMap::default();
11115        let multi_buffer = self.buffer().read(cx);
11116        for range in ranges {
11117            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11118                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
11119            };
11120            unfold_ranges.push(range);
11121        }
11122
11123        let mut ranges = unfold_ranges.into_iter().peekable();
11124        if ranges.peek().is_some() {
11125            self.display_map
11126                .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
11127            if auto_scroll {
11128                self.request_autoscroll(Autoscroll::fit(), cx);
11129            }
11130
11131            for buffer in buffers_affected.into_values() {
11132                self.sync_expanded_diff_hunks(buffer, cx);
11133            }
11134
11135            cx.notify();
11136            self.scrollbar_marker_state.dirty = true;
11137            self.active_indent_guides_state.dirty = true;
11138        }
11139    }
11140
11141    pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
11142        self.display_map.read(cx).fold_placeholder.clone()
11143    }
11144
11145    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11146        if hovered != self.gutter_hovered {
11147            self.gutter_hovered = hovered;
11148            cx.notify();
11149        }
11150    }
11151
11152    pub fn insert_blocks(
11153        &mut self,
11154        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11155        autoscroll: Option<Autoscroll>,
11156        cx: &mut ViewContext<Self>,
11157    ) -> Vec<CustomBlockId> {
11158        let blocks = self
11159            .display_map
11160            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11161        if let Some(autoscroll) = autoscroll {
11162            self.request_autoscroll(autoscroll, cx);
11163        }
11164        cx.notify();
11165        blocks
11166    }
11167
11168    pub fn resize_blocks(
11169        &mut self,
11170        heights: HashMap<CustomBlockId, u32>,
11171        autoscroll: Option<Autoscroll>,
11172        cx: &mut ViewContext<Self>,
11173    ) {
11174        self.display_map
11175            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11176        if let Some(autoscroll) = autoscroll {
11177            self.request_autoscroll(autoscroll, cx);
11178        }
11179        cx.notify();
11180    }
11181
11182    pub fn replace_blocks(
11183        &mut self,
11184        renderers: HashMap<CustomBlockId, RenderBlock>,
11185        autoscroll: Option<Autoscroll>,
11186        cx: &mut ViewContext<Self>,
11187    ) {
11188        self.display_map
11189            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11190        if let Some(autoscroll) = autoscroll {
11191            self.request_autoscroll(autoscroll, cx);
11192        }
11193        cx.notify();
11194    }
11195
11196    pub fn remove_blocks(
11197        &mut self,
11198        block_ids: HashSet<CustomBlockId>,
11199        autoscroll: Option<Autoscroll>,
11200        cx: &mut ViewContext<Self>,
11201    ) {
11202        self.display_map.update(cx, |display_map, cx| {
11203            display_map.remove_blocks(block_ids, cx)
11204        });
11205        if let Some(autoscroll) = autoscroll {
11206            self.request_autoscroll(autoscroll, cx);
11207        }
11208        cx.notify();
11209    }
11210
11211    pub fn row_for_block(
11212        &self,
11213        block_id: CustomBlockId,
11214        cx: &mut ViewContext<Self>,
11215    ) -> Option<DisplayRow> {
11216        self.display_map
11217            .update(cx, |map, cx| map.row_for_block(block_id, cx))
11218    }
11219
11220    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11221        self.focused_block = Some(focused_block);
11222    }
11223
11224    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11225        self.focused_block.take()
11226    }
11227
11228    pub fn insert_creases(
11229        &mut self,
11230        creases: impl IntoIterator<Item = Crease>,
11231        cx: &mut ViewContext<Self>,
11232    ) -> Vec<CreaseId> {
11233        self.display_map
11234            .update(cx, |map, cx| map.insert_creases(creases, cx))
11235    }
11236
11237    pub fn remove_creases(
11238        &mut self,
11239        ids: impl IntoIterator<Item = CreaseId>,
11240        cx: &mut ViewContext<Self>,
11241    ) {
11242        self.display_map
11243            .update(cx, |map, cx| map.remove_creases(ids, cx));
11244    }
11245
11246    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11247        self.display_map
11248            .update(cx, |map, cx| map.snapshot(cx))
11249            .longest_row()
11250    }
11251
11252    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11253        self.display_map
11254            .update(cx, |map, cx| map.snapshot(cx))
11255            .max_point()
11256    }
11257
11258    pub fn text(&self, cx: &AppContext) -> String {
11259        self.buffer.read(cx).read(cx).text()
11260    }
11261
11262    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11263        let text = self.text(cx);
11264        let text = text.trim();
11265
11266        if text.is_empty() {
11267            return None;
11268        }
11269
11270        Some(text.to_string())
11271    }
11272
11273    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11274        self.transact(cx, |this, cx| {
11275            this.buffer
11276                .read(cx)
11277                .as_singleton()
11278                .expect("you can only call set_text on editors for singleton buffers")
11279                .update(cx, |buffer, cx| buffer.set_text(text, cx));
11280        });
11281    }
11282
11283    pub fn display_text(&self, cx: &mut AppContext) -> String {
11284        self.display_map
11285            .update(cx, |map, cx| map.snapshot(cx))
11286            .text()
11287    }
11288
11289    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11290        let mut wrap_guides = smallvec::smallvec![];
11291
11292        if self.show_wrap_guides == Some(false) {
11293            return wrap_guides;
11294        }
11295
11296        let settings = self.buffer.read(cx).settings_at(0, cx);
11297        if settings.show_wrap_guides {
11298            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11299                wrap_guides.push((soft_wrap as usize, true));
11300            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11301                wrap_guides.push((soft_wrap as usize, true));
11302            }
11303            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11304        }
11305
11306        wrap_guides
11307    }
11308
11309    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11310        let settings = self.buffer.read(cx).settings_at(0, cx);
11311        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11312        match mode {
11313            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11314                SoftWrap::None
11315            }
11316            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11317            language_settings::SoftWrap::PreferredLineLength => {
11318                SoftWrap::Column(settings.preferred_line_length)
11319            }
11320            language_settings::SoftWrap::Bounded => {
11321                SoftWrap::Bounded(settings.preferred_line_length)
11322            }
11323        }
11324    }
11325
11326    pub fn set_soft_wrap_mode(
11327        &mut self,
11328        mode: language_settings::SoftWrap,
11329        cx: &mut ViewContext<Self>,
11330    ) {
11331        self.soft_wrap_mode_override = Some(mode);
11332        cx.notify();
11333    }
11334
11335    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11336        self.text_style_refinement = Some(style);
11337    }
11338
11339    /// called by the Element so we know what style we were most recently rendered with.
11340    pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11341        let rem_size = cx.rem_size();
11342        self.display_map.update(cx, |map, cx| {
11343            map.set_font(
11344                style.text.font(),
11345                style.text.font_size.to_pixels(rem_size),
11346                cx,
11347            )
11348        });
11349        self.style = Some(style);
11350    }
11351
11352    pub fn style(&self) -> Option<&EditorStyle> {
11353        self.style.as_ref()
11354    }
11355
11356    // Called by the element. This method is not designed to be called outside of the editor
11357    // element's layout code because it does not notify when rewrapping is computed synchronously.
11358    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11359        self.display_map
11360            .update(cx, |map, cx| map.set_wrap_width(width, cx))
11361    }
11362
11363    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11364        if self.soft_wrap_mode_override.is_some() {
11365            self.soft_wrap_mode_override.take();
11366        } else {
11367            let soft_wrap = match self.soft_wrap_mode(cx) {
11368                SoftWrap::GitDiff => return,
11369                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11370                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11371                    language_settings::SoftWrap::None
11372                }
11373            };
11374            self.soft_wrap_mode_override = Some(soft_wrap);
11375        }
11376        cx.notify();
11377    }
11378
11379    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11380        let Some(workspace) = self.workspace() else {
11381            return;
11382        };
11383        let fs = workspace.read(cx).app_state().fs.clone();
11384        let current_show = TabBarSettings::get_global(cx).show;
11385        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11386            setting.show = Some(!current_show);
11387        });
11388    }
11389
11390    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11391        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11392            self.buffer
11393                .read(cx)
11394                .settings_at(0, cx)
11395                .indent_guides
11396                .enabled
11397        });
11398        self.show_indent_guides = Some(!currently_enabled);
11399        cx.notify();
11400    }
11401
11402    fn should_show_indent_guides(&self) -> Option<bool> {
11403        self.show_indent_guides
11404    }
11405
11406    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11407        let mut editor_settings = EditorSettings::get_global(cx).clone();
11408        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11409        EditorSettings::override_global(editor_settings, cx);
11410    }
11411
11412    pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11413        self.use_relative_line_numbers
11414            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11415    }
11416
11417    pub fn toggle_relative_line_numbers(
11418        &mut self,
11419        _: &ToggleRelativeLineNumbers,
11420        cx: &mut ViewContext<Self>,
11421    ) {
11422        let is_relative = self.should_use_relative_line_numbers(cx);
11423        self.set_relative_line_number(Some(!is_relative), cx)
11424    }
11425
11426    pub fn set_relative_line_number(
11427        &mut self,
11428        is_relative: Option<bool>,
11429        cx: &mut ViewContext<Self>,
11430    ) {
11431        self.use_relative_line_numbers = is_relative;
11432        cx.notify();
11433    }
11434
11435    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11436        self.show_gutter = show_gutter;
11437        cx.notify();
11438    }
11439
11440    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11441        self.show_line_numbers = Some(show_line_numbers);
11442        cx.notify();
11443    }
11444
11445    pub fn set_show_git_diff_gutter(
11446        &mut self,
11447        show_git_diff_gutter: bool,
11448        cx: &mut ViewContext<Self>,
11449    ) {
11450        self.show_git_diff_gutter = Some(show_git_diff_gutter);
11451        cx.notify();
11452    }
11453
11454    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11455        self.show_code_actions = Some(show_code_actions);
11456        cx.notify();
11457    }
11458
11459    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11460        self.show_runnables = Some(show_runnables);
11461        cx.notify();
11462    }
11463
11464    pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11465        if self.display_map.read(cx).masked != masked {
11466            self.display_map.update(cx, |map, _| map.masked = masked);
11467        }
11468        cx.notify()
11469    }
11470
11471    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11472        self.show_wrap_guides = Some(show_wrap_guides);
11473        cx.notify();
11474    }
11475
11476    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11477        self.show_indent_guides = Some(show_indent_guides);
11478        cx.notify();
11479    }
11480
11481    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11482        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11483            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11484                if let Some(dir) = file.abs_path(cx).parent() {
11485                    return Some(dir.to_owned());
11486                }
11487            }
11488
11489            if let Some(project_path) = buffer.read(cx).project_path(cx) {
11490                return Some(project_path.path.to_path_buf());
11491            }
11492        }
11493
11494        None
11495    }
11496
11497    fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11498        self.active_excerpt(cx)?
11499            .1
11500            .read(cx)
11501            .file()
11502            .and_then(|f| f.as_local())
11503    }
11504
11505    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11506        if let Some(target) = self.target_file(cx) {
11507            cx.reveal_path(&target.abs_path(cx));
11508        }
11509    }
11510
11511    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11512        if let Some(file) = self.target_file(cx) {
11513            if let Some(path) = file.abs_path(cx).to_str() {
11514                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11515            }
11516        }
11517    }
11518
11519    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11520        if let Some(file) = self.target_file(cx) {
11521            if let Some(path) = file.path().to_str() {
11522                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11523            }
11524        }
11525    }
11526
11527    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11528        self.show_git_blame_gutter = !self.show_git_blame_gutter;
11529
11530        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11531            self.start_git_blame(true, cx);
11532        }
11533
11534        cx.notify();
11535    }
11536
11537    pub fn toggle_git_blame_inline(
11538        &mut self,
11539        _: &ToggleGitBlameInline,
11540        cx: &mut ViewContext<Self>,
11541    ) {
11542        self.toggle_git_blame_inline_internal(true, cx);
11543        cx.notify();
11544    }
11545
11546    pub fn git_blame_inline_enabled(&self) -> bool {
11547        self.git_blame_inline_enabled
11548    }
11549
11550    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11551        self.show_selection_menu = self
11552            .show_selection_menu
11553            .map(|show_selections_menu| !show_selections_menu)
11554            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11555
11556        cx.notify();
11557    }
11558
11559    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11560        self.show_selection_menu
11561            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11562    }
11563
11564    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11565        if let Some(project) = self.project.as_ref() {
11566            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11567                return;
11568            };
11569
11570            if buffer.read(cx).file().is_none() {
11571                return;
11572            }
11573
11574            let focused = self.focus_handle(cx).contains_focused(cx);
11575
11576            let project = project.clone();
11577            let blame =
11578                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11579            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11580            self.blame = Some(blame);
11581        }
11582    }
11583
11584    fn toggle_git_blame_inline_internal(
11585        &mut self,
11586        user_triggered: bool,
11587        cx: &mut ViewContext<Self>,
11588    ) {
11589        if self.git_blame_inline_enabled {
11590            self.git_blame_inline_enabled = false;
11591            self.show_git_blame_inline = false;
11592            self.show_git_blame_inline_delay_task.take();
11593        } else {
11594            self.git_blame_inline_enabled = true;
11595            self.start_git_blame_inline(user_triggered, cx);
11596        }
11597
11598        cx.notify();
11599    }
11600
11601    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11602        self.start_git_blame(user_triggered, cx);
11603
11604        if ProjectSettings::get_global(cx)
11605            .git
11606            .inline_blame_delay()
11607            .is_some()
11608        {
11609            self.start_inline_blame_timer(cx);
11610        } else {
11611            self.show_git_blame_inline = true
11612        }
11613    }
11614
11615    pub fn blame(&self) -> Option<&Model<GitBlame>> {
11616        self.blame.as_ref()
11617    }
11618
11619    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11620        self.show_git_blame_gutter && self.has_blame_entries(cx)
11621    }
11622
11623    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11624        self.show_git_blame_inline
11625            && self.focus_handle.is_focused(cx)
11626            && !self.newest_selection_head_on_empty_line(cx)
11627            && self.has_blame_entries(cx)
11628    }
11629
11630    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11631        self.blame()
11632            .map_or(false, |blame| blame.read(cx).has_generated_entries())
11633    }
11634
11635    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11636        let cursor_anchor = self.selections.newest_anchor().head();
11637
11638        let snapshot = self.buffer.read(cx).snapshot(cx);
11639        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11640
11641        snapshot.line_len(buffer_row) == 0
11642    }
11643
11644    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11645        let buffer_and_selection = maybe!({
11646            let selection = self.selections.newest::<Point>(cx);
11647            let selection_range = selection.range();
11648
11649            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11650                (buffer, selection_range.start.row..selection_range.end.row)
11651            } else {
11652                let buffer_ranges = self
11653                    .buffer()
11654                    .read(cx)
11655                    .range_to_buffer_ranges(selection_range, cx);
11656
11657                let (buffer, range, _) = if selection.reversed {
11658                    buffer_ranges.first()
11659                } else {
11660                    buffer_ranges.last()
11661                }?;
11662
11663                let snapshot = buffer.read(cx).snapshot();
11664                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11665                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
11666                (buffer.clone(), selection)
11667            };
11668
11669            Some((buffer, selection))
11670        });
11671
11672        let Some((buffer, selection)) = buffer_and_selection else {
11673            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11674        };
11675
11676        let Some(project) = self.project.as_ref() else {
11677            return Task::ready(Err(anyhow!("editor does not have project")));
11678        };
11679
11680        project.update(cx, |project, cx| {
11681            project.get_permalink_to_line(&buffer, selection, cx)
11682        })
11683    }
11684
11685    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11686        let permalink_task = self.get_permalink_to_line(cx);
11687        let workspace = self.workspace();
11688
11689        cx.spawn(|_, mut cx| async move {
11690            match permalink_task.await {
11691                Ok(permalink) => {
11692                    cx.update(|cx| {
11693                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11694                    })
11695                    .ok();
11696                }
11697                Err(err) => {
11698                    let message = format!("Failed to copy permalink: {err}");
11699
11700                    Err::<(), anyhow::Error>(err).log_err();
11701
11702                    if let Some(workspace) = workspace {
11703                        workspace
11704                            .update(&mut cx, |workspace, cx| {
11705                                struct CopyPermalinkToLine;
11706
11707                                workspace.show_toast(
11708                                    Toast::new(
11709                                        NotificationId::unique::<CopyPermalinkToLine>(),
11710                                        message,
11711                                    ),
11712                                    cx,
11713                                )
11714                            })
11715                            .ok();
11716                    }
11717                }
11718            }
11719        })
11720        .detach();
11721    }
11722
11723    pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11724        let selection = self.selections.newest::<Point>(cx).start.row + 1;
11725        if let Some(file) = self.target_file(cx) {
11726            if let Some(path) = file.path().to_str() {
11727                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11728            }
11729        }
11730    }
11731
11732    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11733        let permalink_task = self.get_permalink_to_line(cx);
11734        let workspace = self.workspace();
11735
11736        cx.spawn(|_, mut cx| async move {
11737            match permalink_task.await {
11738                Ok(permalink) => {
11739                    cx.update(|cx| {
11740                        cx.open_url(permalink.as_ref());
11741                    })
11742                    .ok();
11743                }
11744                Err(err) => {
11745                    let message = format!("Failed to open permalink: {err}");
11746
11747                    Err::<(), anyhow::Error>(err).log_err();
11748
11749                    if let Some(workspace) = workspace {
11750                        workspace
11751                            .update(&mut cx, |workspace, cx| {
11752                                struct OpenPermalinkToLine;
11753
11754                                workspace.show_toast(
11755                                    Toast::new(
11756                                        NotificationId::unique::<OpenPermalinkToLine>(),
11757                                        message,
11758                                    ),
11759                                    cx,
11760                                )
11761                            })
11762                            .ok();
11763                    }
11764                }
11765            }
11766        })
11767        .detach();
11768    }
11769
11770    /// Adds a row highlight for the given range. If a row has multiple highlights, the
11771    /// last highlight added will be used.
11772    ///
11773    /// If the range ends at the beginning of a line, then that line will not be highlighted.
11774    pub fn highlight_rows<T: 'static>(
11775        &mut self,
11776        range: Range<Anchor>,
11777        color: Hsla,
11778        should_autoscroll: bool,
11779        cx: &mut ViewContext<Self>,
11780    ) {
11781        let snapshot = self.buffer().read(cx).snapshot(cx);
11782        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11783        let ix = row_highlights.binary_search_by(|highlight| {
11784            Ordering::Equal
11785                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11786                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11787        });
11788
11789        if let Err(mut ix) = ix {
11790            let index = post_inc(&mut self.highlight_order);
11791
11792            // If this range intersects with the preceding highlight, then merge it with
11793            // the preceding highlight. Otherwise insert a new highlight.
11794            let mut merged = false;
11795            if ix > 0 {
11796                let prev_highlight = &mut row_highlights[ix - 1];
11797                if prev_highlight
11798                    .range
11799                    .end
11800                    .cmp(&range.start, &snapshot)
11801                    .is_ge()
11802                {
11803                    ix -= 1;
11804                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11805                        prev_highlight.range.end = range.end;
11806                    }
11807                    merged = true;
11808                    prev_highlight.index = index;
11809                    prev_highlight.color = color;
11810                    prev_highlight.should_autoscroll = should_autoscroll;
11811                }
11812            }
11813
11814            if !merged {
11815                row_highlights.insert(
11816                    ix,
11817                    RowHighlight {
11818                        range: range.clone(),
11819                        index,
11820                        color,
11821                        should_autoscroll,
11822                    },
11823                );
11824            }
11825
11826            // If any of the following highlights intersect with this one, merge them.
11827            while let Some(next_highlight) = row_highlights.get(ix + 1) {
11828                let highlight = &row_highlights[ix];
11829                if next_highlight
11830                    .range
11831                    .start
11832                    .cmp(&highlight.range.end, &snapshot)
11833                    .is_le()
11834                {
11835                    if next_highlight
11836                        .range
11837                        .end
11838                        .cmp(&highlight.range.end, &snapshot)
11839                        .is_gt()
11840                    {
11841                        row_highlights[ix].range.end = next_highlight.range.end;
11842                    }
11843                    row_highlights.remove(ix + 1);
11844                } else {
11845                    break;
11846                }
11847            }
11848        }
11849    }
11850
11851    /// Remove any highlighted row ranges of the given type that intersect the
11852    /// given ranges.
11853    pub fn remove_highlighted_rows<T: 'static>(
11854        &mut self,
11855        ranges_to_remove: Vec<Range<Anchor>>,
11856        cx: &mut ViewContext<Self>,
11857    ) {
11858        let snapshot = self.buffer().read(cx).snapshot(cx);
11859        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11860        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11861        row_highlights.retain(|highlight| {
11862            while let Some(range_to_remove) = ranges_to_remove.peek() {
11863                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11864                    Ordering::Less | Ordering::Equal => {
11865                        ranges_to_remove.next();
11866                    }
11867                    Ordering::Greater => {
11868                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11869                            Ordering::Less | Ordering::Equal => {
11870                                return false;
11871                            }
11872                            Ordering::Greater => break,
11873                        }
11874                    }
11875                }
11876            }
11877
11878            true
11879        })
11880    }
11881
11882    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11883    pub fn clear_row_highlights<T: 'static>(&mut self) {
11884        self.highlighted_rows.remove(&TypeId::of::<T>());
11885    }
11886
11887    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11888    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11889        self.highlighted_rows
11890            .get(&TypeId::of::<T>())
11891            .map_or(&[] as &[_], |vec| vec.as_slice())
11892            .iter()
11893            .map(|highlight| (highlight.range.clone(), highlight.color))
11894    }
11895
11896    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11897    /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11898    /// Allows to ignore certain kinds of highlights.
11899    pub fn highlighted_display_rows(
11900        &mut self,
11901        cx: &mut WindowContext,
11902    ) -> BTreeMap<DisplayRow, Hsla> {
11903        let snapshot = self.snapshot(cx);
11904        let mut used_highlight_orders = HashMap::default();
11905        self.highlighted_rows
11906            .iter()
11907            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11908            .fold(
11909                BTreeMap::<DisplayRow, Hsla>::new(),
11910                |mut unique_rows, highlight| {
11911                    let start = highlight.range.start.to_display_point(&snapshot);
11912                    let end = highlight.range.end.to_display_point(&snapshot);
11913                    let start_row = start.row().0;
11914                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11915                        && end.column() == 0
11916                    {
11917                        end.row().0.saturating_sub(1)
11918                    } else {
11919                        end.row().0
11920                    };
11921                    for row in start_row..=end_row {
11922                        let used_index =
11923                            used_highlight_orders.entry(row).or_insert(highlight.index);
11924                        if highlight.index >= *used_index {
11925                            *used_index = highlight.index;
11926                            unique_rows.insert(DisplayRow(row), highlight.color);
11927                        }
11928                    }
11929                    unique_rows
11930                },
11931            )
11932    }
11933
11934    pub fn highlighted_display_row_for_autoscroll(
11935        &self,
11936        snapshot: &DisplaySnapshot,
11937    ) -> Option<DisplayRow> {
11938        self.highlighted_rows
11939            .values()
11940            .flat_map(|highlighted_rows| highlighted_rows.iter())
11941            .filter_map(|highlight| {
11942                if highlight.should_autoscroll {
11943                    Some(highlight.range.start.to_display_point(snapshot).row())
11944                } else {
11945                    None
11946                }
11947            })
11948            .min()
11949    }
11950
11951    pub fn set_search_within_ranges(
11952        &mut self,
11953        ranges: &[Range<Anchor>],
11954        cx: &mut ViewContext<Self>,
11955    ) {
11956        self.highlight_background::<SearchWithinRange>(
11957            ranges,
11958            |colors| colors.editor_document_highlight_read_background,
11959            cx,
11960        )
11961    }
11962
11963    pub fn set_breadcrumb_header(&mut self, new_header: String) {
11964        self.breadcrumb_header = Some(new_header);
11965    }
11966
11967    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11968        self.clear_background_highlights::<SearchWithinRange>(cx);
11969    }
11970
11971    pub fn highlight_background<T: 'static>(
11972        &mut self,
11973        ranges: &[Range<Anchor>],
11974        color_fetcher: fn(&ThemeColors) -> Hsla,
11975        cx: &mut ViewContext<Self>,
11976    ) {
11977        self.background_highlights
11978            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11979        self.scrollbar_marker_state.dirty = true;
11980        cx.notify();
11981    }
11982
11983    pub fn clear_background_highlights<T: 'static>(
11984        &mut self,
11985        cx: &mut ViewContext<Self>,
11986    ) -> Option<BackgroundHighlight> {
11987        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11988        if !text_highlights.1.is_empty() {
11989            self.scrollbar_marker_state.dirty = true;
11990            cx.notify();
11991        }
11992        Some(text_highlights)
11993    }
11994
11995    pub fn highlight_gutter<T: 'static>(
11996        &mut self,
11997        ranges: &[Range<Anchor>],
11998        color_fetcher: fn(&AppContext) -> Hsla,
11999        cx: &mut ViewContext<Self>,
12000    ) {
12001        self.gutter_highlights
12002            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12003        cx.notify();
12004    }
12005
12006    pub fn clear_gutter_highlights<T: 'static>(
12007        &mut self,
12008        cx: &mut ViewContext<Self>,
12009    ) -> Option<GutterHighlight> {
12010        cx.notify();
12011        self.gutter_highlights.remove(&TypeId::of::<T>())
12012    }
12013
12014    #[cfg(feature = "test-support")]
12015    pub fn all_text_background_highlights(
12016        &mut self,
12017        cx: &mut ViewContext<Self>,
12018    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12019        let snapshot = self.snapshot(cx);
12020        let buffer = &snapshot.buffer_snapshot;
12021        let start = buffer.anchor_before(0);
12022        let end = buffer.anchor_after(buffer.len());
12023        let theme = cx.theme().colors();
12024        self.background_highlights_in_range(start..end, &snapshot, theme)
12025    }
12026
12027    #[cfg(feature = "test-support")]
12028    pub fn search_background_highlights(
12029        &mut self,
12030        cx: &mut ViewContext<Self>,
12031    ) -> Vec<Range<Point>> {
12032        let snapshot = self.buffer().read(cx).snapshot(cx);
12033
12034        let highlights = self
12035            .background_highlights
12036            .get(&TypeId::of::<items::BufferSearchHighlights>());
12037
12038        if let Some((_color, ranges)) = highlights {
12039            ranges
12040                .iter()
12041                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
12042                .collect_vec()
12043        } else {
12044            vec![]
12045        }
12046    }
12047
12048    fn document_highlights_for_position<'a>(
12049        &'a self,
12050        position: Anchor,
12051        buffer: &'a MultiBufferSnapshot,
12052    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
12053        let read_highlights = self
12054            .background_highlights
12055            .get(&TypeId::of::<DocumentHighlightRead>())
12056            .map(|h| &h.1);
12057        let write_highlights = self
12058            .background_highlights
12059            .get(&TypeId::of::<DocumentHighlightWrite>())
12060            .map(|h| &h.1);
12061        let left_position = position.bias_left(buffer);
12062        let right_position = position.bias_right(buffer);
12063        read_highlights
12064            .into_iter()
12065            .chain(write_highlights)
12066            .flat_map(move |ranges| {
12067                let start_ix = match ranges.binary_search_by(|probe| {
12068                    let cmp = probe.end.cmp(&left_position, buffer);
12069                    if cmp.is_ge() {
12070                        Ordering::Greater
12071                    } else {
12072                        Ordering::Less
12073                    }
12074                }) {
12075                    Ok(i) | Err(i) => i,
12076                };
12077
12078                ranges[start_ix..]
12079                    .iter()
12080                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
12081            })
12082    }
12083
12084    pub fn has_background_highlights<T: 'static>(&self) -> bool {
12085        self.background_highlights
12086            .get(&TypeId::of::<T>())
12087            .map_or(false, |(_, highlights)| !highlights.is_empty())
12088    }
12089
12090    pub fn background_highlights_in_range(
12091        &self,
12092        search_range: Range<Anchor>,
12093        display_snapshot: &DisplaySnapshot,
12094        theme: &ThemeColors,
12095    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12096        let mut results = Vec::new();
12097        for (color_fetcher, ranges) in self.background_highlights.values() {
12098            let color = color_fetcher(theme);
12099            let start_ix = match ranges.binary_search_by(|probe| {
12100                let cmp = probe
12101                    .end
12102                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12103                if cmp.is_gt() {
12104                    Ordering::Greater
12105                } else {
12106                    Ordering::Less
12107                }
12108            }) {
12109                Ok(i) | Err(i) => i,
12110            };
12111            for range in &ranges[start_ix..] {
12112                if range
12113                    .start
12114                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12115                    .is_ge()
12116                {
12117                    break;
12118                }
12119
12120                let start = range.start.to_display_point(display_snapshot);
12121                let end = range.end.to_display_point(display_snapshot);
12122                results.push((start..end, color))
12123            }
12124        }
12125        results
12126    }
12127
12128    pub fn background_highlight_row_ranges<T: 'static>(
12129        &self,
12130        search_range: Range<Anchor>,
12131        display_snapshot: &DisplaySnapshot,
12132        count: usize,
12133    ) -> Vec<RangeInclusive<DisplayPoint>> {
12134        let mut results = Vec::new();
12135        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12136            return vec![];
12137        };
12138
12139        let start_ix = match ranges.binary_search_by(|probe| {
12140            let cmp = probe
12141                .end
12142                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12143            if cmp.is_gt() {
12144                Ordering::Greater
12145            } else {
12146                Ordering::Less
12147            }
12148        }) {
12149            Ok(i) | Err(i) => i,
12150        };
12151        let mut push_region = |start: Option<Point>, end: Option<Point>| {
12152            if let (Some(start_display), Some(end_display)) = (start, end) {
12153                results.push(
12154                    start_display.to_display_point(display_snapshot)
12155                        ..=end_display.to_display_point(display_snapshot),
12156                );
12157            }
12158        };
12159        let mut start_row: Option<Point> = None;
12160        let mut end_row: Option<Point> = None;
12161        if ranges.len() > count {
12162            return Vec::new();
12163        }
12164        for range in &ranges[start_ix..] {
12165            if range
12166                .start
12167                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12168                .is_ge()
12169            {
12170                break;
12171            }
12172            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12173            if let Some(current_row) = &end_row {
12174                if end.row == current_row.row {
12175                    continue;
12176                }
12177            }
12178            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12179            if start_row.is_none() {
12180                assert_eq!(end_row, None);
12181                start_row = Some(start);
12182                end_row = Some(end);
12183                continue;
12184            }
12185            if let Some(current_end) = end_row.as_mut() {
12186                if start.row > current_end.row + 1 {
12187                    push_region(start_row, end_row);
12188                    start_row = Some(start);
12189                    end_row = Some(end);
12190                } else {
12191                    // Merge two hunks.
12192                    *current_end = end;
12193                }
12194            } else {
12195                unreachable!();
12196            }
12197        }
12198        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12199        push_region(start_row, end_row);
12200        results
12201    }
12202
12203    pub fn gutter_highlights_in_range(
12204        &self,
12205        search_range: Range<Anchor>,
12206        display_snapshot: &DisplaySnapshot,
12207        cx: &AppContext,
12208    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12209        let mut results = Vec::new();
12210        for (color_fetcher, ranges) in self.gutter_highlights.values() {
12211            let color = color_fetcher(cx);
12212            let start_ix = match ranges.binary_search_by(|probe| {
12213                let cmp = probe
12214                    .end
12215                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12216                if cmp.is_gt() {
12217                    Ordering::Greater
12218                } else {
12219                    Ordering::Less
12220                }
12221            }) {
12222                Ok(i) | Err(i) => i,
12223            };
12224            for range in &ranges[start_ix..] {
12225                if range
12226                    .start
12227                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12228                    .is_ge()
12229                {
12230                    break;
12231                }
12232
12233                let start = range.start.to_display_point(display_snapshot);
12234                let end = range.end.to_display_point(display_snapshot);
12235                results.push((start..end, color))
12236            }
12237        }
12238        results
12239    }
12240
12241    /// Get the text ranges corresponding to the redaction query
12242    pub fn redacted_ranges(
12243        &self,
12244        search_range: Range<Anchor>,
12245        display_snapshot: &DisplaySnapshot,
12246        cx: &WindowContext,
12247    ) -> Vec<Range<DisplayPoint>> {
12248        display_snapshot
12249            .buffer_snapshot
12250            .redacted_ranges(search_range, |file| {
12251                if let Some(file) = file {
12252                    file.is_private()
12253                        && EditorSettings::get(
12254                            Some(SettingsLocation {
12255                                worktree_id: file.worktree_id(cx),
12256                                path: file.path().as_ref(),
12257                            }),
12258                            cx,
12259                        )
12260                        .redact_private_values
12261                } else {
12262                    false
12263                }
12264            })
12265            .map(|range| {
12266                range.start.to_display_point(display_snapshot)
12267                    ..range.end.to_display_point(display_snapshot)
12268            })
12269            .collect()
12270    }
12271
12272    pub fn highlight_text<T: 'static>(
12273        &mut self,
12274        ranges: Vec<Range<Anchor>>,
12275        style: HighlightStyle,
12276        cx: &mut ViewContext<Self>,
12277    ) {
12278        self.display_map.update(cx, |map, _| {
12279            map.highlight_text(TypeId::of::<T>(), ranges, style)
12280        });
12281        cx.notify();
12282    }
12283
12284    pub(crate) fn highlight_inlays<T: 'static>(
12285        &mut self,
12286        highlights: Vec<InlayHighlight>,
12287        style: HighlightStyle,
12288        cx: &mut ViewContext<Self>,
12289    ) {
12290        self.display_map.update(cx, |map, _| {
12291            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12292        });
12293        cx.notify();
12294    }
12295
12296    pub fn text_highlights<'a, T: 'static>(
12297        &'a self,
12298        cx: &'a AppContext,
12299    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12300        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12301    }
12302
12303    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12304        let cleared = self
12305            .display_map
12306            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12307        if cleared {
12308            cx.notify();
12309        }
12310    }
12311
12312    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12313        (self.read_only(cx) || self.blink_manager.read(cx).visible())
12314            && self.focus_handle.is_focused(cx)
12315    }
12316
12317    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12318        self.show_cursor_when_unfocused = is_enabled;
12319        cx.notify();
12320    }
12321
12322    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12323        cx.notify();
12324    }
12325
12326    fn on_buffer_event(
12327        &mut self,
12328        multibuffer: Model<MultiBuffer>,
12329        event: &multi_buffer::Event,
12330        cx: &mut ViewContext<Self>,
12331    ) {
12332        match event {
12333            multi_buffer::Event::Edited {
12334                singleton_buffer_edited,
12335            } => {
12336                self.scrollbar_marker_state.dirty = true;
12337                self.active_indent_guides_state.dirty = true;
12338                self.refresh_active_diagnostics(cx);
12339                self.refresh_code_actions(cx);
12340                if self.has_active_inline_completion(cx) {
12341                    self.update_visible_inline_completion(cx);
12342                }
12343                cx.emit(EditorEvent::BufferEdited);
12344                cx.emit(SearchEvent::MatchesInvalidated);
12345                if *singleton_buffer_edited {
12346                    if let Some(project) = &self.project {
12347                        let project = project.read(cx);
12348                        #[allow(clippy::mutable_key_type)]
12349                        let languages_affected = multibuffer
12350                            .read(cx)
12351                            .all_buffers()
12352                            .into_iter()
12353                            .filter_map(|buffer| {
12354                                let buffer = buffer.read(cx);
12355                                let language = buffer.language()?;
12356                                if project.is_local()
12357                                    && project.language_servers_for_buffer(buffer, cx).count() == 0
12358                                {
12359                                    None
12360                                } else {
12361                                    Some(language)
12362                                }
12363                            })
12364                            .cloned()
12365                            .collect::<HashSet<_>>();
12366                        if !languages_affected.is_empty() {
12367                            self.refresh_inlay_hints(
12368                                InlayHintRefreshReason::BufferEdited(languages_affected),
12369                                cx,
12370                            );
12371                        }
12372                    }
12373                }
12374
12375                let Some(project) = &self.project else { return };
12376                let (telemetry, is_via_ssh) = {
12377                    let project = project.read(cx);
12378                    let telemetry = project.client().telemetry().clone();
12379                    let is_via_ssh = project.is_via_ssh();
12380                    (telemetry, is_via_ssh)
12381                };
12382                refresh_linked_ranges(self, cx);
12383                telemetry.log_edit_event("editor", is_via_ssh);
12384            }
12385            multi_buffer::Event::ExcerptsAdded {
12386                buffer,
12387                predecessor,
12388                excerpts,
12389            } => {
12390                self.tasks_update_task = Some(self.refresh_runnables(cx));
12391                cx.emit(EditorEvent::ExcerptsAdded {
12392                    buffer: buffer.clone(),
12393                    predecessor: *predecessor,
12394                    excerpts: excerpts.clone(),
12395                });
12396                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12397            }
12398            multi_buffer::Event::ExcerptsRemoved { ids } => {
12399                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12400                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12401            }
12402            multi_buffer::Event::ExcerptsEdited { ids } => {
12403                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12404            }
12405            multi_buffer::Event::ExcerptsExpanded { ids } => {
12406                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12407            }
12408            multi_buffer::Event::Reparsed(buffer_id) => {
12409                self.tasks_update_task = Some(self.refresh_runnables(cx));
12410
12411                cx.emit(EditorEvent::Reparsed(*buffer_id));
12412            }
12413            multi_buffer::Event::LanguageChanged(buffer_id) => {
12414                linked_editing_ranges::refresh_linked_ranges(self, cx);
12415                cx.emit(EditorEvent::Reparsed(*buffer_id));
12416                cx.notify();
12417            }
12418            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12419            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12420            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12421                cx.emit(EditorEvent::TitleChanged)
12422            }
12423            multi_buffer::Event::DiffBaseChanged => {
12424                self.scrollbar_marker_state.dirty = true;
12425                cx.emit(EditorEvent::DiffBaseChanged);
12426                cx.notify();
12427            }
12428            multi_buffer::Event::DiffUpdated { buffer } => {
12429                self.sync_expanded_diff_hunks(buffer.clone(), cx);
12430                cx.notify();
12431            }
12432            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12433            multi_buffer::Event::DiagnosticsUpdated => {
12434                self.refresh_active_diagnostics(cx);
12435                self.scrollbar_marker_state.dirty = true;
12436                cx.notify();
12437            }
12438            _ => {}
12439        };
12440    }
12441
12442    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12443        cx.notify();
12444    }
12445
12446    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12447        self.tasks_update_task = Some(self.refresh_runnables(cx));
12448        self.refresh_inline_completion(true, false, cx);
12449        self.refresh_inlay_hints(
12450            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12451                self.selections.newest_anchor().head(),
12452                &self.buffer.read(cx).snapshot(cx),
12453                cx,
12454            )),
12455            cx,
12456        );
12457
12458        let old_cursor_shape = self.cursor_shape;
12459
12460        {
12461            let editor_settings = EditorSettings::get_global(cx);
12462            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12463            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12464            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12465        }
12466
12467        if old_cursor_shape != self.cursor_shape {
12468            cx.emit(EditorEvent::CursorShapeChanged);
12469        }
12470
12471        let project_settings = ProjectSettings::get_global(cx);
12472        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12473
12474        if self.mode == EditorMode::Full {
12475            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12476            if self.git_blame_inline_enabled != inline_blame_enabled {
12477                self.toggle_git_blame_inline_internal(false, cx);
12478            }
12479        }
12480
12481        cx.notify();
12482    }
12483
12484    pub fn set_searchable(&mut self, searchable: bool) {
12485        self.searchable = searchable;
12486    }
12487
12488    pub fn searchable(&self) -> bool {
12489        self.searchable
12490    }
12491
12492    fn open_proposed_changes_editor(
12493        &mut self,
12494        _: &OpenProposedChangesEditor,
12495        cx: &mut ViewContext<Self>,
12496    ) {
12497        let Some(workspace) = self.workspace() else {
12498            cx.propagate();
12499            return;
12500        };
12501
12502        let selections = self.selections.all::<usize>(cx);
12503        let buffer = self.buffer.read(cx);
12504        let mut new_selections_by_buffer = HashMap::default();
12505        for selection in selections {
12506            for (buffer, range, _) in
12507                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12508            {
12509                let mut range = range.to_point(buffer.read(cx));
12510                range.start.column = 0;
12511                range.end.column = buffer.read(cx).line_len(range.end.row);
12512                new_selections_by_buffer
12513                    .entry(buffer)
12514                    .or_insert(Vec::new())
12515                    .push(range)
12516            }
12517        }
12518
12519        let proposed_changes_buffers = new_selections_by_buffer
12520            .into_iter()
12521            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12522            .collect::<Vec<_>>();
12523        let proposed_changes_editor = cx.new_view(|cx| {
12524            ProposedChangesEditor::new(
12525                "Proposed changes",
12526                proposed_changes_buffers,
12527                self.project.clone(),
12528                cx,
12529            )
12530        });
12531
12532        cx.window_context().defer(move |cx| {
12533            workspace.update(cx, |workspace, cx| {
12534                workspace.active_pane().update(cx, |pane, cx| {
12535                    pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12536                });
12537            });
12538        });
12539    }
12540
12541    fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12542        self.open_excerpts_common(true, cx)
12543    }
12544
12545    fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12546        self.open_excerpts_common(false, cx)
12547    }
12548
12549    fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
12550        let selections = self.selections.all::<usize>(cx);
12551        let buffer = self.buffer.read(cx);
12552        if buffer.is_singleton() {
12553            cx.propagate();
12554            return;
12555        }
12556
12557        let Some(workspace) = self.workspace() else {
12558            cx.propagate();
12559            return;
12560        };
12561
12562        let mut new_selections_by_buffer = HashMap::default();
12563        for selection in selections {
12564            for (mut buffer_handle, mut range, _) in
12565                buffer.range_to_buffer_ranges(selection.range(), cx)
12566            {
12567                // When editing branch buffers, jump to the corresponding location
12568                // in their base buffer.
12569                let buffer = buffer_handle.read(cx);
12570                if let Some(base_buffer) = buffer.diff_base_buffer() {
12571                    range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12572                    buffer_handle = base_buffer;
12573                }
12574
12575                if selection.reversed {
12576                    mem::swap(&mut range.start, &mut range.end);
12577                }
12578                new_selections_by_buffer
12579                    .entry(buffer_handle)
12580                    .or_insert(Vec::new())
12581                    .push(range)
12582            }
12583        }
12584
12585        // We defer the pane interaction because we ourselves are a workspace item
12586        // and activating a new item causes the pane to call a method on us reentrantly,
12587        // which panics if we're on the stack.
12588        cx.window_context().defer(move |cx| {
12589            workspace.update(cx, |workspace, cx| {
12590                let pane = if split {
12591                    workspace.adjacent_pane(cx)
12592                } else {
12593                    workspace.active_pane().clone()
12594                };
12595
12596                for (buffer, ranges) in new_selections_by_buffer {
12597                    let editor =
12598                        workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
12599                    editor.update(cx, |editor, cx| {
12600                        editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
12601                            s.select_ranges(ranges);
12602                        });
12603                    });
12604                }
12605            })
12606        });
12607    }
12608
12609    fn jump(
12610        &mut self,
12611        path: ProjectPath,
12612        position: Point,
12613        anchor: language::Anchor,
12614        offset_from_top: u32,
12615        cx: &mut ViewContext<Self>,
12616    ) {
12617        let workspace = self.workspace();
12618        cx.spawn(|_, mut cx| async move {
12619            let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
12620            let editor = workspace.update(&mut cx, |workspace, cx| {
12621                // Reset the preview item id before opening the new item
12622                workspace.active_pane().update(cx, |pane, cx| {
12623                    pane.set_preview_item_id(None, cx);
12624                });
12625                workspace.open_path_preview(path, None, true, true, cx)
12626            })?;
12627            let editor = editor
12628                .await?
12629                .downcast::<Editor>()
12630                .ok_or_else(|| anyhow!("opened item was not an editor"))?
12631                .downgrade();
12632            editor.update(&mut cx, |editor, cx| {
12633                let buffer = editor
12634                    .buffer()
12635                    .read(cx)
12636                    .as_singleton()
12637                    .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
12638                let buffer = buffer.read(cx);
12639                let cursor = if buffer.can_resolve(&anchor) {
12640                    language::ToPoint::to_point(&anchor, buffer)
12641                } else {
12642                    buffer.clip_point(position, Bias::Left)
12643                };
12644
12645                let nav_history = editor.nav_history.take();
12646                editor.change_selections(
12647                    Some(Autoscroll::top_relative(offset_from_top as usize)),
12648                    cx,
12649                    |s| {
12650                        s.select_ranges([cursor..cursor]);
12651                    },
12652                );
12653                editor.nav_history = nav_history;
12654
12655                anyhow::Ok(())
12656            })??;
12657
12658            anyhow::Ok(())
12659        })
12660        .detach_and_log_err(cx);
12661    }
12662
12663    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12664        let snapshot = self.buffer.read(cx).read(cx);
12665        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12666        Some(
12667            ranges
12668                .iter()
12669                .map(move |range| {
12670                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12671                })
12672                .collect(),
12673        )
12674    }
12675
12676    fn selection_replacement_ranges(
12677        &self,
12678        range: Range<OffsetUtf16>,
12679        cx: &mut AppContext,
12680    ) -> Vec<Range<OffsetUtf16>> {
12681        let selections = self.selections.all::<OffsetUtf16>(cx);
12682        let newest_selection = selections
12683            .iter()
12684            .max_by_key(|selection| selection.id)
12685            .unwrap();
12686        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12687        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12688        let snapshot = self.buffer.read(cx).read(cx);
12689        selections
12690            .into_iter()
12691            .map(|mut selection| {
12692                selection.start.0 =
12693                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
12694                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12695                snapshot.clip_offset_utf16(selection.start, Bias::Left)
12696                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12697            })
12698            .collect()
12699    }
12700
12701    fn report_editor_event(
12702        &self,
12703        operation: &'static str,
12704        file_extension: Option<String>,
12705        cx: &AppContext,
12706    ) {
12707        if cfg!(any(test, feature = "test-support")) {
12708            return;
12709        }
12710
12711        let Some(project) = &self.project else { return };
12712
12713        // If None, we are in a file without an extension
12714        let file = self
12715            .buffer
12716            .read(cx)
12717            .as_singleton()
12718            .and_then(|b| b.read(cx).file());
12719        let file_extension = file_extension.or(file
12720            .as_ref()
12721            .and_then(|file| Path::new(file.file_name(cx)).extension())
12722            .and_then(|e| e.to_str())
12723            .map(|a| a.to_string()));
12724
12725        let vim_mode = cx
12726            .global::<SettingsStore>()
12727            .raw_user_settings()
12728            .get("vim_mode")
12729            == Some(&serde_json::Value::Bool(true));
12730
12731        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12732            == language::language_settings::InlineCompletionProvider::Copilot;
12733        let copilot_enabled_for_language = self
12734            .buffer
12735            .read(cx)
12736            .settings_at(0, cx)
12737            .show_inline_completions;
12738
12739        let project = project.read(cx);
12740        let telemetry = project.client().telemetry().clone();
12741        telemetry.report_editor_event(
12742            file_extension,
12743            vim_mode,
12744            operation,
12745            copilot_enabled,
12746            copilot_enabled_for_language,
12747            project.is_via_ssh(),
12748        )
12749    }
12750
12751    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12752    /// with each line being an array of {text, highlight} objects.
12753    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12754        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12755            return;
12756        };
12757
12758        #[derive(Serialize)]
12759        struct Chunk<'a> {
12760            text: String,
12761            highlight: Option<&'a str>,
12762        }
12763
12764        let snapshot = buffer.read(cx).snapshot();
12765        let range = self
12766            .selected_text_range(false, cx)
12767            .and_then(|selection| {
12768                if selection.range.is_empty() {
12769                    None
12770                } else {
12771                    Some(selection.range)
12772                }
12773            })
12774            .unwrap_or_else(|| 0..snapshot.len());
12775
12776        let chunks = snapshot.chunks(range, true);
12777        let mut lines = Vec::new();
12778        let mut line: VecDeque<Chunk> = VecDeque::new();
12779
12780        let Some(style) = self.style.as_ref() else {
12781            return;
12782        };
12783
12784        for chunk in chunks {
12785            let highlight = chunk
12786                .syntax_highlight_id
12787                .and_then(|id| id.name(&style.syntax));
12788            let mut chunk_lines = chunk.text.split('\n').peekable();
12789            while let Some(text) = chunk_lines.next() {
12790                let mut merged_with_last_token = false;
12791                if let Some(last_token) = line.back_mut() {
12792                    if last_token.highlight == highlight {
12793                        last_token.text.push_str(text);
12794                        merged_with_last_token = true;
12795                    }
12796                }
12797
12798                if !merged_with_last_token {
12799                    line.push_back(Chunk {
12800                        text: text.into(),
12801                        highlight,
12802                    });
12803                }
12804
12805                if chunk_lines.peek().is_some() {
12806                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
12807                        line.pop_front();
12808                    }
12809                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
12810                        line.pop_back();
12811                    }
12812
12813                    lines.push(mem::take(&mut line));
12814                }
12815            }
12816        }
12817
12818        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12819            return;
12820        };
12821        cx.write_to_clipboard(ClipboardItem::new_string(lines));
12822    }
12823
12824    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12825        &self.inlay_hint_cache
12826    }
12827
12828    pub fn replay_insert_event(
12829        &mut self,
12830        text: &str,
12831        relative_utf16_range: Option<Range<isize>>,
12832        cx: &mut ViewContext<Self>,
12833    ) {
12834        if !self.input_enabled {
12835            cx.emit(EditorEvent::InputIgnored { text: text.into() });
12836            return;
12837        }
12838        if let Some(relative_utf16_range) = relative_utf16_range {
12839            let selections = self.selections.all::<OffsetUtf16>(cx);
12840            self.change_selections(None, cx, |s| {
12841                let new_ranges = selections.into_iter().map(|range| {
12842                    let start = OffsetUtf16(
12843                        range
12844                            .head()
12845                            .0
12846                            .saturating_add_signed(relative_utf16_range.start),
12847                    );
12848                    let end = OffsetUtf16(
12849                        range
12850                            .head()
12851                            .0
12852                            .saturating_add_signed(relative_utf16_range.end),
12853                    );
12854                    start..end
12855                });
12856                s.select_ranges(new_ranges);
12857            });
12858        }
12859
12860        self.handle_input(text, cx);
12861    }
12862
12863    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12864        let Some(provider) = self.semantics_provider.as_ref() else {
12865            return false;
12866        };
12867
12868        let mut supports = false;
12869        self.buffer().read(cx).for_each_buffer(|buffer| {
12870            supports |= provider.supports_inlay_hints(buffer, cx);
12871        });
12872        supports
12873    }
12874
12875    pub fn focus(&self, cx: &mut WindowContext) {
12876        cx.focus(&self.focus_handle)
12877    }
12878
12879    pub fn is_focused(&self, cx: &WindowContext) -> bool {
12880        self.focus_handle.is_focused(cx)
12881    }
12882
12883    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12884        cx.emit(EditorEvent::Focused);
12885
12886        if let Some(descendant) = self
12887            .last_focused_descendant
12888            .take()
12889            .and_then(|descendant| descendant.upgrade())
12890        {
12891            cx.focus(&descendant);
12892        } else {
12893            if let Some(blame) = self.blame.as_ref() {
12894                blame.update(cx, GitBlame::focus)
12895            }
12896
12897            self.blink_manager.update(cx, BlinkManager::enable);
12898            self.show_cursor_names(cx);
12899            self.buffer.update(cx, |buffer, cx| {
12900                buffer.finalize_last_transaction(cx);
12901                if self.leader_peer_id.is_none() {
12902                    buffer.set_active_selections(
12903                        &self.selections.disjoint_anchors(),
12904                        self.selections.line_mode,
12905                        self.cursor_shape,
12906                        cx,
12907                    );
12908                }
12909            });
12910        }
12911    }
12912
12913    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12914        cx.emit(EditorEvent::FocusedIn)
12915    }
12916
12917    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12918        if event.blurred != self.focus_handle {
12919            self.last_focused_descendant = Some(event.blurred);
12920        }
12921    }
12922
12923    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12924        self.blink_manager.update(cx, BlinkManager::disable);
12925        self.buffer
12926            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12927
12928        if let Some(blame) = self.blame.as_ref() {
12929            blame.update(cx, GitBlame::blur)
12930        }
12931        if !self.hover_state.focused(cx) {
12932            hide_hover(self, cx);
12933        }
12934
12935        self.hide_context_menu(cx);
12936        cx.emit(EditorEvent::Blurred);
12937        cx.notify();
12938    }
12939
12940    pub fn register_action<A: Action>(
12941        &mut self,
12942        listener: impl Fn(&A, &mut WindowContext) + 'static,
12943    ) -> Subscription {
12944        let id = self.next_editor_action_id.post_inc();
12945        let listener = Arc::new(listener);
12946        self.editor_actions.borrow_mut().insert(
12947            id,
12948            Box::new(move |cx| {
12949                let cx = cx.window_context();
12950                let listener = listener.clone();
12951                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12952                    let action = action.downcast_ref().unwrap();
12953                    if phase == DispatchPhase::Bubble {
12954                        listener(action, cx)
12955                    }
12956                })
12957            }),
12958        );
12959
12960        let editor_actions = self.editor_actions.clone();
12961        Subscription::new(move || {
12962            editor_actions.borrow_mut().remove(&id);
12963        })
12964    }
12965
12966    pub fn file_header_size(&self) -> u32 {
12967        FILE_HEADER_HEIGHT
12968    }
12969
12970    pub fn revert(
12971        &mut self,
12972        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12973        cx: &mut ViewContext<Self>,
12974    ) {
12975        self.buffer().update(cx, |multi_buffer, cx| {
12976            for (buffer_id, changes) in revert_changes {
12977                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12978                    buffer.update(cx, |buffer, cx| {
12979                        buffer.edit(
12980                            changes.into_iter().map(|(range, text)| {
12981                                (range, text.to_string().map(Arc::<str>::from))
12982                            }),
12983                            None,
12984                            cx,
12985                        );
12986                    });
12987                }
12988            }
12989        });
12990        self.change_selections(None, cx, |selections| selections.refresh());
12991    }
12992
12993    pub fn to_pixel_point(
12994        &mut self,
12995        source: multi_buffer::Anchor,
12996        editor_snapshot: &EditorSnapshot,
12997        cx: &mut ViewContext<Self>,
12998    ) -> Option<gpui::Point<Pixels>> {
12999        let source_point = source.to_display_point(editor_snapshot);
13000        self.display_to_pixel_point(source_point, editor_snapshot, cx)
13001    }
13002
13003    pub fn display_to_pixel_point(
13004        &mut self,
13005        source: DisplayPoint,
13006        editor_snapshot: &EditorSnapshot,
13007        cx: &mut ViewContext<Self>,
13008    ) -> Option<gpui::Point<Pixels>> {
13009        let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
13010        let text_layout_details = self.text_layout_details(cx);
13011        let scroll_top = text_layout_details
13012            .scroll_anchor
13013            .scroll_position(editor_snapshot)
13014            .y;
13015
13016        if source.row().as_f32() < scroll_top.floor() {
13017            return None;
13018        }
13019        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
13020        let source_y = line_height * (source.row().as_f32() - scroll_top);
13021        Some(gpui::Point::new(source_x, source_y))
13022    }
13023
13024    pub fn has_active_completions_menu(&self) -> bool {
13025        self.context_menu.read().as_ref().map_or(false, |menu| {
13026            menu.visible() && matches!(menu, ContextMenu::Completions(_))
13027        })
13028    }
13029
13030    pub fn register_addon<T: Addon>(&mut self, instance: T) {
13031        self.addons
13032            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
13033    }
13034
13035    pub fn unregister_addon<T: Addon>(&mut self) {
13036        self.addons.remove(&std::any::TypeId::of::<T>());
13037    }
13038
13039    pub fn addon<T: Addon>(&self) -> Option<&T> {
13040        let type_id = std::any::TypeId::of::<T>();
13041        self.addons
13042            .get(&type_id)
13043            .and_then(|item| item.to_any().downcast_ref::<T>())
13044    }
13045}
13046
13047fn hunks_for_selections(
13048    multi_buffer_snapshot: &MultiBufferSnapshot,
13049    selections: &[Selection<Anchor>],
13050) -> Vec<MultiBufferDiffHunk> {
13051    let buffer_rows_for_selections = selections.iter().map(|selection| {
13052        let head = selection.head();
13053        let tail = selection.tail();
13054        let start = MultiBufferRow(tail.to_point(multi_buffer_snapshot).row);
13055        let end = MultiBufferRow(head.to_point(multi_buffer_snapshot).row);
13056        if start > end {
13057            end..start
13058        } else {
13059            start..end
13060        }
13061    });
13062
13063    hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
13064}
13065
13066pub fn hunks_for_rows(
13067    rows: impl Iterator<Item = Range<MultiBufferRow>>,
13068    multi_buffer_snapshot: &MultiBufferSnapshot,
13069) -> Vec<MultiBufferDiffHunk> {
13070    let mut hunks = Vec::new();
13071    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13072        HashMap::default();
13073    for selected_multi_buffer_rows in rows {
13074        let query_rows =
13075            selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
13076        for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
13077            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13078            // when the caret is just above or just below the deleted hunk.
13079            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13080            let related_to_selection = if allow_adjacent {
13081                hunk.row_range.overlaps(&query_rows)
13082                    || hunk.row_range.start == query_rows.end
13083                    || hunk.row_range.end == query_rows.start
13084            } else {
13085                // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
13086                // `hunk.row_range` is exclusive (e.g. [2..3] means 2nd row is selected)
13087                hunk.row_range.overlaps(&selected_multi_buffer_rows)
13088                    || selected_multi_buffer_rows.end == hunk.row_range.start
13089            };
13090            if related_to_selection {
13091                if !processed_buffer_rows
13092                    .entry(hunk.buffer_id)
13093                    .or_default()
13094                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13095                {
13096                    continue;
13097                }
13098                hunks.push(hunk);
13099            }
13100        }
13101    }
13102
13103    hunks
13104}
13105
13106pub trait CollaborationHub {
13107    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13108    fn user_participant_indices<'a>(
13109        &self,
13110        cx: &'a AppContext,
13111    ) -> &'a HashMap<u64, ParticipantIndex>;
13112    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13113}
13114
13115impl CollaborationHub for Model<Project> {
13116    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13117        self.read(cx).collaborators()
13118    }
13119
13120    fn user_participant_indices<'a>(
13121        &self,
13122        cx: &'a AppContext,
13123    ) -> &'a HashMap<u64, ParticipantIndex> {
13124        self.read(cx).user_store().read(cx).participant_indices()
13125    }
13126
13127    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13128        let this = self.read(cx);
13129        let user_ids = this.collaborators().values().map(|c| c.user_id);
13130        this.user_store().read_with(cx, |user_store, cx| {
13131            user_store.participant_names(user_ids, cx)
13132        })
13133    }
13134}
13135
13136pub trait SemanticsProvider {
13137    fn hover(
13138        &self,
13139        buffer: &Model<Buffer>,
13140        position: text::Anchor,
13141        cx: &mut AppContext,
13142    ) -> Option<Task<Vec<project::Hover>>>;
13143
13144    fn inlay_hints(
13145        &self,
13146        buffer_handle: Model<Buffer>,
13147        range: Range<text::Anchor>,
13148        cx: &mut AppContext,
13149    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13150
13151    fn resolve_inlay_hint(
13152        &self,
13153        hint: InlayHint,
13154        buffer_handle: Model<Buffer>,
13155        server_id: LanguageServerId,
13156        cx: &mut AppContext,
13157    ) -> Option<Task<anyhow::Result<InlayHint>>>;
13158
13159    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13160
13161    fn document_highlights(
13162        &self,
13163        buffer: &Model<Buffer>,
13164        position: text::Anchor,
13165        cx: &mut AppContext,
13166    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13167
13168    fn definitions(
13169        &self,
13170        buffer: &Model<Buffer>,
13171        position: text::Anchor,
13172        kind: GotoDefinitionKind,
13173        cx: &mut AppContext,
13174    ) -> Option<Task<Result<Vec<LocationLink>>>>;
13175
13176    fn range_for_rename(
13177        &self,
13178        buffer: &Model<Buffer>,
13179        position: text::Anchor,
13180        cx: &mut AppContext,
13181    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13182
13183    fn perform_rename(
13184        &self,
13185        buffer: &Model<Buffer>,
13186        position: text::Anchor,
13187        new_name: String,
13188        cx: &mut AppContext,
13189    ) -> Option<Task<Result<ProjectTransaction>>>;
13190}
13191
13192pub trait CompletionProvider {
13193    fn completions(
13194        &self,
13195        buffer: &Model<Buffer>,
13196        buffer_position: text::Anchor,
13197        trigger: CompletionContext,
13198        cx: &mut ViewContext<Editor>,
13199    ) -> Task<Result<Vec<Completion>>>;
13200
13201    fn resolve_completions(
13202        &self,
13203        buffer: Model<Buffer>,
13204        completion_indices: Vec<usize>,
13205        completions: Arc<RwLock<Box<[Completion]>>>,
13206        cx: &mut ViewContext<Editor>,
13207    ) -> Task<Result<bool>>;
13208
13209    fn apply_additional_edits_for_completion(
13210        &self,
13211        buffer: Model<Buffer>,
13212        completion: Completion,
13213        push_to_history: bool,
13214        cx: &mut ViewContext<Editor>,
13215    ) -> Task<Result<Option<language::Transaction>>>;
13216
13217    fn is_completion_trigger(
13218        &self,
13219        buffer: &Model<Buffer>,
13220        position: language::Anchor,
13221        text: &str,
13222        trigger_in_words: bool,
13223        cx: &mut ViewContext<Editor>,
13224    ) -> bool;
13225
13226    fn sort_completions(&self) -> bool {
13227        true
13228    }
13229}
13230
13231pub trait CodeActionProvider {
13232    fn code_actions(
13233        &self,
13234        buffer: &Model<Buffer>,
13235        range: Range<text::Anchor>,
13236        cx: &mut WindowContext,
13237    ) -> Task<Result<Vec<CodeAction>>>;
13238
13239    fn apply_code_action(
13240        &self,
13241        buffer_handle: Model<Buffer>,
13242        action: CodeAction,
13243        excerpt_id: ExcerptId,
13244        push_to_history: bool,
13245        cx: &mut WindowContext,
13246    ) -> Task<Result<ProjectTransaction>>;
13247}
13248
13249impl CodeActionProvider for Model<Project> {
13250    fn code_actions(
13251        &self,
13252        buffer: &Model<Buffer>,
13253        range: Range<text::Anchor>,
13254        cx: &mut WindowContext,
13255    ) -> Task<Result<Vec<CodeAction>>> {
13256        self.update(cx, |project, cx| project.code_actions(buffer, range, cx))
13257    }
13258
13259    fn apply_code_action(
13260        &self,
13261        buffer_handle: Model<Buffer>,
13262        action: CodeAction,
13263        _excerpt_id: ExcerptId,
13264        push_to_history: bool,
13265        cx: &mut WindowContext,
13266    ) -> Task<Result<ProjectTransaction>> {
13267        self.update(cx, |project, cx| {
13268            project.apply_code_action(buffer_handle, action, push_to_history, cx)
13269        })
13270    }
13271}
13272
13273fn snippet_completions(
13274    project: &Project,
13275    buffer: &Model<Buffer>,
13276    buffer_position: text::Anchor,
13277    cx: &mut AppContext,
13278) -> Vec<Completion> {
13279    let language = buffer.read(cx).language_at(buffer_position);
13280    let language_name = language.as_ref().map(|language| language.lsp_id());
13281    let snippet_store = project.snippets().read(cx);
13282    let snippets = snippet_store.snippets_for(language_name, cx);
13283
13284    if snippets.is_empty() {
13285        return vec![];
13286    }
13287    let snapshot = buffer.read(cx).text_snapshot();
13288    let chars = snapshot.reversed_chars_for_range(text::Anchor::MIN..buffer_position);
13289
13290    let scope = language.map(|language| language.default_scope());
13291    let classifier = CharClassifier::new(scope).for_completion(true);
13292    let mut last_word = chars
13293        .take_while(|c| classifier.is_word(*c))
13294        .collect::<String>();
13295    last_word = last_word.chars().rev().collect();
13296    let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13297    let to_lsp = |point: &text::Anchor| {
13298        let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13299        point_to_lsp(end)
13300    };
13301    let lsp_end = to_lsp(&buffer_position);
13302    snippets
13303        .into_iter()
13304        .filter_map(|snippet| {
13305            let matching_prefix = snippet
13306                .prefix
13307                .iter()
13308                .find(|prefix| prefix.starts_with(&last_word))?;
13309            let start = as_offset - last_word.len();
13310            let start = snapshot.anchor_before(start);
13311            let range = start..buffer_position;
13312            let lsp_start = to_lsp(&start);
13313            let lsp_range = lsp::Range {
13314                start: lsp_start,
13315                end: lsp_end,
13316            };
13317            Some(Completion {
13318                old_range: range,
13319                new_text: snippet.body.clone(),
13320                label: CodeLabel {
13321                    text: matching_prefix.clone(),
13322                    runs: vec![],
13323                    filter_range: 0..matching_prefix.len(),
13324                },
13325                server_id: LanguageServerId(usize::MAX),
13326                documentation: snippet.description.clone().map(Documentation::SingleLine),
13327                lsp_completion: lsp::CompletionItem {
13328                    label: snippet.prefix.first().unwrap().clone(),
13329                    kind: Some(CompletionItemKind::SNIPPET),
13330                    label_details: snippet.description.as_ref().map(|description| {
13331                        lsp::CompletionItemLabelDetails {
13332                            detail: Some(description.clone()),
13333                            description: None,
13334                        }
13335                    }),
13336                    insert_text_format: Some(InsertTextFormat::SNIPPET),
13337                    text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13338                        lsp::InsertReplaceEdit {
13339                            new_text: snippet.body.clone(),
13340                            insert: lsp_range,
13341                            replace: lsp_range,
13342                        },
13343                    )),
13344                    filter_text: Some(snippet.body.clone()),
13345                    sort_text: Some(char::MAX.to_string()),
13346                    ..Default::default()
13347                },
13348                confirm: None,
13349            })
13350        })
13351        .collect()
13352}
13353
13354impl CompletionProvider for Model<Project> {
13355    fn completions(
13356        &self,
13357        buffer: &Model<Buffer>,
13358        buffer_position: text::Anchor,
13359        options: CompletionContext,
13360        cx: &mut ViewContext<Editor>,
13361    ) -> Task<Result<Vec<Completion>>> {
13362        self.update(cx, |project, cx| {
13363            let snippets = snippet_completions(project, buffer, buffer_position, cx);
13364            let project_completions = project.completions(buffer, buffer_position, options, cx);
13365            cx.background_executor().spawn(async move {
13366                let mut completions = project_completions.await?;
13367                //let snippets = snippets.into_iter().;
13368                completions.extend(snippets);
13369                Ok(completions)
13370            })
13371        })
13372    }
13373
13374    fn resolve_completions(
13375        &self,
13376        buffer: Model<Buffer>,
13377        completion_indices: Vec<usize>,
13378        completions: Arc<RwLock<Box<[Completion]>>>,
13379        cx: &mut ViewContext<Editor>,
13380    ) -> Task<Result<bool>> {
13381        self.update(cx, |project, cx| {
13382            project.resolve_completions(buffer, completion_indices, completions, cx)
13383        })
13384    }
13385
13386    fn apply_additional_edits_for_completion(
13387        &self,
13388        buffer: Model<Buffer>,
13389        completion: Completion,
13390        push_to_history: bool,
13391        cx: &mut ViewContext<Editor>,
13392    ) -> Task<Result<Option<language::Transaction>>> {
13393        self.update(cx, |project, cx| {
13394            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13395        })
13396    }
13397
13398    fn is_completion_trigger(
13399        &self,
13400        buffer: &Model<Buffer>,
13401        position: language::Anchor,
13402        text: &str,
13403        trigger_in_words: bool,
13404        cx: &mut ViewContext<Editor>,
13405    ) -> bool {
13406        if !EditorSettings::get_global(cx).show_completions_on_input {
13407            return false;
13408        }
13409
13410        let mut chars = text.chars();
13411        let char = if let Some(char) = chars.next() {
13412            char
13413        } else {
13414            return false;
13415        };
13416        if chars.next().is_some() {
13417            return false;
13418        }
13419
13420        let buffer = buffer.read(cx);
13421        let classifier = buffer
13422            .snapshot()
13423            .char_classifier_at(position)
13424            .for_completion(true);
13425        if trigger_in_words && classifier.is_word(char) {
13426            return true;
13427        }
13428
13429        buffer
13430            .completion_triggers()
13431            .iter()
13432            .any(|string| string == text)
13433    }
13434}
13435
13436impl SemanticsProvider for Model<Project> {
13437    fn hover(
13438        &self,
13439        buffer: &Model<Buffer>,
13440        position: text::Anchor,
13441        cx: &mut AppContext,
13442    ) -> Option<Task<Vec<project::Hover>>> {
13443        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13444    }
13445
13446    fn document_highlights(
13447        &self,
13448        buffer: &Model<Buffer>,
13449        position: text::Anchor,
13450        cx: &mut AppContext,
13451    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13452        Some(self.update(cx, |project, cx| {
13453            project.document_highlights(buffer, position, cx)
13454        }))
13455    }
13456
13457    fn definitions(
13458        &self,
13459        buffer: &Model<Buffer>,
13460        position: text::Anchor,
13461        kind: GotoDefinitionKind,
13462        cx: &mut AppContext,
13463    ) -> Option<Task<Result<Vec<LocationLink>>>> {
13464        Some(self.update(cx, |project, cx| match kind {
13465            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13466            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13467            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13468            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13469        }))
13470    }
13471
13472    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13473        // TODO: make this work for remote projects
13474        self.read(cx)
13475            .language_servers_for_buffer(buffer.read(cx), cx)
13476            .any(
13477                |(_, server)| match server.capabilities().inlay_hint_provider {
13478                    Some(lsp::OneOf::Left(enabled)) => enabled,
13479                    Some(lsp::OneOf::Right(_)) => true,
13480                    None => false,
13481                },
13482            )
13483    }
13484
13485    fn inlay_hints(
13486        &self,
13487        buffer_handle: Model<Buffer>,
13488        range: Range<text::Anchor>,
13489        cx: &mut AppContext,
13490    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13491        Some(self.update(cx, |project, cx| {
13492            project.inlay_hints(buffer_handle, range, cx)
13493        }))
13494    }
13495
13496    fn resolve_inlay_hint(
13497        &self,
13498        hint: InlayHint,
13499        buffer_handle: Model<Buffer>,
13500        server_id: LanguageServerId,
13501        cx: &mut AppContext,
13502    ) -> Option<Task<anyhow::Result<InlayHint>>> {
13503        Some(self.update(cx, |project, cx| {
13504            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13505        }))
13506    }
13507
13508    fn range_for_rename(
13509        &self,
13510        buffer: &Model<Buffer>,
13511        position: text::Anchor,
13512        cx: &mut AppContext,
13513    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13514        Some(self.update(cx, |project, cx| {
13515            project.prepare_rename(buffer.clone(), position, cx)
13516        }))
13517    }
13518
13519    fn perform_rename(
13520        &self,
13521        buffer: &Model<Buffer>,
13522        position: text::Anchor,
13523        new_name: String,
13524        cx: &mut AppContext,
13525    ) -> Option<Task<Result<ProjectTransaction>>> {
13526        Some(self.update(cx, |project, cx| {
13527            project.perform_rename(buffer.clone(), position, new_name, cx)
13528        }))
13529    }
13530}
13531
13532fn inlay_hint_settings(
13533    location: Anchor,
13534    snapshot: &MultiBufferSnapshot,
13535    cx: &mut ViewContext<'_, Editor>,
13536) -> InlayHintSettings {
13537    let file = snapshot.file_at(location);
13538    let language = snapshot.language_at(location).map(|l| l.name());
13539    language_settings(language, file, cx).inlay_hints
13540}
13541
13542fn consume_contiguous_rows(
13543    contiguous_row_selections: &mut Vec<Selection<Point>>,
13544    selection: &Selection<Point>,
13545    display_map: &DisplaySnapshot,
13546    selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
13547) -> (MultiBufferRow, MultiBufferRow) {
13548    contiguous_row_selections.push(selection.clone());
13549    let start_row = MultiBufferRow(selection.start.row);
13550    let mut end_row = ending_row(selection, display_map);
13551
13552    while let Some(next_selection) = selections.peek() {
13553        if next_selection.start.row <= end_row.0 {
13554            end_row = ending_row(next_selection, display_map);
13555            contiguous_row_selections.push(selections.next().unwrap().clone());
13556        } else {
13557            break;
13558        }
13559    }
13560    (start_row, end_row)
13561}
13562
13563fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13564    if next_selection.end.column > 0 || next_selection.is_empty() {
13565        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13566    } else {
13567        MultiBufferRow(next_selection.end.row)
13568    }
13569}
13570
13571impl EditorSnapshot {
13572    pub fn remote_selections_in_range<'a>(
13573        &'a self,
13574        range: &'a Range<Anchor>,
13575        collaboration_hub: &dyn CollaborationHub,
13576        cx: &'a AppContext,
13577    ) -> impl 'a + Iterator<Item = RemoteSelection> {
13578        let participant_names = collaboration_hub.user_names(cx);
13579        let participant_indices = collaboration_hub.user_participant_indices(cx);
13580        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
13581        let collaborators_by_replica_id = collaborators_by_peer_id
13582            .iter()
13583            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
13584            .collect::<HashMap<_, _>>();
13585        self.buffer_snapshot
13586            .selections_in_range(range, false)
13587            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
13588                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
13589                let participant_index = participant_indices.get(&collaborator.user_id).copied();
13590                let user_name = participant_names.get(&collaborator.user_id).cloned();
13591                Some(RemoteSelection {
13592                    replica_id,
13593                    selection,
13594                    cursor_shape,
13595                    line_mode,
13596                    participant_index,
13597                    peer_id: collaborator.peer_id,
13598                    user_name,
13599                })
13600            })
13601    }
13602
13603    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
13604        self.display_snapshot.buffer_snapshot.language_at(position)
13605    }
13606
13607    pub fn is_focused(&self) -> bool {
13608        self.is_focused
13609    }
13610
13611    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
13612        self.placeholder_text.as_ref()
13613    }
13614
13615    pub fn scroll_position(&self) -> gpui::Point<f32> {
13616        self.scroll_anchor.scroll_position(&self.display_snapshot)
13617    }
13618
13619    fn gutter_dimensions(
13620        &self,
13621        font_id: FontId,
13622        font_size: Pixels,
13623        em_width: Pixels,
13624        em_advance: Pixels,
13625        max_line_number_width: Pixels,
13626        cx: &AppContext,
13627    ) -> GutterDimensions {
13628        if !self.show_gutter {
13629            return GutterDimensions::default();
13630        }
13631        let descent = cx.text_system().descent(font_id, font_size);
13632
13633        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
13634            matches!(
13635                ProjectSettings::get_global(cx).git.git_gutter,
13636                Some(GitGutterSetting::TrackedFiles)
13637            )
13638        });
13639        let gutter_settings = EditorSettings::get_global(cx).gutter;
13640        let show_line_numbers = self
13641            .show_line_numbers
13642            .unwrap_or(gutter_settings.line_numbers);
13643        let line_gutter_width = if show_line_numbers {
13644            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
13645            let min_width_for_number_on_gutter = em_advance * 4.0;
13646            max_line_number_width.max(min_width_for_number_on_gutter)
13647        } else {
13648            0.0.into()
13649        };
13650
13651        let show_code_actions = self
13652            .show_code_actions
13653            .unwrap_or(gutter_settings.code_actions);
13654
13655        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
13656
13657        let git_blame_entries_width =
13658            self.git_blame_gutter_max_author_length
13659                .map(|max_author_length| {
13660                    // Length of the author name, but also space for the commit hash,
13661                    // the spacing and the timestamp.
13662                    let max_char_count = max_author_length
13663                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
13664                        + 7 // length of commit sha
13665                        + 14 // length of max relative timestamp ("60 minutes ago")
13666                        + 4; // gaps and margins
13667
13668                    em_advance * max_char_count
13669                });
13670
13671        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
13672        left_padding += if show_code_actions || show_runnables {
13673            em_width * 3.0
13674        } else if show_git_gutter && show_line_numbers {
13675            em_width * 2.0
13676        } else if show_git_gutter || show_line_numbers {
13677            em_width
13678        } else {
13679            px(0.)
13680        };
13681
13682        let right_padding = if gutter_settings.folds && show_line_numbers {
13683            em_width * 4.0
13684        } else if gutter_settings.folds {
13685            em_width * 3.0
13686        } else if show_line_numbers {
13687            em_width
13688        } else {
13689            px(0.)
13690        };
13691
13692        GutterDimensions {
13693            left_padding,
13694            right_padding,
13695            width: line_gutter_width + left_padding + right_padding,
13696            margin: -descent,
13697            git_blame_entries_width,
13698        }
13699    }
13700
13701    pub fn render_fold_toggle(
13702        &self,
13703        buffer_row: MultiBufferRow,
13704        row_contains_cursor: bool,
13705        editor: View<Editor>,
13706        cx: &mut WindowContext,
13707    ) -> Option<AnyElement> {
13708        let folded = self.is_line_folded(buffer_row);
13709
13710        if let Some(crease) = self
13711            .crease_snapshot
13712            .query_row(buffer_row, &self.buffer_snapshot)
13713        {
13714            let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
13715                if folded {
13716                    editor.update(cx, |editor, cx| {
13717                        editor.fold_at(&crate::FoldAt { buffer_row }, cx)
13718                    });
13719                } else {
13720                    editor.update(cx, |editor, cx| {
13721                        editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
13722                    });
13723                }
13724            });
13725
13726            Some((crease.render_toggle)(
13727                buffer_row,
13728                folded,
13729                toggle_callback,
13730                cx,
13731            ))
13732        } else if folded
13733            || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
13734        {
13735            Some(
13736                Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
13737                    .selected(folded)
13738                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
13739                        if folded {
13740                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
13741                        } else {
13742                            this.fold_at(&FoldAt { buffer_row }, cx);
13743                        }
13744                    }))
13745                    .into_any_element(),
13746            )
13747        } else {
13748            None
13749        }
13750    }
13751
13752    pub fn render_crease_trailer(
13753        &self,
13754        buffer_row: MultiBufferRow,
13755        cx: &mut WindowContext,
13756    ) -> Option<AnyElement> {
13757        let folded = self.is_line_folded(buffer_row);
13758        let crease = self
13759            .crease_snapshot
13760            .query_row(buffer_row, &self.buffer_snapshot)?;
13761        Some((crease.render_trailer)(buffer_row, folded, cx))
13762    }
13763}
13764
13765impl Deref for EditorSnapshot {
13766    type Target = DisplaySnapshot;
13767
13768    fn deref(&self) -> &Self::Target {
13769        &self.display_snapshot
13770    }
13771}
13772
13773#[derive(Clone, Debug, PartialEq, Eq)]
13774pub enum EditorEvent {
13775    InputIgnored {
13776        text: Arc<str>,
13777    },
13778    InputHandled {
13779        utf16_range_to_replace: Option<Range<isize>>,
13780        text: Arc<str>,
13781    },
13782    ExcerptsAdded {
13783        buffer: Model<Buffer>,
13784        predecessor: ExcerptId,
13785        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
13786    },
13787    ExcerptsRemoved {
13788        ids: Vec<ExcerptId>,
13789    },
13790    ExcerptsEdited {
13791        ids: Vec<ExcerptId>,
13792    },
13793    ExcerptsExpanded {
13794        ids: Vec<ExcerptId>,
13795    },
13796    BufferEdited,
13797    Edited {
13798        transaction_id: clock::Lamport,
13799    },
13800    Reparsed(BufferId),
13801    Focused,
13802    FocusedIn,
13803    Blurred,
13804    DirtyChanged,
13805    Saved,
13806    TitleChanged,
13807    DiffBaseChanged,
13808    SelectionsChanged {
13809        local: bool,
13810    },
13811    ScrollPositionChanged {
13812        local: bool,
13813        autoscroll: bool,
13814    },
13815    Closed,
13816    TransactionUndone {
13817        transaction_id: clock::Lamport,
13818    },
13819    TransactionBegun {
13820        transaction_id: clock::Lamport,
13821    },
13822    Reloaded,
13823    CursorShapeChanged,
13824}
13825
13826impl EventEmitter<EditorEvent> for Editor {}
13827
13828impl FocusableView for Editor {
13829    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
13830        self.focus_handle.clone()
13831    }
13832}
13833
13834impl Render for Editor {
13835    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
13836        let settings = ThemeSettings::get_global(cx);
13837
13838        let mut text_style = match self.mode {
13839            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
13840                color: cx.theme().colors().editor_foreground,
13841                font_family: settings.ui_font.family.clone(),
13842                font_features: settings.ui_font.features.clone(),
13843                font_fallbacks: settings.ui_font.fallbacks.clone(),
13844                font_size: rems(0.875).into(),
13845                font_weight: settings.ui_font.weight,
13846                line_height: relative(settings.buffer_line_height.value()),
13847                ..Default::default()
13848            },
13849            EditorMode::Full => TextStyle {
13850                color: cx.theme().colors().editor_foreground,
13851                font_family: settings.buffer_font.family.clone(),
13852                font_features: settings.buffer_font.features.clone(),
13853                font_fallbacks: settings.buffer_font.fallbacks.clone(),
13854                font_size: settings.buffer_font_size(cx).into(),
13855                font_weight: settings.buffer_font.weight,
13856                line_height: relative(settings.buffer_line_height.value()),
13857                ..Default::default()
13858            },
13859        };
13860        if let Some(text_style_refinement) = &self.text_style_refinement {
13861            text_style.refine(text_style_refinement)
13862        }
13863
13864        let background = match self.mode {
13865            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
13866            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
13867            EditorMode::Full => cx.theme().colors().editor_background,
13868        };
13869
13870        EditorElement::new(
13871            cx.view(),
13872            EditorStyle {
13873                background,
13874                local_player: cx.theme().players().local(),
13875                text: text_style,
13876                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
13877                syntax: cx.theme().syntax().clone(),
13878                status: cx.theme().status().clone(),
13879                inlay_hints_style: make_inlay_hints_style(cx),
13880                suggestions_style: HighlightStyle {
13881                    color: Some(cx.theme().status().predictive),
13882                    ..HighlightStyle::default()
13883                },
13884                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
13885            },
13886        )
13887    }
13888}
13889
13890impl ViewInputHandler for Editor {
13891    fn text_for_range(
13892        &mut self,
13893        range_utf16: Range<usize>,
13894        cx: &mut ViewContext<Self>,
13895    ) -> Option<String> {
13896        Some(
13897            self.buffer
13898                .read(cx)
13899                .read(cx)
13900                .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
13901                .collect(),
13902        )
13903    }
13904
13905    fn selected_text_range(
13906        &mut self,
13907        ignore_disabled_input: bool,
13908        cx: &mut ViewContext<Self>,
13909    ) -> Option<UTF16Selection> {
13910        // Prevent the IME menu from appearing when holding down an alphabetic key
13911        // while input is disabled.
13912        if !ignore_disabled_input && !self.input_enabled {
13913            return None;
13914        }
13915
13916        let selection = self.selections.newest::<OffsetUtf16>(cx);
13917        let range = selection.range();
13918
13919        Some(UTF16Selection {
13920            range: range.start.0..range.end.0,
13921            reversed: selection.reversed,
13922        })
13923    }
13924
13925    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
13926        let snapshot = self.buffer.read(cx).read(cx);
13927        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
13928        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
13929    }
13930
13931    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
13932        self.clear_highlights::<InputComposition>(cx);
13933        self.ime_transaction.take();
13934    }
13935
13936    fn replace_text_in_range(
13937        &mut self,
13938        range_utf16: Option<Range<usize>>,
13939        text: &str,
13940        cx: &mut ViewContext<Self>,
13941    ) {
13942        if !self.input_enabled {
13943            cx.emit(EditorEvent::InputIgnored { text: text.into() });
13944            return;
13945        }
13946
13947        self.transact(cx, |this, cx| {
13948            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
13949                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13950                Some(this.selection_replacement_ranges(range_utf16, cx))
13951            } else {
13952                this.marked_text_ranges(cx)
13953            };
13954
13955            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
13956                let newest_selection_id = this.selections.newest_anchor().id;
13957                this.selections
13958                    .all::<OffsetUtf16>(cx)
13959                    .iter()
13960                    .zip(ranges_to_replace.iter())
13961                    .find_map(|(selection, range)| {
13962                        if selection.id == newest_selection_id {
13963                            Some(
13964                                (range.start.0 as isize - selection.head().0 as isize)
13965                                    ..(range.end.0 as isize - selection.head().0 as isize),
13966                            )
13967                        } else {
13968                            None
13969                        }
13970                    })
13971            });
13972
13973            cx.emit(EditorEvent::InputHandled {
13974                utf16_range_to_replace: range_to_replace,
13975                text: text.into(),
13976            });
13977
13978            if let Some(new_selected_ranges) = new_selected_ranges {
13979                this.change_selections(None, cx, |selections| {
13980                    selections.select_ranges(new_selected_ranges)
13981                });
13982                this.backspace(&Default::default(), cx);
13983            }
13984
13985            this.handle_input(text, cx);
13986        });
13987
13988        if let Some(transaction) = self.ime_transaction {
13989            self.buffer.update(cx, |buffer, cx| {
13990                buffer.group_until_transaction(transaction, cx);
13991            });
13992        }
13993
13994        self.unmark_text(cx);
13995    }
13996
13997    fn replace_and_mark_text_in_range(
13998        &mut self,
13999        range_utf16: Option<Range<usize>>,
14000        text: &str,
14001        new_selected_range_utf16: Option<Range<usize>>,
14002        cx: &mut ViewContext<Self>,
14003    ) {
14004        if !self.input_enabled {
14005            return;
14006        }
14007
14008        let transaction = self.transact(cx, |this, cx| {
14009            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14010                let snapshot = this.buffer.read(cx).read(cx);
14011                if let Some(relative_range_utf16) = range_utf16.as_ref() {
14012                    for marked_range in &mut marked_ranges {
14013                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14014                        marked_range.start.0 += relative_range_utf16.start;
14015                        marked_range.start =
14016                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14017                        marked_range.end =
14018                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14019                    }
14020                }
14021                Some(marked_ranges)
14022            } else if let Some(range_utf16) = range_utf16 {
14023                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14024                Some(this.selection_replacement_ranges(range_utf16, cx))
14025            } else {
14026                None
14027            };
14028
14029            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14030                let newest_selection_id = this.selections.newest_anchor().id;
14031                this.selections
14032                    .all::<OffsetUtf16>(cx)
14033                    .iter()
14034                    .zip(ranges_to_replace.iter())
14035                    .find_map(|(selection, range)| {
14036                        if selection.id == newest_selection_id {
14037                            Some(
14038                                (range.start.0 as isize - selection.head().0 as isize)
14039                                    ..(range.end.0 as isize - selection.head().0 as isize),
14040                            )
14041                        } else {
14042                            None
14043                        }
14044                    })
14045            });
14046
14047            cx.emit(EditorEvent::InputHandled {
14048                utf16_range_to_replace: range_to_replace,
14049                text: text.into(),
14050            });
14051
14052            if let Some(ranges) = ranges_to_replace {
14053                this.change_selections(None, cx, |s| s.select_ranges(ranges));
14054            }
14055
14056            let marked_ranges = {
14057                let snapshot = this.buffer.read(cx).read(cx);
14058                this.selections
14059                    .disjoint_anchors()
14060                    .iter()
14061                    .map(|selection| {
14062                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14063                    })
14064                    .collect::<Vec<_>>()
14065            };
14066
14067            if text.is_empty() {
14068                this.unmark_text(cx);
14069            } else {
14070                this.highlight_text::<InputComposition>(
14071                    marked_ranges.clone(),
14072                    HighlightStyle {
14073                        underline: Some(UnderlineStyle {
14074                            thickness: px(1.),
14075                            color: None,
14076                            wavy: false,
14077                        }),
14078                        ..Default::default()
14079                    },
14080                    cx,
14081                );
14082            }
14083
14084            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14085            let use_autoclose = this.use_autoclose;
14086            let use_auto_surround = this.use_auto_surround;
14087            this.set_use_autoclose(false);
14088            this.set_use_auto_surround(false);
14089            this.handle_input(text, cx);
14090            this.set_use_autoclose(use_autoclose);
14091            this.set_use_auto_surround(use_auto_surround);
14092
14093            if let Some(new_selected_range) = new_selected_range_utf16 {
14094                let snapshot = this.buffer.read(cx).read(cx);
14095                let new_selected_ranges = marked_ranges
14096                    .into_iter()
14097                    .map(|marked_range| {
14098                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14099                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14100                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14101                        snapshot.clip_offset_utf16(new_start, Bias::Left)
14102                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14103                    })
14104                    .collect::<Vec<_>>();
14105
14106                drop(snapshot);
14107                this.change_selections(None, cx, |selections| {
14108                    selections.select_ranges(new_selected_ranges)
14109                });
14110            }
14111        });
14112
14113        self.ime_transaction = self.ime_transaction.or(transaction);
14114        if let Some(transaction) = self.ime_transaction {
14115            self.buffer.update(cx, |buffer, cx| {
14116                buffer.group_until_transaction(transaction, cx);
14117            });
14118        }
14119
14120        if self.text_highlights::<InputComposition>(cx).is_none() {
14121            self.ime_transaction.take();
14122        }
14123    }
14124
14125    fn bounds_for_range(
14126        &mut self,
14127        range_utf16: Range<usize>,
14128        element_bounds: gpui::Bounds<Pixels>,
14129        cx: &mut ViewContext<Self>,
14130    ) -> Option<gpui::Bounds<Pixels>> {
14131        let text_layout_details = self.text_layout_details(cx);
14132        let style = &text_layout_details.editor_style;
14133        let font_id = cx.text_system().resolve_font(&style.text.font());
14134        let font_size = style.text.font_size.to_pixels(cx.rem_size());
14135        let line_height = style.text.line_height_in_pixels(cx.rem_size());
14136
14137        let em_width = cx
14138            .text_system()
14139            .typographic_bounds(font_id, font_size, 'm')
14140            .unwrap()
14141            .size
14142            .width;
14143
14144        let snapshot = self.snapshot(cx);
14145        let scroll_position = snapshot.scroll_position();
14146        let scroll_left = scroll_position.x * em_width;
14147
14148        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14149        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14150            + self.gutter_dimensions.width;
14151        let y = line_height * (start.row().as_f32() - scroll_position.y);
14152
14153        Some(Bounds {
14154            origin: element_bounds.origin + point(x, y),
14155            size: size(em_width, line_height),
14156        })
14157    }
14158}
14159
14160trait SelectionExt {
14161    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14162    fn spanned_rows(
14163        &self,
14164        include_end_if_at_line_start: bool,
14165        map: &DisplaySnapshot,
14166    ) -> Range<MultiBufferRow>;
14167}
14168
14169impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14170    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14171        let start = self
14172            .start
14173            .to_point(&map.buffer_snapshot)
14174            .to_display_point(map);
14175        let end = self
14176            .end
14177            .to_point(&map.buffer_snapshot)
14178            .to_display_point(map);
14179        if self.reversed {
14180            end..start
14181        } else {
14182            start..end
14183        }
14184    }
14185
14186    fn spanned_rows(
14187        &self,
14188        include_end_if_at_line_start: bool,
14189        map: &DisplaySnapshot,
14190    ) -> Range<MultiBufferRow> {
14191        let start = self.start.to_point(&map.buffer_snapshot);
14192        let mut end = self.end.to_point(&map.buffer_snapshot);
14193        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14194            end.row -= 1;
14195        }
14196
14197        let buffer_start = map.prev_line_boundary(start).0;
14198        let buffer_end = map.next_line_boundary(end).0;
14199        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14200    }
14201}
14202
14203impl<T: InvalidationRegion> InvalidationStack<T> {
14204    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14205    where
14206        S: Clone + ToOffset,
14207    {
14208        while let Some(region) = self.last() {
14209            let all_selections_inside_invalidation_ranges =
14210                if selections.len() == region.ranges().len() {
14211                    selections
14212                        .iter()
14213                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14214                        .all(|(selection, invalidation_range)| {
14215                            let head = selection.head().to_offset(buffer);
14216                            invalidation_range.start <= head && invalidation_range.end >= head
14217                        })
14218                } else {
14219                    false
14220                };
14221
14222            if all_selections_inside_invalidation_ranges {
14223                break;
14224            } else {
14225                self.pop();
14226            }
14227        }
14228    }
14229}
14230
14231impl<T> Default for InvalidationStack<T> {
14232    fn default() -> Self {
14233        Self(Default::default())
14234    }
14235}
14236
14237impl<T> Deref for InvalidationStack<T> {
14238    type Target = Vec<T>;
14239
14240    fn deref(&self) -> &Self::Target {
14241        &self.0
14242    }
14243}
14244
14245impl<T> DerefMut for InvalidationStack<T> {
14246    fn deref_mut(&mut self) -> &mut Self::Target {
14247        &mut self.0
14248    }
14249}
14250
14251impl InvalidationRegion for SnippetState {
14252    fn ranges(&self) -> &[Range<Anchor>] {
14253        &self.ranges[self.active_index]
14254    }
14255}
14256
14257pub fn diagnostic_block_renderer(
14258    diagnostic: Diagnostic,
14259    max_message_rows: Option<u8>,
14260    allow_closing: bool,
14261    _is_valid: bool,
14262) -> RenderBlock {
14263    let (text_without_backticks, code_ranges) =
14264        highlight_diagnostic_message(&diagnostic, max_message_rows);
14265
14266    Box::new(move |cx: &mut BlockContext| {
14267        let group_id: SharedString = cx.block_id.to_string().into();
14268
14269        let mut text_style = cx.text_style().clone();
14270        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14271        let theme_settings = ThemeSettings::get_global(cx);
14272        text_style.font_family = theme_settings.buffer_font.family.clone();
14273        text_style.font_style = theme_settings.buffer_font.style;
14274        text_style.font_features = theme_settings.buffer_font.features.clone();
14275        text_style.font_weight = theme_settings.buffer_font.weight;
14276
14277        let multi_line_diagnostic = diagnostic.message.contains('\n');
14278
14279        let buttons = |diagnostic: &Diagnostic| {
14280            if multi_line_diagnostic {
14281                v_flex()
14282            } else {
14283                h_flex()
14284            }
14285            .when(allow_closing, |div| {
14286                div.children(diagnostic.is_primary.then(|| {
14287                    IconButton::new("close-block", IconName::XCircle)
14288                        .icon_color(Color::Muted)
14289                        .size(ButtonSize::Compact)
14290                        .style(ButtonStyle::Transparent)
14291                        .visible_on_hover(group_id.clone())
14292                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14293                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14294                }))
14295            })
14296            .child(
14297                IconButton::new("copy-block", IconName::Copy)
14298                    .icon_color(Color::Muted)
14299                    .size(ButtonSize::Compact)
14300                    .style(ButtonStyle::Transparent)
14301                    .visible_on_hover(group_id.clone())
14302                    .on_click({
14303                        let message = diagnostic.message.clone();
14304                        move |_click, cx| {
14305                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14306                        }
14307                    })
14308                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14309            )
14310        };
14311
14312        let icon_size = buttons(&diagnostic)
14313            .into_any_element()
14314            .layout_as_root(AvailableSpace::min_size(), cx);
14315
14316        h_flex()
14317            .id(cx.block_id)
14318            .group(group_id.clone())
14319            .relative()
14320            .size_full()
14321            .pl(cx.gutter_dimensions.width)
14322            .w(cx.max_width - cx.gutter_dimensions.full_width())
14323            .child(
14324                div()
14325                    .flex()
14326                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14327                    .flex_shrink(),
14328            )
14329            .child(buttons(&diagnostic))
14330            .child(div().flex().flex_shrink_0().child(
14331                StyledText::new(text_without_backticks.clone()).with_highlights(
14332                    &text_style,
14333                    code_ranges.iter().map(|range| {
14334                        (
14335                            range.clone(),
14336                            HighlightStyle {
14337                                font_weight: Some(FontWeight::BOLD),
14338                                ..Default::default()
14339                            },
14340                        )
14341                    }),
14342                ),
14343            ))
14344            .into_any_element()
14345    })
14346}
14347
14348pub fn highlight_diagnostic_message(
14349    diagnostic: &Diagnostic,
14350    mut max_message_rows: Option<u8>,
14351) -> (SharedString, Vec<Range<usize>>) {
14352    let mut text_without_backticks = String::new();
14353    let mut code_ranges = Vec::new();
14354
14355    if let Some(source) = &diagnostic.source {
14356        text_without_backticks.push_str(source);
14357        code_ranges.push(0..source.len());
14358        text_without_backticks.push_str(": ");
14359    }
14360
14361    let mut prev_offset = 0;
14362    let mut in_code_block = false;
14363    let has_row_limit = max_message_rows.is_some();
14364    let mut newline_indices = diagnostic
14365        .message
14366        .match_indices('\n')
14367        .filter(|_| has_row_limit)
14368        .map(|(ix, _)| ix)
14369        .fuse()
14370        .peekable();
14371
14372    for (quote_ix, _) in diagnostic
14373        .message
14374        .match_indices('`')
14375        .chain([(diagnostic.message.len(), "")])
14376    {
14377        let mut first_newline_ix = None;
14378        let mut last_newline_ix = None;
14379        while let Some(newline_ix) = newline_indices.peek() {
14380            if *newline_ix < quote_ix {
14381                if first_newline_ix.is_none() {
14382                    first_newline_ix = Some(*newline_ix);
14383                }
14384                last_newline_ix = Some(*newline_ix);
14385
14386                if let Some(rows_left) = &mut max_message_rows {
14387                    if *rows_left == 0 {
14388                        break;
14389                    } else {
14390                        *rows_left -= 1;
14391                    }
14392                }
14393                let _ = newline_indices.next();
14394            } else {
14395                break;
14396            }
14397        }
14398        let prev_len = text_without_backticks.len();
14399        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14400        text_without_backticks.push_str(new_text);
14401        if in_code_block {
14402            code_ranges.push(prev_len..text_without_backticks.len());
14403        }
14404        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14405        in_code_block = !in_code_block;
14406        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14407            text_without_backticks.push_str("...");
14408            break;
14409        }
14410    }
14411
14412    (text_without_backticks.into(), code_ranges)
14413}
14414
14415fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14416    match severity {
14417        DiagnosticSeverity::ERROR => colors.error,
14418        DiagnosticSeverity::WARNING => colors.warning,
14419        DiagnosticSeverity::INFORMATION => colors.info,
14420        DiagnosticSeverity::HINT => colors.info,
14421        _ => colors.ignored,
14422    }
14423}
14424
14425pub fn styled_runs_for_code_label<'a>(
14426    label: &'a CodeLabel,
14427    syntax_theme: &'a theme::SyntaxTheme,
14428) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14429    let fade_out = HighlightStyle {
14430        fade_out: Some(0.35),
14431        ..Default::default()
14432    };
14433
14434    let mut prev_end = label.filter_range.end;
14435    label
14436        .runs
14437        .iter()
14438        .enumerate()
14439        .flat_map(move |(ix, (range, highlight_id))| {
14440            let style = if let Some(style) = highlight_id.style(syntax_theme) {
14441                style
14442            } else {
14443                return Default::default();
14444            };
14445            let mut muted_style = style;
14446            muted_style.highlight(fade_out);
14447
14448            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14449            if range.start >= label.filter_range.end {
14450                if range.start > prev_end {
14451                    runs.push((prev_end..range.start, fade_out));
14452                }
14453                runs.push((range.clone(), muted_style));
14454            } else if range.end <= label.filter_range.end {
14455                runs.push((range.clone(), style));
14456            } else {
14457                runs.push((range.start..label.filter_range.end, style));
14458                runs.push((label.filter_range.end..range.end, muted_style));
14459            }
14460            prev_end = cmp::max(prev_end, range.end);
14461
14462            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14463                runs.push((prev_end..label.text.len(), fade_out));
14464            }
14465
14466            runs
14467        })
14468}
14469
14470pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14471    let mut prev_index = 0;
14472    let mut prev_codepoint: Option<char> = None;
14473    text.char_indices()
14474        .chain([(text.len(), '\0')])
14475        .filter_map(move |(index, codepoint)| {
14476            let prev_codepoint = prev_codepoint.replace(codepoint)?;
14477            let is_boundary = index == text.len()
14478                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14479                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14480            if is_boundary {
14481                let chunk = &text[prev_index..index];
14482                prev_index = index;
14483                Some(chunk)
14484            } else {
14485                None
14486            }
14487        })
14488}
14489
14490pub trait RangeToAnchorExt: Sized {
14491    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14492
14493    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14494        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14495        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14496    }
14497}
14498
14499impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14500    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14501        let start_offset = self.start.to_offset(snapshot);
14502        let end_offset = self.end.to_offset(snapshot);
14503        if start_offset == end_offset {
14504            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14505        } else {
14506            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14507        }
14508    }
14509}
14510
14511pub trait RowExt {
14512    fn as_f32(&self) -> f32;
14513
14514    fn next_row(&self) -> Self;
14515
14516    fn previous_row(&self) -> Self;
14517
14518    fn minus(&self, other: Self) -> u32;
14519}
14520
14521impl RowExt for DisplayRow {
14522    fn as_f32(&self) -> f32 {
14523        self.0 as f32
14524    }
14525
14526    fn next_row(&self) -> Self {
14527        Self(self.0 + 1)
14528    }
14529
14530    fn previous_row(&self) -> Self {
14531        Self(self.0.saturating_sub(1))
14532    }
14533
14534    fn minus(&self, other: Self) -> u32 {
14535        self.0 - other.0
14536    }
14537}
14538
14539impl RowExt for MultiBufferRow {
14540    fn as_f32(&self) -> f32 {
14541        self.0 as f32
14542    }
14543
14544    fn next_row(&self) -> Self {
14545        Self(self.0 + 1)
14546    }
14547
14548    fn previous_row(&self) -> Self {
14549        Self(self.0.saturating_sub(1))
14550    }
14551
14552    fn minus(&self, other: Self) -> u32 {
14553        self.0 - other.0
14554    }
14555}
14556
14557trait RowRangeExt {
14558    type Row;
14559
14560    fn len(&self) -> usize;
14561
14562    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
14563}
14564
14565impl RowRangeExt for Range<MultiBufferRow> {
14566    type Row = MultiBufferRow;
14567
14568    fn len(&self) -> usize {
14569        (self.end.0 - self.start.0) as usize
14570    }
14571
14572    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
14573        (self.start.0..self.end.0).map(MultiBufferRow)
14574    }
14575}
14576
14577impl RowRangeExt for Range<DisplayRow> {
14578    type Row = DisplayRow;
14579
14580    fn len(&self) -> usize {
14581        (self.end.0 - self.start.0) as usize
14582    }
14583
14584    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
14585        (self.start.0..self.end.0).map(DisplayRow)
14586    }
14587}
14588
14589fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
14590    if hunk.diff_base_byte_range.is_empty() {
14591        DiffHunkStatus::Added
14592    } else if hunk.row_range.is_empty() {
14593        DiffHunkStatus::Removed
14594    } else {
14595        DiffHunkStatus::Modified
14596    }
14597}
14598
14599/// If select range has more than one line, we
14600/// just point the cursor to range.start.
14601fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
14602    if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
14603        range
14604    } else {
14605        range.start..range.start
14606    }
14607}