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;
   51use ::git::{parse_git_remote_url, BuildPermalinkParams, GitHostingProviderRegistry};
   52pub(crate) use actions::*;
   53use aho_corasick::AhoCorasick;
   54use anyhow::{anyhow, Context as _, Result};
   55use blink_manager::BlinkManager;
   56use client::{Collaborator, ParticipantIndex};
   57use clock::ReplicaId;
   58use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
   59use convert_case::{Case, Casing};
   60use debounced_delay::DebouncedDelay;
   61use display_map::*;
   62pub use display_map::{DisplayPoint, FoldPlaceholder};
   63pub use editor_settings::{
   64    CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
   65};
   66pub use editor_settings_controls::*;
   67use element::LineWithInvisibles;
   68pub use element::{
   69    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   70};
   71use futures::{future, FutureExt};
   72use fuzzy::{StringMatch, StringMatchCandidate};
   73use git::blame::GitBlame;
   74use gpui::{
   75    div, impl_actions, point, prelude::*, px, relative, size, uniform_list, Action, AnyElement,
   76    AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds, ClipboardEntry,
   77    ClipboardItem, Context, DispatchPhase, ElementId, EntityId, EventEmitter, FocusHandle,
   78    FocusOutEvent, FocusableView, FontId, FontWeight, HighlightStyle, Hsla, InteractiveText,
   79    KeyContext, ListSizingBehavior, Model, MouseButton, PaintQuad, ParentElement, Pixels, Render,
   80    SharedString, Size, StrikethroughStyle, Styled, StyledText, Subscription, Task, TextStyle,
   81    UTF16Selection, UnderlineStyle, UniformListScrollHandle, View, ViewContext, ViewInputHandler,
   82    VisualContext, WeakFocusHandle, WeakView, WindowContext,
   83};
   84use highlight_matching_bracket::refresh_matching_bracket_highlights;
   85use hover_popover::{hide_hover, HoverState};
   86pub(crate) use hunk_diff::HoveredHunk;
   87use hunk_diff::{diff_hunk_to_display, ExpandedHunks};
   88use indent_guides::ActiveIndentGuidesState;
   89use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   90pub use inline_completion_provider::*;
   91pub use items::MAX_TAB_TITLE_LEN;
   92use itertools::Itertools;
   93use language::{
   94    language_settings::{self, all_language_settings, InlayHintSettings},
   95    markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
   96    CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
   97    Point, Selection, SelectionGoal, TransactionId,
   98};
   99use language::{
  100    point_to_lsp, BufferRow, CharClassifier, LanguageServerName, Runnable, RunnableRange,
  101};
  102use linked_editing_ranges::refresh_linked_ranges;
  103pub use proposed_changes_editor::{
  104    ProposedChangesBuffer, ProposedChangesEditor, ProposedChangesEditorToolbar,
  105};
  106use similar::{ChangeTag, TextDiff};
  107use task::{ResolvedTask, TaskTemplate, TaskVariables};
  108
  109use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  110pub use lsp::CompletionContext;
  111use lsp::{
  112    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  113    LanguageServerId,
  114};
  115use mouse_context_menu::MouseContextMenu;
  116use movement::TextLayoutDetails;
  117pub use multi_buffer::{
  118    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
  119    ToPoint,
  120};
  121use multi_buffer::{
  122    ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
  123};
  124use ordered_float::OrderedFloat;
  125use parking_lot::{Mutex, RwLock};
  126use project::{
  127    lsp_store::{FormatTarget, FormatTrigger},
  128    project_settings::{GitGutterSetting, ProjectSettings},
  129    CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Item, Location,
  130    LocationLink, Project, ProjectPath, ProjectTransaction, TaskSourceKind,
  131};
  132use rand::prelude::*;
  133use rpc::{proto::*, ErrorExt};
  134use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  135use selections_collection::{resolve_multiple, MutableSelectionsCollection, SelectionsCollection};
  136use serde::{Deserialize, Serialize};
  137use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  138use smallvec::SmallVec;
  139use snippet::Snippet;
  140use std::{
  141    any::TypeId,
  142    borrow::Cow,
  143    cell::RefCell,
  144    cmp::{self, Ordering, Reverse},
  145    mem,
  146    num::NonZeroU32,
  147    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  148    path::{Path, PathBuf},
  149    rc::Rc,
  150    sync::Arc,
  151    time::{Duration, Instant},
  152};
  153pub use sum_tree::Bias;
  154use sum_tree::TreeMap;
  155use text::{BufferId, OffsetUtf16, Rope};
  156use theme::{
  157    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  158    ThemeColors, ThemeSettings,
  159};
  160use ui::{
  161    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
  162    ListItem, Popover, PopoverMenuHandle, Tooltip,
  163};
  164use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  165use workspace::item::{ItemHandle, PreviewTabsSettings};
  166use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
  167use workspace::{
  168    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  169};
  170use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  171
  172use crate::hover_links::find_url;
  173use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  174
  175pub const FILE_HEADER_HEIGHT: u32 = 1;
  176pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  177pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  178pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  179const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  180const MAX_LINE_LEN: usize = 1024;
  181const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  182const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  183pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  184#[doc(hidden)]
  185pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  186#[doc(hidden)]
  187pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
  188
  189pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  190pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  191
  192pub fn render_parsed_markdown(
  193    element_id: impl Into<ElementId>,
  194    parsed: &language::ParsedMarkdown,
  195    editor_style: &EditorStyle,
  196    workspace: Option<WeakView<Workspace>>,
  197    cx: &mut WindowContext,
  198) -> InteractiveText {
  199    let code_span_background_color = cx
  200        .theme()
  201        .colors()
  202        .editor_document_highlight_read_background;
  203
  204    let highlights = gpui::combine_highlights(
  205        parsed.highlights.iter().filter_map(|(range, highlight)| {
  206            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  207            Some((range.clone(), highlight))
  208        }),
  209        parsed
  210            .regions
  211            .iter()
  212            .zip(&parsed.region_ranges)
  213            .filter_map(|(region, range)| {
  214                if region.code {
  215                    Some((
  216                        range.clone(),
  217                        HighlightStyle {
  218                            background_color: Some(code_span_background_color),
  219                            ..Default::default()
  220                        },
  221                    ))
  222                } else {
  223                    None
  224                }
  225            }),
  226    );
  227
  228    let mut links = Vec::new();
  229    let mut link_ranges = Vec::new();
  230    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  231        if let Some(link) = region.link.clone() {
  232            links.push(link);
  233            link_ranges.push(range.clone());
  234        }
  235    }
  236
  237    InteractiveText::new(
  238        element_id,
  239        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  240    )
  241    .on_click(link_ranges, move |clicked_range_ix, cx| {
  242        match &links[clicked_range_ix] {
  243            markdown::Link::Web { url } => cx.open_url(url),
  244            markdown::Link::Path { path } => {
  245                if let Some(workspace) = &workspace {
  246                    _ = workspace.update(cx, |workspace, cx| {
  247                        workspace.open_abs_path(path.clone(), false, cx).detach();
  248                    });
  249                }
  250            }
  251        }
  252    })
  253}
  254
  255#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  256pub(crate) enum InlayId {
  257    Suggestion(usize),
  258    Hint(usize),
  259}
  260
  261impl InlayId {
  262    fn id(&self) -> usize {
  263        match self {
  264            Self::Suggestion(id) => *id,
  265            Self::Hint(id) => *id,
  266        }
  267    }
  268}
  269
  270enum DiffRowHighlight {}
  271enum DocumentHighlightRead {}
  272enum DocumentHighlightWrite {}
  273enum InputComposition {}
  274
  275#[derive(Copy, Clone, PartialEq, Eq)]
  276pub enum Direction {
  277    Prev,
  278    Next,
  279}
  280
  281#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  282pub enum Navigated {
  283    Yes,
  284    No,
  285}
  286
  287impl Navigated {
  288    pub fn from_bool(yes: bool) -> Navigated {
  289        if yes {
  290            Navigated::Yes
  291        } else {
  292            Navigated::No
  293        }
  294    }
  295}
  296
  297pub fn init_settings(cx: &mut AppContext) {
  298    EditorSettings::register(cx);
  299}
  300
  301pub fn init(cx: &mut AppContext) {
  302    init_settings(cx);
  303
  304    workspace::register_project_item::<Editor>(cx);
  305    workspace::FollowableViewRegistry::register::<Editor>(cx);
  306    workspace::register_serializable_item::<Editor>(cx);
  307
  308    cx.observe_new_views(
  309        |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
  310            workspace.register_action(Editor::new_file);
  311            workspace.register_action(Editor::new_file_vertical);
  312            workspace.register_action(Editor::new_file_horizontal);
  313        },
  314    )
  315    .detach();
  316
  317    cx.on_action(move |_: &workspace::NewFile, cx| {
  318        let app_state = workspace::AppState::global(cx);
  319        if let Some(app_state) = app_state.upgrade() {
  320            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  321                Editor::new_file(workspace, &Default::default(), cx)
  322            })
  323            .detach();
  324        }
  325    });
  326    cx.on_action(move |_: &workspace::NewWindow, cx| {
  327        let app_state = workspace::AppState::global(cx);
  328        if let Some(app_state) = app_state.upgrade() {
  329            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  330                Editor::new_file(workspace, &Default::default(), cx)
  331            })
  332            .detach();
  333        }
  334    });
  335}
  336
  337pub struct SearchWithinRange;
  338
  339trait InvalidationRegion {
  340    fn ranges(&self) -> &[Range<Anchor>];
  341}
  342
  343#[derive(Clone, Debug, PartialEq)]
  344pub enum SelectPhase {
  345    Begin {
  346        position: DisplayPoint,
  347        add: bool,
  348        click_count: usize,
  349    },
  350    BeginColumnar {
  351        position: DisplayPoint,
  352        reset: bool,
  353        goal_column: u32,
  354    },
  355    Extend {
  356        position: DisplayPoint,
  357        click_count: usize,
  358    },
  359    Update {
  360        position: DisplayPoint,
  361        goal_column: u32,
  362        scroll_delta: gpui::Point<f32>,
  363    },
  364    End,
  365}
  366
  367#[derive(Clone, Debug)]
  368pub enum SelectMode {
  369    Character,
  370    Word(Range<Anchor>),
  371    Line(Range<Anchor>),
  372    All,
  373}
  374
  375#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  376pub enum EditorMode {
  377    SingleLine { auto_width: bool },
  378    AutoHeight { max_lines: usize },
  379    Full,
  380}
  381
  382#[derive(Copy, Clone, Debug)]
  383pub enum SoftWrap {
  384    /// Prefer not to wrap at all.
  385    ///
  386    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  387    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  388    GitDiff,
  389    /// Prefer a single line generally, unless an overly long line is encountered.
  390    None,
  391    /// Soft wrap lines that exceed the editor width.
  392    EditorWidth,
  393    /// Soft wrap lines at the preferred line length.
  394    Column(u32),
  395    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  396    Bounded(u32),
  397}
  398
  399#[derive(Clone)]
  400pub struct EditorStyle {
  401    pub background: Hsla,
  402    pub local_player: PlayerColor,
  403    pub text: TextStyle,
  404    pub scrollbar_width: Pixels,
  405    pub syntax: Arc<SyntaxTheme>,
  406    pub status: StatusColors,
  407    pub inlay_hints_style: HighlightStyle,
  408    pub suggestions_style: HighlightStyle,
  409    pub unnecessary_code_fade: f32,
  410}
  411
  412impl Default for EditorStyle {
  413    fn default() -> Self {
  414        Self {
  415            background: Hsla::default(),
  416            local_player: PlayerColor::default(),
  417            text: TextStyle::default(),
  418            scrollbar_width: Pixels::default(),
  419            syntax: Default::default(),
  420            // HACK: Status colors don't have a real default.
  421            // We should look into removing the status colors from the editor
  422            // style and retrieve them directly from the theme.
  423            status: StatusColors::dark(),
  424            inlay_hints_style: HighlightStyle::default(),
  425            suggestions_style: HighlightStyle::default(),
  426            unnecessary_code_fade: Default::default(),
  427        }
  428    }
  429}
  430
  431pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
  432    let show_background = all_language_settings(None, cx)
  433        .language(None)
  434        .inlay_hints
  435        .show_background;
  436
  437    HighlightStyle {
  438        color: Some(cx.theme().status().hint),
  439        background_color: show_background.then(|| cx.theme().status().hint_background),
  440        ..HighlightStyle::default()
  441    }
  442}
  443
  444type CompletionId = usize;
  445
  446#[derive(Clone, Debug)]
  447struct CompletionState {
  448    // render_inlay_ids represents the inlay hints that are inserted
  449    // for rendering the inline completions. They may be discontinuous
  450    // in the event that the completion provider returns some intersection
  451    // with the existing content.
  452    render_inlay_ids: Vec<InlayId>,
  453    // text is the resulting rope that is inserted when the user accepts a completion.
  454    text: Rope,
  455    // position is the position of the cursor when the completion was triggered.
  456    position: multi_buffer::Anchor,
  457    // delete_range is the range of text that this completion state covers.
  458    // if the completion is accepted, this range should be deleted.
  459    delete_range: Option<Range<multi_buffer::Anchor>>,
  460}
  461
  462#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  463struct EditorActionId(usize);
  464
  465impl EditorActionId {
  466    pub fn post_inc(&mut self) -> Self {
  467        let answer = self.0;
  468
  469        *self = Self(answer + 1);
  470
  471        Self(answer)
  472    }
  473}
  474
  475// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  476// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  477
  478type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  479type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
  480
  481#[derive(Default)]
  482struct ScrollbarMarkerState {
  483    scrollbar_size: Size<Pixels>,
  484    dirty: bool,
  485    markers: Arc<[PaintQuad]>,
  486    pending_refresh: Option<Task<Result<()>>>,
  487}
  488
  489impl ScrollbarMarkerState {
  490    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  491        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  492    }
  493}
  494
  495#[derive(Clone, Debug)]
  496struct RunnableTasks {
  497    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  498    offset: MultiBufferOffset,
  499    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  500    column: u32,
  501    // Values of all named captures, including those starting with '_'
  502    extra_variables: HashMap<String, String>,
  503    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  504    context_range: Range<BufferOffset>,
  505}
  506
  507#[derive(Clone)]
  508struct ResolvedTasks {
  509    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  510    position: Anchor,
  511}
  512#[derive(Copy, Clone, Debug)]
  513struct MultiBufferOffset(usize);
  514#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  515struct BufferOffset(usize);
  516
  517// Addons allow storing per-editor state in other crates (e.g. Vim)
  518pub trait Addon: 'static {
  519    fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
  520
  521    fn to_any(&self) -> &dyn std::any::Any;
  522}
  523
  524/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
  525///
  526/// See the [module level documentation](self) for more information.
  527pub struct Editor {
  528    focus_handle: FocusHandle,
  529    last_focused_descendant: Option<WeakFocusHandle>,
  530    /// The text buffer being edited
  531    buffer: Model<MultiBuffer>,
  532    /// Map of how text in the buffer should be displayed.
  533    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  534    pub display_map: Model<DisplayMap>,
  535    pub selections: SelectionsCollection,
  536    pub scroll_manager: ScrollManager,
  537    /// When inline assist editors are linked, they all render cursors because
  538    /// typing enters text into each of them, even the ones that aren't focused.
  539    pub(crate) show_cursor_when_unfocused: bool,
  540    columnar_selection_tail: Option<Anchor>,
  541    add_selections_state: Option<AddSelectionsState>,
  542    select_next_state: Option<SelectNextState>,
  543    select_prev_state: Option<SelectNextState>,
  544    selection_history: SelectionHistory,
  545    autoclose_regions: Vec<AutocloseRegion>,
  546    snippet_stack: InvalidationStack<SnippetState>,
  547    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  548    ime_transaction: Option<TransactionId>,
  549    active_diagnostics: Option<ActiveDiagnosticGroup>,
  550    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  551    project: Option<Model<Project>>,
  552    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  553    completion_provider: Option<Box<dyn CompletionProvider>>,
  554    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  555    blink_manager: Model<BlinkManager>,
  556    show_cursor_names: bool,
  557    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  558    pub show_local_selections: bool,
  559    mode: EditorMode,
  560    show_breadcrumbs: bool,
  561    show_gutter: bool,
  562    show_line_numbers: Option<bool>,
  563    use_relative_line_numbers: Option<bool>,
  564    show_git_diff_gutter: Option<bool>,
  565    show_code_actions: Option<bool>,
  566    show_runnables: Option<bool>,
  567    show_wrap_guides: Option<bool>,
  568    show_indent_guides: Option<bool>,
  569    placeholder_text: Option<Arc<str>>,
  570    highlight_order: usize,
  571    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  572    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  573    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  574    scrollbar_marker_state: ScrollbarMarkerState,
  575    active_indent_guides_state: ActiveIndentGuidesState,
  576    nav_history: Option<ItemNavHistory>,
  577    context_menu: RwLock<Option<ContextMenu>>,
  578    mouse_context_menu: Option<MouseContextMenu>,
  579    hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
  580    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  581    signature_help_state: SignatureHelpState,
  582    auto_signature_help: Option<bool>,
  583    find_all_references_task_sources: Vec<Anchor>,
  584    next_completion_id: CompletionId,
  585    completion_documentation_pre_resolve_debounce: DebouncedDelay,
  586    available_code_actions: Option<(Location, Arc<[AvailableCodeAction]>)>,
  587    code_actions_task: Option<Task<Result<()>>>,
  588    document_highlights_task: Option<Task<()>>,
  589    linked_editing_range_task: Option<Task<Option<()>>>,
  590    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  591    pending_rename: Option<RenameState>,
  592    searchable: bool,
  593    cursor_shape: CursorShape,
  594    current_line_highlight: Option<CurrentLineHighlight>,
  595    collapse_matches: bool,
  596    autoindent_mode: Option<AutoindentMode>,
  597    workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
  598    input_enabled: bool,
  599    use_modal_editing: bool,
  600    read_only: bool,
  601    leader_peer_id: Option<PeerId>,
  602    remote_id: Option<ViewId>,
  603    hover_state: HoverState,
  604    gutter_hovered: bool,
  605    hovered_link_state: Option<HoveredLinkState>,
  606    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  607    code_action_providers: Vec<Arc<dyn CodeActionProvider>>,
  608    active_inline_completion: Option<CompletionState>,
  609    // enable_inline_completions is a switch that Vim can use to disable
  610    // inline completions based on its mode.
  611    enable_inline_completions: bool,
  612    show_inline_completions_override: Option<bool>,
  613    inlay_hint_cache: InlayHintCache,
  614    expanded_hunks: ExpandedHunks,
  615    next_inlay_id: usize,
  616    _subscriptions: Vec<Subscription>,
  617    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  618    gutter_dimensions: GutterDimensions,
  619    style: Option<EditorStyle>,
  620    next_editor_action_id: EditorActionId,
  621    editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
  622    use_autoclose: bool,
  623    use_auto_surround: bool,
  624    auto_replace_emoji_shortcode: bool,
  625    show_git_blame_gutter: bool,
  626    show_git_blame_inline: bool,
  627    show_git_blame_inline_delay_task: Option<Task<()>>,
  628    git_blame_inline_enabled: bool,
  629    serialize_dirty_buffers: bool,
  630    show_selection_menu: Option<bool>,
  631    blame: Option<Model<GitBlame>>,
  632    blame_subscription: Option<Subscription>,
  633    custom_context_menu: Option<
  634        Box<
  635            dyn 'static
  636                + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
  637        >,
  638    >,
  639    last_bounds: Option<Bounds<Pixels>>,
  640    expect_bounds_change: Option<Bounds<Pixels>>,
  641    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  642    tasks_update_task: Option<Task<()>>,
  643    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  644    file_header_size: u32,
  645    breadcrumb_header: Option<String>,
  646    focused_block: Option<FocusedBlock>,
  647    next_scroll_position: NextScrollCursorCenterTopBottom,
  648    addons: HashMap<TypeId, Box<dyn Addon>>,
  649    _scroll_cursor_center_top_bottom_task: Task<()>,
  650}
  651
  652#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  653enum NextScrollCursorCenterTopBottom {
  654    #[default]
  655    Center,
  656    Top,
  657    Bottom,
  658}
  659
  660impl NextScrollCursorCenterTopBottom {
  661    fn next(&self) -> Self {
  662        match self {
  663            Self::Center => Self::Top,
  664            Self::Top => Self::Bottom,
  665            Self::Bottom => Self::Center,
  666        }
  667    }
  668}
  669
  670#[derive(Clone)]
  671pub struct EditorSnapshot {
  672    pub mode: EditorMode,
  673    show_gutter: bool,
  674    show_line_numbers: Option<bool>,
  675    show_git_diff_gutter: Option<bool>,
  676    show_code_actions: Option<bool>,
  677    show_runnables: Option<bool>,
  678    git_blame_gutter_max_author_length: Option<usize>,
  679    pub display_snapshot: DisplaySnapshot,
  680    pub placeholder_text: Option<Arc<str>>,
  681    is_focused: bool,
  682    scroll_anchor: ScrollAnchor,
  683    ongoing_scroll: OngoingScroll,
  684    current_line_highlight: CurrentLineHighlight,
  685    gutter_hovered: bool,
  686}
  687
  688const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  689
  690#[derive(Default, Debug, Clone, Copy)]
  691pub struct GutterDimensions {
  692    pub left_padding: Pixels,
  693    pub right_padding: Pixels,
  694    pub width: Pixels,
  695    pub margin: Pixels,
  696    pub git_blame_entries_width: Option<Pixels>,
  697}
  698
  699impl GutterDimensions {
  700    /// The full width of the space taken up by the gutter.
  701    pub fn full_width(&self) -> Pixels {
  702        self.margin + self.width
  703    }
  704
  705    /// The width of the space reserved for the fold indicators,
  706    /// use alongside 'justify_end' and `gutter_width` to
  707    /// right align content with the line numbers
  708    pub fn fold_area_width(&self) -> Pixels {
  709        self.margin + self.right_padding
  710    }
  711}
  712
  713#[derive(Debug)]
  714pub struct RemoteSelection {
  715    pub replica_id: ReplicaId,
  716    pub selection: Selection<Anchor>,
  717    pub cursor_shape: CursorShape,
  718    pub peer_id: PeerId,
  719    pub line_mode: bool,
  720    pub participant_index: Option<ParticipantIndex>,
  721    pub user_name: Option<SharedString>,
  722}
  723
  724#[derive(Clone, Debug)]
  725struct SelectionHistoryEntry {
  726    selections: Arc<[Selection<Anchor>]>,
  727    select_next_state: Option<SelectNextState>,
  728    select_prev_state: Option<SelectNextState>,
  729    add_selections_state: Option<AddSelectionsState>,
  730}
  731
  732enum SelectionHistoryMode {
  733    Normal,
  734    Undoing,
  735    Redoing,
  736}
  737
  738#[derive(Clone, PartialEq, Eq, Hash)]
  739struct HoveredCursor {
  740    replica_id: u16,
  741    selection_id: usize,
  742}
  743
  744impl Default for SelectionHistoryMode {
  745    fn default() -> Self {
  746        Self::Normal
  747    }
  748}
  749
  750#[derive(Default)]
  751struct SelectionHistory {
  752    #[allow(clippy::type_complexity)]
  753    selections_by_transaction:
  754        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  755    mode: SelectionHistoryMode,
  756    undo_stack: VecDeque<SelectionHistoryEntry>,
  757    redo_stack: VecDeque<SelectionHistoryEntry>,
  758}
  759
  760impl SelectionHistory {
  761    fn insert_transaction(
  762        &mut self,
  763        transaction_id: TransactionId,
  764        selections: Arc<[Selection<Anchor>]>,
  765    ) {
  766        self.selections_by_transaction
  767            .insert(transaction_id, (selections, None));
  768    }
  769
  770    #[allow(clippy::type_complexity)]
  771    fn transaction(
  772        &self,
  773        transaction_id: TransactionId,
  774    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  775        self.selections_by_transaction.get(&transaction_id)
  776    }
  777
  778    #[allow(clippy::type_complexity)]
  779    fn transaction_mut(
  780        &mut self,
  781        transaction_id: TransactionId,
  782    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  783        self.selections_by_transaction.get_mut(&transaction_id)
  784    }
  785
  786    fn push(&mut self, entry: SelectionHistoryEntry) {
  787        if !entry.selections.is_empty() {
  788            match self.mode {
  789                SelectionHistoryMode::Normal => {
  790                    self.push_undo(entry);
  791                    self.redo_stack.clear();
  792                }
  793                SelectionHistoryMode::Undoing => self.push_redo(entry),
  794                SelectionHistoryMode::Redoing => self.push_undo(entry),
  795            }
  796        }
  797    }
  798
  799    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  800        if self
  801            .undo_stack
  802            .back()
  803            .map_or(true, |e| e.selections != entry.selections)
  804        {
  805            self.undo_stack.push_back(entry);
  806            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  807                self.undo_stack.pop_front();
  808            }
  809        }
  810    }
  811
  812    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  813        if self
  814            .redo_stack
  815            .back()
  816            .map_or(true, |e| e.selections != entry.selections)
  817        {
  818            self.redo_stack.push_back(entry);
  819            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  820                self.redo_stack.pop_front();
  821            }
  822        }
  823    }
  824}
  825
  826struct RowHighlight {
  827    index: usize,
  828    range: Range<Anchor>,
  829    color: Hsla,
  830    should_autoscroll: bool,
  831}
  832
  833#[derive(Clone, Debug)]
  834struct AddSelectionsState {
  835    above: bool,
  836    stack: Vec<usize>,
  837}
  838
  839#[derive(Clone)]
  840struct SelectNextState {
  841    query: AhoCorasick,
  842    wordwise: bool,
  843    done: bool,
  844}
  845
  846impl std::fmt::Debug for SelectNextState {
  847    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  848        f.debug_struct(std::any::type_name::<Self>())
  849            .field("wordwise", &self.wordwise)
  850            .field("done", &self.done)
  851            .finish()
  852    }
  853}
  854
  855#[derive(Debug)]
  856struct AutocloseRegion {
  857    selection_id: usize,
  858    range: Range<Anchor>,
  859    pair: BracketPair,
  860}
  861
  862#[derive(Debug)]
  863struct SnippetState {
  864    ranges: Vec<Vec<Range<Anchor>>>,
  865    active_index: usize,
  866}
  867
  868#[doc(hidden)]
  869pub struct RenameState {
  870    pub range: Range<Anchor>,
  871    pub old_name: Arc<str>,
  872    pub editor: View<Editor>,
  873    block_id: CustomBlockId,
  874}
  875
  876struct InvalidationStack<T>(Vec<T>);
  877
  878struct RegisteredInlineCompletionProvider {
  879    provider: Arc<dyn InlineCompletionProviderHandle>,
  880    _subscription: Subscription,
  881}
  882
  883enum ContextMenu {
  884    Completions(CompletionsMenu),
  885    CodeActions(CodeActionsMenu),
  886}
  887
  888impl ContextMenu {
  889    fn select_first(
  890        &mut self,
  891        provider: Option<&dyn CompletionProvider>,
  892        cx: &mut ViewContext<Editor>,
  893    ) -> bool {
  894        if self.visible() {
  895            match self {
  896                ContextMenu::Completions(menu) => menu.select_first(provider, cx),
  897                ContextMenu::CodeActions(menu) => menu.select_first(cx),
  898            }
  899            true
  900        } else {
  901            false
  902        }
  903    }
  904
  905    fn select_prev(
  906        &mut self,
  907        provider: Option<&dyn CompletionProvider>,
  908        cx: &mut ViewContext<Editor>,
  909    ) -> bool {
  910        if self.visible() {
  911            match self {
  912                ContextMenu::Completions(menu) => menu.select_prev(provider, cx),
  913                ContextMenu::CodeActions(menu) => menu.select_prev(cx),
  914            }
  915            true
  916        } else {
  917            false
  918        }
  919    }
  920
  921    fn select_next(
  922        &mut self,
  923        provider: Option<&dyn CompletionProvider>,
  924        cx: &mut ViewContext<Editor>,
  925    ) -> bool {
  926        if self.visible() {
  927            match self {
  928                ContextMenu::Completions(menu) => menu.select_next(provider, cx),
  929                ContextMenu::CodeActions(menu) => menu.select_next(cx),
  930            }
  931            true
  932        } else {
  933            false
  934        }
  935    }
  936
  937    fn select_last(
  938        &mut self,
  939        provider: Option<&dyn CompletionProvider>,
  940        cx: &mut ViewContext<Editor>,
  941    ) -> bool {
  942        if self.visible() {
  943            match self {
  944                ContextMenu::Completions(menu) => menu.select_last(provider, cx),
  945                ContextMenu::CodeActions(menu) => menu.select_last(cx),
  946            }
  947            true
  948        } else {
  949            false
  950        }
  951    }
  952
  953    fn visible(&self) -> bool {
  954        match self {
  955            ContextMenu::Completions(menu) => menu.visible(),
  956            ContextMenu::CodeActions(menu) => menu.visible(),
  957        }
  958    }
  959
  960    fn render(
  961        &self,
  962        cursor_position: DisplayPoint,
  963        style: &EditorStyle,
  964        max_height: Pixels,
  965        workspace: Option<WeakView<Workspace>>,
  966        cx: &mut ViewContext<Editor>,
  967    ) -> (ContextMenuOrigin, AnyElement) {
  968        match self {
  969            ContextMenu::Completions(menu) => (
  970                ContextMenuOrigin::EditorPoint(cursor_position),
  971                menu.render(style, max_height, workspace, cx),
  972            ),
  973            ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
  974        }
  975    }
  976}
  977
  978enum ContextMenuOrigin {
  979    EditorPoint(DisplayPoint),
  980    GutterIndicator(DisplayRow),
  981}
  982
  983#[derive(Clone)]
  984struct CompletionsMenu {
  985    id: CompletionId,
  986    sort_completions: bool,
  987    initial_position: Anchor,
  988    buffer: Model<Buffer>,
  989    completions: Arc<RwLock<Box<[Completion]>>>,
  990    match_candidates: Arc<[StringMatchCandidate]>,
  991    matches: Arc<[StringMatch]>,
  992    selected_item: usize,
  993    scroll_handle: UniformListScrollHandle,
  994    selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
  995}
  996
  997impl CompletionsMenu {
  998    fn select_first(
  999        &mut self,
 1000        provider: Option<&dyn CompletionProvider>,
 1001        cx: &mut ViewContext<Editor>,
 1002    ) {
 1003        self.selected_item = 0;
 1004        self.scroll_handle.scroll_to_item(self.selected_item);
 1005        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1006        cx.notify();
 1007    }
 1008
 1009    fn select_prev(
 1010        &mut self,
 1011        provider: Option<&dyn CompletionProvider>,
 1012        cx: &mut ViewContext<Editor>,
 1013    ) {
 1014        if self.selected_item > 0 {
 1015            self.selected_item -= 1;
 1016        } else {
 1017            self.selected_item = self.matches.len() - 1;
 1018        }
 1019        self.scroll_handle.scroll_to_item(self.selected_item);
 1020        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1021        cx.notify();
 1022    }
 1023
 1024    fn select_next(
 1025        &mut self,
 1026        provider: Option<&dyn CompletionProvider>,
 1027        cx: &mut ViewContext<Editor>,
 1028    ) {
 1029        if self.selected_item + 1 < self.matches.len() {
 1030            self.selected_item += 1;
 1031        } else {
 1032            self.selected_item = 0;
 1033        }
 1034        self.scroll_handle.scroll_to_item(self.selected_item);
 1035        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1036        cx.notify();
 1037    }
 1038
 1039    fn select_last(
 1040        &mut self,
 1041        provider: Option<&dyn CompletionProvider>,
 1042        cx: &mut ViewContext<Editor>,
 1043    ) {
 1044        self.selected_item = self.matches.len() - 1;
 1045        self.scroll_handle.scroll_to_item(self.selected_item);
 1046        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1047        cx.notify();
 1048    }
 1049
 1050    fn pre_resolve_completion_documentation(
 1051        buffer: Model<Buffer>,
 1052        completions: Arc<RwLock<Box<[Completion]>>>,
 1053        matches: Arc<[StringMatch]>,
 1054        editor: &Editor,
 1055        cx: &mut ViewContext<Editor>,
 1056    ) -> Task<()> {
 1057        let settings = EditorSettings::get_global(cx);
 1058        if !settings.show_completion_documentation {
 1059            return Task::ready(());
 1060        }
 1061
 1062        let Some(provider) = editor.completion_provider.as_ref() else {
 1063            return Task::ready(());
 1064        };
 1065
 1066        let resolve_task = provider.resolve_completions(
 1067            buffer,
 1068            matches.iter().map(|m| m.candidate_id).collect(),
 1069            completions.clone(),
 1070            cx,
 1071        );
 1072
 1073        cx.spawn(move |this, mut cx| async move {
 1074            if let Some(true) = resolve_task.await.log_err() {
 1075                this.update(&mut cx, |_, cx| cx.notify()).ok();
 1076            }
 1077        })
 1078    }
 1079
 1080    fn attempt_resolve_selected_completion_documentation(
 1081        &mut self,
 1082        provider: Option<&dyn CompletionProvider>,
 1083        cx: &mut ViewContext<Editor>,
 1084    ) {
 1085        let settings = EditorSettings::get_global(cx);
 1086        if !settings.show_completion_documentation {
 1087            return;
 1088        }
 1089
 1090        let completion_index = self.matches[self.selected_item].candidate_id;
 1091        let Some(provider) = provider else {
 1092            return;
 1093        };
 1094
 1095        let resolve_task = provider.resolve_completions(
 1096            self.buffer.clone(),
 1097            vec![completion_index],
 1098            self.completions.clone(),
 1099            cx,
 1100        );
 1101
 1102        let delay_ms =
 1103            EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
 1104        let delay = Duration::from_millis(delay_ms);
 1105
 1106        self.selected_completion_documentation_resolve_debounce
 1107            .lock()
 1108            .fire_new(delay, cx, |_, cx| {
 1109                cx.spawn(move |this, mut cx| async move {
 1110                    if let Some(true) = resolve_task.await.log_err() {
 1111                        this.update(&mut cx, |_, cx| cx.notify()).ok();
 1112                    }
 1113                })
 1114            });
 1115    }
 1116
 1117    fn visible(&self) -> bool {
 1118        !self.matches.is_empty()
 1119    }
 1120
 1121    fn render(
 1122        &self,
 1123        style: &EditorStyle,
 1124        max_height: Pixels,
 1125        workspace: Option<WeakView<Workspace>>,
 1126        cx: &mut ViewContext<Editor>,
 1127    ) -> AnyElement {
 1128        let settings = EditorSettings::get_global(cx);
 1129        let show_completion_documentation = settings.show_completion_documentation;
 1130
 1131        let widest_completion_ix = self
 1132            .matches
 1133            .iter()
 1134            .enumerate()
 1135            .max_by_key(|(_, mat)| {
 1136                let completions = self.completions.read();
 1137                let completion = &completions[mat.candidate_id];
 1138                let documentation = &completion.documentation;
 1139
 1140                let mut len = completion.label.text.chars().count();
 1141                if let Some(Documentation::SingleLine(text)) = documentation {
 1142                    if show_completion_documentation {
 1143                        len += text.chars().count();
 1144                    }
 1145                }
 1146
 1147                len
 1148            })
 1149            .map(|(ix, _)| ix);
 1150
 1151        let completions = self.completions.clone();
 1152        let matches = self.matches.clone();
 1153        let selected_item = self.selected_item;
 1154        let style = style.clone();
 1155
 1156        let multiline_docs = if show_completion_documentation {
 1157            let mat = &self.matches[selected_item];
 1158            let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
 1159                Some(Documentation::MultiLinePlainText(text)) => {
 1160                    Some(div().child(SharedString::from(text.clone())))
 1161                }
 1162                Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
 1163                    Some(div().child(render_parsed_markdown(
 1164                        "completions_markdown",
 1165                        parsed,
 1166                        &style,
 1167                        workspace,
 1168                        cx,
 1169                    )))
 1170                }
 1171                _ => None,
 1172            };
 1173            multiline_docs.map(|div| {
 1174                div.id("multiline_docs")
 1175                    .max_h(max_height)
 1176                    .flex_1()
 1177                    .px_1p5()
 1178                    .py_1()
 1179                    .min_w(px(260.))
 1180                    .max_w(px(640.))
 1181                    .w(px(500.))
 1182                    .overflow_y_scroll()
 1183                    .occlude()
 1184            })
 1185        } else {
 1186            None
 1187        };
 1188
 1189        let list = uniform_list(
 1190            cx.view().clone(),
 1191            "completions",
 1192            matches.len(),
 1193            move |_editor, range, cx| {
 1194                let start_ix = range.start;
 1195                let completions_guard = completions.read();
 1196
 1197                matches[range]
 1198                    .iter()
 1199                    .enumerate()
 1200                    .map(|(ix, mat)| {
 1201                        let item_ix = start_ix + ix;
 1202                        let candidate_id = mat.candidate_id;
 1203                        let completion = &completions_guard[candidate_id];
 1204
 1205                        let documentation = if show_completion_documentation {
 1206                            &completion.documentation
 1207                        } else {
 1208                            &None
 1209                        };
 1210
 1211                        let highlights = gpui::combine_highlights(
 1212                            mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
 1213                            styled_runs_for_code_label(&completion.label, &style.syntax).map(
 1214                                |(range, mut highlight)| {
 1215                                    // Ignore font weight for syntax highlighting, as we'll use it
 1216                                    // for fuzzy matches.
 1217                                    highlight.font_weight = None;
 1218
 1219                                    if completion.lsp_completion.deprecated.unwrap_or(false) {
 1220                                        highlight.strikethrough = Some(StrikethroughStyle {
 1221                                            thickness: 1.0.into(),
 1222                                            ..Default::default()
 1223                                        });
 1224                                        highlight.color = Some(cx.theme().colors().text_muted);
 1225                                    }
 1226
 1227                                    (range, highlight)
 1228                                },
 1229                            ),
 1230                        );
 1231                        let completion_label = StyledText::new(completion.label.text.clone())
 1232                            .with_highlights(&style.text, highlights);
 1233                        let documentation_label =
 1234                            if let Some(Documentation::SingleLine(text)) = documentation {
 1235                                if text.trim().is_empty() {
 1236                                    None
 1237                                } else {
 1238                                    Some(
 1239                                        Label::new(text.clone())
 1240                                            .ml_4()
 1241                                            .size(LabelSize::Small)
 1242                                            .color(Color::Muted),
 1243                                    )
 1244                                }
 1245                            } else {
 1246                                None
 1247                            };
 1248
 1249                        let color_swatch = completion
 1250                            .color()
 1251                            .map(|color| div().size_4().bg(color).rounded_sm());
 1252
 1253                        div().min_w(px(220.)).max_w(px(540.)).child(
 1254                            ListItem::new(mat.candidate_id)
 1255                                .inset(true)
 1256                                .selected(item_ix == selected_item)
 1257                                .on_click(cx.listener(move |editor, _event, cx| {
 1258                                    cx.stop_propagation();
 1259                                    if let Some(task) = editor.confirm_completion(
 1260                                        &ConfirmCompletion {
 1261                                            item_ix: Some(item_ix),
 1262                                        },
 1263                                        cx,
 1264                                    ) {
 1265                                        task.detach_and_log_err(cx)
 1266                                    }
 1267                                }))
 1268                                .start_slot::<Div>(color_swatch)
 1269                                .child(h_flex().overflow_hidden().child(completion_label))
 1270                                .end_slot::<Label>(documentation_label),
 1271                        )
 1272                    })
 1273                    .collect()
 1274            },
 1275        )
 1276        .occlude()
 1277        .max_h(max_height)
 1278        .track_scroll(self.scroll_handle.clone())
 1279        .with_width_from_item(widest_completion_ix)
 1280        .with_sizing_behavior(ListSizingBehavior::Infer);
 1281
 1282        Popover::new()
 1283            .child(list)
 1284            .when_some(multiline_docs, |popover, multiline_docs| {
 1285                popover.aside(multiline_docs)
 1286            })
 1287            .into_any_element()
 1288    }
 1289
 1290    pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
 1291        let mut matches = if let Some(query) = query {
 1292            fuzzy::match_strings(
 1293                &self.match_candidates,
 1294                query,
 1295                query.chars().any(|c| c.is_uppercase()),
 1296                100,
 1297                &Default::default(),
 1298                executor,
 1299            )
 1300            .await
 1301        } else {
 1302            self.match_candidates
 1303                .iter()
 1304                .enumerate()
 1305                .map(|(candidate_id, candidate)| StringMatch {
 1306                    candidate_id,
 1307                    score: Default::default(),
 1308                    positions: Default::default(),
 1309                    string: candidate.string.clone(),
 1310                })
 1311                .collect()
 1312        };
 1313
 1314        // Remove all candidates where the query's start does not match the start of any word in the candidate
 1315        if let Some(query) = query {
 1316            if let Some(query_start) = query.chars().next() {
 1317                matches.retain(|string_match| {
 1318                    split_words(&string_match.string).any(|word| {
 1319                        // Check that the first codepoint of the word as lowercase matches the first
 1320                        // codepoint of the query as lowercase
 1321                        word.chars()
 1322                            .flat_map(|codepoint| codepoint.to_lowercase())
 1323                            .zip(query_start.to_lowercase())
 1324                            .all(|(word_cp, query_cp)| word_cp == query_cp)
 1325                    })
 1326                });
 1327            }
 1328        }
 1329
 1330        let completions = self.completions.read();
 1331        if self.sort_completions {
 1332            matches.sort_unstable_by_key(|mat| {
 1333                // We do want to strike a balance here between what the language server tells us
 1334                // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
 1335                // `Creat` and there is a local variable called `CreateComponent`).
 1336                // So what we do is: we bucket all matches into two buckets
 1337                // - Strong matches
 1338                // - Weak matches
 1339                // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
 1340                // and the Weak matches are the rest.
 1341                //
 1342                // For the strong matches, we sort by the language-servers score first and for the weak
 1343                // matches, we prefer our fuzzy finder first.
 1344                //
 1345                // The thinking behind that: it's useless to take the sort_text the language-server gives
 1346                // us into account when it's obviously a bad match.
 1347
 1348                #[derive(PartialEq, Eq, PartialOrd, Ord)]
 1349                enum MatchScore<'a> {
 1350                    Strong {
 1351                        sort_text: Option<&'a str>,
 1352                        score: Reverse<OrderedFloat<f64>>,
 1353                        sort_key: (usize, &'a str),
 1354                    },
 1355                    Weak {
 1356                        score: Reverse<OrderedFloat<f64>>,
 1357                        sort_text: Option<&'a str>,
 1358                        sort_key: (usize, &'a str),
 1359                    },
 1360                }
 1361
 1362                let completion = &completions[mat.candidate_id];
 1363                let sort_key = completion.sort_key();
 1364                let sort_text = completion.lsp_completion.sort_text.as_deref();
 1365                let score = Reverse(OrderedFloat(mat.score));
 1366
 1367                if mat.score >= 0.2 {
 1368                    MatchScore::Strong {
 1369                        sort_text,
 1370                        score,
 1371                        sort_key,
 1372                    }
 1373                } else {
 1374                    MatchScore::Weak {
 1375                        score,
 1376                        sort_text,
 1377                        sort_key,
 1378                    }
 1379                }
 1380            });
 1381        }
 1382
 1383        for mat in &mut matches {
 1384            let completion = &completions[mat.candidate_id];
 1385            mat.string.clone_from(&completion.label.text);
 1386            for position in &mut mat.positions {
 1387                *position += completion.label.filter_range.start;
 1388            }
 1389        }
 1390        drop(completions);
 1391
 1392        self.matches = matches.into();
 1393        self.selected_item = 0;
 1394    }
 1395}
 1396
 1397struct AvailableCodeAction {
 1398    excerpt_id: ExcerptId,
 1399    action: CodeAction,
 1400    provider: Arc<dyn CodeActionProvider>,
 1401}
 1402
 1403#[derive(Clone)]
 1404struct CodeActionContents {
 1405    tasks: Option<Arc<ResolvedTasks>>,
 1406    actions: Option<Arc<[AvailableCodeAction]>>,
 1407}
 1408
 1409impl CodeActionContents {
 1410    fn len(&self) -> usize {
 1411        match (&self.tasks, &self.actions) {
 1412            (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
 1413            (Some(tasks), None) => tasks.templates.len(),
 1414            (None, Some(actions)) => actions.len(),
 1415            (None, None) => 0,
 1416        }
 1417    }
 1418
 1419    fn is_empty(&self) -> bool {
 1420        match (&self.tasks, &self.actions) {
 1421            (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
 1422            (Some(tasks), None) => tasks.templates.is_empty(),
 1423            (None, Some(actions)) => actions.is_empty(),
 1424            (None, None) => true,
 1425        }
 1426    }
 1427
 1428    fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
 1429        self.tasks
 1430            .iter()
 1431            .flat_map(|tasks| {
 1432                tasks
 1433                    .templates
 1434                    .iter()
 1435                    .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
 1436            })
 1437            .chain(self.actions.iter().flat_map(|actions| {
 1438                actions.iter().map(|available| CodeActionsItem::CodeAction {
 1439                    excerpt_id: available.excerpt_id,
 1440                    action: available.action.clone(),
 1441                    provider: available.provider.clone(),
 1442                })
 1443            }))
 1444    }
 1445    fn get(&self, index: usize) -> Option<CodeActionsItem> {
 1446        match (&self.tasks, &self.actions) {
 1447            (Some(tasks), Some(actions)) => {
 1448                if index < tasks.templates.len() {
 1449                    tasks
 1450                        .templates
 1451                        .get(index)
 1452                        .cloned()
 1453                        .map(|(kind, task)| CodeActionsItem::Task(kind, task))
 1454                } else {
 1455                    actions.get(index - tasks.templates.len()).map(|available| {
 1456                        CodeActionsItem::CodeAction {
 1457                            excerpt_id: available.excerpt_id,
 1458                            action: available.action.clone(),
 1459                            provider: available.provider.clone(),
 1460                        }
 1461                    })
 1462                }
 1463            }
 1464            (Some(tasks), None) => tasks
 1465                .templates
 1466                .get(index)
 1467                .cloned()
 1468                .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
 1469            (None, Some(actions)) => {
 1470                actions
 1471                    .get(index)
 1472                    .map(|available| CodeActionsItem::CodeAction {
 1473                        excerpt_id: available.excerpt_id,
 1474                        action: available.action.clone(),
 1475                        provider: available.provider.clone(),
 1476                    })
 1477            }
 1478            (None, None) => None,
 1479        }
 1480    }
 1481}
 1482
 1483#[allow(clippy::large_enum_variant)]
 1484#[derive(Clone)]
 1485enum CodeActionsItem {
 1486    Task(TaskSourceKind, ResolvedTask),
 1487    CodeAction {
 1488        excerpt_id: ExcerptId,
 1489        action: CodeAction,
 1490        provider: Arc<dyn CodeActionProvider>,
 1491    },
 1492}
 1493
 1494impl CodeActionsItem {
 1495    fn as_task(&self) -> Option<&ResolvedTask> {
 1496        let Self::Task(_, task) = self else {
 1497            return None;
 1498        };
 1499        Some(task)
 1500    }
 1501    fn as_code_action(&self) -> Option<&CodeAction> {
 1502        let Self::CodeAction { action, .. } = self else {
 1503            return None;
 1504        };
 1505        Some(action)
 1506    }
 1507    fn label(&self) -> String {
 1508        match self {
 1509            Self::CodeAction { action, .. } => action.lsp_action.title.clone(),
 1510            Self::Task(_, task) => task.resolved_label.clone(),
 1511        }
 1512    }
 1513}
 1514
 1515struct CodeActionsMenu {
 1516    actions: CodeActionContents,
 1517    buffer: Model<Buffer>,
 1518    selected_item: usize,
 1519    scroll_handle: UniformListScrollHandle,
 1520    deployed_from_indicator: Option<DisplayRow>,
 1521}
 1522
 1523impl CodeActionsMenu {
 1524    fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
 1525        self.selected_item = 0;
 1526        self.scroll_handle.scroll_to_item(self.selected_item);
 1527        cx.notify()
 1528    }
 1529
 1530    fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
 1531        if self.selected_item > 0 {
 1532            self.selected_item -= 1;
 1533        } else {
 1534            self.selected_item = self.actions.len() - 1;
 1535        }
 1536        self.scroll_handle.scroll_to_item(self.selected_item);
 1537        cx.notify();
 1538    }
 1539
 1540    fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
 1541        if self.selected_item + 1 < self.actions.len() {
 1542            self.selected_item += 1;
 1543        } else {
 1544            self.selected_item = 0;
 1545        }
 1546        self.scroll_handle.scroll_to_item(self.selected_item);
 1547        cx.notify();
 1548    }
 1549
 1550    fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
 1551        self.selected_item = self.actions.len() - 1;
 1552        self.scroll_handle.scroll_to_item(self.selected_item);
 1553        cx.notify()
 1554    }
 1555
 1556    fn visible(&self) -> bool {
 1557        !self.actions.is_empty()
 1558    }
 1559
 1560    fn render(
 1561        &self,
 1562        cursor_position: DisplayPoint,
 1563        _style: &EditorStyle,
 1564        max_height: Pixels,
 1565        cx: &mut ViewContext<Editor>,
 1566    ) -> (ContextMenuOrigin, AnyElement) {
 1567        let actions = self.actions.clone();
 1568        let selected_item = self.selected_item;
 1569        let element = uniform_list(
 1570            cx.view().clone(),
 1571            "code_actions_menu",
 1572            self.actions.len(),
 1573            move |_this, range, cx| {
 1574                actions
 1575                    .iter()
 1576                    .skip(range.start)
 1577                    .take(range.end - range.start)
 1578                    .enumerate()
 1579                    .map(|(ix, action)| {
 1580                        let item_ix = range.start + ix;
 1581                        let selected = selected_item == item_ix;
 1582                        let colors = cx.theme().colors();
 1583                        div()
 1584                            .px_1()
 1585                            .rounded_md()
 1586                            .text_color(colors.text)
 1587                            .when(selected, |style| {
 1588                                style
 1589                                    .bg(colors.element_active)
 1590                                    .text_color(colors.text_accent)
 1591                            })
 1592                            .hover(|style| {
 1593                                style
 1594                                    .bg(colors.element_hover)
 1595                                    .text_color(colors.text_accent)
 1596                            })
 1597                            .whitespace_nowrap()
 1598                            .when_some(action.as_code_action(), |this, action| {
 1599                                this.on_mouse_down(
 1600                                    MouseButton::Left,
 1601                                    cx.listener(move |editor, _, cx| {
 1602                                        cx.stop_propagation();
 1603                                        if let Some(task) = editor.confirm_code_action(
 1604                                            &ConfirmCodeAction {
 1605                                                item_ix: Some(item_ix),
 1606                                            },
 1607                                            cx,
 1608                                        ) {
 1609                                            task.detach_and_log_err(cx)
 1610                                        }
 1611                                    }),
 1612                                )
 1613                                // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
 1614                                .child(SharedString::from(action.lsp_action.title.clone()))
 1615                            })
 1616                            .when_some(action.as_task(), |this, task| {
 1617                                this.on_mouse_down(
 1618                                    MouseButton::Left,
 1619                                    cx.listener(move |editor, _, cx| {
 1620                                        cx.stop_propagation();
 1621                                        if let Some(task) = editor.confirm_code_action(
 1622                                            &ConfirmCodeAction {
 1623                                                item_ix: Some(item_ix),
 1624                                            },
 1625                                            cx,
 1626                                        ) {
 1627                                            task.detach_and_log_err(cx)
 1628                                        }
 1629                                    }),
 1630                                )
 1631                                .child(SharedString::from(task.resolved_label.clone()))
 1632                            })
 1633                    })
 1634                    .collect()
 1635            },
 1636        )
 1637        .elevation_1(cx)
 1638        .p_1()
 1639        .max_h(max_height)
 1640        .occlude()
 1641        .track_scroll(self.scroll_handle.clone())
 1642        .with_width_from_item(
 1643            self.actions
 1644                .iter()
 1645                .enumerate()
 1646                .max_by_key(|(_, action)| match action {
 1647                    CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
 1648                    CodeActionsItem::CodeAction { action, .. } => {
 1649                        action.lsp_action.title.chars().count()
 1650                    }
 1651                })
 1652                .map(|(ix, _)| ix),
 1653        )
 1654        .with_sizing_behavior(ListSizingBehavior::Infer)
 1655        .into_any_element();
 1656
 1657        let cursor_position = if let Some(row) = self.deployed_from_indicator {
 1658            ContextMenuOrigin::GutterIndicator(row)
 1659        } else {
 1660            ContextMenuOrigin::EditorPoint(cursor_position)
 1661        };
 1662
 1663        (cursor_position, element)
 1664    }
 1665}
 1666
 1667#[derive(Debug)]
 1668struct ActiveDiagnosticGroup {
 1669    primary_range: Range<Anchor>,
 1670    primary_message: String,
 1671    group_id: usize,
 1672    blocks: HashMap<CustomBlockId, Diagnostic>,
 1673    is_valid: bool,
 1674}
 1675
 1676#[derive(Serialize, Deserialize, Clone, Debug)]
 1677pub struct ClipboardSelection {
 1678    pub len: usize,
 1679    pub is_entire_line: bool,
 1680    pub first_line_indent: u32,
 1681}
 1682
 1683#[derive(Debug)]
 1684pub(crate) struct NavigationData {
 1685    cursor_anchor: Anchor,
 1686    cursor_position: Point,
 1687    scroll_anchor: ScrollAnchor,
 1688    scroll_top_row: u32,
 1689}
 1690
 1691#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1692pub enum GotoDefinitionKind {
 1693    Symbol,
 1694    Declaration,
 1695    Type,
 1696    Implementation,
 1697}
 1698
 1699#[derive(Debug, Clone)]
 1700enum InlayHintRefreshReason {
 1701    Toggle(bool),
 1702    SettingsChange(InlayHintSettings),
 1703    NewLinesShown,
 1704    BufferEdited(HashSet<Arc<Language>>),
 1705    RefreshRequested,
 1706    ExcerptsRemoved(Vec<ExcerptId>),
 1707}
 1708
 1709impl InlayHintRefreshReason {
 1710    fn description(&self) -> &'static str {
 1711        match self {
 1712            Self::Toggle(_) => "toggle",
 1713            Self::SettingsChange(_) => "settings change",
 1714            Self::NewLinesShown => "new lines shown",
 1715            Self::BufferEdited(_) => "buffer edited",
 1716            Self::RefreshRequested => "refresh requested",
 1717            Self::ExcerptsRemoved(_) => "excerpts removed",
 1718        }
 1719    }
 1720}
 1721
 1722pub(crate) struct FocusedBlock {
 1723    id: BlockId,
 1724    focus_handle: WeakFocusHandle,
 1725}
 1726
 1727impl Editor {
 1728    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
 1729        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1730        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1731        Self::new(
 1732            EditorMode::SingleLine { auto_width: false },
 1733            buffer,
 1734            None,
 1735            false,
 1736            cx,
 1737        )
 1738    }
 1739
 1740    pub fn multi_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(EditorMode::Full, buffer, None, false, cx)
 1744    }
 1745
 1746    pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
 1747        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1748        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1749        Self::new(
 1750            EditorMode::SingleLine { auto_width: true },
 1751            buffer,
 1752            None,
 1753            false,
 1754            cx,
 1755        )
 1756    }
 1757
 1758    pub fn auto_height(max_lines: usize, 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::AutoHeight { max_lines },
 1763            buffer,
 1764            None,
 1765            false,
 1766            cx,
 1767        )
 1768    }
 1769
 1770    pub fn for_buffer(
 1771        buffer: Model<Buffer>,
 1772        project: Option<Model<Project>>,
 1773        cx: &mut ViewContext<Self>,
 1774    ) -> Self {
 1775        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1776        Self::new(EditorMode::Full, buffer, project, false, cx)
 1777    }
 1778
 1779    pub fn for_multibuffer(
 1780        buffer: Model<MultiBuffer>,
 1781        project: Option<Model<Project>>,
 1782        show_excerpt_controls: bool,
 1783        cx: &mut ViewContext<Self>,
 1784    ) -> Self {
 1785        Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
 1786    }
 1787
 1788    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 1789        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1790        let mut clone = Self::new(
 1791            self.mode,
 1792            self.buffer.clone(),
 1793            self.project.clone(),
 1794            show_excerpt_controls,
 1795            cx,
 1796        );
 1797        self.display_map.update(cx, |display_map, cx| {
 1798            let snapshot = display_map.snapshot(cx);
 1799            clone.display_map.update(cx, |display_map, cx| {
 1800                display_map.set_state(&snapshot, cx);
 1801            });
 1802        });
 1803        clone.selections.clone_state(&self.selections);
 1804        clone.scroll_manager.clone_state(&self.scroll_manager);
 1805        clone.searchable = self.searchable;
 1806        clone
 1807    }
 1808
 1809    pub fn new(
 1810        mode: EditorMode,
 1811        buffer: Model<MultiBuffer>,
 1812        project: Option<Model<Project>>,
 1813        show_excerpt_controls: bool,
 1814        cx: &mut ViewContext<Self>,
 1815    ) -> Self {
 1816        let style = cx.text_style();
 1817        let font_size = style.font_size.to_pixels(cx.rem_size());
 1818        let editor = cx.view().downgrade();
 1819        let fold_placeholder = FoldPlaceholder {
 1820            constrain_width: true,
 1821            render: Arc::new(move |fold_id, fold_range, cx| {
 1822                let editor = editor.clone();
 1823                div()
 1824                    .id(fold_id)
 1825                    .bg(cx.theme().colors().ghost_element_background)
 1826                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1827                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1828                    .rounded_sm()
 1829                    .size_full()
 1830                    .cursor_pointer()
 1831                    .child("")
 1832                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 1833                    .on_click(move |_, cx| {
 1834                        editor
 1835                            .update(cx, |editor, cx| {
 1836                                editor.unfold_ranges(
 1837                                    [fold_range.start..fold_range.end],
 1838                                    true,
 1839                                    false,
 1840                                    cx,
 1841                                );
 1842                                cx.stop_propagation();
 1843                            })
 1844                            .ok();
 1845                    })
 1846                    .into_any()
 1847            }),
 1848            merge_adjacent: true,
 1849        };
 1850        let file_header_size = if show_excerpt_controls { 3 } else { 2 };
 1851        let display_map = cx.new_model(|cx| {
 1852            DisplayMap::new(
 1853                buffer.clone(),
 1854                style.font(),
 1855                font_size,
 1856                None,
 1857                show_excerpt_controls,
 1858                file_header_size,
 1859                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1860                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1861                fold_placeholder,
 1862                cx,
 1863            )
 1864        });
 1865
 1866        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1867
 1868        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1869
 1870        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1871            .then(|| language_settings::SoftWrap::None);
 1872
 1873        let mut project_subscriptions = Vec::new();
 1874        if mode == EditorMode::Full {
 1875            if let Some(project) = project.as_ref() {
 1876                if buffer.read(cx).is_singleton() {
 1877                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
 1878                        cx.emit(EditorEvent::TitleChanged);
 1879                    }));
 1880                }
 1881                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
 1882                    if let project::Event::RefreshInlayHints = event {
 1883                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1884                    } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1885                        if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1886                            let focus_handle = editor.focus_handle(cx);
 1887                            if focus_handle.is_focused(cx) {
 1888                                let snapshot = buffer.read(cx).snapshot();
 1889                                for (range, snippet) in snippet_edits {
 1890                                    let editor_range =
 1891                                        language::range_from_lsp(*range).to_offset(&snapshot);
 1892                                    editor
 1893                                        .insert_snippet(&[editor_range], snippet.clone(), cx)
 1894                                        .ok();
 1895                                }
 1896                            }
 1897                        }
 1898                    }
 1899                }));
 1900                if let Some(task_inventory) = project
 1901                    .read(cx)
 1902                    .task_store()
 1903                    .read(cx)
 1904                    .task_inventory()
 1905                    .cloned()
 1906                {
 1907                    project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
 1908                        editor.tasks_update_task = Some(editor.refresh_runnables(cx));
 1909                    }));
 1910                }
 1911            }
 1912        }
 1913
 1914        let inlay_hint_settings = inlay_hint_settings(
 1915            selections.newest_anchor().head(),
 1916            &buffer.read(cx).snapshot(cx),
 1917            cx,
 1918        );
 1919        let focus_handle = cx.focus_handle();
 1920        cx.on_focus(&focus_handle, Self::handle_focus).detach();
 1921        cx.on_focus_in(&focus_handle, Self::handle_focus_in)
 1922            .detach();
 1923        cx.on_focus_out(&focus_handle, Self::handle_focus_out)
 1924            .detach();
 1925        cx.on_blur(&focus_handle, Self::handle_blur).detach();
 1926
 1927        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1928            Some(false)
 1929        } else {
 1930            None
 1931        };
 1932
 1933        let mut code_action_providers = Vec::new();
 1934        if let Some(project) = project.clone() {
 1935            code_action_providers.push(Arc::new(project) as Arc<_>);
 1936        }
 1937
 1938        let mut this = Self {
 1939            focus_handle,
 1940            show_cursor_when_unfocused: false,
 1941            last_focused_descendant: None,
 1942            buffer: buffer.clone(),
 1943            display_map: display_map.clone(),
 1944            selections,
 1945            scroll_manager: ScrollManager::new(cx),
 1946            columnar_selection_tail: None,
 1947            add_selections_state: None,
 1948            select_next_state: None,
 1949            select_prev_state: None,
 1950            selection_history: Default::default(),
 1951            autoclose_regions: Default::default(),
 1952            snippet_stack: Default::default(),
 1953            select_larger_syntax_node_stack: Vec::new(),
 1954            ime_transaction: Default::default(),
 1955            active_diagnostics: None,
 1956            soft_wrap_mode_override,
 1957            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1958            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1959            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1960            project,
 1961            blink_manager: blink_manager.clone(),
 1962            show_local_selections: true,
 1963            mode,
 1964            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1965            show_gutter: mode == EditorMode::Full,
 1966            show_line_numbers: None,
 1967            use_relative_line_numbers: None,
 1968            show_git_diff_gutter: None,
 1969            show_code_actions: None,
 1970            show_runnables: None,
 1971            show_wrap_guides: None,
 1972            show_indent_guides,
 1973            placeholder_text: None,
 1974            highlight_order: 0,
 1975            highlighted_rows: HashMap::default(),
 1976            background_highlights: Default::default(),
 1977            gutter_highlights: TreeMap::default(),
 1978            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1979            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1980            nav_history: None,
 1981            context_menu: RwLock::new(None),
 1982            mouse_context_menu: None,
 1983            hunk_controls_menu_handle: PopoverMenuHandle::default(),
 1984            completion_tasks: Default::default(),
 1985            signature_help_state: SignatureHelpState::default(),
 1986            auto_signature_help: None,
 1987            find_all_references_task_sources: Vec::new(),
 1988            next_completion_id: 0,
 1989            completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
 1990            next_inlay_id: 0,
 1991            code_action_providers,
 1992            available_code_actions: Default::default(),
 1993            code_actions_task: Default::default(),
 1994            document_highlights_task: Default::default(),
 1995            linked_editing_range_task: Default::default(),
 1996            pending_rename: Default::default(),
 1997            searchable: true,
 1998            cursor_shape: EditorSettings::get_global(cx)
 1999                .cursor_shape
 2000                .unwrap_or_default(),
 2001            current_line_highlight: None,
 2002            autoindent_mode: Some(AutoindentMode::EachLine),
 2003            collapse_matches: false,
 2004            workspace: None,
 2005            input_enabled: true,
 2006            use_modal_editing: mode == EditorMode::Full,
 2007            read_only: false,
 2008            use_autoclose: true,
 2009            use_auto_surround: true,
 2010            auto_replace_emoji_shortcode: false,
 2011            leader_peer_id: None,
 2012            remote_id: None,
 2013            hover_state: Default::default(),
 2014            hovered_link_state: Default::default(),
 2015            inline_completion_provider: None,
 2016            active_inline_completion: None,
 2017            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 2018            expanded_hunks: ExpandedHunks::default(),
 2019            gutter_hovered: false,
 2020            pixel_position_of_newest_cursor: None,
 2021            last_bounds: None,
 2022            expect_bounds_change: None,
 2023            gutter_dimensions: GutterDimensions::default(),
 2024            style: None,
 2025            show_cursor_names: false,
 2026            hovered_cursors: Default::default(),
 2027            next_editor_action_id: EditorActionId::default(),
 2028            editor_actions: Rc::default(),
 2029            show_inline_completions_override: None,
 2030            enable_inline_completions: true,
 2031            custom_context_menu: None,
 2032            show_git_blame_gutter: false,
 2033            show_git_blame_inline: false,
 2034            show_selection_menu: None,
 2035            show_git_blame_inline_delay_task: None,
 2036            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 2037            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 2038                .session
 2039                .restore_unsaved_buffers,
 2040            blame: None,
 2041            blame_subscription: None,
 2042            file_header_size,
 2043            tasks: Default::default(),
 2044            _subscriptions: vec![
 2045                cx.observe(&buffer, Self::on_buffer_changed),
 2046                cx.subscribe(&buffer, Self::on_buffer_event),
 2047                cx.observe(&display_map, Self::on_display_map_changed),
 2048                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 2049                cx.observe_global::<SettingsStore>(Self::settings_changed),
 2050                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 2051                cx.observe_window_activation(|editor, cx| {
 2052                    let active = cx.is_window_active();
 2053                    editor.blink_manager.update(cx, |blink_manager, cx| {
 2054                        if active {
 2055                            blink_manager.enable(cx);
 2056                        } else {
 2057                            blink_manager.disable(cx);
 2058                        }
 2059                    });
 2060                }),
 2061            ],
 2062            tasks_update_task: None,
 2063            linked_edit_ranges: Default::default(),
 2064            previous_search_ranges: None,
 2065            breadcrumb_header: None,
 2066            focused_block: None,
 2067            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 2068            addons: HashMap::default(),
 2069            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 2070        };
 2071        this.tasks_update_task = Some(this.refresh_runnables(cx));
 2072        this._subscriptions.extend(project_subscriptions);
 2073
 2074        this.end_selection(cx);
 2075        this.scroll_manager.show_scrollbar(cx);
 2076
 2077        if mode == EditorMode::Full {
 2078            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 2079            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 2080
 2081            if this.git_blame_inline_enabled {
 2082                this.git_blame_inline_enabled = true;
 2083                this.start_git_blame_inline(false, cx);
 2084            }
 2085        }
 2086
 2087        this.report_editor_event("open", None, cx);
 2088        this
 2089    }
 2090
 2091    pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
 2092        self.mouse_context_menu
 2093            .as_ref()
 2094            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
 2095    }
 2096
 2097    fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
 2098        let mut key_context = KeyContext::new_with_defaults();
 2099        key_context.add("Editor");
 2100        let mode = match self.mode {
 2101            EditorMode::SingleLine { .. } => "single_line",
 2102            EditorMode::AutoHeight { .. } => "auto_height",
 2103            EditorMode::Full => "full",
 2104        };
 2105
 2106        if EditorSettings::jupyter_enabled(cx) {
 2107            key_context.add("jupyter");
 2108        }
 2109
 2110        key_context.set("mode", mode);
 2111        if self.pending_rename.is_some() {
 2112            key_context.add("renaming");
 2113        }
 2114        if self.context_menu_visible() {
 2115            match self.context_menu.read().as_ref() {
 2116                Some(ContextMenu::Completions(_)) => {
 2117                    key_context.add("menu");
 2118                    key_context.add("showing_completions")
 2119                }
 2120                Some(ContextMenu::CodeActions(_)) => {
 2121                    key_context.add("menu");
 2122                    key_context.add("showing_code_actions")
 2123                }
 2124                None => {}
 2125            }
 2126        }
 2127
 2128        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 2129        if !self.focus_handle(cx).contains_focused(cx)
 2130            || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
 2131        {
 2132            for addon in self.addons.values() {
 2133                addon.extend_key_context(&mut key_context, cx)
 2134            }
 2135        }
 2136
 2137        if let Some(extension) = self
 2138            .buffer
 2139            .read(cx)
 2140            .as_singleton()
 2141            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 2142        {
 2143            key_context.set("extension", extension.to_string());
 2144        }
 2145
 2146        if self.has_active_inline_completion(cx) {
 2147            key_context.add("copilot_suggestion");
 2148            key_context.add("inline_completion");
 2149        }
 2150
 2151        key_context
 2152    }
 2153
 2154    pub fn new_file(
 2155        workspace: &mut Workspace,
 2156        _: &workspace::NewFile,
 2157        cx: &mut ViewContext<Workspace>,
 2158    ) {
 2159        Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
 2160            "Failed to create buffer",
 2161            cx,
 2162            |e, _| match e.error_code() {
 2163                ErrorCode::RemoteUpgradeRequired => Some(format!(
 2164                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2165                e.error_tag("required").unwrap_or("the latest version")
 2166            )),
 2167                _ => None,
 2168            },
 2169        );
 2170    }
 2171
 2172    pub fn new_in_workspace(
 2173        workspace: &mut Workspace,
 2174        cx: &mut ViewContext<Workspace>,
 2175    ) -> Task<Result<View<Editor>>> {
 2176        let project = workspace.project().clone();
 2177        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2178
 2179        cx.spawn(|workspace, mut cx| async move {
 2180            let buffer = create.await?;
 2181            workspace.update(&mut cx, |workspace, cx| {
 2182                let editor =
 2183                    cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
 2184                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 2185                editor
 2186            })
 2187        })
 2188    }
 2189
 2190    fn new_file_vertical(
 2191        workspace: &mut Workspace,
 2192        _: &workspace::NewFileSplitVertical,
 2193        cx: &mut ViewContext<Workspace>,
 2194    ) {
 2195        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
 2196    }
 2197
 2198    fn new_file_horizontal(
 2199        workspace: &mut Workspace,
 2200        _: &workspace::NewFileSplitHorizontal,
 2201        cx: &mut ViewContext<Workspace>,
 2202    ) {
 2203        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
 2204    }
 2205
 2206    fn new_file_in_direction(
 2207        workspace: &mut Workspace,
 2208        direction: SplitDirection,
 2209        cx: &mut ViewContext<Workspace>,
 2210    ) {
 2211        let project = workspace.project().clone();
 2212        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2213
 2214        cx.spawn(|workspace, mut cx| async move {
 2215            let buffer = create.await?;
 2216            workspace.update(&mut cx, move |workspace, cx| {
 2217                workspace.split_item(
 2218                    direction,
 2219                    Box::new(
 2220                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 2221                    ),
 2222                    cx,
 2223                )
 2224            })?;
 2225            anyhow::Ok(())
 2226        })
 2227        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 2228            ErrorCode::RemoteUpgradeRequired => Some(format!(
 2229                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2230                e.error_tag("required").unwrap_or("the latest version")
 2231            )),
 2232            _ => None,
 2233        });
 2234    }
 2235
 2236    pub fn leader_peer_id(&self) -> Option<PeerId> {
 2237        self.leader_peer_id
 2238    }
 2239
 2240    pub fn buffer(&self) -> &Model<MultiBuffer> {
 2241        &self.buffer
 2242    }
 2243
 2244    pub fn workspace(&self) -> Option<View<Workspace>> {
 2245        self.workspace.as_ref()?.0.upgrade()
 2246    }
 2247
 2248    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
 2249        self.buffer().read(cx).title(cx)
 2250    }
 2251
 2252    pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
 2253        let git_blame_gutter_max_author_length = self
 2254            .render_git_blame_gutter(cx)
 2255            .then(|| {
 2256                if let Some(blame) = self.blame.as_ref() {
 2257                    let max_author_length =
 2258                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 2259                    Some(max_author_length)
 2260                } else {
 2261                    None
 2262                }
 2263            })
 2264            .flatten();
 2265
 2266        EditorSnapshot {
 2267            mode: self.mode,
 2268            show_gutter: self.show_gutter,
 2269            show_line_numbers: self.show_line_numbers,
 2270            show_git_diff_gutter: self.show_git_diff_gutter,
 2271            show_code_actions: self.show_code_actions,
 2272            show_runnables: self.show_runnables,
 2273            git_blame_gutter_max_author_length,
 2274            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 2275            scroll_anchor: self.scroll_manager.anchor(),
 2276            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 2277            placeholder_text: self.placeholder_text.clone(),
 2278            is_focused: self.focus_handle.is_focused(cx),
 2279            current_line_highlight: self
 2280                .current_line_highlight
 2281                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 2282            gutter_hovered: self.gutter_hovered,
 2283        }
 2284    }
 2285
 2286    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
 2287        self.buffer.read(cx).language_at(point, cx)
 2288    }
 2289
 2290    pub fn file_at<T: ToOffset>(
 2291        &self,
 2292        point: T,
 2293        cx: &AppContext,
 2294    ) -> Option<Arc<dyn language::File>> {
 2295        self.buffer.read(cx).read(cx).file_at(point).cloned()
 2296    }
 2297
 2298    pub fn active_excerpt(
 2299        &self,
 2300        cx: &AppContext,
 2301    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
 2302        self.buffer
 2303            .read(cx)
 2304            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 2305    }
 2306
 2307    pub fn mode(&self) -> EditorMode {
 2308        self.mode
 2309    }
 2310
 2311    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 2312        self.collaboration_hub.as_deref()
 2313    }
 2314
 2315    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 2316        self.collaboration_hub = Some(hub);
 2317    }
 2318
 2319    pub fn set_custom_context_menu(
 2320        &mut self,
 2321        f: impl 'static
 2322            + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
 2323    ) {
 2324        self.custom_context_menu = Some(Box::new(f))
 2325    }
 2326
 2327    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 2328        self.completion_provider = provider;
 2329    }
 2330
 2331    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 2332        self.semantics_provider.clone()
 2333    }
 2334
 2335    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 2336        self.semantics_provider = provider;
 2337    }
 2338
 2339    pub fn set_inline_completion_provider<T>(
 2340        &mut self,
 2341        provider: Option<Model<T>>,
 2342        cx: &mut ViewContext<Self>,
 2343    ) where
 2344        T: InlineCompletionProvider,
 2345    {
 2346        self.inline_completion_provider =
 2347            provider.map(|provider| RegisteredInlineCompletionProvider {
 2348                _subscription: cx.observe(&provider, |this, _, cx| {
 2349                    if this.focus_handle.is_focused(cx) {
 2350                        this.update_visible_inline_completion(cx);
 2351                    }
 2352                }),
 2353                provider: Arc::new(provider),
 2354            });
 2355        self.refresh_inline_completion(false, false, cx);
 2356    }
 2357
 2358    pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
 2359        self.placeholder_text.as_deref()
 2360    }
 2361
 2362    pub fn set_placeholder_text(
 2363        &mut self,
 2364        placeholder_text: impl Into<Arc<str>>,
 2365        cx: &mut ViewContext<Self>,
 2366    ) {
 2367        let placeholder_text = Some(placeholder_text.into());
 2368        if self.placeholder_text != placeholder_text {
 2369            self.placeholder_text = placeholder_text;
 2370            cx.notify();
 2371        }
 2372    }
 2373
 2374    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
 2375        self.cursor_shape = cursor_shape;
 2376
 2377        // Disrupt blink for immediate user feedback that the cursor shape has changed
 2378        self.blink_manager.update(cx, BlinkManager::show_cursor);
 2379
 2380        cx.notify();
 2381    }
 2382
 2383    pub fn set_current_line_highlight(
 2384        &mut self,
 2385        current_line_highlight: Option<CurrentLineHighlight>,
 2386    ) {
 2387        self.current_line_highlight = current_line_highlight;
 2388    }
 2389
 2390    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 2391        self.collapse_matches = collapse_matches;
 2392    }
 2393
 2394    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 2395        if self.collapse_matches {
 2396            return range.start..range.start;
 2397        }
 2398        range.clone()
 2399    }
 2400
 2401    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
 2402        if self.display_map.read(cx).clip_at_line_ends != clip {
 2403            self.display_map
 2404                .update(cx, |map, _| map.clip_at_line_ends = clip);
 2405        }
 2406    }
 2407
 2408    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 2409        self.input_enabled = input_enabled;
 2410    }
 2411
 2412    pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
 2413        self.enable_inline_completions = enabled;
 2414    }
 2415
 2416    pub fn set_autoindent(&mut self, autoindent: bool) {
 2417        if autoindent {
 2418            self.autoindent_mode = Some(AutoindentMode::EachLine);
 2419        } else {
 2420            self.autoindent_mode = None;
 2421        }
 2422    }
 2423
 2424    pub fn read_only(&self, cx: &AppContext) -> bool {
 2425        self.read_only || self.buffer.read(cx).read_only()
 2426    }
 2427
 2428    pub fn set_read_only(&mut self, read_only: bool) {
 2429        self.read_only = read_only;
 2430    }
 2431
 2432    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 2433        self.use_autoclose = autoclose;
 2434    }
 2435
 2436    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 2437        self.use_auto_surround = auto_surround;
 2438    }
 2439
 2440    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 2441        self.auto_replace_emoji_shortcode = auto_replace;
 2442    }
 2443
 2444    pub fn toggle_inline_completions(
 2445        &mut self,
 2446        _: &ToggleInlineCompletions,
 2447        cx: &mut ViewContext<Self>,
 2448    ) {
 2449        if self.show_inline_completions_override.is_some() {
 2450            self.set_show_inline_completions(None, cx);
 2451        } else {
 2452            let cursor = self.selections.newest_anchor().head();
 2453            if let Some((buffer, cursor_buffer_position)) =
 2454                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 2455            {
 2456                let show_inline_completions =
 2457                    !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
 2458                self.set_show_inline_completions(Some(show_inline_completions), cx);
 2459            }
 2460        }
 2461    }
 2462
 2463    pub fn set_show_inline_completions(
 2464        &mut self,
 2465        show_inline_completions: Option<bool>,
 2466        cx: &mut ViewContext<Self>,
 2467    ) {
 2468        self.show_inline_completions_override = show_inline_completions;
 2469        self.refresh_inline_completion(false, true, cx);
 2470    }
 2471
 2472    fn should_show_inline_completions(
 2473        &self,
 2474        buffer: &Model<Buffer>,
 2475        buffer_position: language::Anchor,
 2476        cx: &AppContext,
 2477    ) -> bool {
 2478        if let Some(provider) = self.inline_completion_provider() {
 2479            if let Some(show_inline_completions) = self.show_inline_completions_override {
 2480                show_inline_completions
 2481            } else {
 2482                self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
 2483            }
 2484        } else {
 2485            false
 2486        }
 2487    }
 2488
 2489    pub fn set_use_modal_editing(&mut self, to: bool) {
 2490        self.use_modal_editing = to;
 2491    }
 2492
 2493    pub fn use_modal_editing(&self) -> bool {
 2494        self.use_modal_editing
 2495    }
 2496
 2497    fn selections_did_change(
 2498        &mut self,
 2499        local: bool,
 2500        old_cursor_position: &Anchor,
 2501        show_completions: bool,
 2502        cx: &mut ViewContext<Self>,
 2503    ) {
 2504        cx.invalidate_character_coordinates();
 2505
 2506        // Copy selections to primary selection buffer
 2507        #[cfg(target_os = "linux")]
 2508        if local {
 2509            let selections = self.selections.all::<usize>(cx);
 2510            let buffer_handle = self.buffer.read(cx).read(cx);
 2511
 2512            let mut text = String::new();
 2513            for (index, selection) in selections.iter().enumerate() {
 2514                let text_for_selection = buffer_handle
 2515                    .text_for_range(selection.start..selection.end)
 2516                    .collect::<String>();
 2517
 2518                text.push_str(&text_for_selection);
 2519                if index != selections.len() - 1 {
 2520                    text.push('\n');
 2521                }
 2522            }
 2523
 2524            if !text.is_empty() {
 2525                cx.write_to_primary(ClipboardItem::new_string(text));
 2526            }
 2527        }
 2528
 2529        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
 2530            self.buffer.update(cx, |buffer, cx| {
 2531                buffer.set_active_selections(
 2532                    &self.selections.disjoint_anchors(),
 2533                    self.selections.line_mode,
 2534                    self.cursor_shape,
 2535                    cx,
 2536                )
 2537            });
 2538        }
 2539        let display_map = self
 2540            .display_map
 2541            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2542        let buffer = &display_map.buffer_snapshot;
 2543        self.add_selections_state = None;
 2544        self.select_next_state = None;
 2545        self.select_prev_state = None;
 2546        self.select_larger_syntax_node_stack.clear();
 2547        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2548        self.snippet_stack
 2549            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2550        self.take_rename(false, cx);
 2551
 2552        let new_cursor_position = self.selections.newest_anchor().head();
 2553
 2554        self.push_to_nav_history(
 2555            *old_cursor_position,
 2556            Some(new_cursor_position.to_point(buffer)),
 2557            cx,
 2558        );
 2559
 2560        if local {
 2561            let new_cursor_position = self.selections.newest_anchor().head();
 2562            let mut context_menu = self.context_menu.write();
 2563            let completion_menu = match context_menu.as_ref() {
 2564                Some(ContextMenu::Completions(menu)) => Some(menu),
 2565
 2566                _ => {
 2567                    *context_menu = None;
 2568                    None
 2569                }
 2570            };
 2571
 2572            if let Some(completion_menu) = completion_menu {
 2573                let cursor_position = new_cursor_position.to_offset(buffer);
 2574                let (word_range, kind) =
 2575                    buffer.surrounding_word(completion_menu.initial_position, true);
 2576                if kind == Some(CharKind::Word)
 2577                    && word_range.to_inclusive().contains(&cursor_position)
 2578                {
 2579                    let mut completion_menu = completion_menu.clone();
 2580                    drop(context_menu);
 2581
 2582                    let query = Self::completion_query(buffer, cursor_position);
 2583                    cx.spawn(move |this, mut cx| async move {
 2584                        completion_menu
 2585                            .filter(query.as_deref(), cx.background_executor().clone())
 2586                            .await;
 2587
 2588                        this.update(&mut cx, |this, cx| {
 2589                            let mut context_menu = this.context_menu.write();
 2590                            let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
 2591                                return;
 2592                            };
 2593
 2594                            if menu.id > completion_menu.id {
 2595                                return;
 2596                            }
 2597
 2598                            *context_menu = Some(ContextMenu::Completions(completion_menu));
 2599                            drop(context_menu);
 2600                            cx.notify();
 2601                        })
 2602                    })
 2603                    .detach();
 2604
 2605                    if show_completions {
 2606                        self.show_completions(&ShowCompletions { trigger: None }, cx);
 2607                    }
 2608                } else {
 2609                    drop(context_menu);
 2610                    self.hide_context_menu(cx);
 2611                }
 2612            } else {
 2613                drop(context_menu);
 2614            }
 2615
 2616            hide_hover(self, cx);
 2617
 2618            if old_cursor_position.to_display_point(&display_map).row()
 2619                != new_cursor_position.to_display_point(&display_map).row()
 2620            {
 2621                self.available_code_actions.take();
 2622            }
 2623            self.refresh_code_actions(cx);
 2624            self.refresh_document_highlights(cx);
 2625            refresh_matching_bracket_highlights(self, cx);
 2626            self.discard_inline_completion(false, cx);
 2627            linked_editing_ranges::refresh_linked_ranges(self, cx);
 2628            if self.git_blame_inline_enabled {
 2629                self.start_inline_blame_timer(cx);
 2630            }
 2631        }
 2632
 2633        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2634        cx.emit(EditorEvent::SelectionsChanged { local });
 2635
 2636        if self.selections.disjoint_anchors().len() == 1 {
 2637            cx.emit(SearchEvent::ActiveMatchChanged)
 2638        }
 2639        cx.notify();
 2640    }
 2641
 2642    pub fn change_selections<R>(
 2643        &mut self,
 2644        autoscroll: Option<Autoscroll>,
 2645        cx: &mut ViewContext<Self>,
 2646        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2647    ) -> R {
 2648        self.change_selections_inner(autoscroll, true, cx, change)
 2649    }
 2650
 2651    pub fn change_selections_inner<R>(
 2652        &mut self,
 2653        autoscroll: Option<Autoscroll>,
 2654        request_completions: bool,
 2655        cx: &mut ViewContext<Self>,
 2656        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2657    ) -> R {
 2658        let old_cursor_position = self.selections.newest_anchor().head();
 2659        self.push_to_selection_history();
 2660
 2661        let (changed, result) = self.selections.change_with(cx, change);
 2662
 2663        if changed {
 2664            if let Some(autoscroll) = autoscroll {
 2665                self.request_autoscroll(autoscroll, cx);
 2666            }
 2667            self.selections_did_change(true, &old_cursor_position, request_completions, cx);
 2668
 2669            if self.should_open_signature_help_automatically(
 2670                &old_cursor_position,
 2671                self.signature_help_state.backspace_pressed(),
 2672                cx,
 2673            ) {
 2674                self.show_signature_help(&ShowSignatureHelp, cx);
 2675            }
 2676            self.signature_help_state.set_backspace_pressed(false);
 2677        }
 2678
 2679        result
 2680    }
 2681
 2682    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2683    where
 2684        I: IntoIterator<Item = (Range<S>, T)>,
 2685        S: ToOffset,
 2686        T: Into<Arc<str>>,
 2687    {
 2688        if self.read_only(cx) {
 2689            return;
 2690        }
 2691
 2692        self.buffer
 2693            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2694    }
 2695
 2696    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2697    where
 2698        I: IntoIterator<Item = (Range<S>, T)>,
 2699        S: ToOffset,
 2700        T: Into<Arc<str>>,
 2701    {
 2702        if self.read_only(cx) {
 2703            return;
 2704        }
 2705
 2706        self.buffer.update(cx, |buffer, cx| {
 2707            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2708        });
 2709    }
 2710
 2711    pub fn edit_with_block_indent<I, S, T>(
 2712        &mut self,
 2713        edits: I,
 2714        original_indent_columns: Vec<u32>,
 2715        cx: &mut ViewContext<Self>,
 2716    ) where
 2717        I: IntoIterator<Item = (Range<S>, T)>,
 2718        S: ToOffset,
 2719        T: Into<Arc<str>>,
 2720    {
 2721        if self.read_only(cx) {
 2722            return;
 2723        }
 2724
 2725        self.buffer.update(cx, |buffer, cx| {
 2726            buffer.edit(
 2727                edits,
 2728                Some(AutoindentMode::Block {
 2729                    original_indent_columns,
 2730                }),
 2731                cx,
 2732            )
 2733        });
 2734    }
 2735
 2736    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
 2737        self.hide_context_menu(cx);
 2738
 2739        match phase {
 2740            SelectPhase::Begin {
 2741                position,
 2742                add,
 2743                click_count,
 2744            } => self.begin_selection(position, add, click_count, cx),
 2745            SelectPhase::BeginColumnar {
 2746                position,
 2747                goal_column,
 2748                reset,
 2749            } => self.begin_columnar_selection(position, goal_column, reset, cx),
 2750            SelectPhase::Extend {
 2751                position,
 2752                click_count,
 2753            } => self.extend_selection(position, click_count, cx),
 2754            SelectPhase::Update {
 2755                position,
 2756                goal_column,
 2757                scroll_delta,
 2758            } => self.update_selection(position, goal_column, scroll_delta, cx),
 2759            SelectPhase::End => self.end_selection(cx),
 2760        }
 2761    }
 2762
 2763    fn extend_selection(
 2764        &mut self,
 2765        position: DisplayPoint,
 2766        click_count: usize,
 2767        cx: &mut ViewContext<Self>,
 2768    ) {
 2769        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2770        let tail = self.selections.newest::<usize>(cx).tail();
 2771        self.begin_selection(position, false, click_count, cx);
 2772
 2773        let position = position.to_offset(&display_map, Bias::Left);
 2774        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2775
 2776        let mut pending_selection = self
 2777            .selections
 2778            .pending_anchor()
 2779            .expect("extend_selection not called with pending selection");
 2780        if position >= tail {
 2781            pending_selection.start = tail_anchor;
 2782        } else {
 2783            pending_selection.end = tail_anchor;
 2784            pending_selection.reversed = true;
 2785        }
 2786
 2787        let mut pending_mode = self.selections.pending_mode().unwrap();
 2788        match &mut pending_mode {
 2789            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2790            _ => {}
 2791        }
 2792
 2793        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 2794            s.set_pending(pending_selection, pending_mode)
 2795        });
 2796    }
 2797
 2798    fn begin_selection(
 2799        &mut self,
 2800        position: DisplayPoint,
 2801        add: bool,
 2802        click_count: usize,
 2803        cx: &mut ViewContext<Self>,
 2804    ) {
 2805        if !self.focus_handle.is_focused(cx) {
 2806            self.last_focused_descendant = None;
 2807            cx.focus(&self.focus_handle);
 2808        }
 2809
 2810        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2811        let buffer = &display_map.buffer_snapshot;
 2812        let newest_selection = self.selections.newest_anchor().clone();
 2813        let position = display_map.clip_point(position, Bias::Left);
 2814
 2815        let start;
 2816        let end;
 2817        let mode;
 2818        let auto_scroll;
 2819        match click_count {
 2820            1 => {
 2821                start = buffer.anchor_before(position.to_point(&display_map));
 2822                end = start;
 2823                mode = SelectMode::Character;
 2824                auto_scroll = true;
 2825            }
 2826            2 => {
 2827                let range = movement::surrounding_word(&display_map, position);
 2828                start = buffer.anchor_before(range.start.to_point(&display_map));
 2829                end = buffer.anchor_before(range.end.to_point(&display_map));
 2830                mode = SelectMode::Word(start..end);
 2831                auto_scroll = true;
 2832            }
 2833            3 => {
 2834                let position = display_map
 2835                    .clip_point(position, Bias::Left)
 2836                    .to_point(&display_map);
 2837                let line_start = display_map.prev_line_boundary(position).0;
 2838                let next_line_start = buffer.clip_point(
 2839                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2840                    Bias::Left,
 2841                );
 2842                start = buffer.anchor_before(line_start);
 2843                end = buffer.anchor_before(next_line_start);
 2844                mode = SelectMode::Line(start..end);
 2845                auto_scroll = true;
 2846            }
 2847            _ => {
 2848                start = buffer.anchor_before(0);
 2849                end = buffer.anchor_before(buffer.len());
 2850                mode = SelectMode::All;
 2851                auto_scroll = false;
 2852            }
 2853        }
 2854
 2855        let point_to_delete: Option<usize> = {
 2856            let selected_points: Vec<Selection<Point>> =
 2857                self.selections.disjoint_in_range(start..end, cx);
 2858
 2859            if !add || click_count > 1 {
 2860                None
 2861            } else if !selected_points.is_empty() {
 2862                Some(selected_points[0].id)
 2863            } else {
 2864                let clicked_point_already_selected =
 2865                    self.selections.disjoint.iter().find(|selection| {
 2866                        selection.start.to_point(buffer) == start.to_point(buffer)
 2867                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2868                    });
 2869
 2870                clicked_point_already_selected.map(|selection| selection.id)
 2871            }
 2872        };
 2873
 2874        let selections_count = self.selections.count();
 2875
 2876        self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
 2877            if let Some(point_to_delete) = point_to_delete {
 2878                s.delete(point_to_delete);
 2879
 2880                if selections_count == 1 {
 2881                    s.set_pending_anchor_range(start..end, mode);
 2882                }
 2883            } else {
 2884                if !add {
 2885                    s.clear_disjoint();
 2886                } else if click_count > 1 {
 2887                    s.delete(newest_selection.id)
 2888                }
 2889
 2890                s.set_pending_anchor_range(start..end, mode);
 2891            }
 2892        });
 2893    }
 2894
 2895    fn begin_columnar_selection(
 2896        &mut self,
 2897        position: DisplayPoint,
 2898        goal_column: u32,
 2899        reset: bool,
 2900        cx: &mut ViewContext<Self>,
 2901    ) {
 2902        if !self.focus_handle.is_focused(cx) {
 2903            self.last_focused_descendant = None;
 2904            cx.focus(&self.focus_handle);
 2905        }
 2906
 2907        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2908
 2909        if reset {
 2910            let pointer_position = display_map
 2911                .buffer_snapshot
 2912                .anchor_before(position.to_point(&display_map));
 2913
 2914            self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 2915                s.clear_disjoint();
 2916                s.set_pending_anchor_range(
 2917                    pointer_position..pointer_position,
 2918                    SelectMode::Character,
 2919                );
 2920            });
 2921        }
 2922
 2923        let tail = self.selections.newest::<Point>(cx).tail();
 2924        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2925
 2926        if !reset {
 2927            self.select_columns(
 2928                tail.to_display_point(&display_map),
 2929                position,
 2930                goal_column,
 2931                &display_map,
 2932                cx,
 2933            );
 2934        }
 2935    }
 2936
 2937    fn update_selection(
 2938        &mut self,
 2939        position: DisplayPoint,
 2940        goal_column: u32,
 2941        scroll_delta: gpui::Point<f32>,
 2942        cx: &mut ViewContext<Self>,
 2943    ) {
 2944        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2945
 2946        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2947            let tail = tail.to_display_point(&display_map);
 2948            self.select_columns(tail, position, goal_column, &display_map, cx);
 2949        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2950            let buffer = self.buffer.read(cx).snapshot(cx);
 2951            let head;
 2952            let tail;
 2953            let mode = self.selections.pending_mode().unwrap();
 2954            match &mode {
 2955                SelectMode::Character => {
 2956                    head = position.to_point(&display_map);
 2957                    tail = pending.tail().to_point(&buffer);
 2958                }
 2959                SelectMode::Word(original_range) => {
 2960                    let original_display_range = original_range.start.to_display_point(&display_map)
 2961                        ..original_range.end.to_display_point(&display_map);
 2962                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2963                        ..original_display_range.end.to_point(&display_map);
 2964                    if movement::is_inside_word(&display_map, position)
 2965                        || original_display_range.contains(&position)
 2966                    {
 2967                        let word_range = movement::surrounding_word(&display_map, position);
 2968                        if word_range.start < original_display_range.start {
 2969                            head = word_range.start.to_point(&display_map);
 2970                        } else {
 2971                            head = word_range.end.to_point(&display_map);
 2972                        }
 2973                    } else {
 2974                        head = position.to_point(&display_map);
 2975                    }
 2976
 2977                    if head <= original_buffer_range.start {
 2978                        tail = original_buffer_range.end;
 2979                    } else {
 2980                        tail = original_buffer_range.start;
 2981                    }
 2982                }
 2983                SelectMode::Line(original_range) => {
 2984                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2985
 2986                    let position = display_map
 2987                        .clip_point(position, Bias::Left)
 2988                        .to_point(&display_map);
 2989                    let line_start = display_map.prev_line_boundary(position).0;
 2990                    let next_line_start = buffer.clip_point(
 2991                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2992                        Bias::Left,
 2993                    );
 2994
 2995                    if line_start < original_range.start {
 2996                        head = line_start
 2997                    } else {
 2998                        head = next_line_start
 2999                    }
 3000
 3001                    if head <= original_range.start {
 3002                        tail = original_range.end;
 3003                    } else {
 3004                        tail = original_range.start;
 3005                    }
 3006                }
 3007                SelectMode::All => {
 3008                    return;
 3009                }
 3010            };
 3011
 3012            if head < tail {
 3013                pending.start = buffer.anchor_before(head);
 3014                pending.end = buffer.anchor_before(tail);
 3015                pending.reversed = true;
 3016            } else {
 3017                pending.start = buffer.anchor_before(tail);
 3018                pending.end = buffer.anchor_before(head);
 3019                pending.reversed = false;
 3020            }
 3021
 3022            self.change_selections(None, cx, |s| {
 3023                s.set_pending(pending, mode);
 3024            });
 3025        } else {
 3026            log::error!("update_selection dispatched with no pending selection");
 3027            return;
 3028        }
 3029
 3030        self.apply_scroll_delta(scroll_delta, cx);
 3031        cx.notify();
 3032    }
 3033
 3034    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 3035        self.columnar_selection_tail.take();
 3036        if self.selections.pending_anchor().is_some() {
 3037            let selections = self.selections.all::<usize>(cx);
 3038            self.change_selections(None, cx, |s| {
 3039                s.select(selections);
 3040                s.clear_pending();
 3041            });
 3042        }
 3043    }
 3044
 3045    fn select_columns(
 3046        &mut self,
 3047        tail: DisplayPoint,
 3048        head: DisplayPoint,
 3049        goal_column: u32,
 3050        display_map: &DisplaySnapshot,
 3051        cx: &mut ViewContext<Self>,
 3052    ) {
 3053        let start_row = cmp::min(tail.row(), head.row());
 3054        let end_row = cmp::max(tail.row(), head.row());
 3055        let start_column = cmp::min(tail.column(), goal_column);
 3056        let end_column = cmp::max(tail.column(), goal_column);
 3057        let reversed = start_column < tail.column();
 3058
 3059        let selection_ranges = (start_row.0..=end_row.0)
 3060            .map(DisplayRow)
 3061            .filter_map(|row| {
 3062                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 3063                    let start = display_map
 3064                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 3065                        .to_point(display_map);
 3066                    let end = display_map
 3067                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 3068                        .to_point(display_map);
 3069                    if reversed {
 3070                        Some(end..start)
 3071                    } else {
 3072                        Some(start..end)
 3073                    }
 3074                } else {
 3075                    None
 3076                }
 3077            })
 3078            .collect::<Vec<_>>();
 3079
 3080        self.change_selections(None, cx, |s| {
 3081            s.select_ranges(selection_ranges);
 3082        });
 3083        cx.notify();
 3084    }
 3085
 3086    pub fn has_pending_nonempty_selection(&self) -> bool {
 3087        let pending_nonempty_selection = match self.selections.pending_anchor() {
 3088            Some(Selection { start, end, .. }) => start != end,
 3089            None => false,
 3090        };
 3091
 3092        pending_nonempty_selection
 3093            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 3094    }
 3095
 3096    pub fn has_pending_selection(&self) -> bool {
 3097        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 3098    }
 3099
 3100    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 3101        if self.clear_expanded_diff_hunks(cx) {
 3102            cx.notify();
 3103            return;
 3104        }
 3105        if self.dismiss_menus_and_popups(true, cx) {
 3106            return;
 3107        }
 3108
 3109        if self.mode == EditorMode::Full
 3110            && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
 3111        {
 3112            return;
 3113        }
 3114
 3115        cx.propagate();
 3116    }
 3117
 3118    pub fn dismiss_menus_and_popups(
 3119        &mut self,
 3120        should_report_inline_completion_event: bool,
 3121        cx: &mut ViewContext<Self>,
 3122    ) -> bool {
 3123        if self.take_rename(false, cx).is_some() {
 3124            return true;
 3125        }
 3126
 3127        if hide_hover(self, cx) {
 3128            return true;
 3129        }
 3130
 3131        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 3132            return true;
 3133        }
 3134
 3135        if self.hide_context_menu(cx).is_some() {
 3136            return true;
 3137        }
 3138
 3139        if self.mouse_context_menu.take().is_some() {
 3140            return true;
 3141        }
 3142
 3143        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 3144            return true;
 3145        }
 3146
 3147        if self.snippet_stack.pop().is_some() {
 3148            return true;
 3149        }
 3150
 3151        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 3152            self.dismiss_diagnostics(cx);
 3153            return true;
 3154        }
 3155
 3156        false
 3157    }
 3158
 3159    fn linked_editing_ranges_for(
 3160        &self,
 3161        selection: Range<text::Anchor>,
 3162        cx: &AppContext,
 3163    ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
 3164        if self.linked_edit_ranges.is_empty() {
 3165            return None;
 3166        }
 3167        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 3168            selection.end.buffer_id.and_then(|end_buffer_id| {
 3169                if selection.start.buffer_id != Some(end_buffer_id) {
 3170                    return None;
 3171                }
 3172                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 3173                let snapshot = buffer.read(cx).snapshot();
 3174                self.linked_edit_ranges
 3175                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 3176                    .map(|ranges| (ranges, snapshot, buffer))
 3177            })?;
 3178        use text::ToOffset as TO;
 3179        // find offset from the start of current range to current cursor position
 3180        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 3181
 3182        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 3183        let start_difference = start_offset - start_byte_offset;
 3184        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 3185        let end_difference = end_offset - start_byte_offset;
 3186        // Current range has associated linked ranges.
 3187        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3188        for range in linked_ranges.iter() {
 3189            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 3190            let end_offset = start_offset + end_difference;
 3191            let start_offset = start_offset + start_difference;
 3192            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 3193                continue;
 3194            }
 3195            if self.selections.disjoint_anchor_ranges().iter().any(|s| {
 3196                if s.start.buffer_id != selection.start.buffer_id
 3197                    || s.end.buffer_id != selection.end.buffer_id
 3198                {
 3199                    return false;
 3200                }
 3201                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 3202                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 3203            }) {
 3204                continue;
 3205            }
 3206            let start = buffer_snapshot.anchor_after(start_offset);
 3207            let end = buffer_snapshot.anchor_after(end_offset);
 3208            linked_edits
 3209                .entry(buffer.clone())
 3210                .or_default()
 3211                .push(start..end);
 3212        }
 3213        Some(linked_edits)
 3214    }
 3215
 3216    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3217        let text: Arc<str> = text.into();
 3218
 3219        if self.read_only(cx) {
 3220            return;
 3221        }
 3222
 3223        let selections = self.selections.all_adjusted(cx);
 3224        let mut bracket_inserted = false;
 3225        let mut edits = Vec::new();
 3226        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3227        let mut new_selections = Vec::with_capacity(selections.len());
 3228        let mut new_autoclose_regions = Vec::new();
 3229        let snapshot = self.buffer.read(cx).read(cx);
 3230
 3231        for (selection, autoclose_region) in
 3232            self.selections_with_autoclose_regions(selections, &snapshot)
 3233        {
 3234            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 3235                // Determine if the inserted text matches the opening or closing
 3236                // bracket of any of this language's bracket pairs.
 3237                let mut bracket_pair = None;
 3238                let mut is_bracket_pair_start = false;
 3239                let mut is_bracket_pair_end = false;
 3240                if !text.is_empty() {
 3241                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 3242                    //  and they are removing the character that triggered IME popup.
 3243                    for (pair, enabled) in scope.brackets() {
 3244                        if !pair.close && !pair.surround {
 3245                            continue;
 3246                        }
 3247
 3248                        if enabled && pair.start.ends_with(text.as_ref()) {
 3249                            bracket_pair = Some(pair.clone());
 3250                            is_bracket_pair_start = true;
 3251                            break;
 3252                        }
 3253                        if pair.end.as_str() == text.as_ref() {
 3254                            bracket_pair = Some(pair.clone());
 3255                            is_bracket_pair_end = true;
 3256                            break;
 3257                        }
 3258                    }
 3259                }
 3260
 3261                if let Some(bracket_pair) = bracket_pair {
 3262                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 3263                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 3264                    let auto_surround =
 3265                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 3266                    if selection.is_empty() {
 3267                        if is_bracket_pair_start {
 3268                            let prefix_len = bracket_pair.start.len() - text.len();
 3269
 3270                            // If the inserted text is a suffix of an opening bracket and the
 3271                            // selection is preceded by the rest of the opening bracket, then
 3272                            // insert the closing bracket.
 3273                            let following_text_allows_autoclose = snapshot
 3274                                .chars_at(selection.start)
 3275                                .next()
 3276                                .map_or(true, |c| scope.should_autoclose_before(c));
 3277                            let preceding_text_matches_prefix = prefix_len == 0
 3278                                || (selection.start.column >= (prefix_len as u32)
 3279                                    && snapshot.contains_str_at(
 3280                                        Point::new(
 3281                                            selection.start.row,
 3282                                            selection.start.column - (prefix_len as u32),
 3283                                        ),
 3284                                        &bracket_pair.start[..prefix_len],
 3285                                    ));
 3286
 3287                            if autoclose
 3288                                && bracket_pair.close
 3289                                && following_text_allows_autoclose
 3290                                && preceding_text_matches_prefix
 3291                            {
 3292                                let anchor = snapshot.anchor_before(selection.end);
 3293                                new_selections.push((selection.map(|_| anchor), text.len()));
 3294                                new_autoclose_regions.push((
 3295                                    anchor,
 3296                                    text.len(),
 3297                                    selection.id,
 3298                                    bracket_pair.clone(),
 3299                                ));
 3300                                edits.push((
 3301                                    selection.range(),
 3302                                    format!("{}{}", text, bracket_pair.end).into(),
 3303                                ));
 3304                                bracket_inserted = true;
 3305                                continue;
 3306                            }
 3307                        }
 3308
 3309                        if let Some(region) = autoclose_region {
 3310                            // If the selection is followed by an auto-inserted closing bracket,
 3311                            // then don't insert that closing bracket again; just move the selection
 3312                            // past the closing bracket.
 3313                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3314                                && text.as_ref() == region.pair.end.as_str();
 3315                            if should_skip {
 3316                                let anchor = snapshot.anchor_after(selection.end);
 3317                                new_selections
 3318                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3319                                continue;
 3320                            }
 3321                        }
 3322
 3323                        let always_treat_brackets_as_autoclosed = snapshot
 3324                            .settings_at(selection.start, cx)
 3325                            .always_treat_brackets_as_autoclosed;
 3326                        if always_treat_brackets_as_autoclosed
 3327                            && is_bracket_pair_end
 3328                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3329                        {
 3330                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3331                            // and the inserted text is a closing bracket and the selection is followed
 3332                            // by the closing bracket then move the selection past the closing bracket.
 3333                            let anchor = snapshot.anchor_after(selection.end);
 3334                            new_selections.push((selection.map(|_| anchor), text.len()));
 3335                            continue;
 3336                        }
 3337                    }
 3338                    // If an opening bracket is 1 character long and is typed while
 3339                    // text is selected, then surround that text with the bracket pair.
 3340                    else if auto_surround
 3341                        && bracket_pair.surround
 3342                        && is_bracket_pair_start
 3343                        && bracket_pair.start.chars().count() == 1
 3344                    {
 3345                        edits.push((selection.start..selection.start, text.clone()));
 3346                        edits.push((
 3347                            selection.end..selection.end,
 3348                            bracket_pair.end.as_str().into(),
 3349                        ));
 3350                        bracket_inserted = true;
 3351                        new_selections.push((
 3352                            Selection {
 3353                                id: selection.id,
 3354                                start: snapshot.anchor_after(selection.start),
 3355                                end: snapshot.anchor_before(selection.end),
 3356                                reversed: selection.reversed,
 3357                                goal: selection.goal,
 3358                            },
 3359                            0,
 3360                        ));
 3361                        continue;
 3362                    }
 3363                }
 3364            }
 3365
 3366            if self.auto_replace_emoji_shortcode
 3367                && selection.is_empty()
 3368                && text.as_ref().ends_with(':')
 3369            {
 3370                if let Some(possible_emoji_short_code) =
 3371                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3372                {
 3373                    if !possible_emoji_short_code.is_empty() {
 3374                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3375                            let emoji_shortcode_start = Point::new(
 3376                                selection.start.row,
 3377                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3378                            );
 3379
 3380                            // Remove shortcode from buffer
 3381                            edits.push((
 3382                                emoji_shortcode_start..selection.start,
 3383                                "".to_string().into(),
 3384                            ));
 3385                            new_selections.push((
 3386                                Selection {
 3387                                    id: selection.id,
 3388                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3389                                    end: snapshot.anchor_before(selection.start),
 3390                                    reversed: selection.reversed,
 3391                                    goal: selection.goal,
 3392                                },
 3393                                0,
 3394                            ));
 3395
 3396                            // Insert emoji
 3397                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3398                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3399                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3400
 3401                            continue;
 3402                        }
 3403                    }
 3404                }
 3405            }
 3406
 3407            // If not handling any auto-close operation, then just replace the selected
 3408            // text with the given input and move the selection to the end of the
 3409            // newly inserted text.
 3410            let anchor = snapshot.anchor_after(selection.end);
 3411            if !self.linked_edit_ranges.is_empty() {
 3412                let start_anchor = snapshot.anchor_before(selection.start);
 3413
 3414                let is_word_char = text.chars().next().map_or(true, |char| {
 3415                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3416                    classifier.is_word(char)
 3417                });
 3418
 3419                if is_word_char {
 3420                    if let Some(ranges) = self
 3421                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3422                    {
 3423                        for (buffer, edits) in ranges {
 3424                            linked_edits
 3425                                .entry(buffer.clone())
 3426                                .or_default()
 3427                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3428                        }
 3429                    }
 3430                }
 3431            }
 3432
 3433            new_selections.push((selection.map(|_| anchor), 0));
 3434            edits.push((selection.start..selection.end, text.clone()));
 3435        }
 3436
 3437        drop(snapshot);
 3438
 3439        self.transact(cx, |this, cx| {
 3440            this.buffer.update(cx, |buffer, cx| {
 3441                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3442            });
 3443            for (buffer, edits) in linked_edits {
 3444                buffer.update(cx, |buffer, cx| {
 3445                    let snapshot = buffer.snapshot();
 3446                    let edits = edits
 3447                        .into_iter()
 3448                        .map(|(range, text)| {
 3449                            use text::ToPoint as TP;
 3450                            let end_point = TP::to_point(&range.end, &snapshot);
 3451                            let start_point = TP::to_point(&range.start, &snapshot);
 3452                            (start_point..end_point, text)
 3453                        })
 3454                        .sorted_by_key(|(range, _)| range.start)
 3455                        .collect::<Vec<_>>();
 3456                    buffer.edit(edits, None, cx);
 3457                })
 3458            }
 3459            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3460            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3461            let snapshot = this.buffer.read(cx).read(cx);
 3462            let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
 3463                .zip(new_selection_deltas)
 3464                .map(|(selection, delta)| Selection {
 3465                    id: selection.id,
 3466                    start: selection.start + delta,
 3467                    end: selection.end + delta,
 3468                    reversed: selection.reversed,
 3469                    goal: SelectionGoal::None,
 3470                })
 3471                .collect::<Vec<_>>();
 3472
 3473            let mut i = 0;
 3474            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3475                let position = position.to_offset(&snapshot) + delta;
 3476                let start = snapshot.anchor_before(position);
 3477                let end = snapshot.anchor_after(position);
 3478                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3479                    match existing_state.range.start.cmp(&start, &snapshot) {
 3480                        Ordering::Less => i += 1,
 3481                        Ordering::Greater => break,
 3482                        Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
 3483                            Ordering::Less => i += 1,
 3484                            Ordering::Equal => break,
 3485                            Ordering::Greater => break,
 3486                        },
 3487                    }
 3488                }
 3489                this.autoclose_regions.insert(
 3490                    i,
 3491                    AutocloseRegion {
 3492                        selection_id,
 3493                        range: start..end,
 3494                        pair,
 3495                    },
 3496                );
 3497            }
 3498
 3499            drop(snapshot);
 3500            let had_active_inline_completion = this.has_active_inline_completion(cx);
 3501            this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
 3502                s.select(new_selections)
 3503            });
 3504
 3505            if !bracket_inserted {
 3506                if let Some(on_type_format_task) =
 3507                    this.trigger_on_type_formatting(text.to_string(), cx)
 3508                {
 3509                    on_type_format_task.detach_and_log_err(cx);
 3510                }
 3511            }
 3512
 3513            let editor_settings = EditorSettings::get_global(cx);
 3514            if bracket_inserted
 3515                && (editor_settings.auto_signature_help
 3516                    || editor_settings.show_signature_help_after_edits)
 3517            {
 3518                this.show_signature_help(&ShowSignatureHelp, cx);
 3519            }
 3520
 3521            let trigger_in_words = !had_active_inline_completion;
 3522            this.trigger_completion_on_input(&text, trigger_in_words, cx);
 3523            linked_editing_ranges::refresh_linked_ranges(this, cx);
 3524            this.refresh_inline_completion(true, false, cx);
 3525        });
 3526    }
 3527
 3528    fn find_possible_emoji_shortcode_at_position(
 3529        snapshot: &MultiBufferSnapshot,
 3530        position: Point,
 3531    ) -> Option<String> {
 3532        let mut chars = Vec::new();
 3533        let mut found_colon = false;
 3534        for char in snapshot.reversed_chars_at(position).take(100) {
 3535            // Found a possible emoji shortcode in the middle of the buffer
 3536            if found_colon {
 3537                if char.is_whitespace() {
 3538                    chars.reverse();
 3539                    return Some(chars.iter().collect());
 3540                }
 3541                // If the previous character is not a whitespace, we are in the middle of a word
 3542                // and we only want to complete the shortcode if the word is made up of other emojis
 3543                let mut containing_word = String::new();
 3544                for ch in snapshot
 3545                    .reversed_chars_at(position)
 3546                    .skip(chars.len() + 1)
 3547                    .take(100)
 3548                {
 3549                    if ch.is_whitespace() {
 3550                        break;
 3551                    }
 3552                    containing_word.push(ch);
 3553                }
 3554                let containing_word = containing_word.chars().rev().collect::<String>();
 3555                if util::word_consists_of_emojis(containing_word.as_str()) {
 3556                    chars.reverse();
 3557                    return Some(chars.iter().collect());
 3558                }
 3559            }
 3560
 3561            if char.is_whitespace() || !char.is_ascii() {
 3562                return None;
 3563            }
 3564            if char == ':' {
 3565                found_colon = true;
 3566            } else {
 3567                chars.push(char);
 3568            }
 3569        }
 3570        // Found a possible emoji shortcode at the beginning of the buffer
 3571        chars.reverse();
 3572        Some(chars.iter().collect())
 3573    }
 3574
 3575    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 3576        self.transact(cx, |this, cx| {
 3577            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3578                let selections = this.selections.all::<usize>(cx);
 3579                let multi_buffer = this.buffer.read(cx);
 3580                let buffer = multi_buffer.snapshot(cx);
 3581                selections
 3582                    .iter()
 3583                    .map(|selection| {
 3584                        let start_point = selection.start.to_point(&buffer);
 3585                        let mut indent =
 3586                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3587                        indent.len = cmp::min(indent.len, start_point.column);
 3588                        let start = selection.start;
 3589                        let end = selection.end;
 3590                        let selection_is_empty = start == end;
 3591                        let language_scope = buffer.language_scope_at(start);
 3592                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3593                            &language_scope
 3594                        {
 3595                            let leading_whitespace_len = buffer
 3596                                .reversed_chars_at(start)
 3597                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3598                                .map(|c| c.len_utf8())
 3599                                .sum::<usize>();
 3600
 3601                            let trailing_whitespace_len = buffer
 3602                                .chars_at(end)
 3603                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3604                                .map(|c| c.len_utf8())
 3605                                .sum::<usize>();
 3606
 3607                            let insert_extra_newline =
 3608                                language.brackets().any(|(pair, enabled)| {
 3609                                    let pair_start = pair.start.trim_end();
 3610                                    let pair_end = pair.end.trim_start();
 3611
 3612                                    enabled
 3613                                        && pair.newline
 3614                                        && buffer.contains_str_at(
 3615                                            end + trailing_whitespace_len,
 3616                                            pair_end,
 3617                                        )
 3618                                        && buffer.contains_str_at(
 3619                                            (start - leading_whitespace_len)
 3620                                                .saturating_sub(pair_start.len()),
 3621                                            pair_start,
 3622                                        )
 3623                                });
 3624
 3625                            // Comment extension on newline is allowed only for cursor selections
 3626                            let comment_delimiter = maybe!({
 3627                                if !selection_is_empty {
 3628                                    return None;
 3629                                }
 3630
 3631                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3632                                    return None;
 3633                                }
 3634
 3635                                let delimiters = language.line_comment_prefixes();
 3636                                let max_len_of_delimiter =
 3637                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3638                                let (snapshot, range) =
 3639                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3640
 3641                                let mut index_of_first_non_whitespace = 0;
 3642                                let comment_candidate = snapshot
 3643                                    .chars_for_range(range)
 3644                                    .skip_while(|c| {
 3645                                        let should_skip = c.is_whitespace();
 3646                                        if should_skip {
 3647                                            index_of_first_non_whitespace += 1;
 3648                                        }
 3649                                        should_skip
 3650                                    })
 3651                                    .take(max_len_of_delimiter)
 3652                                    .collect::<String>();
 3653                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3654                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3655                                })?;
 3656                                let cursor_is_placed_after_comment_marker =
 3657                                    index_of_first_non_whitespace + comment_prefix.len()
 3658                                        <= start_point.column as usize;
 3659                                if cursor_is_placed_after_comment_marker {
 3660                                    Some(comment_prefix.clone())
 3661                                } else {
 3662                                    None
 3663                                }
 3664                            });
 3665                            (comment_delimiter, insert_extra_newline)
 3666                        } else {
 3667                            (None, false)
 3668                        };
 3669
 3670                        let capacity_for_delimiter = comment_delimiter
 3671                            .as_deref()
 3672                            .map(str::len)
 3673                            .unwrap_or_default();
 3674                        let mut new_text =
 3675                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3676                        new_text.push('\n');
 3677                        new_text.extend(indent.chars());
 3678                        if let Some(delimiter) = &comment_delimiter {
 3679                            new_text.push_str(delimiter);
 3680                        }
 3681                        if insert_extra_newline {
 3682                            new_text = new_text.repeat(2);
 3683                        }
 3684
 3685                        let anchor = buffer.anchor_after(end);
 3686                        let new_selection = selection.map(|_| anchor);
 3687                        (
 3688                            (start..end, new_text),
 3689                            (insert_extra_newline, new_selection),
 3690                        )
 3691                    })
 3692                    .unzip()
 3693            };
 3694
 3695            this.edit_with_autoindent(edits, cx);
 3696            let buffer = this.buffer.read(cx).snapshot(cx);
 3697            let new_selections = selection_fixup_info
 3698                .into_iter()
 3699                .map(|(extra_newline_inserted, new_selection)| {
 3700                    let mut cursor = new_selection.end.to_point(&buffer);
 3701                    if extra_newline_inserted {
 3702                        cursor.row -= 1;
 3703                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3704                    }
 3705                    new_selection.map(|_| cursor)
 3706                })
 3707                .collect();
 3708
 3709            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3710            this.refresh_inline_completion(true, false, cx);
 3711        });
 3712    }
 3713
 3714    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3715        let buffer = self.buffer.read(cx);
 3716        let snapshot = buffer.snapshot(cx);
 3717
 3718        let mut edits = Vec::new();
 3719        let mut rows = Vec::new();
 3720
 3721        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3722            let cursor = selection.head();
 3723            let row = cursor.row;
 3724
 3725            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3726
 3727            let newline = "\n".to_string();
 3728            edits.push((start_of_line..start_of_line, newline));
 3729
 3730            rows.push(row + rows_inserted as u32);
 3731        }
 3732
 3733        self.transact(cx, |editor, cx| {
 3734            editor.edit(edits, cx);
 3735
 3736            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3737                let mut index = 0;
 3738                s.move_cursors_with(|map, _, _| {
 3739                    let row = rows[index];
 3740                    index += 1;
 3741
 3742                    let point = Point::new(row, 0);
 3743                    let boundary = map.next_line_boundary(point).1;
 3744                    let clipped = map.clip_point(boundary, Bias::Left);
 3745
 3746                    (clipped, SelectionGoal::None)
 3747                });
 3748            });
 3749
 3750            let mut indent_edits = Vec::new();
 3751            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3752            for row in rows {
 3753                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3754                for (row, indent) in indents {
 3755                    if indent.len == 0 {
 3756                        continue;
 3757                    }
 3758
 3759                    let text = match indent.kind {
 3760                        IndentKind::Space => " ".repeat(indent.len as usize),
 3761                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3762                    };
 3763                    let point = Point::new(row.0, 0);
 3764                    indent_edits.push((point..point, text));
 3765                }
 3766            }
 3767            editor.edit(indent_edits, cx);
 3768        });
 3769    }
 3770
 3771    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3772        let buffer = self.buffer.read(cx);
 3773        let snapshot = buffer.snapshot(cx);
 3774
 3775        let mut edits = Vec::new();
 3776        let mut rows = Vec::new();
 3777        let mut rows_inserted = 0;
 3778
 3779        for selection in self.selections.all_adjusted(cx) {
 3780            let cursor = selection.head();
 3781            let row = cursor.row;
 3782
 3783            let point = Point::new(row + 1, 0);
 3784            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3785
 3786            let newline = "\n".to_string();
 3787            edits.push((start_of_line..start_of_line, newline));
 3788
 3789            rows_inserted += 1;
 3790            rows.push(row + rows_inserted);
 3791        }
 3792
 3793        self.transact(cx, |editor, cx| {
 3794            editor.edit(edits, cx);
 3795
 3796            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3797                let mut index = 0;
 3798                s.move_cursors_with(|map, _, _| {
 3799                    let row = rows[index];
 3800                    index += 1;
 3801
 3802                    let point = Point::new(row, 0);
 3803                    let boundary = map.next_line_boundary(point).1;
 3804                    let clipped = map.clip_point(boundary, Bias::Left);
 3805
 3806                    (clipped, SelectionGoal::None)
 3807                });
 3808            });
 3809
 3810            let mut indent_edits = Vec::new();
 3811            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3812            for row in rows {
 3813                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3814                for (row, indent) in indents {
 3815                    if indent.len == 0 {
 3816                        continue;
 3817                    }
 3818
 3819                    let text = match indent.kind {
 3820                        IndentKind::Space => " ".repeat(indent.len as usize),
 3821                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3822                    };
 3823                    let point = Point::new(row.0, 0);
 3824                    indent_edits.push((point..point, text));
 3825                }
 3826            }
 3827            editor.edit(indent_edits, cx);
 3828        });
 3829    }
 3830
 3831    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3832        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3833            original_indent_columns: Vec::new(),
 3834        });
 3835        self.insert_with_autoindent_mode(text, autoindent, cx);
 3836    }
 3837
 3838    fn insert_with_autoindent_mode(
 3839        &mut self,
 3840        text: &str,
 3841        autoindent_mode: Option<AutoindentMode>,
 3842        cx: &mut ViewContext<Self>,
 3843    ) {
 3844        if self.read_only(cx) {
 3845            return;
 3846        }
 3847
 3848        let text: Arc<str> = text.into();
 3849        self.transact(cx, |this, cx| {
 3850            let old_selections = this.selections.all_adjusted(cx);
 3851            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3852                let anchors = {
 3853                    let snapshot = buffer.read(cx);
 3854                    old_selections
 3855                        .iter()
 3856                        .map(|s| {
 3857                            let anchor = snapshot.anchor_after(s.head());
 3858                            s.map(|_| anchor)
 3859                        })
 3860                        .collect::<Vec<_>>()
 3861                };
 3862                buffer.edit(
 3863                    old_selections
 3864                        .iter()
 3865                        .map(|s| (s.start..s.end, text.clone())),
 3866                    autoindent_mode,
 3867                    cx,
 3868                );
 3869                anchors
 3870            });
 3871
 3872            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3873                s.select_anchors(selection_anchors);
 3874            })
 3875        });
 3876    }
 3877
 3878    fn trigger_completion_on_input(
 3879        &mut self,
 3880        text: &str,
 3881        trigger_in_words: bool,
 3882        cx: &mut ViewContext<Self>,
 3883    ) {
 3884        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3885            self.show_completions(
 3886                &ShowCompletions {
 3887                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3888                },
 3889                cx,
 3890            );
 3891        } else {
 3892            self.hide_context_menu(cx);
 3893        }
 3894    }
 3895
 3896    fn is_completion_trigger(
 3897        &self,
 3898        text: &str,
 3899        trigger_in_words: bool,
 3900        cx: &mut ViewContext<Self>,
 3901    ) -> bool {
 3902        let position = self.selections.newest_anchor().head();
 3903        let multibuffer = self.buffer.read(cx);
 3904        let Some(buffer) = position
 3905            .buffer_id
 3906            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3907        else {
 3908            return false;
 3909        };
 3910
 3911        if let Some(completion_provider) = &self.completion_provider {
 3912            completion_provider.is_completion_trigger(
 3913                &buffer,
 3914                position.text_anchor,
 3915                text,
 3916                trigger_in_words,
 3917                cx,
 3918            )
 3919        } else {
 3920            false
 3921        }
 3922    }
 3923
 3924    /// If any empty selections is touching the start of its innermost containing autoclose
 3925    /// region, expand it to select the brackets.
 3926    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 3927        let selections = self.selections.all::<usize>(cx);
 3928        let buffer = self.buffer.read(cx).read(cx);
 3929        let new_selections = self
 3930            .selections_with_autoclose_regions(selections, &buffer)
 3931            .map(|(mut selection, region)| {
 3932                if !selection.is_empty() {
 3933                    return selection;
 3934                }
 3935
 3936                if let Some(region) = region {
 3937                    let mut range = region.range.to_offset(&buffer);
 3938                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3939                        range.start -= region.pair.start.len();
 3940                        if buffer.contains_str_at(range.start, &region.pair.start)
 3941                            && buffer.contains_str_at(range.end, &region.pair.end)
 3942                        {
 3943                            range.end += region.pair.end.len();
 3944                            selection.start = range.start;
 3945                            selection.end = range.end;
 3946
 3947                            return selection;
 3948                        }
 3949                    }
 3950                }
 3951
 3952                let always_treat_brackets_as_autoclosed = buffer
 3953                    .settings_at(selection.start, cx)
 3954                    .always_treat_brackets_as_autoclosed;
 3955
 3956                if !always_treat_brackets_as_autoclosed {
 3957                    return selection;
 3958                }
 3959
 3960                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3961                    for (pair, enabled) in scope.brackets() {
 3962                        if !enabled || !pair.close {
 3963                            continue;
 3964                        }
 3965
 3966                        if buffer.contains_str_at(selection.start, &pair.end) {
 3967                            let pair_start_len = pair.start.len();
 3968                            if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
 3969                            {
 3970                                selection.start -= pair_start_len;
 3971                                selection.end += pair.end.len();
 3972
 3973                                return selection;
 3974                            }
 3975                        }
 3976                    }
 3977                }
 3978
 3979                selection
 3980            })
 3981            .collect();
 3982
 3983        drop(buffer);
 3984        self.change_selections(None, cx, |selections| selections.select(new_selections));
 3985    }
 3986
 3987    /// Iterate the given selections, and for each one, find the smallest surrounding
 3988    /// autoclose region. This uses the ordering of the selections and the autoclose
 3989    /// regions to avoid repeated comparisons.
 3990    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3991        &'a self,
 3992        selections: impl IntoIterator<Item = Selection<D>>,
 3993        buffer: &'a MultiBufferSnapshot,
 3994    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3995        let mut i = 0;
 3996        let mut regions = self.autoclose_regions.as_slice();
 3997        selections.into_iter().map(move |selection| {
 3998            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3999
 4000            let mut enclosing = None;
 4001            while let Some(pair_state) = regions.get(i) {
 4002                if pair_state.range.end.to_offset(buffer) < range.start {
 4003                    regions = &regions[i + 1..];
 4004                    i = 0;
 4005                } else if pair_state.range.start.to_offset(buffer) > range.end {
 4006                    break;
 4007                } else {
 4008                    if pair_state.selection_id == selection.id {
 4009                        enclosing = Some(pair_state);
 4010                    }
 4011                    i += 1;
 4012                }
 4013            }
 4014
 4015            (selection.clone(), enclosing)
 4016        })
 4017    }
 4018
 4019    /// Remove any autoclose regions that no longer contain their selection.
 4020    fn invalidate_autoclose_regions(
 4021        &mut self,
 4022        mut selections: &[Selection<Anchor>],
 4023        buffer: &MultiBufferSnapshot,
 4024    ) {
 4025        self.autoclose_regions.retain(|state| {
 4026            let mut i = 0;
 4027            while let Some(selection) = selections.get(i) {
 4028                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 4029                    selections = &selections[1..];
 4030                    continue;
 4031                }
 4032                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 4033                    break;
 4034                }
 4035                if selection.id == state.selection_id {
 4036                    return true;
 4037                } else {
 4038                    i += 1;
 4039                }
 4040            }
 4041            false
 4042        });
 4043    }
 4044
 4045    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 4046        let offset = position.to_offset(buffer);
 4047        let (word_range, kind) = buffer.surrounding_word(offset, true);
 4048        if offset > word_range.start && kind == Some(CharKind::Word) {
 4049            Some(
 4050                buffer
 4051                    .text_for_range(word_range.start..offset)
 4052                    .collect::<String>(),
 4053            )
 4054        } else {
 4055            None
 4056        }
 4057    }
 4058
 4059    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 4060        self.refresh_inlay_hints(
 4061            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 4062            cx,
 4063        );
 4064    }
 4065
 4066    pub fn inlay_hints_enabled(&self) -> bool {
 4067        self.inlay_hint_cache.enabled
 4068    }
 4069
 4070    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 4071        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 4072            return;
 4073        }
 4074
 4075        let reason_description = reason.description();
 4076        let ignore_debounce = matches!(
 4077            reason,
 4078            InlayHintRefreshReason::SettingsChange(_)
 4079                | InlayHintRefreshReason::Toggle(_)
 4080                | InlayHintRefreshReason::ExcerptsRemoved(_)
 4081        );
 4082        let (invalidate_cache, required_languages) = match reason {
 4083            InlayHintRefreshReason::Toggle(enabled) => {
 4084                self.inlay_hint_cache.enabled = enabled;
 4085                if enabled {
 4086                    (InvalidationStrategy::RefreshRequested, None)
 4087                } else {
 4088                    self.inlay_hint_cache.clear();
 4089                    self.splice_inlays(
 4090                        self.visible_inlay_hints(cx)
 4091                            .iter()
 4092                            .map(|inlay| inlay.id)
 4093                            .collect(),
 4094                        Vec::new(),
 4095                        cx,
 4096                    );
 4097                    return;
 4098                }
 4099            }
 4100            InlayHintRefreshReason::SettingsChange(new_settings) => {
 4101                match self.inlay_hint_cache.update_settings(
 4102                    &self.buffer,
 4103                    new_settings,
 4104                    self.visible_inlay_hints(cx),
 4105                    cx,
 4106                ) {
 4107                    ControlFlow::Break(Some(InlaySplice {
 4108                        to_remove,
 4109                        to_insert,
 4110                    })) => {
 4111                        self.splice_inlays(to_remove, to_insert, cx);
 4112                        return;
 4113                    }
 4114                    ControlFlow::Break(None) => return,
 4115                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 4116                }
 4117            }
 4118            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 4119                if let Some(InlaySplice {
 4120                    to_remove,
 4121                    to_insert,
 4122                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 4123                {
 4124                    self.splice_inlays(to_remove, to_insert, cx);
 4125                }
 4126                return;
 4127            }
 4128            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 4129            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 4130                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 4131            }
 4132            InlayHintRefreshReason::RefreshRequested => {
 4133                (InvalidationStrategy::RefreshRequested, None)
 4134            }
 4135        };
 4136
 4137        if let Some(InlaySplice {
 4138            to_remove,
 4139            to_insert,
 4140        }) = self.inlay_hint_cache.spawn_hint_refresh(
 4141            reason_description,
 4142            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 4143            invalidate_cache,
 4144            ignore_debounce,
 4145            cx,
 4146        ) {
 4147            self.splice_inlays(to_remove, to_insert, cx);
 4148        }
 4149    }
 4150
 4151    fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
 4152        self.display_map
 4153            .read(cx)
 4154            .current_inlays()
 4155            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 4156            .cloned()
 4157            .collect()
 4158    }
 4159
 4160    pub fn excerpts_for_inlay_hints_query(
 4161        &self,
 4162        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 4163        cx: &mut ViewContext<Editor>,
 4164    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 4165        let Some(project) = self.project.as_ref() else {
 4166            return HashMap::default();
 4167        };
 4168        let project = project.read(cx);
 4169        let multi_buffer = self.buffer().read(cx);
 4170        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 4171        let multi_buffer_visible_start = self
 4172            .scroll_manager
 4173            .anchor()
 4174            .anchor
 4175            .to_point(&multi_buffer_snapshot);
 4176        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 4177            multi_buffer_visible_start
 4178                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 4179            Bias::Left,
 4180        );
 4181        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 4182        multi_buffer
 4183            .range_to_buffer_ranges(multi_buffer_visible_range, cx)
 4184            .into_iter()
 4185            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 4186            .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
 4187                let buffer = buffer_handle.read(cx);
 4188                let buffer_file = project::File::from_dyn(buffer.file())?;
 4189                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 4190                let worktree_entry = buffer_worktree
 4191                    .read(cx)
 4192                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 4193                if worktree_entry.is_ignored {
 4194                    return None;
 4195                }
 4196
 4197                let language = buffer.language()?;
 4198                if let Some(restrict_to_languages) = restrict_to_languages {
 4199                    if !restrict_to_languages.contains(language) {
 4200                        return None;
 4201                    }
 4202                }
 4203                Some((
 4204                    excerpt_id,
 4205                    (
 4206                        buffer_handle,
 4207                        buffer.version().clone(),
 4208                        excerpt_visible_range,
 4209                    ),
 4210                ))
 4211            })
 4212            .collect()
 4213    }
 4214
 4215    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 4216        TextLayoutDetails {
 4217            text_system: cx.text_system().clone(),
 4218            editor_style: self.style.clone().unwrap(),
 4219            rem_size: cx.rem_size(),
 4220            scroll_anchor: self.scroll_manager.anchor(),
 4221            visible_rows: self.visible_line_count(),
 4222            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 4223        }
 4224    }
 4225
 4226    fn splice_inlays(
 4227        &self,
 4228        to_remove: Vec<InlayId>,
 4229        to_insert: Vec<Inlay>,
 4230        cx: &mut ViewContext<Self>,
 4231    ) {
 4232        self.display_map.update(cx, |display_map, cx| {
 4233            display_map.splice_inlays(to_remove, to_insert, cx);
 4234        });
 4235        cx.notify();
 4236    }
 4237
 4238    fn trigger_on_type_formatting(
 4239        &self,
 4240        input: String,
 4241        cx: &mut ViewContext<Self>,
 4242    ) -> Option<Task<Result<()>>> {
 4243        if input.len() != 1 {
 4244            return None;
 4245        }
 4246
 4247        let project = self.project.as_ref()?;
 4248        let position = self.selections.newest_anchor().head();
 4249        let (buffer, buffer_position) = self
 4250            .buffer
 4251            .read(cx)
 4252            .text_anchor_for_position(position, cx)?;
 4253
 4254        let settings = language_settings::language_settings(
 4255            buffer.read(cx).language_at(buffer_position).as_ref(),
 4256            buffer.read(cx).file(),
 4257            cx,
 4258        );
 4259        if !settings.use_on_type_format {
 4260            return None;
 4261        }
 4262
 4263        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 4264        // hence we do LSP request & edit on host side only — add formats to host's history.
 4265        let push_to_lsp_host_history = true;
 4266        // If this is not the host, append its history with new edits.
 4267        let push_to_client_history = project.read(cx).is_via_collab();
 4268
 4269        let on_type_formatting = project.update(cx, |project, cx| {
 4270            project.on_type_format(
 4271                buffer.clone(),
 4272                buffer_position,
 4273                input,
 4274                push_to_lsp_host_history,
 4275                cx,
 4276            )
 4277        });
 4278        Some(cx.spawn(|editor, mut cx| async move {
 4279            if let Some(transaction) = on_type_formatting.await? {
 4280                if push_to_client_history {
 4281                    buffer
 4282                        .update(&mut cx, |buffer, _| {
 4283                            buffer.push_transaction(transaction, Instant::now());
 4284                        })
 4285                        .ok();
 4286                }
 4287                editor.update(&mut cx, |editor, cx| {
 4288                    editor.refresh_document_highlights(cx);
 4289                })?;
 4290            }
 4291            Ok(())
 4292        }))
 4293    }
 4294
 4295    pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
 4296        if self.pending_rename.is_some() {
 4297            return;
 4298        }
 4299
 4300        let Some(provider) = self.completion_provider.as_ref() else {
 4301            return;
 4302        };
 4303
 4304        let position = self.selections.newest_anchor().head();
 4305        let (buffer, buffer_position) =
 4306            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4307                output
 4308            } else {
 4309                return;
 4310            };
 4311
 4312        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4313        let is_followup_invoke = {
 4314            let context_menu_state = self.context_menu.read();
 4315            matches!(
 4316                context_menu_state.deref(),
 4317                Some(ContextMenu::Completions(_))
 4318            )
 4319        };
 4320        let trigger_kind = match (&options.trigger, is_followup_invoke) {
 4321            (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
 4322            (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4323                CompletionTriggerKind::TRIGGER_CHARACTER
 4324            }
 4325
 4326            _ => CompletionTriggerKind::INVOKED,
 4327        };
 4328        let completion_context = CompletionContext {
 4329            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 4330                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4331                    Some(String::from(trigger))
 4332                } else {
 4333                    None
 4334                }
 4335            }),
 4336            trigger_kind,
 4337        };
 4338        let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
 4339        let sort_completions = provider.sort_completions();
 4340
 4341        let id = post_inc(&mut self.next_completion_id);
 4342        let task = cx.spawn(|this, mut cx| {
 4343            async move {
 4344                this.update(&mut cx, |this, _| {
 4345                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4346                })?;
 4347                let completions = completions.await.log_err();
 4348                let menu = if let Some(completions) = completions {
 4349                    let mut menu = CompletionsMenu {
 4350                        id,
 4351                        sort_completions,
 4352                        initial_position: position,
 4353                        match_candidates: completions
 4354                            .iter()
 4355                            .enumerate()
 4356                            .map(|(id, completion)| {
 4357                                StringMatchCandidate::new(
 4358                                    id,
 4359                                    completion.label.text[completion.label.filter_range.clone()]
 4360                                        .into(),
 4361                                )
 4362                            })
 4363                            .collect(),
 4364                        buffer: buffer.clone(),
 4365                        completions: Arc::new(RwLock::new(completions.into())),
 4366                        matches: Vec::new().into(),
 4367                        selected_item: 0,
 4368                        scroll_handle: UniformListScrollHandle::new(),
 4369                        selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
 4370                            DebouncedDelay::new(),
 4371                        )),
 4372                    };
 4373                    menu.filter(query.as_deref(), cx.background_executor().clone())
 4374                        .await;
 4375
 4376                    if menu.matches.is_empty() {
 4377                        None
 4378                    } else {
 4379                        this.update(&mut cx, |editor, cx| {
 4380                            let completions = menu.completions.clone();
 4381                            let matches = menu.matches.clone();
 4382
 4383                            let delay_ms = EditorSettings::get_global(cx)
 4384                                .completion_documentation_secondary_query_debounce;
 4385                            let delay = Duration::from_millis(delay_ms);
 4386                            editor
 4387                                .completion_documentation_pre_resolve_debounce
 4388                                .fire_new(delay, cx, |editor, cx| {
 4389                                    CompletionsMenu::pre_resolve_completion_documentation(
 4390                                        buffer,
 4391                                        completions,
 4392                                        matches,
 4393                                        editor,
 4394                                        cx,
 4395                                    )
 4396                                });
 4397                        })
 4398                        .ok();
 4399                        Some(menu)
 4400                    }
 4401                } else {
 4402                    None
 4403                };
 4404
 4405                this.update(&mut cx, |this, cx| {
 4406                    let mut context_menu = this.context_menu.write();
 4407                    match context_menu.as_ref() {
 4408                        None => {}
 4409
 4410                        Some(ContextMenu::Completions(prev_menu)) => {
 4411                            if prev_menu.id > id {
 4412                                return;
 4413                            }
 4414                        }
 4415
 4416                        _ => return,
 4417                    }
 4418
 4419                    if this.focus_handle.is_focused(cx) && menu.is_some() {
 4420                        let menu = menu.unwrap();
 4421                        *context_menu = Some(ContextMenu::Completions(menu));
 4422                        drop(context_menu);
 4423                        this.discard_inline_completion(false, cx);
 4424                        cx.notify();
 4425                    } else if this.completion_tasks.len() <= 1 {
 4426                        // If there are no more completion tasks and the last menu was
 4427                        // empty, we should hide it. If it was already hidden, we should
 4428                        // also show the copilot completion when available.
 4429                        drop(context_menu);
 4430                        if this.hide_context_menu(cx).is_none() {
 4431                            this.update_visible_inline_completion(cx);
 4432                        }
 4433                    }
 4434                })?;
 4435
 4436                Ok::<_, anyhow::Error>(())
 4437            }
 4438            .log_err()
 4439        });
 4440
 4441        self.completion_tasks.push((id, task));
 4442    }
 4443
 4444    pub fn confirm_completion(
 4445        &mut self,
 4446        action: &ConfirmCompletion,
 4447        cx: &mut ViewContext<Self>,
 4448    ) -> Option<Task<Result<()>>> {
 4449        self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
 4450    }
 4451
 4452    pub fn compose_completion(
 4453        &mut self,
 4454        action: &ComposeCompletion,
 4455        cx: &mut ViewContext<Self>,
 4456    ) -> Option<Task<Result<()>>> {
 4457        self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
 4458    }
 4459
 4460    fn do_completion(
 4461        &mut self,
 4462        item_ix: Option<usize>,
 4463        intent: CompletionIntent,
 4464        cx: &mut ViewContext<Editor>,
 4465    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 4466        use language::ToOffset as _;
 4467
 4468        let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 4469            menu
 4470        } else {
 4471            return None;
 4472        };
 4473
 4474        let mat = completions_menu
 4475            .matches
 4476            .get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4477        let buffer_handle = completions_menu.buffer;
 4478        let completions = completions_menu.completions.read();
 4479        let completion = completions.get(mat.candidate_id)?;
 4480        cx.stop_propagation();
 4481
 4482        let snippet;
 4483        let text;
 4484
 4485        if completion.is_snippet() {
 4486            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4487            text = snippet.as_ref().unwrap().text.clone();
 4488        } else {
 4489            snippet = None;
 4490            text = completion.new_text.clone();
 4491        };
 4492        let selections = self.selections.all::<usize>(cx);
 4493        let buffer = buffer_handle.read(cx);
 4494        let old_range = completion.old_range.to_offset(buffer);
 4495        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4496
 4497        let newest_selection = self.selections.newest_anchor();
 4498        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4499            return None;
 4500        }
 4501
 4502        let lookbehind = newest_selection
 4503            .start
 4504            .text_anchor
 4505            .to_offset(buffer)
 4506            .saturating_sub(old_range.start);
 4507        let lookahead = old_range
 4508            .end
 4509            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4510        let mut common_prefix_len = old_text
 4511            .bytes()
 4512            .zip(text.bytes())
 4513            .take_while(|(a, b)| a == b)
 4514            .count();
 4515
 4516        let snapshot = self.buffer.read(cx).snapshot(cx);
 4517        let mut range_to_replace: Option<Range<isize>> = None;
 4518        let mut ranges = Vec::new();
 4519        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4520        for selection in &selections {
 4521            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4522                let start = selection.start.saturating_sub(lookbehind);
 4523                let end = selection.end + lookahead;
 4524                if selection.id == newest_selection.id {
 4525                    range_to_replace = Some(
 4526                        ((start + common_prefix_len) as isize - selection.start as isize)
 4527                            ..(end as isize - selection.start as isize),
 4528                    );
 4529                }
 4530                ranges.push(start + common_prefix_len..end);
 4531            } else {
 4532                common_prefix_len = 0;
 4533                ranges.clear();
 4534                ranges.extend(selections.iter().map(|s| {
 4535                    if s.id == newest_selection.id {
 4536                        range_to_replace = Some(
 4537                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4538                                - selection.start as isize
 4539                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4540                                    - selection.start as isize,
 4541                        );
 4542                        old_range.clone()
 4543                    } else {
 4544                        s.start..s.end
 4545                    }
 4546                }));
 4547                break;
 4548            }
 4549            if !self.linked_edit_ranges.is_empty() {
 4550                let start_anchor = snapshot.anchor_before(selection.head());
 4551                let end_anchor = snapshot.anchor_after(selection.tail());
 4552                if let Some(ranges) = self
 4553                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4554                {
 4555                    for (buffer, edits) in ranges {
 4556                        linked_edits.entry(buffer.clone()).or_default().extend(
 4557                            edits
 4558                                .into_iter()
 4559                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4560                        );
 4561                    }
 4562                }
 4563            }
 4564        }
 4565        let text = &text[common_prefix_len..];
 4566
 4567        cx.emit(EditorEvent::InputHandled {
 4568            utf16_range_to_replace: range_to_replace,
 4569            text: text.into(),
 4570        });
 4571
 4572        self.transact(cx, |this, cx| {
 4573            if let Some(mut snippet) = snippet {
 4574                snippet.text = text.to_string();
 4575                for tabstop in snippet.tabstops.iter_mut().flatten() {
 4576                    tabstop.start -= common_prefix_len as isize;
 4577                    tabstop.end -= common_prefix_len as isize;
 4578                }
 4579
 4580                this.insert_snippet(&ranges, snippet, cx).log_err();
 4581            } else {
 4582                this.buffer.update(cx, |buffer, cx| {
 4583                    buffer.edit(
 4584                        ranges.iter().map(|range| (range.clone(), text)),
 4585                        this.autoindent_mode.clone(),
 4586                        cx,
 4587                    );
 4588                });
 4589            }
 4590            for (buffer, edits) in linked_edits {
 4591                buffer.update(cx, |buffer, cx| {
 4592                    let snapshot = buffer.snapshot();
 4593                    let edits = edits
 4594                        .into_iter()
 4595                        .map(|(range, text)| {
 4596                            use text::ToPoint as TP;
 4597                            let end_point = TP::to_point(&range.end, &snapshot);
 4598                            let start_point = TP::to_point(&range.start, &snapshot);
 4599                            (start_point..end_point, text)
 4600                        })
 4601                        .sorted_by_key(|(range, _)| range.start)
 4602                        .collect::<Vec<_>>();
 4603                    buffer.edit(edits, None, cx);
 4604                })
 4605            }
 4606
 4607            this.refresh_inline_completion(true, false, cx);
 4608        });
 4609
 4610        let show_new_completions_on_confirm = completion
 4611            .confirm
 4612            .as_ref()
 4613            .map_or(false, |confirm| confirm(intent, cx));
 4614        if show_new_completions_on_confirm {
 4615            self.show_completions(&ShowCompletions { trigger: None }, cx);
 4616        }
 4617
 4618        let provider = self.completion_provider.as_ref()?;
 4619        let apply_edits = provider.apply_additional_edits_for_completion(
 4620            buffer_handle,
 4621            completion.clone(),
 4622            true,
 4623            cx,
 4624        );
 4625
 4626        let editor_settings = EditorSettings::get_global(cx);
 4627        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4628            // After the code completion is finished, users often want to know what signatures are needed.
 4629            // so we should automatically call signature_help
 4630            self.show_signature_help(&ShowSignatureHelp, cx);
 4631        }
 4632
 4633        Some(cx.foreground_executor().spawn(async move {
 4634            apply_edits.await?;
 4635            Ok(())
 4636        }))
 4637    }
 4638
 4639    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 4640        let mut context_menu = self.context_menu.write();
 4641        if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4642            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4643                // Toggle if we're selecting the same one
 4644                *context_menu = None;
 4645                cx.notify();
 4646                return;
 4647            } else {
 4648                // Otherwise, clear it and start a new one
 4649                *context_menu = None;
 4650                cx.notify();
 4651            }
 4652        }
 4653        drop(context_menu);
 4654        let snapshot = self.snapshot(cx);
 4655        let deployed_from_indicator = action.deployed_from_indicator;
 4656        let mut task = self.code_actions_task.take();
 4657        let action = action.clone();
 4658        cx.spawn(|editor, mut cx| async move {
 4659            while let Some(prev_task) = task {
 4660                prev_task.await.log_err();
 4661                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4662            }
 4663
 4664            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 4665                if editor.focus_handle.is_focused(cx) {
 4666                    let multibuffer_point = action
 4667                        .deployed_from_indicator
 4668                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4669                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4670                    let (buffer, buffer_row) = snapshot
 4671                        .buffer_snapshot
 4672                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4673                        .and_then(|(buffer_snapshot, range)| {
 4674                            editor
 4675                                .buffer
 4676                                .read(cx)
 4677                                .buffer(buffer_snapshot.remote_id())
 4678                                .map(|buffer| (buffer, range.start.row))
 4679                        })?;
 4680                    let (_, code_actions) = editor
 4681                        .available_code_actions
 4682                        .clone()
 4683                        .and_then(|(location, code_actions)| {
 4684                            let snapshot = location.buffer.read(cx).snapshot();
 4685                            let point_range = location.range.to_point(&snapshot);
 4686                            let point_range = point_range.start.row..=point_range.end.row;
 4687                            if point_range.contains(&buffer_row) {
 4688                                Some((location, code_actions))
 4689                            } else {
 4690                                None
 4691                            }
 4692                        })
 4693                        .unzip();
 4694                    let buffer_id = buffer.read(cx).remote_id();
 4695                    let tasks = editor
 4696                        .tasks
 4697                        .get(&(buffer_id, buffer_row))
 4698                        .map(|t| Arc::new(t.to_owned()));
 4699                    if tasks.is_none() && code_actions.is_none() {
 4700                        return None;
 4701                    }
 4702
 4703                    editor.completion_tasks.clear();
 4704                    editor.discard_inline_completion(false, cx);
 4705                    let task_context =
 4706                        tasks
 4707                            .as_ref()
 4708                            .zip(editor.project.clone())
 4709                            .map(|(tasks, project)| {
 4710                                let position = Point::new(buffer_row, tasks.column);
 4711                                let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 4712                                let location = Location {
 4713                                    buffer: buffer.clone(),
 4714                                    range: range_start..range_start,
 4715                                };
 4716                                // Fill in the environmental variables from the tree-sitter captures
 4717                                let mut captured_task_variables = TaskVariables::default();
 4718                                for (capture_name, value) in tasks.extra_variables.clone() {
 4719                                    captured_task_variables.insert(
 4720                                        task::VariableName::Custom(capture_name.into()),
 4721                                        value.clone(),
 4722                                    );
 4723                                }
 4724                                project.update(cx, |project, cx| {
 4725                                    project.task_store().update(cx, |task_store, cx| {
 4726                                        task_store.task_context_for_location(
 4727                                            captured_task_variables,
 4728                                            location,
 4729                                            cx,
 4730                                        )
 4731                                    })
 4732                                })
 4733                            });
 4734
 4735                    Some(cx.spawn(|editor, mut cx| async move {
 4736                        let task_context = match task_context {
 4737                            Some(task_context) => task_context.await,
 4738                            None => None,
 4739                        };
 4740                        let resolved_tasks =
 4741                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4742                                Arc::new(ResolvedTasks {
 4743                                    templates: tasks
 4744                                        .templates
 4745                                        .iter()
 4746                                        .filter_map(|(kind, template)| {
 4747                                            template
 4748                                                .resolve_task(&kind.to_id_base(), &task_context)
 4749                                                .map(|task| (kind.clone(), task))
 4750                                        })
 4751                                        .collect(),
 4752                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4753                                        multibuffer_point.row,
 4754                                        tasks.column,
 4755                                    )),
 4756                                })
 4757                            });
 4758                        let spawn_straight_away = resolved_tasks
 4759                            .as_ref()
 4760                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4761                            && code_actions
 4762                                .as_ref()
 4763                                .map_or(true, |actions| actions.is_empty());
 4764                        if let Ok(task) = editor.update(&mut cx, |editor, cx| {
 4765                            *editor.context_menu.write() =
 4766                                Some(ContextMenu::CodeActions(CodeActionsMenu {
 4767                                    buffer,
 4768                                    actions: CodeActionContents {
 4769                                        tasks: resolved_tasks,
 4770                                        actions: code_actions,
 4771                                    },
 4772                                    selected_item: Default::default(),
 4773                                    scroll_handle: UniformListScrollHandle::default(),
 4774                                    deployed_from_indicator,
 4775                                }));
 4776                            if spawn_straight_away {
 4777                                if let Some(task) = editor.confirm_code_action(
 4778                                    &ConfirmCodeAction { item_ix: Some(0) },
 4779                                    cx,
 4780                                ) {
 4781                                    cx.notify();
 4782                                    return task;
 4783                                }
 4784                            }
 4785                            cx.notify();
 4786                            Task::ready(Ok(()))
 4787                        }) {
 4788                            task.await
 4789                        } else {
 4790                            Ok(())
 4791                        }
 4792                    }))
 4793                } else {
 4794                    Some(Task::ready(Ok(())))
 4795                }
 4796            })?;
 4797            if let Some(task) = spawned_test_task {
 4798                task.await?;
 4799            }
 4800
 4801            Ok::<_, anyhow::Error>(())
 4802        })
 4803        .detach_and_log_err(cx);
 4804    }
 4805
 4806    pub fn confirm_code_action(
 4807        &mut self,
 4808        action: &ConfirmCodeAction,
 4809        cx: &mut ViewContext<Self>,
 4810    ) -> Option<Task<Result<()>>> {
 4811        let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4812            menu
 4813        } else {
 4814            return None;
 4815        };
 4816        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4817        let action = actions_menu.actions.get(action_ix)?;
 4818        let title = action.label();
 4819        let buffer = actions_menu.buffer;
 4820        let workspace = self.workspace()?;
 4821
 4822        match action {
 4823            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4824                workspace.update(cx, |workspace, cx| {
 4825                    workspace::tasks::schedule_resolved_task(
 4826                        workspace,
 4827                        task_source_kind,
 4828                        resolved_task,
 4829                        false,
 4830                        cx,
 4831                    );
 4832
 4833                    Some(Task::ready(Ok(())))
 4834                })
 4835            }
 4836            CodeActionsItem::CodeAction {
 4837                excerpt_id,
 4838                action,
 4839                provider,
 4840            } => {
 4841                let apply_code_action =
 4842                    provider.apply_code_action(buffer, action, excerpt_id, true, cx);
 4843                let workspace = workspace.downgrade();
 4844                Some(cx.spawn(|editor, cx| async move {
 4845                    let project_transaction = apply_code_action.await?;
 4846                    Self::open_project_transaction(
 4847                        &editor,
 4848                        workspace,
 4849                        project_transaction,
 4850                        title,
 4851                        cx,
 4852                    )
 4853                    .await
 4854                }))
 4855            }
 4856        }
 4857    }
 4858
 4859    pub async fn open_project_transaction(
 4860        this: &WeakView<Editor>,
 4861        workspace: WeakView<Workspace>,
 4862        transaction: ProjectTransaction,
 4863        title: String,
 4864        mut cx: AsyncWindowContext,
 4865    ) -> Result<()> {
 4866        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4867        cx.update(|cx| {
 4868            entries.sort_unstable_by_key(|(buffer, _)| {
 4869                buffer.read(cx).file().map(|f| f.path().clone())
 4870            });
 4871        })?;
 4872
 4873        // If the project transaction's edits are all contained within this editor, then
 4874        // avoid opening a new editor to display them.
 4875
 4876        if let Some((buffer, transaction)) = entries.first() {
 4877            if entries.len() == 1 {
 4878                let excerpt = this.update(&mut cx, |editor, cx| {
 4879                    editor
 4880                        .buffer()
 4881                        .read(cx)
 4882                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4883                })?;
 4884                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4885                    if excerpted_buffer == *buffer {
 4886                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4887                            let excerpt_range = excerpt_range.to_offset(buffer);
 4888                            buffer
 4889                                .edited_ranges_for_transaction::<usize>(transaction)
 4890                                .all(|range| {
 4891                                    excerpt_range.start <= range.start
 4892                                        && excerpt_range.end >= range.end
 4893                                })
 4894                        })?;
 4895
 4896                        if all_edits_within_excerpt {
 4897                            return Ok(());
 4898                        }
 4899                    }
 4900                }
 4901            }
 4902        } else {
 4903            return Ok(());
 4904        }
 4905
 4906        let mut ranges_to_highlight = Vec::new();
 4907        let excerpt_buffer = cx.new_model(|cx| {
 4908            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4909            for (buffer_handle, transaction) in &entries {
 4910                let buffer = buffer_handle.read(cx);
 4911                ranges_to_highlight.extend(
 4912                    multibuffer.push_excerpts_with_context_lines(
 4913                        buffer_handle.clone(),
 4914                        buffer
 4915                            .edited_ranges_for_transaction::<usize>(transaction)
 4916                            .collect(),
 4917                        DEFAULT_MULTIBUFFER_CONTEXT,
 4918                        cx,
 4919                    ),
 4920                );
 4921            }
 4922            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4923            multibuffer
 4924        })?;
 4925
 4926        workspace.update(&mut cx, |workspace, cx| {
 4927            let project = workspace.project().clone();
 4928            let editor =
 4929                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 4930            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 4931            editor.update(cx, |editor, cx| {
 4932                editor.highlight_background::<Self>(
 4933                    &ranges_to_highlight,
 4934                    |theme| theme.editor_highlighted_line_background,
 4935                    cx,
 4936                );
 4937            });
 4938        })?;
 4939
 4940        Ok(())
 4941    }
 4942
 4943    pub fn clear_code_action_providers(&mut self) {
 4944        self.code_action_providers.clear();
 4945        self.available_code_actions.take();
 4946    }
 4947
 4948    pub fn push_code_action_provider(
 4949        &mut self,
 4950        provider: Arc<dyn CodeActionProvider>,
 4951        cx: &mut ViewContext<Self>,
 4952    ) {
 4953        self.code_action_providers.push(provider);
 4954        self.refresh_code_actions(cx);
 4955    }
 4956
 4957    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4958        let buffer = self.buffer.read(cx);
 4959        let newest_selection = self.selections.newest_anchor().clone();
 4960        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4961        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4962        if start_buffer != end_buffer {
 4963            return None;
 4964        }
 4965
 4966        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 4967            cx.background_executor()
 4968                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4969                .await;
 4970
 4971            let (providers, tasks) = this.update(&mut cx, |this, cx| {
 4972                let providers = this.code_action_providers.clone();
 4973                let tasks = this
 4974                    .code_action_providers
 4975                    .iter()
 4976                    .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
 4977                    .collect::<Vec<_>>();
 4978                (providers, tasks)
 4979            })?;
 4980
 4981            let mut actions = Vec::new();
 4982            for (provider, provider_actions) in
 4983                providers.into_iter().zip(future::join_all(tasks).await)
 4984            {
 4985                if let Some(provider_actions) = provider_actions.log_err() {
 4986                    actions.extend(provider_actions.into_iter().map(|action| {
 4987                        AvailableCodeAction {
 4988                            excerpt_id: newest_selection.start.excerpt_id,
 4989                            action,
 4990                            provider: provider.clone(),
 4991                        }
 4992                    }));
 4993                }
 4994            }
 4995
 4996            this.update(&mut cx, |this, cx| {
 4997                this.available_code_actions = if actions.is_empty() {
 4998                    None
 4999                } else {
 5000                    Some((
 5001                        Location {
 5002                            buffer: start_buffer,
 5003                            range: start..end,
 5004                        },
 5005                        actions.into(),
 5006                    ))
 5007                };
 5008                cx.notify();
 5009            })
 5010        }));
 5011        None
 5012    }
 5013
 5014    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 5015        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 5016            self.show_git_blame_inline = false;
 5017
 5018            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 5019                cx.background_executor().timer(delay).await;
 5020
 5021                this.update(&mut cx, |this, cx| {
 5022                    this.show_git_blame_inline = true;
 5023                    cx.notify();
 5024                })
 5025                .log_err();
 5026            }));
 5027        }
 5028    }
 5029
 5030    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 5031        if self.pending_rename.is_some() {
 5032            return None;
 5033        }
 5034
 5035        let provider = self.semantics_provider.clone()?;
 5036        let buffer = self.buffer.read(cx);
 5037        let newest_selection = self.selections.newest_anchor().clone();
 5038        let cursor_position = newest_selection.head();
 5039        let (cursor_buffer, cursor_buffer_position) =
 5040            buffer.text_anchor_for_position(cursor_position, cx)?;
 5041        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 5042        if cursor_buffer != tail_buffer {
 5043            return None;
 5044        }
 5045
 5046        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 5047            cx.background_executor()
 5048                .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
 5049                .await;
 5050
 5051            let highlights = if let Some(highlights) = cx
 5052                .update(|cx| {
 5053                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 5054                })
 5055                .ok()
 5056                .flatten()
 5057            {
 5058                highlights.await.log_err()
 5059            } else {
 5060                None
 5061            };
 5062
 5063            if let Some(highlights) = highlights {
 5064                this.update(&mut cx, |this, cx| {
 5065                    if this.pending_rename.is_some() {
 5066                        return;
 5067                    }
 5068
 5069                    let buffer_id = cursor_position.buffer_id;
 5070                    let buffer = this.buffer.read(cx);
 5071                    if !buffer
 5072                        .text_anchor_for_position(cursor_position, cx)
 5073                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 5074                    {
 5075                        return;
 5076                    }
 5077
 5078                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 5079                    let mut write_ranges = Vec::new();
 5080                    let mut read_ranges = Vec::new();
 5081                    for highlight in highlights {
 5082                        for (excerpt_id, excerpt_range) in
 5083                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 5084                        {
 5085                            let start = highlight
 5086                                .range
 5087                                .start
 5088                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 5089                            let end = highlight
 5090                                .range
 5091                                .end
 5092                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 5093                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 5094                                continue;
 5095                            }
 5096
 5097                            let range = Anchor {
 5098                                buffer_id,
 5099                                excerpt_id,
 5100                                text_anchor: start,
 5101                            }..Anchor {
 5102                                buffer_id,
 5103                                excerpt_id,
 5104                                text_anchor: end,
 5105                            };
 5106                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 5107                                write_ranges.push(range);
 5108                            } else {
 5109                                read_ranges.push(range);
 5110                            }
 5111                        }
 5112                    }
 5113
 5114                    this.highlight_background::<DocumentHighlightRead>(
 5115                        &read_ranges,
 5116                        |theme| theme.editor_document_highlight_read_background,
 5117                        cx,
 5118                    );
 5119                    this.highlight_background::<DocumentHighlightWrite>(
 5120                        &write_ranges,
 5121                        |theme| theme.editor_document_highlight_write_background,
 5122                        cx,
 5123                    );
 5124                    cx.notify();
 5125                })
 5126                .log_err();
 5127            }
 5128        }));
 5129        None
 5130    }
 5131
 5132    pub fn refresh_inline_completion(
 5133        &mut self,
 5134        debounce: bool,
 5135        user_requested: bool,
 5136        cx: &mut ViewContext<Self>,
 5137    ) -> Option<()> {
 5138        let provider = self.inline_completion_provider()?;
 5139        let cursor = self.selections.newest_anchor().head();
 5140        let (buffer, cursor_buffer_position) =
 5141            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5142
 5143        if !user_requested
 5144            && (!self.enable_inline_completions
 5145                || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx))
 5146        {
 5147            self.discard_inline_completion(false, cx);
 5148            return None;
 5149        }
 5150
 5151        self.update_visible_inline_completion(cx);
 5152        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 5153        Some(())
 5154    }
 5155
 5156    fn cycle_inline_completion(
 5157        &mut self,
 5158        direction: Direction,
 5159        cx: &mut ViewContext<Self>,
 5160    ) -> Option<()> {
 5161        let provider = self.inline_completion_provider()?;
 5162        let cursor = self.selections.newest_anchor().head();
 5163        let (buffer, cursor_buffer_position) =
 5164            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5165        if !self.enable_inline_completions
 5166            || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 5167        {
 5168            return None;
 5169        }
 5170
 5171        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5172        self.update_visible_inline_completion(cx);
 5173
 5174        Some(())
 5175    }
 5176
 5177    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 5178        if !self.has_active_inline_completion(cx) {
 5179            self.refresh_inline_completion(false, true, cx);
 5180            return;
 5181        }
 5182
 5183        self.update_visible_inline_completion(cx);
 5184    }
 5185
 5186    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 5187        self.show_cursor_names(cx);
 5188    }
 5189
 5190    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 5191        self.show_cursor_names = true;
 5192        cx.notify();
 5193        cx.spawn(|this, mut cx| async move {
 5194            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5195            this.update(&mut cx, |this, cx| {
 5196                this.show_cursor_names = false;
 5197                cx.notify()
 5198            })
 5199            .ok()
 5200        })
 5201        .detach();
 5202    }
 5203
 5204    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 5205        if self.has_active_inline_completion(cx) {
 5206            self.cycle_inline_completion(Direction::Next, cx);
 5207        } else {
 5208            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5209            if is_copilot_disabled {
 5210                cx.propagate();
 5211            }
 5212        }
 5213    }
 5214
 5215    pub fn previous_inline_completion(
 5216        &mut self,
 5217        _: &PreviousInlineCompletion,
 5218        cx: &mut ViewContext<Self>,
 5219    ) {
 5220        if self.has_active_inline_completion(cx) {
 5221            self.cycle_inline_completion(Direction::Prev, cx);
 5222        } else {
 5223            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5224            if is_copilot_disabled {
 5225                cx.propagate();
 5226            }
 5227        }
 5228    }
 5229
 5230    pub fn accept_inline_completion(
 5231        &mut self,
 5232        _: &AcceptInlineCompletion,
 5233        cx: &mut ViewContext<Self>,
 5234    ) {
 5235        let Some(completion) = self.take_active_inline_completion(cx) else {
 5236            return;
 5237        };
 5238        if let Some(provider) = self.inline_completion_provider() {
 5239            provider.accept(cx);
 5240        }
 5241
 5242        cx.emit(EditorEvent::InputHandled {
 5243            utf16_range_to_replace: None,
 5244            text: completion.text.to_string().into(),
 5245        });
 5246
 5247        if let Some(range) = completion.delete_range {
 5248            self.change_selections(None, cx, |s| s.select_ranges([range]))
 5249        }
 5250        self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
 5251        self.refresh_inline_completion(true, true, cx);
 5252        cx.notify();
 5253    }
 5254
 5255    pub fn accept_partial_inline_completion(
 5256        &mut self,
 5257        _: &AcceptPartialInlineCompletion,
 5258        cx: &mut ViewContext<Self>,
 5259    ) {
 5260        if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
 5261            if let Some(completion) = self.take_active_inline_completion(cx) {
 5262                let mut partial_completion = completion
 5263                    .text
 5264                    .chars()
 5265                    .by_ref()
 5266                    .take_while(|c| c.is_alphabetic())
 5267                    .collect::<String>();
 5268                if partial_completion.is_empty() {
 5269                    partial_completion = completion
 5270                        .text
 5271                        .chars()
 5272                        .by_ref()
 5273                        .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5274                        .collect::<String>();
 5275                }
 5276
 5277                cx.emit(EditorEvent::InputHandled {
 5278                    utf16_range_to_replace: None,
 5279                    text: partial_completion.clone().into(),
 5280                });
 5281
 5282                if let Some(range) = completion.delete_range {
 5283                    self.change_selections(None, cx, |s| s.select_ranges([range]))
 5284                }
 5285                self.insert_with_autoindent_mode(&partial_completion, None, cx);
 5286
 5287                self.refresh_inline_completion(true, true, cx);
 5288                cx.notify();
 5289            }
 5290        }
 5291    }
 5292
 5293    fn discard_inline_completion(
 5294        &mut self,
 5295        should_report_inline_completion_event: bool,
 5296        cx: &mut ViewContext<Self>,
 5297    ) -> bool {
 5298        if let Some(provider) = self.inline_completion_provider() {
 5299            provider.discard(should_report_inline_completion_event, cx);
 5300        }
 5301
 5302        self.take_active_inline_completion(cx).is_some()
 5303    }
 5304
 5305    pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
 5306        if let Some(completion) = self.active_inline_completion.as_ref() {
 5307            let buffer = self.buffer.read(cx).read(cx);
 5308            completion.position.is_valid(&buffer)
 5309        } else {
 5310            false
 5311        }
 5312    }
 5313
 5314    fn take_active_inline_completion(
 5315        &mut self,
 5316        cx: &mut ViewContext<Self>,
 5317    ) -> Option<CompletionState> {
 5318        let completion = self.active_inline_completion.take()?;
 5319        let render_inlay_ids = completion.render_inlay_ids.clone();
 5320        self.display_map.update(cx, |map, cx| {
 5321            map.splice_inlays(render_inlay_ids, Default::default(), cx);
 5322        });
 5323        let buffer = self.buffer.read(cx).read(cx);
 5324
 5325        if completion.position.is_valid(&buffer) {
 5326            Some(completion)
 5327        } else {
 5328            None
 5329        }
 5330    }
 5331
 5332    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
 5333        let selection = self.selections.newest_anchor();
 5334        let cursor = selection.head();
 5335
 5336        let excerpt_id = cursor.excerpt_id;
 5337
 5338        if self.context_menu.read().is_none()
 5339            && self.completion_tasks.is_empty()
 5340            && selection.start == selection.end
 5341        {
 5342            if let Some(provider) = self.inline_completion_provider() {
 5343                if let Some((buffer, cursor_buffer_position)) =
 5344                    self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5345                {
 5346                    if let Some(proposal) =
 5347                        provider.active_completion_text(&buffer, cursor_buffer_position, cx)
 5348                    {
 5349                        let mut to_remove = Vec::new();
 5350                        if let Some(completion) = self.active_inline_completion.take() {
 5351                            to_remove.extend(completion.render_inlay_ids.iter());
 5352                        }
 5353
 5354                        let to_add = proposal
 5355                            .inlays
 5356                            .iter()
 5357                            .filter_map(|inlay| {
 5358                                let snapshot = self.buffer.read(cx).snapshot(cx);
 5359                                let id = post_inc(&mut self.next_inlay_id);
 5360                                match inlay {
 5361                                    InlayProposal::Hint(position, hint) => {
 5362                                        let position =
 5363                                            snapshot.anchor_in_excerpt(excerpt_id, *position)?;
 5364                                        Some(Inlay::hint(id, position, hint))
 5365                                    }
 5366                                    InlayProposal::Suggestion(position, text) => {
 5367                                        let position =
 5368                                            snapshot.anchor_in_excerpt(excerpt_id, *position)?;
 5369                                        Some(Inlay::suggestion(id, position, text.clone()))
 5370                                    }
 5371                                }
 5372                            })
 5373                            .collect_vec();
 5374
 5375                        self.active_inline_completion = Some(CompletionState {
 5376                            position: cursor,
 5377                            text: proposal.text,
 5378                            delete_range: proposal.delete_range.and_then(|range| {
 5379                                let snapshot = self.buffer.read(cx).snapshot(cx);
 5380                                let start = snapshot.anchor_in_excerpt(excerpt_id, range.start);
 5381                                let end = snapshot.anchor_in_excerpt(excerpt_id, range.end);
 5382                                Some(start?..end?)
 5383                            }),
 5384                            render_inlay_ids: to_add.iter().map(|i| i.id).collect(),
 5385                        });
 5386
 5387                        self.display_map
 5388                            .update(cx, move |map, cx| map.splice_inlays(to_remove, to_add, cx));
 5389
 5390                        cx.notify();
 5391                        return;
 5392                    }
 5393                }
 5394            }
 5395        }
 5396
 5397        self.discard_inline_completion(false, cx);
 5398    }
 5399
 5400    fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5401        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 5402    }
 5403
 5404    fn render_code_actions_indicator(
 5405        &self,
 5406        _style: &EditorStyle,
 5407        row: DisplayRow,
 5408        is_active: bool,
 5409        cx: &mut ViewContext<Self>,
 5410    ) -> Option<IconButton> {
 5411        if self.available_code_actions.is_some() {
 5412            Some(
 5413                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5414                    .shape(ui::IconButtonShape::Square)
 5415                    .icon_size(IconSize::XSmall)
 5416                    .icon_color(Color::Muted)
 5417                    .selected(is_active)
 5418                    .tooltip({
 5419                        let focus_handle = self.focus_handle.clone();
 5420                        move |cx| {
 5421                            Tooltip::for_action_in(
 5422                                "Toggle Code Actions",
 5423                                &ToggleCodeActions {
 5424                                    deployed_from_indicator: None,
 5425                                },
 5426                                &focus_handle,
 5427                                cx,
 5428                            )
 5429                        }
 5430                    })
 5431                    .on_click(cx.listener(move |editor, _e, cx| {
 5432                        editor.focus(cx);
 5433                        editor.toggle_code_actions(
 5434                            &ToggleCodeActions {
 5435                                deployed_from_indicator: Some(row),
 5436                            },
 5437                            cx,
 5438                        );
 5439                    })),
 5440            )
 5441        } else {
 5442            None
 5443        }
 5444    }
 5445
 5446    fn clear_tasks(&mut self) {
 5447        self.tasks.clear()
 5448    }
 5449
 5450    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5451        if self.tasks.insert(key, value).is_some() {
 5452            // This case should hopefully be rare, but just in case...
 5453            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5454        }
 5455    }
 5456
 5457    fn render_run_indicator(
 5458        &self,
 5459        _style: &EditorStyle,
 5460        is_active: bool,
 5461        row: DisplayRow,
 5462        cx: &mut ViewContext<Self>,
 5463    ) -> IconButton {
 5464        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5465            .shape(ui::IconButtonShape::Square)
 5466            .icon_size(IconSize::XSmall)
 5467            .icon_color(Color::Muted)
 5468            .selected(is_active)
 5469            .on_click(cx.listener(move |editor, _e, cx| {
 5470                editor.focus(cx);
 5471                editor.toggle_code_actions(
 5472                    &ToggleCodeActions {
 5473                        deployed_from_indicator: Some(row),
 5474                    },
 5475                    cx,
 5476                );
 5477            }))
 5478    }
 5479
 5480    pub fn context_menu_visible(&self) -> bool {
 5481        self.context_menu
 5482            .read()
 5483            .as_ref()
 5484            .map_or(false, |menu| menu.visible())
 5485    }
 5486
 5487    fn render_context_menu(
 5488        &self,
 5489        cursor_position: DisplayPoint,
 5490        style: &EditorStyle,
 5491        max_height: Pixels,
 5492        cx: &mut ViewContext<Editor>,
 5493    ) -> Option<(ContextMenuOrigin, AnyElement)> {
 5494        self.context_menu.read().as_ref().map(|menu| {
 5495            menu.render(
 5496                cursor_position,
 5497                style,
 5498                max_height,
 5499                self.workspace.as_ref().map(|(w, _)| w.clone()),
 5500                cx,
 5501            )
 5502        })
 5503    }
 5504
 5505    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
 5506        cx.notify();
 5507        self.completion_tasks.clear();
 5508        let context_menu = self.context_menu.write().take();
 5509        if context_menu.is_some() {
 5510            self.update_visible_inline_completion(cx);
 5511        }
 5512        context_menu
 5513    }
 5514
 5515    pub fn insert_snippet(
 5516        &mut self,
 5517        insertion_ranges: &[Range<usize>],
 5518        snippet: Snippet,
 5519        cx: &mut ViewContext<Self>,
 5520    ) -> Result<()> {
 5521        struct Tabstop<T> {
 5522            is_end_tabstop: bool,
 5523            ranges: Vec<Range<T>>,
 5524        }
 5525
 5526        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5527            let snippet_text: Arc<str> = snippet.text.clone().into();
 5528            buffer.edit(
 5529                insertion_ranges
 5530                    .iter()
 5531                    .cloned()
 5532                    .map(|range| (range, snippet_text.clone())),
 5533                Some(AutoindentMode::EachLine),
 5534                cx,
 5535            );
 5536
 5537            let snapshot = &*buffer.read(cx);
 5538            let snippet = &snippet;
 5539            snippet
 5540                .tabstops
 5541                .iter()
 5542                .map(|tabstop| {
 5543                    let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
 5544                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5545                    });
 5546                    let mut tabstop_ranges = tabstop
 5547                        .iter()
 5548                        .flat_map(|tabstop_range| {
 5549                            let mut delta = 0_isize;
 5550                            insertion_ranges.iter().map(move |insertion_range| {
 5551                                let insertion_start = insertion_range.start as isize + delta;
 5552                                delta +=
 5553                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5554
 5555                                let start = ((insertion_start + tabstop_range.start) as usize)
 5556                                    .min(snapshot.len());
 5557                                let end = ((insertion_start + tabstop_range.end) as usize)
 5558                                    .min(snapshot.len());
 5559                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5560                            })
 5561                        })
 5562                        .collect::<Vec<_>>();
 5563                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5564
 5565                    Tabstop {
 5566                        is_end_tabstop,
 5567                        ranges: tabstop_ranges,
 5568                    }
 5569                })
 5570                .collect::<Vec<_>>()
 5571        });
 5572        if let Some(tabstop) = tabstops.first() {
 5573            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5574                s.select_ranges(tabstop.ranges.iter().cloned());
 5575            });
 5576
 5577            // If we're already at the last tabstop and it's at the end of the snippet,
 5578            // we're done, we don't need to keep the state around.
 5579            if !tabstop.is_end_tabstop {
 5580                let ranges = tabstops
 5581                    .into_iter()
 5582                    .map(|tabstop| tabstop.ranges)
 5583                    .collect::<Vec<_>>();
 5584                self.snippet_stack.push(SnippetState {
 5585                    active_index: 0,
 5586                    ranges,
 5587                });
 5588            }
 5589
 5590            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5591            if self.autoclose_regions.is_empty() {
 5592                let snapshot = self.buffer.read(cx).snapshot(cx);
 5593                for selection in &mut self.selections.all::<Point>(cx) {
 5594                    let selection_head = selection.head();
 5595                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5596                        continue;
 5597                    };
 5598
 5599                    let mut bracket_pair = None;
 5600                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5601                    let prev_chars = snapshot
 5602                        .reversed_chars_at(selection_head)
 5603                        .collect::<String>();
 5604                    for (pair, enabled) in scope.brackets() {
 5605                        if enabled
 5606                            && pair.close
 5607                            && prev_chars.starts_with(pair.start.as_str())
 5608                            && next_chars.starts_with(pair.end.as_str())
 5609                        {
 5610                            bracket_pair = Some(pair.clone());
 5611                            break;
 5612                        }
 5613                    }
 5614                    if let Some(pair) = bracket_pair {
 5615                        let start = snapshot.anchor_after(selection_head);
 5616                        let end = snapshot.anchor_after(selection_head);
 5617                        self.autoclose_regions.push(AutocloseRegion {
 5618                            selection_id: selection.id,
 5619                            range: start..end,
 5620                            pair,
 5621                        });
 5622                    }
 5623                }
 5624            }
 5625        }
 5626        Ok(())
 5627    }
 5628
 5629    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5630        self.move_to_snippet_tabstop(Bias::Right, cx)
 5631    }
 5632
 5633    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5634        self.move_to_snippet_tabstop(Bias::Left, cx)
 5635    }
 5636
 5637    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5638        if let Some(mut snippet) = self.snippet_stack.pop() {
 5639            match bias {
 5640                Bias::Left => {
 5641                    if snippet.active_index > 0 {
 5642                        snippet.active_index -= 1;
 5643                    } else {
 5644                        self.snippet_stack.push(snippet);
 5645                        return false;
 5646                    }
 5647                }
 5648                Bias::Right => {
 5649                    if snippet.active_index + 1 < snippet.ranges.len() {
 5650                        snippet.active_index += 1;
 5651                    } else {
 5652                        self.snippet_stack.push(snippet);
 5653                        return false;
 5654                    }
 5655                }
 5656            }
 5657            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5658                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5659                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5660                });
 5661                // If snippet state is not at the last tabstop, push it back on the stack
 5662                if snippet.active_index + 1 < snippet.ranges.len() {
 5663                    self.snippet_stack.push(snippet);
 5664                }
 5665                return true;
 5666            }
 5667        }
 5668
 5669        false
 5670    }
 5671
 5672    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 5673        self.transact(cx, |this, cx| {
 5674            this.select_all(&SelectAll, cx);
 5675            this.insert("", cx);
 5676        });
 5677    }
 5678
 5679    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 5680        self.transact(cx, |this, cx| {
 5681            this.select_autoclose_pair(cx);
 5682            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5683            if !this.linked_edit_ranges.is_empty() {
 5684                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5685                let snapshot = this.buffer.read(cx).snapshot(cx);
 5686
 5687                for selection in selections.iter() {
 5688                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5689                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 5690                    if selection_start.buffer_id != selection_end.buffer_id {
 5691                        continue;
 5692                    }
 5693                    if let Some(ranges) =
 5694                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 5695                    {
 5696                        for (buffer, entries) in ranges {
 5697                            linked_ranges.entry(buffer).or_default().extend(entries);
 5698                        }
 5699                    }
 5700                }
 5701            }
 5702
 5703            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 5704            if !this.selections.line_mode {
 5705                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 5706                for selection in &mut selections {
 5707                    if selection.is_empty() {
 5708                        let old_head = selection.head();
 5709                        let mut new_head =
 5710                            movement::left(&display_map, old_head.to_display_point(&display_map))
 5711                                .to_point(&display_map);
 5712                        if let Some((buffer, line_buffer_range)) = display_map
 5713                            .buffer_snapshot
 5714                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 5715                        {
 5716                            let indent_size =
 5717                                buffer.indent_size_for_line(line_buffer_range.start.row);
 5718                            let indent_len = match indent_size.kind {
 5719                                IndentKind::Space => {
 5720                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 5721                                }
 5722                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 5723                            };
 5724                            if old_head.column <= indent_size.len && old_head.column > 0 {
 5725                                let indent_len = indent_len.get();
 5726                                new_head = cmp::min(
 5727                                    new_head,
 5728                                    MultiBufferPoint::new(
 5729                                        old_head.row,
 5730                                        ((old_head.column - 1) / indent_len) * indent_len,
 5731                                    ),
 5732                                );
 5733                            }
 5734                        }
 5735
 5736                        selection.set_head(new_head, SelectionGoal::None);
 5737                    }
 5738                }
 5739            }
 5740
 5741            this.signature_help_state.set_backspace_pressed(true);
 5742            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5743            this.insert("", cx);
 5744            let empty_str: Arc<str> = Arc::from("");
 5745            for (buffer, edits) in linked_ranges {
 5746                let snapshot = buffer.read(cx).snapshot();
 5747                use text::ToPoint as TP;
 5748
 5749                let edits = edits
 5750                    .into_iter()
 5751                    .map(|range| {
 5752                        let end_point = TP::to_point(&range.end, &snapshot);
 5753                        let mut start_point = TP::to_point(&range.start, &snapshot);
 5754
 5755                        if end_point == start_point {
 5756                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 5757                                .saturating_sub(1);
 5758                            start_point = TP::to_point(&offset, &snapshot);
 5759                        };
 5760
 5761                        (start_point..end_point, empty_str.clone())
 5762                    })
 5763                    .sorted_by_key(|(range, _)| range.start)
 5764                    .collect::<Vec<_>>();
 5765                buffer.update(cx, |this, cx| {
 5766                    this.edit(edits, None, cx);
 5767                })
 5768            }
 5769            this.refresh_inline_completion(true, false, cx);
 5770            linked_editing_ranges::refresh_linked_ranges(this, cx);
 5771        });
 5772    }
 5773
 5774    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 5775        self.transact(cx, |this, cx| {
 5776            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5777                let line_mode = s.line_mode;
 5778                s.move_with(|map, selection| {
 5779                    if selection.is_empty() && !line_mode {
 5780                        let cursor = movement::right(map, selection.head());
 5781                        selection.end = cursor;
 5782                        selection.reversed = true;
 5783                        selection.goal = SelectionGoal::None;
 5784                    }
 5785                })
 5786            });
 5787            this.insert("", cx);
 5788            this.refresh_inline_completion(true, false, cx);
 5789        });
 5790    }
 5791
 5792    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 5793        if self.move_to_prev_snippet_tabstop(cx) {
 5794            return;
 5795        }
 5796
 5797        self.outdent(&Outdent, cx);
 5798    }
 5799
 5800    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 5801        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 5802            return;
 5803        }
 5804
 5805        let mut selections = self.selections.all_adjusted(cx);
 5806        let buffer = self.buffer.read(cx);
 5807        let snapshot = buffer.snapshot(cx);
 5808        let rows_iter = selections.iter().map(|s| s.head().row);
 5809        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 5810
 5811        let mut edits = Vec::new();
 5812        let mut prev_edited_row = 0;
 5813        let mut row_delta = 0;
 5814        for selection in &mut selections {
 5815            if selection.start.row != prev_edited_row {
 5816                row_delta = 0;
 5817            }
 5818            prev_edited_row = selection.end.row;
 5819
 5820            // If the selection is non-empty, then increase the indentation of the selected lines.
 5821            if !selection.is_empty() {
 5822                row_delta =
 5823                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5824                continue;
 5825            }
 5826
 5827            // If the selection is empty and the cursor is in the leading whitespace before the
 5828            // suggested indentation, then auto-indent the line.
 5829            let cursor = selection.head();
 5830            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 5831            if let Some(suggested_indent) =
 5832                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 5833            {
 5834                if cursor.column < suggested_indent.len
 5835                    && cursor.column <= current_indent.len
 5836                    && current_indent.len <= suggested_indent.len
 5837                {
 5838                    selection.start = Point::new(cursor.row, suggested_indent.len);
 5839                    selection.end = selection.start;
 5840                    if row_delta == 0 {
 5841                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 5842                            cursor.row,
 5843                            current_indent,
 5844                            suggested_indent,
 5845                        ));
 5846                        row_delta = suggested_indent.len - current_indent.len;
 5847                    }
 5848                    continue;
 5849                }
 5850            }
 5851
 5852            // Otherwise, insert a hard or soft tab.
 5853            let settings = buffer.settings_at(cursor, cx);
 5854            let tab_size = if settings.hard_tabs {
 5855                IndentSize::tab()
 5856            } else {
 5857                let tab_size = settings.tab_size.get();
 5858                let char_column = snapshot
 5859                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 5860                    .flat_map(str::chars)
 5861                    .count()
 5862                    + row_delta as usize;
 5863                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 5864                IndentSize::spaces(chars_to_next_tab_stop)
 5865            };
 5866            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 5867            selection.end = selection.start;
 5868            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 5869            row_delta += tab_size.len;
 5870        }
 5871
 5872        self.transact(cx, |this, cx| {
 5873            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5874            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5875            this.refresh_inline_completion(true, false, cx);
 5876        });
 5877    }
 5878
 5879    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 5880        if self.read_only(cx) {
 5881            return;
 5882        }
 5883        let mut selections = self.selections.all::<Point>(cx);
 5884        let mut prev_edited_row = 0;
 5885        let mut row_delta = 0;
 5886        let mut edits = Vec::new();
 5887        let buffer = self.buffer.read(cx);
 5888        let snapshot = buffer.snapshot(cx);
 5889        for selection in &mut selections {
 5890            if selection.start.row != prev_edited_row {
 5891                row_delta = 0;
 5892            }
 5893            prev_edited_row = selection.end.row;
 5894
 5895            row_delta =
 5896                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5897        }
 5898
 5899        self.transact(cx, |this, cx| {
 5900            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5901            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5902        });
 5903    }
 5904
 5905    fn indent_selection(
 5906        buffer: &MultiBuffer,
 5907        snapshot: &MultiBufferSnapshot,
 5908        selection: &mut Selection<Point>,
 5909        edits: &mut Vec<(Range<Point>, String)>,
 5910        delta_for_start_row: u32,
 5911        cx: &AppContext,
 5912    ) -> u32 {
 5913        let settings = buffer.settings_at(selection.start, cx);
 5914        let tab_size = settings.tab_size.get();
 5915        let indent_kind = if settings.hard_tabs {
 5916            IndentKind::Tab
 5917        } else {
 5918            IndentKind::Space
 5919        };
 5920        let mut start_row = selection.start.row;
 5921        let mut end_row = selection.end.row + 1;
 5922
 5923        // If a selection ends at the beginning of a line, don't indent
 5924        // that last line.
 5925        if selection.end.column == 0 && selection.end.row > selection.start.row {
 5926            end_row -= 1;
 5927        }
 5928
 5929        // Avoid re-indenting a row that has already been indented by a
 5930        // previous selection, but still update this selection's column
 5931        // to reflect that indentation.
 5932        if delta_for_start_row > 0 {
 5933            start_row += 1;
 5934            selection.start.column += delta_for_start_row;
 5935            if selection.end.row == selection.start.row {
 5936                selection.end.column += delta_for_start_row;
 5937            }
 5938        }
 5939
 5940        let mut delta_for_end_row = 0;
 5941        let has_multiple_rows = start_row + 1 != end_row;
 5942        for row in start_row..end_row {
 5943            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 5944            let indent_delta = match (current_indent.kind, indent_kind) {
 5945                (IndentKind::Space, IndentKind::Space) => {
 5946                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 5947                    IndentSize::spaces(columns_to_next_tab_stop)
 5948                }
 5949                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 5950                (_, IndentKind::Tab) => IndentSize::tab(),
 5951            };
 5952
 5953            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 5954                0
 5955            } else {
 5956                selection.start.column
 5957            };
 5958            let row_start = Point::new(row, start);
 5959            edits.push((
 5960                row_start..row_start,
 5961                indent_delta.chars().collect::<String>(),
 5962            ));
 5963
 5964            // Update this selection's endpoints to reflect the indentation.
 5965            if row == selection.start.row {
 5966                selection.start.column += indent_delta.len;
 5967            }
 5968            if row == selection.end.row {
 5969                selection.end.column += indent_delta.len;
 5970                delta_for_end_row = indent_delta.len;
 5971            }
 5972        }
 5973
 5974        if selection.start.row == selection.end.row {
 5975            delta_for_start_row + delta_for_end_row
 5976        } else {
 5977            delta_for_end_row
 5978        }
 5979    }
 5980
 5981    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 5982        if self.read_only(cx) {
 5983            return;
 5984        }
 5985        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5986        let selections = self.selections.all::<Point>(cx);
 5987        let mut deletion_ranges = Vec::new();
 5988        let mut last_outdent = None;
 5989        {
 5990            let buffer = self.buffer.read(cx);
 5991            let snapshot = buffer.snapshot(cx);
 5992            for selection in &selections {
 5993                let settings = buffer.settings_at(selection.start, cx);
 5994                let tab_size = settings.tab_size.get();
 5995                let mut rows = selection.spanned_rows(false, &display_map);
 5996
 5997                // Avoid re-outdenting a row that has already been outdented by a
 5998                // previous selection.
 5999                if let Some(last_row) = last_outdent {
 6000                    if last_row == rows.start {
 6001                        rows.start = rows.start.next_row();
 6002                    }
 6003                }
 6004                let has_multiple_rows = rows.len() > 1;
 6005                for row in rows.iter_rows() {
 6006                    let indent_size = snapshot.indent_size_for_line(row);
 6007                    if indent_size.len > 0 {
 6008                        let deletion_len = match indent_size.kind {
 6009                            IndentKind::Space => {
 6010                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 6011                                if columns_to_prev_tab_stop == 0 {
 6012                                    tab_size
 6013                                } else {
 6014                                    columns_to_prev_tab_stop
 6015                                }
 6016                            }
 6017                            IndentKind::Tab => 1,
 6018                        };
 6019                        let start = if has_multiple_rows
 6020                            || deletion_len > selection.start.column
 6021                            || indent_size.len < selection.start.column
 6022                        {
 6023                            0
 6024                        } else {
 6025                            selection.start.column - deletion_len
 6026                        };
 6027                        deletion_ranges.push(
 6028                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 6029                        );
 6030                        last_outdent = Some(row);
 6031                    }
 6032                }
 6033            }
 6034        }
 6035
 6036        self.transact(cx, |this, cx| {
 6037            this.buffer.update(cx, |buffer, cx| {
 6038                let empty_str: Arc<str> = Arc::default();
 6039                buffer.edit(
 6040                    deletion_ranges
 6041                        .into_iter()
 6042                        .map(|range| (range, empty_str.clone())),
 6043                    None,
 6044                    cx,
 6045                );
 6046            });
 6047            let selections = this.selections.all::<usize>(cx);
 6048            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6049        });
 6050    }
 6051
 6052    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 6053        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6054        let selections = self.selections.all::<Point>(cx);
 6055
 6056        let mut new_cursors = Vec::new();
 6057        let mut edit_ranges = Vec::new();
 6058        let mut selections = selections.iter().peekable();
 6059        while let Some(selection) = selections.next() {
 6060            let mut rows = selection.spanned_rows(false, &display_map);
 6061            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6062
 6063            // Accumulate contiguous regions of rows that we want to delete.
 6064            while let Some(next_selection) = selections.peek() {
 6065                let next_rows = next_selection.spanned_rows(false, &display_map);
 6066                if next_rows.start <= rows.end {
 6067                    rows.end = next_rows.end;
 6068                    selections.next().unwrap();
 6069                } else {
 6070                    break;
 6071                }
 6072            }
 6073
 6074            let buffer = &display_map.buffer_snapshot;
 6075            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6076            let edit_end;
 6077            let cursor_buffer_row;
 6078            if buffer.max_point().row >= rows.end.0 {
 6079                // If there's a line after the range, delete the \n from the end of the row range
 6080                // and position the cursor on the next line.
 6081                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6082                cursor_buffer_row = rows.end;
 6083            } else {
 6084                // If there isn't a line after the range, delete the \n from the line before the
 6085                // start of the row range and position the cursor there.
 6086                edit_start = edit_start.saturating_sub(1);
 6087                edit_end = buffer.len();
 6088                cursor_buffer_row = rows.start.previous_row();
 6089            }
 6090
 6091            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6092            *cursor.column_mut() =
 6093                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6094
 6095            new_cursors.push((
 6096                selection.id,
 6097                buffer.anchor_after(cursor.to_point(&display_map)),
 6098            ));
 6099            edit_ranges.push(edit_start..edit_end);
 6100        }
 6101
 6102        self.transact(cx, |this, cx| {
 6103            let buffer = this.buffer.update(cx, |buffer, cx| {
 6104                let empty_str: Arc<str> = Arc::default();
 6105                buffer.edit(
 6106                    edit_ranges
 6107                        .into_iter()
 6108                        .map(|range| (range, empty_str.clone())),
 6109                    None,
 6110                    cx,
 6111                );
 6112                buffer.snapshot(cx)
 6113            });
 6114            let new_selections = new_cursors
 6115                .into_iter()
 6116                .map(|(id, cursor)| {
 6117                    let cursor = cursor.to_point(&buffer);
 6118                    Selection {
 6119                        id,
 6120                        start: cursor,
 6121                        end: cursor,
 6122                        reversed: false,
 6123                        goal: SelectionGoal::None,
 6124                    }
 6125                })
 6126                .collect();
 6127
 6128            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6129                s.select(new_selections);
 6130            });
 6131        });
 6132    }
 6133
 6134    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 6135        if self.read_only(cx) {
 6136            return;
 6137        }
 6138        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6139        for selection in self.selections.all::<Point>(cx) {
 6140            let start = MultiBufferRow(selection.start.row);
 6141            let end = if selection.start.row == selection.end.row {
 6142                MultiBufferRow(selection.start.row + 1)
 6143            } else {
 6144                MultiBufferRow(selection.end.row)
 6145            };
 6146
 6147            if let Some(last_row_range) = row_ranges.last_mut() {
 6148                if start <= last_row_range.end {
 6149                    last_row_range.end = end;
 6150                    continue;
 6151                }
 6152            }
 6153            row_ranges.push(start..end);
 6154        }
 6155
 6156        let snapshot = self.buffer.read(cx).snapshot(cx);
 6157        let mut cursor_positions = Vec::new();
 6158        for row_range in &row_ranges {
 6159            let anchor = snapshot.anchor_before(Point::new(
 6160                row_range.end.previous_row().0,
 6161                snapshot.line_len(row_range.end.previous_row()),
 6162            ));
 6163            cursor_positions.push(anchor..anchor);
 6164        }
 6165
 6166        self.transact(cx, |this, cx| {
 6167            for row_range in row_ranges.into_iter().rev() {
 6168                for row in row_range.iter_rows().rev() {
 6169                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6170                    let next_line_row = row.next_row();
 6171                    let indent = snapshot.indent_size_for_line(next_line_row);
 6172                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 6173
 6174                    let replace = if snapshot.line_len(next_line_row) > indent.len {
 6175                        " "
 6176                    } else {
 6177                        ""
 6178                    };
 6179
 6180                    this.buffer.update(cx, |buffer, cx| {
 6181                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6182                    });
 6183                }
 6184            }
 6185
 6186            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6187                s.select_anchor_ranges(cursor_positions)
 6188            });
 6189        });
 6190    }
 6191
 6192    pub fn sort_lines_case_sensitive(
 6193        &mut self,
 6194        _: &SortLinesCaseSensitive,
 6195        cx: &mut ViewContext<Self>,
 6196    ) {
 6197        self.manipulate_lines(cx, |lines| lines.sort())
 6198    }
 6199
 6200    pub fn sort_lines_case_insensitive(
 6201        &mut self,
 6202        _: &SortLinesCaseInsensitive,
 6203        cx: &mut ViewContext<Self>,
 6204    ) {
 6205        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 6206    }
 6207
 6208    pub fn unique_lines_case_insensitive(
 6209        &mut self,
 6210        _: &UniqueLinesCaseInsensitive,
 6211        cx: &mut ViewContext<Self>,
 6212    ) {
 6213        self.manipulate_lines(cx, |lines| {
 6214            let mut seen = HashSet::default();
 6215            lines.retain(|line| seen.insert(line.to_lowercase()));
 6216        })
 6217    }
 6218
 6219    pub fn unique_lines_case_sensitive(
 6220        &mut self,
 6221        _: &UniqueLinesCaseSensitive,
 6222        cx: &mut ViewContext<Self>,
 6223    ) {
 6224        self.manipulate_lines(cx, |lines| {
 6225            let mut seen = HashSet::default();
 6226            lines.retain(|line| seen.insert(*line));
 6227        })
 6228    }
 6229
 6230    pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
 6231        let mut revert_changes = HashMap::default();
 6232        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 6233        for hunk in hunks_for_rows(
 6234            Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
 6235            &multi_buffer_snapshot,
 6236        ) {
 6237            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 6238        }
 6239        if !revert_changes.is_empty() {
 6240            self.transact(cx, |editor, cx| {
 6241                editor.revert(revert_changes, cx);
 6242            });
 6243        }
 6244    }
 6245
 6246    pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
 6247        let Some(project) = self.project.clone() else {
 6248            return;
 6249        };
 6250        self.reload(project, cx).detach_and_notify_err(cx);
 6251    }
 6252
 6253    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 6254        let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
 6255        if !revert_changes.is_empty() {
 6256            self.transact(cx, |editor, cx| {
 6257                editor.revert(revert_changes, cx);
 6258            });
 6259        }
 6260    }
 6261
 6262    fn apply_selected_diff_hunks(&mut self, _: &ApplyDiffHunk, cx: &mut ViewContext<Self>) {
 6263        let snapshot = self.buffer.read(cx).snapshot(cx);
 6264        let hunks = hunks_for_selections(&snapshot, &self.selections.disjoint_anchors());
 6265        let mut ranges_by_buffer = HashMap::default();
 6266        self.transact(cx, |editor, cx| {
 6267            for hunk in hunks {
 6268                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
 6269                    ranges_by_buffer
 6270                        .entry(buffer.clone())
 6271                        .or_insert_with(Vec::new)
 6272                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
 6273                }
 6274            }
 6275
 6276            for (buffer, ranges) in ranges_by_buffer {
 6277                buffer.update(cx, |buffer, cx| {
 6278                    buffer.merge_into_base(ranges, cx);
 6279                });
 6280            }
 6281        });
 6282    }
 6283
 6284    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 6285        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6286            let project_path = buffer.read(cx).project_path(cx)?;
 6287            let project = self.project.as_ref()?.read(cx);
 6288            let entry = project.entry_for_path(&project_path, cx)?;
 6289            let abs_path = project.absolute_path(&project_path, cx)?;
 6290            let parent = if entry.is_symlink {
 6291                abs_path.canonicalize().ok()?
 6292            } else {
 6293                abs_path
 6294            }
 6295            .parent()?
 6296            .to_path_buf();
 6297            Some(parent)
 6298        }) {
 6299            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 6300        }
 6301    }
 6302
 6303    fn gather_revert_changes(
 6304        &mut self,
 6305        selections: &[Selection<Anchor>],
 6306        cx: &mut ViewContext<'_, Editor>,
 6307    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 6308        let mut revert_changes = HashMap::default();
 6309        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 6310        for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
 6311            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 6312        }
 6313        revert_changes
 6314    }
 6315
 6316    pub fn prepare_revert_change(
 6317        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6318        multi_buffer: &Model<MultiBuffer>,
 6319        hunk: &MultiBufferDiffHunk,
 6320        cx: &AppContext,
 6321    ) -> Option<()> {
 6322        let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
 6323        let buffer = buffer.read(cx);
 6324        let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
 6325        let buffer_snapshot = buffer.snapshot();
 6326        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6327        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6328            probe
 6329                .0
 6330                .start
 6331                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6332                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6333        }) {
 6334            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6335            Some(())
 6336        } else {
 6337            None
 6338        }
 6339    }
 6340
 6341    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 6342        self.manipulate_lines(cx, |lines| lines.reverse())
 6343    }
 6344
 6345    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 6346        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 6347    }
 6348
 6349    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6350    where
 6351        Fn: FnMut(&mut Vec<&str>),
 6352    {
 6353        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6354        let buffer = self.buffer.read(cx).snapshot(cx);
 6355
 6356        let mut edits = Vec::new();
 6357
 6358        let selections = self.selections.all::<Point>(cx);
 6359        let mut selections = selections.iter().peekable();
 6360        let mut contiguous_row_selections = Vec::new();
 6361        let mut new_selections = Vec::new();
 6362        let mut added_lines = 0;
 6363        let mut removed_lines = 0;
 6364
 6365        while let Some(selection) = selections.next() {
 6366            let (start_row, end_row) = consume_contiguous_rows(
 6367                &mut contiguous_row_selections,
 6368                selection,
 6369                &display_map,
 6370                &mut selections,
 6371            );
 6372
 6373            let start_point = Point::new(start_row.0, 0);
 6374            let end_point = Point::new(
 6375                end_row.previous_row().0,
 6376                buffer.line_len(end_row.previous_row()),
 6377            );
 6378            let text = buffer
 6379                .text_for_range(start_point..end_point)
 6380                .collect::<String>();
 6381
 6382            let mut lines = text.split('\n').collect_vec();
 6383
 6384            let lines_before = lines.len();
 6385            callback(&mut lines);
 6386            let lines_after = lines.len();
 6387
 6388            edits.push((start_point..end_point, lines.join("\n")));
 6389
 6390            // Selections must change based on added and removed line count
 6391            let start_row =
 6392                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6393            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6394            new_selections.push(Selection {
 6395                id: selection.id,
 6396                start: start_row,
 6397                end: end_row,
 6398                goal: SelectionGoal::None,
 6399                reversed: selection.reversed,
 6400            });
 6401
 6402            if lines_after > lines_before {
 6403                added_lines += lines_after - lines_before;
 6404            } else if lines_before > lines_after {
 6405                removed_lines += lines_before - lines_after;
 6406            }
 6407        }
 6408
 6409        self.transact(cx, |this, cx| {
 6410            let buffer = this.buffer.update(cx, |buffer, cx| {
 6411                buffer.edit(edits, None, cx);
 6412                buffer.snapshot(cx)
 6413            });
 6414
 6415            // Recalculate offsets on newly edited buffer
 6416            let new_selections = new_selections
 6417                .iter()
 6418                .map(|s| {
 6419                    let start_point = Point::new(s.start.0, 0);
 6420                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6421                    Selection {
 6422                        id: s.id,
 6423                        start: buffer.point_to_offset(start_point),
 6424                        end: buffer.point_to_offset(end_point),
 6425                        goal: s.goal,
 6426                        reversed: s.reversed,
 6427                    }
 6428                })
 6429                .collect();
 6430
 6431            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6432                s.select(new_selections);
 6433            });
 6434
 6435            this.request_autoscroll(Autoscroll::fit(), cx);
 6436        });
 6437    }
 6438
 6439    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 6440        self.manipulate_text(cx, |text| text.to_uppercase())
 6441    }
 6442
 6443    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 6444        self.manipulate_text(cx, |text| text.to_lowercase())
 6445    }
 6446
 6447    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 6448        self.manipulate_text(cx, |text| {
 6449            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6450            // https://github.com/rutrum/convert-case/issues/16
 6451            text.split('\n')
 6452                .map(|line| line.to_case(Case::Title))
 6453                .join("\n")
 6454        })
 6455    }
 6456
 6457    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6458        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6459    }
 6460
 6461    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6462        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6463    }
 6464
 6465    pub fn convert_to_upper_camel_case(
 6466        &mut self,
 6467        _: &ConvertToUpperCamelCase,
 6468        cx: &mut ViewContext<Self>,
 6469    ) {
 6470        self.manipulate_text(cx, |text| {
 6471            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6472            // https://github.com/rutrum/convert-case/issues/16
 6473            text.split('\n')
 6474                .map(|line| line.to_case(Case::UpperCamel))
 6475                .join("\n")
 6476        })
 6477    }
 6478
 6479    pub fn convert_to_lower_camel_case(
 6480        &mut self,
 6481        _: &ConvertToLowerCamelCase,
 6482        cx: &mut ViewContext<Self>,
 6483    ) {
 6484        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6485    }
 6486
 6487    pub fn convert_to_opposite_case(
 6488        &mut self,
 6489        _: &ConvertToOppositeCase,
 6490        cx: &mut ViewContext<Self>,
 6491    ) {
 6492        self.manipulate_text(cx, |text| {
 6493            text.chars()
 6494                .fold(String::with_capacity(text.len()), |mut t, c| {
 6495                    if c.is_uppercase() {
 6496                        t.extend(c.to_lowercase());
 6497                    } else {
 6498                        t.extend(c.to_uppercase());
 6499                    }
 6500                    t
 6501                })
 6502        })
 6503    }
 6504
 6505    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6506    where
 6507        Fn: FnMut(&str) -> String,
 6508    {
 6509        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6510        let buffer = self.buffer.read(cx).snapshot(cx);
 6511
 6512        let mut new_selections = Vec::new();
 6513        let mut edits = Vec::new();
 6514        let mut selection_adjustment = 0i32;
 6515
 6516        for selection in self.selections.all::<usize>(cx) {
 6517            let selection_is_empty = selection.is_empty();
 6518
 6519            let (start, end) = if selection_is_empty {
 6520                let word_range = movement::surrounding_word(
 6521                    &display_map,
 6522                    selection.start.to_display_point(&display_map),
 6523                );
 6524                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6525                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6526                (start, end)
 6527            } else {
 6528                (selection.start, selection.end)
 6529            };
 6530
 6531            let text = buffer.text_for_range(start..end).collect::<String>();
 6532            let old_length = text.len() as i32;
 6533            let text = callback(&text);
 6534
 6535            new_selections.push(Selection {
 6536                start: (start as i32 - selection_adjustment) as usize,
 6537                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6538                goal: SelectionGoal::None,
 6539                ..selection
 6540            });
 6541
 6542            selection_adjustment += old_length - text.len() as i32;
 6543
 6544            edits.push((start..end, text));
 6545        }
 6546
 6547        self.transact(cx, |this, cx| {
 6548            this.buffer.update(cx, |buffer, cx| {
 6549                buffer.edit(edits, None, cx);
 6550            });
 6551
 6552            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6553                s.select(new_selections);
 6554            });
 6555
 6556            this.request_autoscroll(Autoscroll::fit(), cx);
 6557        });
 6558    }
 6559
 6560    pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
 6561        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6562        let buffer = &display_map.buffer_snapshot;
 6563        let selections = self.selections.all::<Point>(cx);
 6564
 6565        let mut edits = Vec::new();
 6566        let mut selections_iter = selections.iter().peekable();
 6567        while let Some(selection) = selections_iter.next() {
 6568            // Avoid duplicating the same lines twice.
 6569            let mut rows = selection.spanned_rows(false, &display_map);
 6570
 6571            while let Some(next_selection) = selections_iter.peek() {
 6572                let next_rows = next_selection.spanned_rows(false, &display_map);
 6573                if next_rows.start < rows.end {
 6574                    rows.end = next_rows.end;
 6575                    selections_iter.next().unwrap();
 6576                } else {
 6577                    break;
 6578                }
 6579            }
 6580
 6581            // Copy the text from the selected row region and splice it either at the start
 6582            // or end of the region.
 6583            let start = Point::new(rows.start.0, 0);
 6584            let end = Point::new(
 6585                rows.end.previous_row().0,
 6586                buffer.line_len(rows.end.previous_row()),
 6587            );
 6588            let text = buffer
 6589                .text_for_range(start..end)
 6590                .chain(Some("\n"))
 6591                .collect::<String>();
 6592            let insert_location = if upwards {
 6593                Point::new(rows.end.0, 0)
 6594            } else {
 6595                start
 6596            };
 6597            edits.push((insert_location..insert_location, text));
 6598        }
 6599
 6600        self.transact(cx, |this, cx| {
 6601            this.buffer.update(cx, |buffer, cx| {
 6602                buffer.edit(edits, None, cx);
 6603            });
 6604
 6605            this.request_autoscroll(Autoscroll::fit(), cx);
 6606        });
 6607    }
 6608
 6609    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6610        self.duplicate_line(true, cx);
 6611    }
 6612
 6613    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6614        self.duplicate_line(false, cx);
 6615    }
 6616
 6617    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6618        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6619        let buffer = self.buffer.read(cx).snapshot(cx);
 6620
 6621        let mut edits = Vec::new();
 6622        let mut unfold_ranges = Vec::new();
 6623        let mut refold_ranges = Vec::new();
 6624
 6625        let selections = self.selections.all::<Point>(cx);
 6626        let mut selections = selections.iter().peekable();
 6627        let mut contiguous_row_selections = Vec::new();
 6628        let mut new_selections = Vec::new();
 6629
 6630        while let Some(selection) = selections.next() {
 6631            // Find all the selections that span a contiguous row range
 6632            let (start_row, end_row) = consume_contiguous_rows(
 6633                &mut contiguous_row_selections,
 6634                selection,
 6635                &display_map,
 6636                &mut selections,
 6637            );
 6638
 6639            // Move the text spanned by the row range to be before the line preceding the row range
 6640            if start_row.0 > 0 {
 6641                let range_to_move = Point::new(
 6642                    start_row.previous_row().0,
 6643                    buffer.line_len(start_row.previous_row()),
 6644                )
 6645                    ..Point::new(
 6646                        end_row.previous_row().0,
 6647                        buffer.line_len(end_row.previous_row()),
 6648                    );
 6649                let insertion_point = display_map
 6650                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6651                    .0;
 6652
 6653                // Don't move lines across excerpts
 6654                if buffer
 6655                    .excerpt_boundaries_in_range((
 6656                        Bound::Excluded(insertion_point),
 6657                        Bound::Included(range_to_move.end),
 6658                    ))
 6659                    .next()
 6660                    .is_none()
 6661                {
 6662                    let text = buffer
 6663                        .text_for_range(range_to_move.clone())
 6664                        .flat_map(|s| s.chars())
 6665                        .skip(1)
 6666                        .chain(['\n'])
 6667                        .collect::<String>();
 6668
 6669                    edits.push((
 6670                        buffer.anchor_after(range_to_move.start)
 6671                            ..buffer.anchor_before(range_to_move.end),
 6672                        String::new(),
 6673                    ));
 6674                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6675                    edits.push((insertion_anchor..insertion_anchor, text));
 6676
 6677                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6678
 6679                    // Move selections up
 6680                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6681                        |mut selection| {
 6682                            selection.start.row -= row_delta;
 6683                            selection.end.row -= row_delta;
 6684                            selection
 6685                        },
 6686                    ));
 6687
 6688                    // Move folds up
 6689                    unfold_ranges.push(range_to_move.clone());
 6690                    for fold in display_map.folds_in_range(
 6691                        buffer.anchor_before(range_to_move.start)
 6692                            ..buffer.anchor_after(range_to_move.end),
 6693                    ) {
 6694                        let mut start = fold.range.start.to_point(&buffer);
 6695                        let mut end = fold.range.end.to_point(&buffer);
 6696                        start.row -= row_delta;
 6697                        end.row -= row_delta;
 6698                        refold_ranges.push((start..end, fold.placeholder.clone()));
 6699                    }
 6700                }
 6701            }
 6702
 6703            // If we didn't move line(s), preserve the existing selections
 6704            new_selections.append(&mut contiguous_row_selections);
 6705        }
 6706
 6707        self.transact(cx, |this, cx| {
 6708            this.unfold_ranges(unfold_ranges, true, true, cx);
 6709            this.buffer.update(cx, |buffer, cx| {
 6710                for (range, text) in edits {
 6711                    buffer.edit([(range, text)], None, cx);
 6712                }
 6713            });
 6714            this.fold_ranges(refold_ranges, true, cx);
 6715            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6716                s.select(new_selections);
 6717            })
 6718        });
 6719    }
 6720
 6721    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 6722        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6723        let buffer = self.buffer.read(cx).snapshot(cx);
 6724
 6725        let mut edits = Vec::new();
 6726        let mut unfold_ranges = Vec::new();
 6727        let mut refold_ranges = Vec::new();
 6728
 6729        let selections = self.selections.all::<Point>(cx);
 6730        let mut selections = selections.iter().peekable();
 6731        let mut contiguous_row_selections = Vec::new();
 6732        let mut new_selections = Vec::new();
 6733
 6734        while let Some(selection) = selections.next() {
 6735            // Find all the selections that span a contiguous row range
 6736            let (start_row, end_row) = consume_contiguous_rows(
 6737                &mut contiguous_row_selections,
 6738                selection,
 6739                &display_map,
 6740                &mut selections,
 6741            );
 6742
 6743            // Move the text spanned by the row range to be after the last line of the row range
 6744            if end_row.0 <= buffer.max_point().row {
 6745                let range_to_move =
 6746                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 6747                let insertion_point = display_map
 6748                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 6749                    .0;
 6750
 6751                // Don't move lines across excerpt boundaries
 6752                if buffer
 6753                    .excerpt_boundaries_in_range((
 6754                        Bound::Excluded(range_to_move.start),
 6755                        Bound::Included(insertion_point),
 6756                    ))
 6757                    .next()
 6758                    .is_none()
 6759                {
 6760                    let mut text = String::from("\n");
 6761                    text.extend(buffer.text_for_range(range_to_move.clone()));
 6762                    text.pop(); // Drop trailing newline
 6763                    edits.push((
 6764                        buffer.anchor_after(range_to_move.start)
 6765                            ..buffer.anchor_before(range_to_move.end),
 6766                        String::new(),
 6767                    ));
 6768                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6769                    edits.push((insertion_anchor..insertion_anchor, text));
 6770
 6771                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 6772
 6773                    // Move selections down
 6774                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6775                        |mut selection| {
 6776                            selection.start.row += row_delta;
 6777                            selection.end.row += row_delta;
 6778                            selection
 6779                        },
 6780                    ));
 6781
 6782                    // Move folds down
 6783                    unfold_ranges.push(range_to_move.clone());
 6784                    for fold in display_map.folds_in_range(
 6785                        buffer.anchor_before(range_to_move.start)
 6786                            ..buffer.anchor_after(range_to_move.end),
 6787                    ) {
 6788                        let mut start = fold.range.start.to_point(&buffer);
 6789                        let mut end = fold.range.end.to_point(&buffer);
 6790                        start.row += row_delta;
 6791                        end.row += row_delta;
 6792                        refold_ranges.push((start..end, fold.placeholder.clone()));
 6793                    }
 6794                }
 6795            }
 6796
 6797            // If we didn't move line(s), preserve the existing selections
 6798            new_selections.append(&mut contiguous_row_selections);
 6799        }
 6800
 6801        self.transact(cx, |this, cx| {
 6802            this.unfold_ranges(unfold_ranges, true, true, cx);
 6803            this.buffer.update(cx, |buffer, cx| {
 6804                for (range, text) in edits {
 6805                    buffer.edit([(range, text)], None, cx);
 6806                }
 6807            });
 6808            this.fold_ranges(refold_ranges, true, cx);
 6809            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 6810        });
 6811    }
 6812
 6813    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 6814        let text_layout_details = &self.text_layout_details(cx);
 6815        self.transact(cx, |this, cx| {
 6816            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6817                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 6818                let line_mode = s.line_mode;
 6819                s.move_with(|display_map, selection| {
 6820                    if !selection.is_empty() || line_mode {
 6821                        return;
 6822                    }
 6823
 6824                    let mut head = selection.head();
 6825                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 6826                    if head.column() == display_map.line_len(head.row()) {
 6827                        transpose_offset = display_map
 6828                            .buffer_snapshot
 6829                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6830                    }
 6831
 6832                    if transpose_offset == 0 {
 6833                        return;
 6834                    }
 6835
 6836                    *head.column_mut() += 1;
 6837                    head = display_map.clip_point(head, Bias::Right);
 6838                    let goal = SelectionGoal::HorizontalPosition(
 6839                        display_map
 6840                            .x_for_display_point(head, text_layout_details)
 6841                            .into(),
 6842                    );
 6843                    selection.collapse_to(head, goal);
 6844
 6845                    let transpose_start = display_map
 6846                        .buffer_snapshot
 6847                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6848                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 6849                        let transpose_end = display_map
 6850                            .buffer_snapshot
 6851                            .clip_offset(transpose_offset + 1, Bias::Right);
 6852                        if let Some(ch) =
 6853                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 6854                        {
 6855                            edits.push((transpose_start..transpose_offset, String::new()));
 6856                            edits.push((transpose_end..transpose_end, ch.to_string()));
 6857                        }
 6858                    }
 6859                });
 6860                edits
 6861            });
 6862            this.buffer
 6863                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6864            let selections = this.selections.all::<usize>(cx);
 6865            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6866                s.select(selections);
 6867            });
 6868        });
 6869    }
 6870
 6871    pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
 6872        self.rewrap_impl(true, cx)
 6873    }
 6874
 6875    pub fn rewrap_impl(&mut self, only_text: bool, cx: &mut ViewContext<Self>) {
 6876        let buffer = self.buffer.read(cx).snapshot(cx);
 6877        let selections = self.selections.all::<Point>(cx);
 6878        let mut selections = selections.iter().peekable();
 6879
 6880        let mut edits = Vec::new();
 6881        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 6882
 6883        while let Some(selection) = selections.next() {
 6884            let mut start_row = selection.start.row;
 6885            let mut end_row = selection.end.row;
 6886
 6887            // Skip selections that overlap with a range that has already been rewrapped.
 6888            let selection_range = start_row..end_row;
 6889            if rewrapped_row_ranges
 6890                .iter()
 6891                .any(|range| range.overlaps(&selection_range))
 6892            {
 6893                continue;
 6894            }
 6895
 6896            let mut should_rewrap = !only_text;
 6897
 6898            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 6899                match language_scope.language_name().0.as_ref() {
 6900                    "Markdown" | "Plain Text" => {
 6901                        should_rewrap = true;
 6902                    }
 6903                    _ => {}
 6904                }
 6905            }
 6906
 6907            // Since not all lines in the selection may be at the same indent
 6908            // level, choose the indent size that is the most common between all
 6909            // of the lines.
 6910            //
 6911            // If there is a tie, we use the deepest indent.
 6912            let (indent_size, indent_end) = {
 6913                let mut indent_size_occurrences = HashMap::default();
 6914                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 6915
 6916                for row in start_row..=end_row {
 6917                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 6918                    rows_by_indent_size.entry(indent).or_default().push(row);
 6919                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 6920                }
 6921
 6922                let indent_size = indent_size_occurrences
 6923                    .into_iter()
 6924                    .max_by_key(|(indent, count)| (*count, indent.len))
 6925                    .map(|(indent, _)| indent)
 6926                    .unwrap_or_default();
 6927                let row = rows_by_indent_size[&indent_size][0];
 6928                let indent_end = Point::new(row, indent_size.len);
 6929
 6930                (indent_size, indent_end)
 6931            };
 6932
 6933            let mut line_prefix = indent_size.chars().collect::<String>();
 6934
 6935            if let Some(comment_prefix) =
 6936                buffer
 6937                    .language_scope_at(selection.head())
 6938                    .and_then(|language| {
 6939                        language
 6940                            .line_comment_prefixes()
 6941                            .iter()
 6942                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 6943                            .cloned()
 6944                    })
 6945            {
 6946                line_prefix.push_str(&comment_prefix);
 6947                should_rewrap = true;
 6948            }
 6949
 6950            if selection.is_empty() {
 6951                'expand_upwards: while start_row > 0 {
 6952                    let prev_row = start_row - 1;
 6953                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 6954                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 6955                    {
 6956                        start_row = prev_row;
 6957                    } else {
 6958                        break 'expand_upwards;
 6959                    }
 6960                }
 6961
 6962                'expand_downwards: while end_row < buffer.max_point().row {
 6963                    let next_row = end_row + 1;
 6964                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 6965                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 6966                    {
 6967                        end_row = next_row;
 6968                    } else {
 6969                        break 'expand_downwards;
 6970                    }
 6971                }
 6972            }
 6973
 6974            if !should_rewrap {
 6975                continue;
 6976            }
 6977
 6978            let start = Point::new(start_row, 0);
 6979            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 6980            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 6981            let Some(lines_without_prefixes) = selection_text
 6982                .lines()
 6983                .map(|line| {
 6984                    line.strip_prefix(&line_prefix)
 6985                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 6986                        .ok_or_else(|| {
 6987                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 6988                        })
 6989                })
 6990                .collect::<Result<Vec<_>, _>>()
 6991                .log_err()
 6992            else {
 6993                continue;
 6994            };
 6995
 6996            let unwrapped_text = lines_without_prefixes.join(" ");
 6997            let wrap_column = buffer
 6998                .settings_at(Point::new(start_row, 0), cx)
 6999                .preferred_line_length as usize;
 7000            let mut wrapped_text = String::new();
 7001            let mut current_line = line_prefix.clone();
 7002            for word in unwrapped_text.split_whitespace() {
 7003                if current_line.len() + word.len() >= wrap_column {
 7004                    wrapped_text.push_str(&current_line);
 7005                    wrapped_text.push('\n');
 7006                    current_line.truncate(line_prefix.len());
 7007                }
 7008
 7009                if current_line.len() > line_prefix.len() {
 7010                    current_line.push(' ');
 7011                }
 7012
 7013                current_line.push_str(word);
 7014            }
 7015
 7016            if !current_line.is_empty() {
 7017                wrapped_text.push_str(&current_line);
 7018            }
 7019
 7020            let diff = TextDiff::from_lines(&selection_text, &wrapped_text);
 7021            let mut offset = start.to_offset(&buffer);
 7022            let mut moved_since_edit = true;
 7023
 7024            for change in diff.iter_all_changes() {
 7025                let value = change.value();
 7026                match change.tag() {
 7027                    ChangeTag::Equal => {
 7028                        offset += value.len();
 7029                        moved_since_edit = true;
 7030                    }
 7031                    ChangeTag::Delete => {
 7032                        let start = buffer.anchor_after(offset);
 7033                        let end = buffer.anchor_before(offset + value.len());
 7034
 7035                        if moved_since_edit {
 7036                            edits.push((start..end, String::new()));
 7037                        } else {
 7038                            edits.last_mut().unwrap().0.end = end;
 7039                        }
 7040
 7041                        offset += value.len();
 7042                        moved_since_edit = false;
 7043                    }
 7044                    ChangeTag::Insert => {
 7045                        if moved_since_edit {
 7046                            let anchor = buffer.anchor_after(offset);
 7047                            edits.push((anchor..anchor, value.to_string()));
 7048                        } else {
 7049                            edits.last_mut().unwrap().1.push_str(value);
 7050                        }
 7051
 7052                        moved_since_edit = false;
 7053                    }
 7054                }
 7055            }
 7056
 7057            rewrapped_row_ranges.push(start_row..=end_row);
 7058        }
 7059
 7060        self.buffer
 7061            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7062    }
 7063
 7064    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 7065        let mut text = String::new();
 7066        let buffer = self.buffer.read(cx).snapshot(cx);
 7067        let mut selections = self.selections.all::<Point>(cx);
 7068        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7069        {
 7070            let max_point = buffer.max_point();
 7071            let mut is_first = true;
 7072            for selection in &mut selections {
 7073                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7074                if is_entire_line {
 7075                    selection.start = Point::new(selection.start.row, 0);
 7076                    if !selection.is_empty() && selection.end.column == 0 {
 7077                        selection.end = cmp::min(max_point, selection.end);
 7078                    } else {
 7079                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7080                    }
 7081                    selection.goal = SelectionGoal::None;
 7082                }
 7083                if is_first {
 7084                    is_first = false;
 7085                } else {
 7086                    text += "\n";
 7087                }
 7088                let mut len = 0;
 7089                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7090                    text.push_str(chunk);
 7091                    len += chunk.len();
 7092                }
 7093                clipboard_selections.push(ClipboardSelection {
 7094                    len,
 7095                    is_entire_line,
 7096                    first_line_indent: buffer
 7097                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7098                        .len,
 7099                });
 7100            }
 7101        }
 7102
 7103        self.transact(cx, |this, cx| {
 7104            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7105                s.select(selections);
 7106            });
 7107            this.insert("", cx);
 7108            cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7109                text,
 7110                clipboard_selections,
 7111            ));
 7112        });
 7113    }
 7114
 7115    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 7116        let selections = self.selections.all::<Point>(cx);
 7117        let buffer = self.buffer.read(cx).read(cx);
 7118        let mut text = String::new();
 7119
 7120        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7121        {
 7122            let max_point = buffer.max_point();
 7123            let mut is_first = true;
 7124            for selection in selections.iter() {
 7125                let mut start = selection.start;
 7126                let mut end = selection.end;
 7127                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7128                if is_entire_line {
 7129                    start = Point::new(start.row, 0);
 7130                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 7131                }
 7132                if is_first {
 7133                    is_first = false;
 7134                } else {
 7135                    text += "\n";
 7136                }
 7137                let mut len = 0;
 7138                for chunk in buffer.text_for_range(start..end) {
 7139                    text.push_str(chunk);
 7140                    len += chunk.len();
 7141                }
 7142                clipboard_selections.push(ClipboardSelection {
 7143                    len,
 7144                    is_entire_line,
 7145                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 7146                });
 7147            }
 7148        }
 7149
 7150        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7151            text,
 7152            clipboard_selections,
 7153        ));
 7154    }
 7155
 7156    pub fn do_paste(
 7157        &mut self,
 7158        text: &String,
 7159        clipboard_selections: Option<Vec<ClipboardSelection>>,
 7160        handle_entire_lines: bool,
 7161        cx: &mut ViewContext<Self>,
 7162    ) {
 7163        if self.read_only(cx) {
 7164            return;
 7165        }
 7166
 7167        let clipboard_text = Cow::Borrowed(text);
 7168
 7169        self.transact(cx, |this, cx| {
 7170            if let Some(mut clipboard_selections) = clipboard_selections {
 7171                let old_selections = this.selections.all::<usize>(cx);
 7172                let all_selections_were_entire_line =
 7173                    clipboard_selections.iter().all(|s| s.is_entire_line);
 7174                let first_selection_indent_column =
 7175                    clipboard_selections.first().map(|s| s.first_line_indent);
 7176                if clipboard_selections.len() != old_selections.len() {
 7177                    clipboard_selections.drain(..);
 7178                }
 7179
 7180                this.buffer.update(cx, |buffer, cx| {
 7181                    let snapshot = buffer.read(cx);
 7182                    let mut start_offset = 0;
 7183                    let mut edits = Vec::new();
 7184                    let mut original_indent_columns = Vec::new();
 7185                    for (ix, selection) in old_selections.iter().enumerate() {
 7186                        let to_insert;
 7187                        let entire_line;
 7188                        let original_indent_column;
 7189                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 7190                            let end_offset = start_offset + clipboard_selection.len;
 7191                            to_insert = &clipboard_text[start_offset..end_offset];
 7192                            entire_line = clipboard_selection.is_entire_line;
 7193                            start_offset = end_offset + 1;
 7194                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7195                        } else {
 7196                            to_insert = clipboard_text.as_str();
 7197                            entire_line = all_selections_were_entire_line;
 7198                            original_indent_column = first_selection_indent_column
 7199                        }
 7200
 7201                        // If the corresponding selection was empty when this slice of the
 7202                        // clipboard text was written, then the entire line containing the
 7203                        // selection was copied. If this selection is also currently empty,
 7204                        // then paste the line before the current line of the buffer.
 7205                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7206                            let column = selection.start.to_point(&snapshot).column as usize;
 7207                            let line_start = selection.start - column;
 7208                            line_start..line_start
 7209                        } else {
 7210                            selection.range()
 7211                        };
 7212
 7213                        edits.push((range, to_insert));
 7214                        original_indent_columns.extend(original_indent_column);
 7215                    }
 7216                    drop(snapshot);
 7217
 7218                    buffer.edit(
 7219                        edits,
 7220                        Some(AutoindentMode::Block {
 7221                            original_indent_columns,
 7222                        }),
 7223                        cx,
 7224                    );
 7225                });
 7226
 7227                let selections = this.selections.all::<usize>(cx);
 7228                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 7229            } else {
 7230                this.insert(&clipboard_text, cx);
 7231            }
 7232        });
 7233    }
 7234
 7235    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 7236        if let Some(item) = cx.read_from_clipboard() {
 7237            let entries = item.entries();
 7238
 7239            match entries.first() {
 7240                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7241                // of all the pasted entries.
 7242                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7243                    .do_paste(
 7244                        clipboard_string.text(),
 7245                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7246                        true,
 7247                        cx,
 7248                    ),
 7249                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
 7250            }
 7251        }
 7252    }
 7253
 7254    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 7255        if self.read_only(cx) {
 7256            return;
 7257        }
 7258
 7259        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7260            if let Some((selections, _)) =
 7261                self.selection_history.transaction(transaction_id).cloned()
 7262            {
 7263                self.change_selections(None, cx, |s| {
 7264                    s.select_anchors(selections.to_vec());
 7265                });
 7266            }
 7267            self.request_autoscroll(Autoscroll::fit(), cx);
 7268            self.unmark_text(cx);
 7269            self.refresh_inline_completion(true, false, cx);
 7270            cx.emit(EditorEvent::Edited { transaction_id });
 7271            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7272        }
 7273    }
 7274
 7275    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 7276        if self.read_only(cx) {
 7277            return;
 7278        }
 7279
 7280        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7281            if let Some((_, Some(selections))) =
 7282                self.selection_history.transaction(transaction_id).cloned()
 7283            {
 7284                self.change_selections(None, cx, |s| {
 7285                    s.select_anchors(selections.to_vec());
 7286                });
 7287            }
 7288            self.request_autoscroll(Autoscroll::fit(), cx);
 7289            self.unmark_text(cx);
 7290            self.refresh_inline_completion(true, false, cx);
 7291            cx.emit(EditorEvent::Edited { transaction_id });
 7292        }
 7293    }
 7294
 7295    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 7296        self.buffer
 7297            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7298    }
 7299
 7300    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 7301        self.buffer
 7302            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7303    }
 7304
 7305    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 7306        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7307            let line_mode = s.line_mode;
 7308            s.move_with(|map, selection| {
 7309                let cursor = if selection.is_empty() && !line_mode {
 7310                    movement::left(map, selection.start)
 7311                } else {
 7312                    selection.start
 7313                };
 7314                selection.collapse_to(cursor, SelectionGoal::None);
 7315            });
 7316        })
 7317    }
 7318
 7319    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 7320        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7321            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7322        })
 7323    }
 7324
 7325    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 7326        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7327            let line_mode = s.line_mode;
 7328            s.move_with(|map, selection| {
 7329                let cursor = if selection.is_empty() && !line_mode {
 7330                    movement::right(map, selection.end)
 7331                } else {
 7332                    selection.end
 7333                };
 7334                selection.collapse_to(cursor, SelectionGoal::None)
 7335            });
 7336        })
 7337    }
 7338
 7339    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 7340        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7341            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7342        })
 7343    }
 7344
 7345    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 7346        if self.take_rename(true, cx).is_some() {
 7347            return;
 7348        }
 7349
 7350        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7351            cx.propagate();
 7352            return;
 7353        }
 7354
 7355        let text_layout_details = &self.text_layout_details(cx);
 7356        let selection_count = self.selections.count();
 7357        let first_selection = self.selections.first_anchor();
 7358
 7359        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7360            let line_mode = s.line_mode;
 7361            s.move_with(|map, selection| {
 7362                if !selection.is_empty() && !line_mode {
 7363                    selection.goal = SelectionGoal::None;
 7364                }
 7365                let (cursor, goal) = movement::up(
 7366                    map,
 7367                    selection.start,
 7368                    selection.goal,
 7369                    false,
 7370                    text_layout_details,
 7371                );
 7372                selection.collapse_to(cursor, goal);
 7373            });
 7374        });
 7375
 7376        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7377        {
 7378            cx.propagate();
 7379        }
 7380    }
 7381
 7382    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 7383        if self.take_rename(true, cx).is_some() {
 7384            return;
 7385        }
 7386
 7387        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7388            cx.propagate();
 7389            return;
 7390        }
 7391
 7392        let text_layout_details = &self.text_layout_details(cx);
 7393
 7394        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7395            let line_mode = s.line_mode;
 7396            s.move_with(|map, selection| {
 7397                if !selection.is_empty() && !line_mode {
 7398                    selection.goal = SelectionGoal::None;
 7399                }
 7400                let (cursor, goal) = movement::up_by_rows(
 7401                    map,
 7402                    selection.start,
 7403                    action.lines,
 7404                    selection.goal,
 7405                    false,
 7406                    text_layout_details,
 7407                );
 7408                selection.collapse_to(cursor, goal);
 7409            });
 7410        })
 7411    }
 7412
 7413    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 7414        if self.take_rename(true, cx).is_some() {
 7415            return;
 7416        }
 7417
 7418        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7419            cx.propagate();
 7420            return;
 7421        }
 7422
 7423        let text_layout_details = &self.text_layout_details(cx);
 7424
 7425        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7426            let line_mode = s.line_mode;
 7427            s.move_with(|map, selection| {
 7428                if !selection.is_empty() && !line_mode {
 7429                    selection.goal = SelectionGoal::None;
 7430                }
 7431                let (cursor, goal) = movement::down_by_rows(
 7432                    map,
 7433                    selection.start,
 7434                    action.lines,
 7435                    selection.goal,
 7436                    false,
 7437                    text_layout_details,
 7438                );
 7439                selection.collapse_to(cursor, goal);
 7440            });
 7441        })
 7442    }
 7443
 7444    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 7445        let text_layout_details = &self.text_layout_details(cx);
 7446        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7447            s.move_heads_with(|map, head, goal| {
 7448                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7449            })
 7450        })
 7451    }
 7452
 7453    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 7454        let text_layout_details = &self.text_layout_details(cx);
 7455        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7456            s.move_heads_with(|map, head, goal| {
 7457                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7458            })
 7459        })
 7460    }
 7461
 7462    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 7463        let Some(row_count) = self.visible_row_count() else {
 7464            return;
 7465        };
 7466
 7467        let text_layout_details = &self.text_layout_details(cx);
 7468
 7469        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7470            s.move_heads_with(|map, head, goal| {
 7471                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7472            })
 7473        })
 7474    }
 7475
 7476    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 7477        if self.take_rename(true, cx).is_some() {
 7478            return;
 7479        }
 7480
 7481        if self
 7482            .context_menu
 7483            .write()
 7484            .as_mut()
 7485            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 7486            .unwrap_or(false)
 7487        {
 7488            return;
 7489        }
 7490
 7491        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7492            cx.propagate();
 7493            return;
 7494        }
 7495
 7496        let Some(row_count) = self.visible_row_count() else {
 7497            return;
 7498        };
 7499
 7500        let autoscroll = if action.center_cursor {
 7501            Autoscroll::center()
 7502        } else {
 7503            Autoscroll::fit()
 7504        };
 7505
 7506        let text_layout_details = &self.text_layout_details(cx);
 7507
 7508        self.change_selections(Some(autoscroll), cx, |s| {
 7509            let line_mode = s.line_mode;
 7510            s.move_with(|map, selection| {
 7511                if !selection.is_empty() && !line_mode {
 7512                    selection.goal = SelectionGoal::None;
 7513                }
 7514                let (cursor, goal) = movement::up_by_rows(
 7515                    map,
 7516                    selection.end,
 7517                    row_count,
 7518                    selection.goal,
 7519                    false,
 7520                    text_layout_details,
 7521                );
 7522                selection.collapse_to(cursor, goal);
 7523            });
 7524        });
 7525    }
 7526
 7527    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 7528        let text_layout_details = &self.text_layout_details(cx);
 7529        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7530            s.move_heads_with(|map, head, goal| {
 7531                movement::up(map, head, goal, false, text_layout_details)
 7532            })
 7533        })
 7534    }
 7535
 7536    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 7537        self.take_rename(true, cx);
 7538
 7539        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7540            cx.propagate();
 7541            return;
 7542        }
 7543
 7544        let text_layout_details = &self.text_layout_details(cx);
 7545        let selection_count = self.selections.count();
 7546        let first_selection = self.selections.first_anchor();
 7547
 7548        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7549            let line_mode = s.line_mode;
 7550            s.move_with(|map, selection| {
 7551                if !selection.is_empty() && !line_mode {
 7552                    selection.goal = SelectionGoal::None;
 7553                }
 7554                let (cursor, goal) = movement::down(
 7555                    map,
 7556                    selection.end,
 7557                    selection.goal,
 7558                    false,
 7559                    text_layout_details,
 7560                );
 7561                selection.collapse_to(cursor, goal);
 7562            });
 7563        });
 7564
 7565        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7566        {
 7567            cx.propagate();
 7568        }
 7569    }
 7570
 7571    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 7572        let Some(row_count) = self.visible_row_count() else {
 7573            return;
 7574        };
 7575
 7576        let text_layout_details = &self.text_layout_details(cx);
 7577
 7578        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7579            s.move_heads_with(|map, head, goal| {
 7580                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 7581            })
 7582        })
 7583    }
 7584
 7585    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 7586        if self.take_rename(true, cx).is_some() {
 7587            return;
 7588        }
 7589
 7590        if self
 7591            .context_menu
 7592            .write()
 7593            .as_mut()
 7594            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 7595            .unwrap_or(false)
 7596        {
 7597            return;
 7598        }
 7599
 7600        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7601            cx.propagate();
 7602            return;
 7603        }
 7604
 7605        let Some(row_count) = self.visible_row_count() else {
 7606            return;
 7607        };
 7608
 7609        let autoscroll = if action.center_cursor {
 7610            Autoscroll::center()
 7611        } else {
 7612            Autoscroll::fit()
 7613        };
 7614
 7615        let text_layout_details = &self.text_layout_details(cx);
 7616        self.change_selections(Some(autoscroll), cx, |s| {
 7617            let line_mode = s.line_mode;
 7618            s.move_with(|map, selection| {
 7619                if !selection.is_empty() && !line_mode {
 7620                    selection.goal = SelectionGoal::None;
 7621                }
 7622                let (cursor, goal) = movement::down_by_rows(
 7623                    map,
 7624                    selection.end,
 7625                    row_count,
 7626                    selection.goal,
 7627                    false,
 7628                    text_layout_details,
 7629                );
 7630                selection.collapse_to(cursor, goal);
 7631            });
 7632        });
 7633    }
 7634
 7635    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 7636        let text_layout_details = &self.text_layout_details(cx);
 7637        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7638            s.move_heads_with(|map, head, goal| {
 7639                movement::down(map, head, goal, false, text_layout_details)
 7640            })
 7641        });
 7642    }
 7643
 7644    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 7645        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7646            context_menu.select_first(self.completion_provider.as_deref(), cx);
 7647        }
 7648    }
 7649
 7650    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 7651        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7652            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 7653        }
 7654    }
 7655
 7656    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7657        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7658            context_menu.select_next(self.completion_provider.as_deref(), cx);
 7659        }
 7660    }
 7661
 7662    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 7663        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7664            context_menu.select_last(self.completion_provider.as_deref(), cx);
 7665        }
 7666    }
 7667
 7668    pub fn move_to_previous_word_start(
 7669        &mut self,
 7670        _: &MoveToPreviousWordStart,
 7671        cx: &mut ViewContext<Self>,
 7672    ) {
 7673        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7674            s.move_cursors_with(|map, head, _| {
 7675                (
 7676                    movement::previous_word_start(map, head),
 7677                    SelectionGoal::None,
 7678                )
 7679            });
 7680        })
 7681    }
 7682
 7683    pub fn move_to_previous_subword_start(
 7684        &mut self,
 7685        _: &MoveToPreviousSubwordStart,
 7686        cx: &mut ViewContext<Self>,
 7687    ) {
 7688        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7689            s.move_cursors_with(|map, head, _| {
 7690                (
 7691                    movement::previous_subword_start(map, head),
 7692                    SelectionGoal::None,
 7693                )
 7694            });
 7695        })
 7696    }
 7697
 7698    pub fn select_to_previous_word_start(
 7699        &mut self,
 7700        _: &SelectToPreviousWordStart,
 7701        cx: &mut ViewContext<Self>,
 7702    ) {
 7703        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7704            s.move_heads_with(|map, head, _| {
 7705                (
 7706                    movement::previous_word_start(map, head),
 7707                    SelectionGoal::None,
 7708                )
 7709            });
 7710        })
 7711    }
 7712
 7713    pub fn select_to_previous_subword_start(
 7714        &mut self,
 7715        _: &SelectToPreviousSubwordStart,
 7716        cx: &mut ViewContext<Self>,
 7717    ) {
 7718        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7719            s.move_heads_with(|map, head, _| {
 7720                (
 7721                    movement::previous_subword_start(map, head),
 7722                    SelectionGoal::None,
 7723                )
 7724            });
 7725        })
 7726    }
 7727
 7728    pub fn delete_to_previous_word_start(
 7729        &mut self,
 7730        action: &DeleteToPreviousWordStart,
 7731        cx: &mut ViewContext<Self>,
 7732    ) {
 7733        self.transact(cx, |this, cx| {
 7734            this.select_autoclose_pair(cx);
 7735            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7736                let line_mode = s.line_mode;
 7737                s.move_with(|map, selection| {
 7738                    if selection.is_empty() && !line_mode {
 7739                        let cursor = if action.ignore_newlines {
 7740                            movement::previous_word_start(map, selection.head())
 7741                        } else {
 7742                            movement::previous_word_start_or_newline(map, selection.head())
 7743                        };
 7744                        selection.set_head(cursor, SelectionGoal::None);
 7745                    }
 7746                });
 7747            });
 7748            this.insert("", cx);
 7749        });
 7750    }
 7751
 7752    pub fn delete_to_previous_subword_start(
 7753        &mut self,
 7754        _: &DeleteToPreviousSubwordStart,
 7755        cx: &mut ViewContext<Self>,
 7756    ) {
 7757        self.transact(cx, |this, cx| {
 7758            this.select_autoclose_pair(cx);
 7759            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7760                let line_mode = s.line_mode;
 7761                s.move_with(|map, selection| {
 7762                    if selection.is_empty() && !line_mode {
 7763                        let cursor = movement::previous_subword_start(map, selection.head());
 7764                        selection.set_head(cursor, SelectionGoal::None);
 7765                    }
 7766                });
 7767            });
 7768            this.insert("", cx);
 7769        });
 7770    }
 7771
 7772    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 7773        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7774            s.move_cursors_with(|map, head, _| {
 7775                (movement::next_word_end(map, head), SelectionGoal::None)
 7776            });
 7777        })
 7778    }
 7779
 7780    pub fn move_to_next_subword_end(
 7781        &mut self,
 7782        _: &MoveToNextSubwordEnd,
 7783        cx: &mut ViewContext<Self>,
 7784    ) {
 7785        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7786            s.move_cursors_with(|map, head, _| {
 7787                (movement::next_subword_end(map, head), SelectionGoal::None)
 7788            });
 7789        })
 7790    }
 7791
 7792    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 7793        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7794            s.move_heads_with(|map, head, _| {
 7795                (movement::next_word_end(map, head), SelectionGoal::None)
 7796            });
 7797        })
 7798    }
 7799
 7800    pub fn select_to_next_subword_end(
 7801        &mut self,
 7802        _: &SelectToNextSubwordEnd,
 7803        cx: &mut ViewContext<Self>,
 7804    ) {
 7805        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7806            s.move_heads_with(|map, head, _| {
 7807                (movement::next_subword_end(map, head), SelectionGoal::None)
 7808            });
 7809        })
 7810    }
 7811
 7812    pub fn delete_to_next_word_end(
 7813        &mut self,
 7814        action: &DeleteToNextWordEnd,
 7815        cx: &mut ViewContext<Self>,
 7816    ) {
 7817        self.transact(cx, |this, cx| {
 7818            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7819                let line_mode = s.line_mode;
 7820                s.move_with(|map, selection| {
 7821                    if selection.is_empty() && !line_mode {
 7822                        let cursor = if action.ignore_newlines {
 7823                            movement::next_word_end(map, selection.head())
 7824                        } else {
 7825                            movement::next_word_end_or_newline(map, selection.head())
 7826                        };
 7827                        selection.set_head(cursor, SelectionGoal::None);
 7828                    }
 7829                });
 7830            });
 7831            this.insert("", cx);
 7832        });
 7833    }
 7834
 7835    pub fn delete_to_next_subword_end(
 7836        &mut self,
 7837        _: &DeleteToNextSubwordEnd,
 7838        cx: &mut ViewContext<Self>,
 7839    ) {
 7840        self.transact(cx, |this, cx| {
 7841            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7842                s.move_with(|map, selection| {
 7843                    if selection.is_empty() {
 7844                        let cursor = movement::next_subword_end(map, selection.head());
 7845                        selection.set_head(cursor, SelectionGoal::None);
 7846                    }
 7847                });
 7848            });
 7849            this.insert("", cx);
 7850        });
 7851    }
 7852
 7853    pub fn move_to_beginning_of_line(
 7854        &mut self,
 7855        action: &MoveToBeginningOfLine,
 7856        cx: &mut ViewContext<Self>,
 7857    ) {
 7858        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7859            s.move_cursors_with(|map, head, _| {
 7860                (
 7861                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7862                    SelectionGoal::None,
 7863                )
 7864            });
 7865        })
 7866    }
 7867
 7868    pub fn select_to_beginning_of_line(
 7869        &mut self,
 7870        action: &SelectToBeginningOfLine,
 7871        cx: &mut ViewContext<Self>,
 7872    ) {
 7873        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7874            s.move_heads_with(|map, head, _| {
 7875                (
 7876                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7877                    SelectionGoal::None,
 7878                )
 7879            });
 7880        });
 7881    }
 7882
 7883    pub fn delete_to_beginning_of_line(
 7884        &mut self,
 7885        _: &DeleteToBeginningOfLine,
 7886        cx: &mut ViewContext<Self>,
 7887    ) {
 7888        self.transact(cx, |this, cx| {
 7889            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7890                s.move_with(|_, selection| {
 7891                    selection.reversed = true;
 7892                });
 7893            });
 7894
 7895            this.select_to_beginning_of_line(
 7896                &SelectToBeginningOfLine {
 7897                    stop_at_soft_wraps: false,
 7898                },
 7899                cx,
 7900            );
 7901            this.backspace(&Backspace, cx);
 7902        });
 7903    }
 7904
 7905    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 7906        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7907            s.move_cursors_with(|map, head, _| {
 7908                (
 7909                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7910                    SelectionGoal::None,
 7911                )
 7912            });
 7913        })
 7914    }
 7915
 7916    pub fn select_to_end_of_line(
 7917        &mut self,
 7918        action: &SelectToEndOfLine,
 7919        cx: &mut ViewContext<Self>,
 7920    ) {
 7921        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7922            s.move_heads_with(|map, head, _| {
 7923                (
 7924                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7925                    SelectionGoal::None,
 7926                )
 7927            });
 7928        })
 7929    }
 7930
 7931    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 7932        self.transact(cx, |this, cx| {
 7933            this.select_to_end_of_line(
 7934                &SelectToEndOfLine {
 7935                    stop_at_soft_wraps: false,
 7936                },
 7937                cx,
 7938            );
 7939            this.delete(&Delete, cx);
 7940        });
 7941    }
 7942
 7943    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 7944        self.transact(cx, |this, cx| {
 7945            this.select_to_end_of_line(
 7946                &SelectToEndOfLine {
 7947                    stop_at_soft_wraps: false,
 7948                },
 7949                cx,
 7950            );
 7951            this.cut(&Cut, cx);
 7952        });
 7953    }
 7954
 7955    pub fn move_to_start_of_paragraph(
 7956        &mut self,
 7957        _: &MoveToStartOfParagraph,
 7958        cx: &mut ViewContext<Self>,
 7959    ) {
 7960        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7961            cx.propagate();
 7962            return;
 7963        }
 7964
 7965        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7966            s.move_with(|map, selection| {
 7967                selection.collapse_to(
 7968                    movement::start_of_paragraph(map, selection.head(), 1),
 7969                    SelectionGoal::None,
 7970                )
 7971            });
 7972        })
 7973    }
 7974
 7975    pub fn move_to_end_of_paragraph(
 7976        &mut self,
 7977        _: &MoveToEndOfParagraph,
 7978        cx: &mut ViewContext<Self>,
 7979    ) {
 7980        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7981            cx.propagate();
 7982            return;
 7983        }
 7984
 7985        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7986            s.move_with(|map, selection| {
 7987                selection.collapse_to(
 7988                    movement::end_of_paragraph(map, selection.head(), 1),
 7989                    SelectionGoal::None,
 7990                )
 7991            });
 7992        })
 7993    }
 7994
 7995    pub fn select_to_start_of_paragraph(
 7996        &mut self,
 7997        _: &SelectToStartOfParagraph,
 7998        cx: &mut ViewContext<Self>,
 7999    ) {
 8000        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8001            cx.propagate();
 8002            return;
 8003        }
 8004
 8005        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8006            s.move_heads_with(|map, head, _| {
 8007                (
 8008                    movement::start_of_paragraph(map, head, 1),
 8009                    SelectionGoal::None,
 8010                )
 8011            });
 8012        })
 8013    }
 8014
 8015    pub fn select_to_end_of_paragraph(
 8016        &mut self,
 8017        _: &SelectToEndOfParagraph,
 8018        cx: &mut ViewContext<Self>,
 8019    ) {
 8020        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8021            cx.propagate();
 8022            return;
 8023        }
 8024
 8025        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8026            s.move_heads_with(|map, head, _| {
 8027                (
 8028                    movement::end_of_paragraph(map, head, 1),
 8029                    SelectionGoal::None,
 8030                )
 8031            });
 8032        })
 8033    }
 8034
 8035    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 8036        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8037            cx.propagate();
 8038            return;
 8039        }
 8040
 8041        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8042            s.select_ranges(vec![0..0]);
 8043        });
 8044    }
 8045
 8046    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 8047        let mut selection = self.selections.last::<Point>(cx);
 8048        selection.set_head(Point::zero(), SelectionGoal::None);
 8049
 8050        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8051            s.select(vec![selection]);
 8052        });
 8053    }
 8054
 8055    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 8056        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8057            cx.propagate();
 8058            return;
 8059        }
 8060
 8061        let cursor = self.buffer.read(cx).read(cx).len();
 8062        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8063            s.select_ranges(vec![cursor..cursor])
 8064        });
 8065    }
 8066
 8067    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 8068        self.nav_history = nav_history;
 8069    }
 8070
 8071    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 8072        self.nav_history.as_ref()
 8073    }
 8074
 8075    fn push_to_nav_history(
 8076        &mut self,
 8077        cursor_anchor: Anchor,
 8078        new_position: Option<Point>,
 8079        cx: &mut ViewContext<Self>,
 8080    ) {
 8081        if let Some(nav_history) = self.nav_history.as_mut() {
 8082            let buffer = self.buffer.read(cx).read(cx);
 8083            let cursor_position = cursor_anchor.to_point(&buffer);
 8084            let scroll_state = self.scroll_manager.anchor();
 8085            let scroll_top_row = scroll_state.top_row(&buffer);
 8086            drop(buffer);
 8087
 8088            if let Some(new_position) = new_position {
 8089                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 8090                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 8091                    return;
 8092                }
 8093            }
 8094
 8095            nav_history.push(
 8096                Some(NavigationData {
 8097                    cursor_anchor,
 8098                    cursor_position,
 8099                    scroll_anchor: scroll_state,
 8100                    scroll_top_row,
 8101                }),
 8102                cx,
 8103            );
 8104        }
 8105    }
 8106
 8107    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 8108        let buffer = self.buffer.read(cx).snapshot(cx);
 8109        let mut selection = self.selections.first::<usize>(cx);
 8110        selection.set_head(buffer.len(), SelectionGoal::None);
 8111        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8112            s.select(vec![selection]);
 8113        });
 8114    }
 8115
 8116    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 8117        let end = self.buffer.read(cx).read(cx).len();
 8118        self.change_selections(None, cx, |s| {
 8119            s.select_ranges(vec![0..end]);
 8120        });
 8121    }
 8122
 8123    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 8124        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8125        let mut selections = self.selections.all::<Point>(cx);
 8126        let max_point = display_map.buffer_snapshot.max_point();
 8127        for selection in &mut selections {
 8128            let rows = selection.spanned_rows(true, &display_map);
 8129            selection.start = Point::new(rows.start.0, 0);
 8130            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 8131            selection.reversed = false;
 8132        }
 8133        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8134            s.select(selections);
 8135        });
 8136    }
 8137
 8138    pub fn split_selection_into_lines(
 8139        &mut self,
 8140        _: &SplitSelectionIntoLines,
 8141        cx: &mut ViewContext<Self>,
 8142    ) {
 8143        let mut to_unfold = Vec::new();
 8144        let mut new_selection_ranges = Vec::new();
 8145        {
 8146            let selections = self.selections.all::<Point>(cx);
 8147            let buffer = self.buffer.read(cx).read(cx);
 8148            for selection in selections {
 8149                for row in selection.start.row..selection.end.row {
 8150                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 8151                    new_selection_ranges.push(cursor..cursor);
 8152                }
 8153                new_selection_ranges.push(selection.end..selection.end);
 8154                to_unfold.push(selection.start..selection.end);
 8155            }
 8156        }
 8157        self.unfold_ranges(to_unfold, true, true, cx);
 8158        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8159            s.select_ranges(new_selection_ranges);
 8160        });
 8161    }
 8162
 8163    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 8164        self.add_selection(true, cx);
 8165    }
 8166
 8167    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 8168        self.add_selection(false, cx);
 8169    }
 8170
 8171    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 8172        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8173        let mut selections = self.selections.all::<Point>(cx);
 8174        let text_layout_details = self.text_layout_details(cx);
 8175        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 8176            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 8177            let range = oldest_selection.display_range(&display_map).sorted();
 8178
 8179            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 8180            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 8181            let positions = start_x.min(end_x)..start_x.max(end_x);
 8182
 8183            selections.clear();
 8184            let mut stack = Vec::new();
 8185            for row in range.start.row().0..=range.end.row().0 {
 8186                if let Some(selection) = self.selections.build_columnar_selection(
 8187                    &display_map,
 8188                    DisplayRow(row),
 8189                    &positions,
 8190                    oldest_selection.reversed,
 8191                    &text_layout_details,
 8192                ) {
 8193                    stack.push(selection.id);
 8194                    selections.push(selection);
 8195                }
 8196            }
 8197
 8198            if above {
 8199                stack.reverse();
 8200            }
 8201
 8202            AddSelectionsState { above, stack }
 8203        });
 8204
 8205        let last_added_selection = *state.stack.last().unwrap();
 8206        let mut new_selections = Vec::new();
 8207        if above == state.above {
 8208            let end_row = if above {
 8209                DisplayRow(0)
 8210            } else {
 8211                display_map.max_point().row()
 8212            };
 8213
 8214            'outer: for selection in selections {
 8215                if selection.id == last_added_selection {
 8216                    let range = selection.display_range(&display_map).sorted();
 8217                    debug_assert_eq!(range.start.row(), range.end.row());
 8218                    let mut row = range.start.row();
 8219                    let positions =
 8220                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 8221                            px(start)..px(end)
 8222                        } else {
 8223                            let start_x =
 8224                                display_map.x_for_display_point(range.start, &text_layout_details);
 8225                            let end_x =
 8226                                display_map.x_for_display_point(range.end, &text_layout_details);
 8227                            start_x.min(end_x)..start_x.max(end_x)
 8228                        };
 8229
 8230                    while row != end_row {
 8231                        if above {
 8232                            row.0 -= 1;
 8233                        } else {
 8234                            row.0 += 1;
 8235                        }
 8236
 8237                        if let Some(new_selection) = self.selections.build_columnar_selection(
 8238                            &display_map,
 8239                            row,
 8240                            &positions,
 8241                            selection.reversed,
 8242                            &text_layout_details,
 8243                        ) {
 8244                            state.stack.push(new_selection.id);
 8245                            if above {
 8246                                new_selections.push(new_selection);
 8247                                new_selections.push(selection);
 8248                            } else {
 8249                                new_selections.push(selection);
 8250                                new_selections.push(new_selection);
 8251                            }
 8252
 8253                            continue 'outer;
 8254                        }
 8255                    }
 8256                }
 8257
 8258                new_selections.push(selection);
 8259            }
 8260        } else {
 8261            new_selections = selections;
 8262            new_selections.retain(|s| s.id != last_added_selection);
 8263            state.stack.pop();
 8264        }
 8265
 8266        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8267            s.select(new_selections);
 8268        });
 8269        if state.stack.len() > 1 {
 8270            self.add_selections_state = Some(state);
 8271        }
 8272    }
 8273
 8274    pub fn select_next_match_internal(
 8275        &mut self,
 8276        display_map: &DisplaySnapshot,
 8277        replace_newest: bool,
 8278        autoscroll: Option<Autoscroll>,
 8279        cx: &mut ViewContext<Self>,
 8280    ) -> Result<()> {
 8281        fn select_next_match_ranges(
 8282            this: &mut Editor,
 8283            range: Range<usize>,
 8284            replace_newest: bool,
 8285            auto_scroll: Option<Autoscroll>,
 8286            cx: &mut ViewContext<Editor>,
 8287        ) {
 8288            this.unfold_ranges([range.clone()], false, true, cx);
 8289            this.change_selections(auto_scroll, cx, |s| {
 8290                if replace_newest {
 8291                    s.delete(s.newest_anchor().id);
 8292                }
 8293                s.insert_range(range.clone());
 8294            });
 8295        }
 8296
 8297        let buffer = &display_map.buffer_snapshot;
 8298        let mut selections = self.selections.all::<usize>(cx);
 8299        if let Some(mut select_next_state) = self.select_next_state.take() {
 8300            let query = &select_next_state.query;
 8301            if !select_next_state.done {
 8302                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8303                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8304                let mut next_selected_range = None;
 8305
 8306                let bytes_after_last_selection =
 8307                    buffer.bytes_in_range(last_selection.end..buffer.len());
 8308                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 8309                let query_matches = query
 8310                    .stream_find_iter(bytes_after_last_selection)
 8311                    .map(|result| (last_selection.end, result))
 8312                    .chain(
 8313                        query
 8314                            .stream_find_iter(bytes_before_first_selection)
 8315                            .map(|result| (0, result)),
 8316                    );
 8317
 8318                for (start_offset, query_match) in query_matches {
 8319                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8320                    let offset_range =
 8321                        start_offset + query_match.start()..start_offset + query_match.end();
 8322                    let display_range = offset_range.start.to_display_point(display_map)
 8323                        ..offset_range.end.to_display_point(display_map);
 8324
 8325                    if !select_next_state.wordwise
 8326                        || (!movement::is_inside_word(display_map, display_range.start)
 8327                            && !movement::is_inside_word(display_map, display_range.end))
 8328                    {
 8329                        // TODO: This is n^2, because we might check all the selections
 8330                        if !selections
 8331                            .iter()
 8332                            .any(|selection| selection.range().overlaps(&offset_range))
 8333                        {
 8334                            next_selected_range = Some(offset_range);
 8335                            break;
 8336                        }
 8337                    }
 8338                }
 8339
 8340                if let Some(next_selected_range) = next_selected_range {
 8341                    select_next_match_ranges(
 8342                        self,
 8343                        next_selected_range,
 8344                        replace_newest,
 8345                        autoscroll,
 8346                        cx,
 8347                    );
 8348                } else {
 8349                    select_next_state.done = true;
 8350                }
 8351            }
 8352
 8353            self.select_next_state = Some(select_next_state);
 8354        } else {
 8355            let mut only_carets = true;
 8356            let mut same_text_selected = true;
 8357            let mut selected_text = None;
 8358
 8359            let mut selections_iter = selections.iter().peekable();
 8360            while let Some(selection) = selections_iter.next() {
 8361                if selection.start != selection.end {
 8362                    only_carets = false;
 8363                }
 8364
 8365                if same_text_selected {
 8366                    if selected_text.is_none() {
 8367                        selected_text =
 8368                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8369                    }
 8370
 8371                    if let Some(next_selection) = selections_iter.peek() {
 8372                        if next_selection.range().len() == selection.range().len() {
 8373                            let next_selected_text = buffer
 8374                                .text_for_range(next_selection.range())
 8375                                .collect::<String>();
 8376                            if Some(next_selected_text) != selected_text {
 8377                                same_text_selected = false;
 8378                                selected_text = None;
 8379                            }
 8380                        } else {
 8381                            same_text_selected = false;
 8382                            selected_text = None;
 8383                        }
 8384                    }
 8385                }
 8386            }
 8387
 8388            if only_carets {
 8389                for selection in &mut selections {
 8390                    let word_range = movement::surrounding_word(
 8391                        display_map,
 8392                        selection.start.to_display_point(display_map),
 8393                    );
 8394                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 8395                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 8396                    selection.goal = SelectionGoal::None;
 8397                    selection.reversed = false;
 8398                    select_next_match_ranges(
 8399                        self,
 8400                        selection.start..selection.end,
 8401                        replace_newest,
 8402                        autoscroll,
 8403                        cx,
 8404                    );
 8405                }
 8406
 8407                if selections.len() == 1 {
 8408                    let selection = selections
 8409                        .last()
 8410                        .expect("ensured that there's only one selection");
 8411                    let query = buffer
 8412                        .text_for_range(selection.start..selection.end)
 8413                        .collect::<String>();
 8414                    let is_empty = query.is_empty();
 8415                    let select_state = SelectNextState {
 8416                        query: AhoCorasick::new(&[query])?,
 8417                        wordwise: true,
 8418                        done: is_empty,
 8419                    };
 8420                    self.select_next_state = Some(select_state);
 8421                } else {
 8422                    self.select_next_state = None;
 8423                }
 8424            } else if let Some(selected_text) = selected_text {
 8425                self.select_next_state = Some(SelectNextState {
 8426                    query: AhoCorasick::new(&[selected_text])?,
 8427                    wordwise: false,
 8428                    done: false,
 8429                });
 8430                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 8431            }
 8432        }
 8433        Ok(())
 8434    }
 8435
 8436    pub fn select_all_matches(
 8437        &mut self,
 8438        _action: &SelectAllMatches,
 8439        cx: &mut ViewContext<Self>,
 8440    ) -> Result<()> {
 8441        self.push_to_selection_history();
 8442        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8443
 8444        self.select_next_match_internal(&display_map, false, None, cx)?;
 8445        let Some(select_next_state) = self.select_next_state.as_mut() else {
 8446            return Ok(());
 8447        };
 8448        if select_next_state.done {
 8449            return Ok(());
 8450        }
 8451
 8452        let mut new_selections = self.selections.all::<usize>(cx);
 8453
 8454        let buffer = &display_map.buffer_snapshot;
 8455        let query_matches = select_next_state
 8456            .query
 8457            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 8458
 8459        for query_match in query_matches {
 8460            let query_match = query_match.unwrap(); // can only fail due to I/O
 8461            let offset_range = query_match.start()..query_match.end();
 8462            let display_range = offset_range.start.to_display_point(&display_map)
 8463                ..offset_range.end.to_display_point(&display_map);
 8464
 8465            if !select_next_state.wordwise
 8466                || (!movement::is_inside_word(&display_map, display_range.start)
 8467                    && !movement::is_inside_word(&display_map, display_range.end))
 8468            {
 8469                self.selections.change_with(cx, |selections| {
 8470                    new_selections.push(Selection {
 8471                        id: selections.new_selection_id(),
 8472                        start: offset_range.start,
 8473                        end: offset_range.end,
 8474                        reversed: false,
 8475                        goal: SelectionGoal::None,
 8476                    });
 8477                });
 8478            }
 8479        }
 8480
 8481        new_selections.sort_by_key(|selection| selection.start);
 8482        let mut ix = 0;
 8483        while ix + 1 < new_selections.len() {
 8484            let current_selection = &new_selections[ix];
 8485            let next_selection = &new_selections[ix + 1];
 8486            if current_selection.range().overlaps(&next_selection.range()) {
 8487                if current_selection.id < next_selection.id {
 8488                    new_selections.remove(ix + 1);
 8489                } else {
 8490                    new_selections.remove(ix);
 8491                }
 8492            } else {
 8493                ix += 1;
 8494            }
 8495        }
 8496
 8497        select_next_state.done = true;
 8498        self.unfold_ranges(
 8499            new_selections.iter().map(|selection| selection.range()),
 8500            false,
 8501            false,
 8502            cx,
 8503        );
 8504        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 8505            selections.select(new_selections)
 8506        });
 8507
 8508        Ok(())
 8509    }
 8510
 8511    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 8512        self.push_to_selection_history();
 8513        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8514        self.select_next_match_internal(
 8515            &display_map,
 8516            action.replace_newest,
 8517            Some(Autoscroll::newest()),
 8518            cx,
 8519        )?;
 8520        Ok(())
 8521    }
 8522
 8523    pub fn select_previous(
 8524        &mut self,
 8525        action: &SelectPrevious,
 8526        cx: &mut ViewContext<Self>,
 8527    ) -> Result<()> {
 8528        self.push_to_selection_history();
 8529        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8530        let buffer = &display_map.buffer_snapshot;
 8531        let mut selections = self.selections.all::<usize>(cx);
 8532        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8533            let query = &select_prev_state.query;
 8534            if !select_prev_state.done {
 8535                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8536                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8537                let mut next_selected_range = None;
 8538                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8539                let bytes_before_last_selection =
 8540                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8541                let bytes_after_first_selection =
 8542                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8543                let query_matches = query
 8544                    .stream_find_iter(bytes_before_last_selection)
 8545                    .map(|result| (last_selection.start, result))
 8546                    .chain(
 8547                        query
 8548                            .stream_find_iter(bytes_after_first_selection)
 8549                            .map(|result| (buffer.len(), result)),
 8550                    );
 8551                for (end_offset, query_match) in query_matches {
 8552                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8553                    let offset_range =
 8554                        end_offset - query_match.end()..end_offset - query_match.start();
 8555                    let display_range = offset_range.start.to_display_point(&display_map)
 8556                        ..offset_range.end.to_display_point(&display_map);
 8557
 8558                    if !select_prev_state.wordwise
 8559                        || (!movement::is_inside_word(&display_map, display_range.start)
 8560                            && !movement::is_inside_word(&display_map, display_range.end))
 8561                    {
 8562                        next_selected_range = Some(offset_range);
 8563                        break;
 8564                    }
 8565                }
 8566
 8567                if let Some(next_selected_range) = next_selected_range {
 8568                    self.unfold_ranges([next_selected_range.clone()], false, true, cx);
 8569                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8570                        if action.replace_newest {
 8571                            s.delete(s.newest_anchor().id);
 8572                        }
 8573                        s.insert_range(next_selected_range);
 8574                    });
 8575                } else {
 8576                    select_prev_state.done = true;
 8577                }
 8578            }
 8579
 8580            self.select_prev_state = Some(select_prev_state);
 8581        } else {
 8582            let mut only_carets = true;
 8583            let mut same_text_selected = true;
 8584            let mut selected_text = None;
 8585
 8586            let mut selections_iter = selections.iter().peekable();
 8587            while let Some(selection) = selections_iter.next() {
 8588                if selection.start != selection.end {
 8589                    only_carets = false;
 8590                }
 8591
 8592                if same_text_selected {
 8593                    if selected_text.is_none() {
 8594                        selected_text =
 8595                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8596                    }
 8597
 8598                    if let Some(next_selection) = selections_iter.peek() {
 8599                        if next_selection.range().len() == selection.range().len() {
 8600                            let next_selected_text = buffer
 8601                                .text_for_range(next_selection.range())
 8602                                .collect::<String>();
 8603                            if Some(next_selected_text) != selected_text {
 8604                                same_text_selected = false;
 8605                                selected_text = None;
 8606                            }
 8607                        } else {
 8608                            same_text_selected = false;
 8609                            selected_text = None;
 8610                        }
 8611                    }
 8612                }
 8613            }
 8614
 8615            if only_carets {
 8616                for selection in &mut selections {
 8617                    let word_range = movement::surrounding_word(
 8618                        &display_map,
 8619                        selection.start.to_display_point(&display_map),
 8620                    );
 8621                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8622                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8623                    selection.goal = SelectionGoal::None;
 8624                    selection.reversed = false;
 8625                }
 8626                if selections.len() == 1 {
 8627                    let selection = selections
 8628                        .last()
 8629                        .expect("ensured that there's only one selection");
 8630                    let query = buffer
 8631                        .text_for_range(selection.start..selection.end)
 8632                        .collect::<String>();
 8633                    let is_empty = query.is_empty();
 8634                    let select_state = SelectNextState {
 8635                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8636                        wordwise: true,
 8637                        done: is_empty,
 8638                    };
 8639                    self.select_prev_state = Some(select_state);
 8640                } else {
 8641                    self.select_prev_state = None;
 8642                }
 8643
 8644                self.unfold_ranges(
 8645                    selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8646                    false,
 8647                    true,
 8648                    cx,
 8649                );
 8650                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8651                    s.select(selections);
 8652                });
 8653            } else if let Some(selected_text) = selected_text {
 8654                self.select_prev_state = Some(SelectNextState {
 8655                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8656                    wordwise: false,
 8657                    done: false,
 8658                });
 8659                self.select_previous(action, cx)?;
 8660            }
 8661        }
 8662        Ok(())
 8663    }
 8664
 8665    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 8666        let text_layout_details = &self.text_layout_details(cx);
 8667        self.transact(cx, |this, cx| {
 8668            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8669            let mut edits = Vec::new();
 8670            let mut selection_edit_ranges = Vec::new();
 8671            let mut last_toggled_row = None;
 8672            let snapshot = this.buffer.read(cx).read(cx);
 8673            let empty_str: Arc<str> = Arc::default();
 8674            let mut suffixes_inserted = Vec::new();
 8675
 8676            fn comment_prefix_range(
 8677                snapshot: &MultiBufferSnapshot,
 8678                row: MultiBufferRow,
 8679                comment_prefix: &str,
 8680                comment_prefix_whitespace: &str,
 8681            ) -> Range<Point> {
 8682                let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
 8683
 8684                let mut line_bytes = snapshot
 8685                    .bytes_in_range(start..snapshot.max_point())
 8686                    .flatten()
 8687                    .copied();
 8688
 8689                // If this line currently begins with the line comment prefix, then record
 8690                // the range containing the prefix.
 8691                if line_bytes
 8692                    .by_ref()
 8693                    .take(comment_prefix.len())
 8694                    .eq(comment_prefix.bytes())
 8695                {
 8696                    // Include any whitespace that matches the comment prefix.
 8697                    let matching_whitespace_len = line_bytes
 8698                        .zip(comment_prefix_whitespace.bytes())
 8699                        .take_while(|(a, b)| a == b)
 8700                        .count() as u32;
 8701                    let end = Point::new(
 8702                        start.row,
 8703                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 8704                    );
 8705                    start..end
 8706                } else {
 8707                    start..start
 8708                }
 8709            }
 8710
 8711            fn comment_suffix_range(
 8712                snapshot: &MultiBufferSnapshot,
 8713                row: MultiBufferRow,
 8714                comment_suffix: &str,
 8715                comment_suffix_has_leading_space: bool,
 8716            ) -> Range<Point> {
 8717                let end = Point::new(row.0, snapshot.line_len(row));
 8718                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 8719
 8720                let mut line_end_bytes = snapshot
 8721                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 8722                    .flatten()
 8723                    .copied();
 8724
 8725                let leading_space_len = if suffix_start_column > 0
 8726                    && line_end_bytes.next() == Some(b' ')
 8727                    && comment_suffix_has_leading_space
 8728                {
 8729                    1
 8730                } else {
 8731                    0
 8732                };
 8733
 8734                // If this line currently begins with the line comment prefix, then record
 8735                // the range containing the prefix.
 8736                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 8737                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 8738                    start..end
 8739                } else {
 8740                    end..end
 8741                }
 8742            }
 8743
 8744            // TODO: Handle selections that cross excerpts
 8745            for selection in &mut selections {
 8746                let start_column = snapshot
 8747                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 8748                    .len;
 8749                let language = if let Some(language) =
 8750                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 8751                {
 8752                    language
 8753                } else {
 8754                    continue;
 8755                };
 8756
 8757                selection_edit_ranges.clear();
 8758
 8759                // If multiple selections contain a given row, avoid processing that
 8760                // row more than once.
 8761                let mut start_row = MultiBufferRow(selection.start.row);
 8762                if last_toggled_row == Some(start_row) {
 8763                    start_row = start_row.next_row();
 8764                }
 8765                let end_row =
 8766                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 8767                        MultiBufferRow(selection.end.row - 1)
 8768                    } else {
 8769                        MultiBufferRow(selection.end.row)
 8770                    };
 8771                last_toggled_row = Some(end_row);
 8772
 8773                if start_row > end_row {
 8774                    continue;
 8775                }
 8776
 8777                // If the language has line comments, toggle those.
 8778                let full_comment_prefixes = language.line_comment_prefixes();
 8779                if !full_comment_prefixes.is_empty() {
 8780                    let first_prefix = full_comment_prefixes
 8781                        .first()
 8782                        .expect("prefixes is non-empty");
 8783                    let prefix_trimmed_lengths = full_comment_prefixes
 8784                        .iter()
 8785                        .map(|p| p.trim_end_matches(' ').len())
 8786                        .collect::<SmallVec<[usize; 4]>>();
 8787
 8788                    let mut all_selection_lines_are_comments = true;
 8789
 8790                    for row in start_row.0..=end_row.0 {
 8791                        let row = MultiBufferRow(row);
 8792                        if start_row < end_row && snapshot.is_line_blank(row) {
 8793                            continue;
 8794                        }
 8795
 8796                        let prefix_range = full_comment_prefixes
 8797                            .iter()
 8798                            .zip(prefix_trimmed_lengths.iter().copied())
 8799                            .map(|(prefix, trimmed_prefix_len)| {
 8800                                comment_prefix_range(
 8801                                    snapshot.deref(),
 8802                                    row,
 8803                                    &prefix[..trimmed_prefix_len],
 8804                                    &prefix[trimmed_prefix_len..],
 8805                                )
 8806                            })
 8807                            .max_by_key(|range| range.end.column - range.start.column)
 8808                            .expect("prefixes is non-empty");
 8809
 8810                        if prefix_range.is_empty() {
 8811                            all_selection_lines_are_comments = false;
 8812                        }
 8813
 8814                        selection_edit_ranges.push(prefix_range);
 8815                    }
 8816
 8817                    if all_selection_lines_are_comments {
 8818                        edits.extend(
 8819                            selection_edit_ranges
 8820                                .iter()
 8821                                .cloned()
 8822                                .map(|range| (range, empty_str.clone())),
 8823                        );
 8824                    } else {
 8825                        let min_column = selection_edit_ranges
 8826                            .iter()
 8827                            .map(|range| range.start.column)
 8828                            .min()
 8829                            .unwrap_or(0);
 8830                        edits.extend(selection_edit_ranges.iter().map(|range| {
 8831                            let position = Point::new(range.start.row, min_column);
 8832                            (position..position, first_prefix.clone())
 8833                        }));
 8834                    }
 8835                } else if let Some((full_comment_prefix, comment_suffix)) =
 8836                    language.block_comment_delimiters()
 8837                {
 8838                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 8839                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 8840                    let prefix_range = comment_prefix_range(
 8841                        snapshot.deref(),
 8842                        start_row,
 8843                        comment_prefix,
 8844                        comment_prefix_whitespace,
 8845                    );
 8846                    let suffix_range = comment_suffix_range(
 8847                        snapshot.deref(),
 8848                        end_row,
 8849                        comment_suffix.trim_start_matches(' '),
 8850                        comment_suffix.starts_with(' '),
 8851                    );
 8852
 8853                    if prefix_range.is_empty() || suffix_range.is_empty() {
 8854                        edits.push((
 8855                            prefix_range.start..prefix_range.start,
 8856                            full_comment_prefix.clone(),
 8857                        ));
 8858                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 8859                        suffixes_inserted.push((end_row, comment_suffix.len()));
 8860                    } else {
 8861                        edits.push((prefix_range, empty_str.clone()));
 8862                        edits.push((suffix_range, empty_str.clone()));
 8863                    }
 8864                } else {
 8865                    continue;
 8866                }
 8867            }
 8868
 8869            drop(snapshot);
 8870            this.buffer.update(cx, |buffer, cx| {
 8871                buffer.edit(edits, None, cx);
 8872            });
 8873
 8874            // Adjust selections so that they end before any comment suffixes that
 8875            // were inserted.
 8876            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 8877            let mut selections = this.selections.all::<Point>(cx);
 8878            let snapshot = this.buffer.read(cx).read(cx);
 8879            for selection in &mut selections {
 8880                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 8881                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 8882                        Ordering::Less => {
 8883                            suffixes_inserted.next();
 8884                            continue;
 8885                        }
 8886                        Ordering::Greater => break,
 8887                        Ordering::Equal => {
 8888                            if selection.end.column == snapshot.line_len(row) {
 8889                                if selection.is_empty() {
 8890                                    selection.start.column -= suffix_len as u32;
 8891                                }
 8892                                selection.end.column -= suffix_len as u32;
 8893                            }
 8894                            break;
 8895                        }
 8896                    }
 8897                }
 8898            }
 8899
 8900            drop(snapshot);
 8901            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 8902
 8903            let selections = this.selections.all::<Point>(cx);
 8904            let selections_on_single_row = selections.windows(2).all(|selections| {
 8905                selections[0].start.row == selections[1].start.row
 8906                    && selections[0].end.row == selections[1].end.row
 8907                    && selections[0].start.row == selections[0].end.row
 8908            });
 8909            let selections_selecting = selections
 8910                .iter()
 8911                .any(|selection| selection.start != selection.end);
 8912            let advance_downwards = action.advance_downwards
 8913                && selections_on_single_row
 8914                && !selections_selecting
 8915                && !matches!(this.mode, EditorMode::SingleLine { .. });
 8916
 8917            if advance_downwards {
 8918                let snapshot = this.buffer.read(cx).snapshot(cx);
 8919
 8920                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8921                    s.move_cursors_with(|display_snapshot, display_point, _| {
 8922                        let mut point = display_point.to_point(display_snapshot);
 8923                        point.row += 1;
 8924                        point = snapshot.clip_point(point, Bias::Left);
 8925                        let display_point = point.to_display_point(display_snapshot);
 8926                        let goal = SelectionGoal::HorizontalPosition(
 8927                            display_snapshot
 8928                                .x_for_display_point(display_point, text_layout_details)
 8929                                .into(),
 8930                        );
 8931                        (display_point, goal)
 8932                    })
 8933                });
 8934            }
 8935        });
 8936    }
 8937
 8938    pub fn select_enclosing_symbol(
 8939        &mut self,
 8940        _: &SelectEnclosingSymbol,
 8941        cx: &mut ViewContext<Self>,
 8942    ) {
 8943        let buffer = self.buffer.read(cx).snapshot(cx);
 8944        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8945
 8946        fn update_selection(
 8947            selection: &Selection<usize>,
 8948            buffer_snap: &MultiBufferSnapshot,
 8949        ) -> Option<Selection<usize>> {
 8950            let cursor = selection.head();
 8951            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 8952            for symbol in symbols.iter().rev() {
 8953                let start = symbol.range.start.to_offset(buffer_snap);
 8954                let end = symbol.range.end.to_offset(buffer_snap);
 8955                let new_range = start..end;
 8956                if start < selection.start || end > selection.end {
 8957                    return Some(Selection {
 8958                        id: selection.id,
 8959                        start: new_range.start,
 8960                        end: new_range.end,
 8961                        goal: SelectionGoal::None,
 8962                        reversed: selection.reversed,
 8963                    });
 8964                }
 8965            }
 8966            None
 8967        }
 8968
 8969        let mut selected_larger_symbol = false;
 8970        let new_selections = old_selections
 8971            .iter()
 8972            .map(|selection| match update_selection(selection, &buffer) {
 8973                Some(new_selection) => {
 8974                    if new_selection.range() != selection.range() {
 8975                        selected_larger_symbol = true;
 8976                    }
 8977                    new_selection
 8978                }
 8979                None => selection.clone(),
 8980            })
 8981            .collect::<Vec<_>>();
 8982
 8983        if selected_larger_symbol {
 8984            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8985                s.select(new_selections);
 8986            });
 8987        }
 8988    }
 8989
 8990    pub fn select_larger_syntax_node(
 8991        &mut self,
 8992        _: &SelectLargerSyntaxNode,
 8993        cx: &mut ViewContext<Self>,
 8994    ) {
 8995        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8996        let buffer = self.buffer.read(cx).snapshot(cx);
 8997        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8998
 8999        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9000        let mut selected_larger_node = false;
 9001        let new_selections = old_selections
 9002            .iter()
 9003            .map(|selection| {
 9004                let old_range = selection.start..selection.end;
 9005                let mut new_range = old_range.clone();
 9006                while let Some(containing_range) =
 9007                    buffer.range_for_syntax_ancestor(new_range.clone())
 9008                {
 9009                    new_range = containing_range;
 9010                    if !display_map.intersects_fold(new_range.start)
 9011                        && !display_map.intersects_fold(new_range.end)
 9012                    {
 9013                        break;
 9014                    }
 9015                }
 9016
 9017                selected_larger_node |= new_range != old_range;
 9018                Selection {
 9019                    id: selection.id,
 9020                    start: new_range.start,
 9021                    end: new_range.end,
 9022                    goal: SelectionGoal::None,
 9023                    reversed: selection.reversed,
 9024                }
 9025            })
 9026            .collect::<Vec<_>>();
 9027
 9028        if selected_larger_node {
 9029            stack.push(old_selections);
 9030            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9031                s.select(new_selections);
 9032            });
 9033        }
 9034        self.select_larger_syntax_node_stack = stack;
 9035    }
 9036
 9037    pub fn select_smaller_syntax_node(
 9038        &mut self,
 9039        _: &SelectSmallerSyntaxNode,
 9040        cx: &mut ViewContext<Self>,
 9041    ) {
 9042        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9043        if let Some(selections) = stack.pop() {
 9044            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9045                s.select(selections.to_vec());
 9046            });
 9047        }
 9048        self.select_larger_syntax_node_stack = stack;
 9049    }
 9050
 9051    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 9052        if !EditorSettings::get_global(cx).gutter.runnables {
 9053            self.clear_tasks();
 9054            return Task::ready(());
 9055        }
 9056        let project = self.project.clone();
 9057        cx.spawn(|this, mut cx| async move {
 9058            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 9059                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 9060            }) else {
 9061                return;
 9062            };
 9063
 9064            let Some(project) = project else {
 9065                return;
 9066            };
 9067
 9068            let hide_runnables = project
 9069                .update(&mut cx, |project, cx| {
 9070                    // Do not display any test indicators in non-dev server remote projects.
 9071                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 9072                })
 9073                .unwrap_or(true);
 9074            if hide_runnables {
 9075                return;
 9076            }
 9077            let new_rows =
 9078                cx.background_executor()
 9079                    .spawn({
 9080                        let snapshot = display_snapshot.clone();
 9081                        async move {
 9082                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 9083                        }
 9084                    })
 9085                    .await;
 9086            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 9087
 9088            this.update(&mut cx, |this, _| {
 9089                this.clear_tasks();
 9090                for (key, value) in rows {
 9091                    this.insert_tasks(key, value);
 9092                }
 9093            })
 9094            .ok();
 9095        })
 9096    }
 9097    fn fetch_runnable_ranges(
 9098        snapshot: &DisplaySnapshot,
 9099        range: Range<Anchor>,
 9100    ) -> Vec<language::RunnableRange> {
 9101        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 9102    }
 9103
 9104    fn runnable_rows(
 9105        project: Model<Project>,
 9106        snapshot: DisplaySnapshot,
 9107        runnable_ranges: Vec<RunnableRange>,
 9108        mut cx: AsyncWindowContext,
 9109    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 9110        runnable_ranges
 9111            .into_iter()
 9112            .filter_map(|mut runnable| {
 9113                let tasks = cx
 9114                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 9115                    .ok()?;
 9116                if tasks.is_empty() {
 9117                    return None;
 9118                }
 9119
 9120                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 9121
 9122                let row = snapshot
 9123                    .buffer_snapshot
 9124                    .buffer_line_for_row(MultiBufferRow(point.row))?
 9125                    .1
 9126                    .start
 9127                    .row;
 9128
 9129                let context_range =
 9130                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 9131                Some((
 9132                    (runnable.buffer_id, row),
 9133                    RunnableTasks {
 9134                        templates: tasks,
 9135                        offset: MultiBufferOffset(runnable.run_range.start),
 9136                        context_range,
 9137                        column: point.column,
 9138                        extra_variables: runnable.extra_captures,
 9139                    },
 9140                ))
 9141            })
 9142            .collect()
 9143    }
 9144
 9145    fn templates_with_tags(
 9146        project: &Model<Project>,
 9147        runnable: &mut Runnable,
 9148        cx: &WindowContext<'_>,
 9149    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 9150        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 9151            let (worktree_id, file) = project
 9152                .buffer_for_id(runnable.buffer, cx)
 9153                .and_then(|buffer| buffer.read(cx).file())
 9154                .map(|file| (file.worktree_id(cx), file.clone()))
 9155                .unzip();
 9156
 9157            (
 9158                project.task_store().read(cx).task_inventory().cloned(),
 9159                worktree_id,
 9160                file,
 9161            )
 9162        });
 9163
 9164        let tags = mem::take(&mut runnable.tags);
 9165        let mut tags: Vec<_> = tags
 9166            .into_iter()
 9167            .flat_map(|tag| {
 9168                let tag = tag.0.clone();
 9169                inventory
 9170                    .as_ref()
 9171                    .into_iter()
 9172                    .flat_map(|inventory| {
 9173                        inventory.read(cx).list_tasks(
 9174                            file.clone(),
 9175                            Some(runnable.language.clone()),
 9176                            worktree_id,
 9177                            cx,
 9178                        )
 9179                    })
 9180                    .filter(move |(_, template)| {
 9181                        template.tags.iter().any(|source_tag| source_tag == &tag)
 9182                    })
 9183            })
 9184            .sorted_by_key(|(kind, _)| kind.to_owned())
 9185            .collect();
 9186        if let Some((leading_tag_source, _)) = tags.first() {
 9187            // Strongest source wins; if we have worktree tag binding, prefer that to
 9188            // global and language bindings;
 9189            // if we have a global binding, prefer that to language binding.
 9190            let first_mismatch = tags
 9191                .iter()
 9192                .position(|(tag_source, _)| tag_source != leading_tag_source);
 9193            if let Some(index) = first_mismatch {
 9194                tags.truncate(index);
 9195            }
 9196        }
 9197
 9198        tags
 9199    }
 9200
 9201    pub fn move_to_enclosing_bracket(
 9202        &mut self,
 9203        _: &MoveToEnclosingBracket,
 9204        cx: &mut ViewContext<Self>,
 9205    ) {
 9206        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9207            s.move_offsets_with(|snapshot, selection| {
 9208                let Some(enclosing_bracket_ranges) =
 9209                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 9210                else {
 9211                    return;
 9212                };
 9213
 9214                let mut best_length = usize::MAX;
 9215                let mut best_inside = false;
 9216                let mut best_in_bracket_range = false;
 9217                let mut best_destination = None;
 9218                for (open, close) in enclosing_bracket_ranges {
 9219                    let close = close.to_inclusive();
 9220                    let length = close.end() - open.start;
 9221                    let inside = selection.start >= open.end && selection.end <= *close.start();
 9222                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 9223                        || close.contains(&selection.head());
 9224
 9225                    // If best is next to a bracket and current isn't, skip
 9226                    if !in_bracket_range && best_in_bracket_range {
 9227                        continue;
 9228                    }
 9229
 9230                    // Prefer smaller lengths unless best is inside and current isn't
 9231                    if length > best_length && (best_inside || !inside) {
 9232                        continue;
 9233                    }
 9234
 9235                    best_length = length;
 9236                    best_inside = inside;
 9237                    best_in_bracket_range = in_bracket_range;
 9238                    best_destination = Some(
 9239                        if close.contains(&selection.start) && close.contains(&selection.end) {
 9240                            if inside {
 9241                                open.end
 9242                            } else {
 9243                                open.start
 9244                            }
 9245                        } else if inside {
 9246                            *close.start()
 9247                        } else {
 9248                            *close.end()
 9249                        },
 9250                    );
 9251                }
 9252
 9253                if let Some(destination) = best_destination {
 9254                    selection.collapse_to(destination, SelectionGoal::None);
 9255                }
 9256            })
 9257        });
 9258    }
 9259
 9260    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 9261        self.end_selection(cx);
 9262        self.selection_history.mode = SelectionHistoryMode::Undoing;
 9263        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 9264            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9265            self.select_next_state = entry.select_next_state;
 9266            self.select_prev_state = entry.select_prev_state;
 9267            self.add_selections_state = entry.add_selections_state;
 9268            self.request_autoscroll(Autoscroll::newest(), cx);
 9269        }
 9270        self.selection_history.mode = SelectionHistoryMode::Normal;
 9271    }
 9272
 9273    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 9274        self.end_selection(cx);
 9275        self.selection_history.mode = SelectionHistoryMode::Redoing;
 9276        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 9277            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9278            self.select_next_state = entry.select_next_state;
 9279            self.select_prev_state = entry.select_prev_state;
 9280            self.add_selections_state = entry.add_selections_state;
 9281            self.request_autoscroll(Autoscroll::newest(), cx);
 9282        }
 9283        self.selection_history.mode = SelectionHistoryMode::Normal;
 9284    }
 9285
 9286    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 9287        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 9288    }
 9289
 9290    pub fn expand_excerpts_down(
 9291        &mut self,
 9292        action: &ExpandExcerptsDown,
 9293        cx: &mut ViewContext<Self>,
 9294    ) {
 9295        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 9296    }
 9297
 9298    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 9299        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 9300    }
 9301
 9302    pub fn expand_excerpts_for_direction(
 9303        &mut self,
 9304        lines: u32,
 9305        direction: ExpandExcerptDirection,
 9306        cx: &mut ViewContext<Self>,
 9307    ) {
 9308        let selections = self.selections.disjoint_anchors();
 9309
 9310        let lines = if lines == 0 {
 9311            EditorSettings::get_global(cx).expand_excerpt_lines
 9312        } else {
 9313            lines
 9314        };
 9315
 9316        self.buffer.update(cx, |buffer, cx| {
 9317            buffer.expand_excerpts(
 9318                selections
 9319                    .iter()
 9320                    .map(|selection| selection.head().excerpt_id)
 9321                    .dedup(),
 9322                lines,
 9323                direction,
 9324                cx,
 9325            )
 9326        })
 9327    }
 9328
 9329    pub fn expand_excerpt(
 9330        &mut self,
 9331        excerpt: ExcerptId,
 9332        direction: ExpandExcerptDirection,
 9333        cx: &mut ViewContext<Self>,
 9334    ) {
 9335        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 9336        self.buffer.update(cx, |buffer, cx| {
 9337            buffer.expand_excerpts([excerpt], lines, direction, cx)
 9338        })
 9339    }
 9340
 9341    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 9342        self.go_to_diagnostic_impl(Direction::Next, cx)
 9343    }
 9344
 9345    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 9346        self.go_to_diagnostic_impl(Direction::Prev, cx)
 9347    }
 9348
 9349    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 9350        let buffer = self.buffer.read(cx).snapshot(cx);
 9351        let selection = self.selections.newest::<usize>(cx);
 9352
 9353        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 9354        if direction == Direction::Next {
 9355            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 9356                let (group_id, jump_to) = popover.activation_info();
 9357                if self.activate_diagnostics(group_id, cx) {
 9358                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9359                        let mut new_selection = s.newest_anchor().clone();
 9360                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 9361                        s.select_anchors(vec![new_selection.clone()]);
 9362                    });
 9363                }
 9364                return;
 9365            }
 9366        }
 9367
 9368        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 9369            active_diagnostics
 9370                .primary_range
 9371                .to_offset(&buffer)
 9372                .to_inclusive()
 9373        });
 9374        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 9375            if active_primary_range.contains(&selection.head()) {
 9376                *active_primary_range.start()
 9377            } else {
 9378                selection.head()
 9379            }
 9380        } else {
 9381            selection.head()
 9382        };
 9383        let snapshot = self.snapshot(cx);
 9384        loop {
 9385            let diagnostics = if direction == Direction::Prev {
 9386                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 9387            } else {
 9388                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 9389            }
 9390            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 9391            let group = diagnostics
 9392                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 9393                // be sorted in a stable way
 9394                // skip until we are at current active diagnostic, if it exists
 9395                .skip_while(|entry| {
 9396                    (match direction {
 9397                        Direction::Prev => entry.range.start >= search_start,
 9398                        Direction::Next => entry.range.start <= search_start,
 9399                    }) && self
 9400                        .active_diagnostics
 9401                        .as_ref()
 9402                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 9403                })
 9404                .find_map(|entry| {
 9405                    if entry.diagnostic.is_primary
 9406                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 9407                        && !entry.range.is_empty()
 9408                        // if we match with the active diagnostic, skip it
 9409                        && Some(entry.diagnostic.group_id)
 9410                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 9411                    {
 9412                        Some((entry.range, entry.diagnostic.group_id))
 9413                    } else {
 9414                        None
 9415                    }
 9416                });
 9417
 9418            if let Some((primary_range, group_id)) = group {
 9419                if self.activate_diagnostics(group_id, cx) {
 9420                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9421                        s.select(vec![Selection {
 9422                            id: selection.id,
 9423                            start: primary_range.start,
 9424                            end: primary_range.start,
 9425                            reversed: false,
 9426                            goal: SelectionGoal::None,
 9427                        }]);
 9428                    });
 9429                }
 9430                break;
 9431            } else {
 9432                // Cycle around to the start of the buffer, potentially moving back to the start of
 9433                // the currently active diagnostic.
 9434                active_primary_range.take();
 9435                if direction == Direction::Prev {
 9436                    if search_start == buffer.len() {
 9437                        break;
 9438                    } else {
 9439                        search_start = buffer.len();
 9440                    }
 9441                } else if search_start == 0 {
 9442                    break;
 9443                } else {
 9444                    search_start = 0;
 9445                }
 9446            }
 9447        }
 9448    }
 9449
 9450    fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 9451        let snapshot = self
 9452            .display_map
 9453            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9454        let selection = self.selections.newest::<Point>(cx);
 9455        self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
 9456    }
 9457
 9458    fn go_to_hunk_after_position(
 9459        &mut self,
 9460        snapshot: &DisplaySnapshot,
 9461        position: Point,
 9462        cx: &mut ViewContext<'_, Editor>,
 9463    ) -> Option<MultiBufferDiffHunk> {
 9464        if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9465            snapshot,
 9466            position,
 9467            false,
 9468            snapshot
 9469                .buffer_snapshot
 9470                .git_diff_hunks_in_range(MultiBufferRow(position.row + 1)..MultiBufferRow::MAX),
 9471            cx,
 9472        ) {
 9473            return Some(hunk);
 9474        }
 9475
 9476        let wrapped_point = Point::zero();
 9477        self.go_to_next_hunk_in_direction(
 9478            snapshot,
 9479            wrapped_point,
 9480            true,
 9481            snapshot.buffer_snapshot.git_diff_hunks_in_range(
 9482                MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
 9483            ),
 9484            cx,
 9485        )
 9486    }
 9487
 9488    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 9489        let snapshot = self
 9490            .display_map
 9491            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9492        let selection = self.selections.newest::<Point>(cx);
 9493
 9494        self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
 9495    }
 9496
 9497    fn go_to_hunk_before_position(
 9498        &mut self,
 9499        snapshot: &DisplaySnapshot,
 9500        position: Point,
 9501        cx: &mut ViewContext<'_, Editor>,
 9502    ) -> Option<MultiBufferDiffHunk> {
 9503        if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9504            snapshot,
 9505            position,
 9506            false,
 9507            snapshot
 9508                .buffer_snapshot
 9509                .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(position.row)),
 9510            cx,
 9511        ) {
 9512            return Some(hunk);
 9513        }
 9514
 9515        let wrapped_point = snapshot.buffer_snapshot.max_point();
 9516        self.go_to_next_hunk_in_direction(
 9517            snapshot,
 9518            wrapped_point,
 9519            true,
 9520            snapshot
 9521                .buffer_snapshot
 9522                .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(wrapped_point.row)),
 9523            cx,
 9524        )
 9525    }
 9526
 9527    fn go_to_next_hunk_in_direction(
 9528        &mut self,
 9529        snapshot: &DisplaySnapshot,
 9530        initial_point: Point,
 9531        is_wrapped: bool,
 9532        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
 9533        cx: &mut ViewContext<Editor>,
 9534    ) -> Option<MultiBufferDiffHunk> {
 9535        let display_point = initial_point.to_display_point(snapshot);
 9536        let mut hunks = hunks
 9537            .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
 9538            .filter(|(display_hunk, _)| {
 9539                is_wrapped || !display_hunk.contains_display_row(display_point.row())
 9540            })
 9541            .dedup();
 9542
 9543        if let Some((display_hunk, hunk)) = hunks.next() {
 9544            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9545                let row = display_hunk.start_display_row();
 9546                let point = DisplayPoint::new(row, 0);
 9547                s.select_display_ranges([point..point]);
 9548            });
 9549
 9550            Some(hunk)
 9551        } else {
 9552            None
 9553        }
 9554    }
 9555
 9556    pub fn go_to_definition(
 9557        &mut self,
 9558        _: &GoToDefinition,
 9559        cx: &mut ViewContext<Self>,
 9560    ) -> Task<Result<Navigated>> {
 9561        let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
 9562        cx.spawn(|editor, mut cx| async move {
 9563            if definition.await? == Navigated::Yes {
 9564                return Ok(Navigated::Yes);
 9565            }
 9566            match editor.update(&mut cx, |editor, cx| {
 9567                editor.find_all_references(&FindAllReferences, cx)
 9568            })? {
 9569                Some(references) => references.await,
 9570                None => Ok(Navigated::No),
 9571            }
 9572        })
 9573    }
 9574
 9575    pub fn go_to_declaration(
 9576        &mut self,
 9577        _: &GoToDeclaration,
 9578        cx: &mut ViewContext<Self>,
 9579    ) -> Task<Result<Navigated>> {
 9580        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
 9581    }
 9582
 9583    pub fn go_to_declaration_split(
 9584        &mut self,
 9585        _: &GoToDeclaration,
 9586        cx: &mut ViewContext<Self>,
 9587    ) -> Task<Result<Navigated>> {
 9588        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
 9589    }
 9590
 9591    pub fn go_to_implementation(
 9592        &mut self,
 9593        _: &GoToImplementation,
 9594        cx: &mut ViewContext<Self>,
 9595    ) -> Task<Result<Navigated>> {
 9596        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 9597    }
 9598
 9599    pub fn go_to_implementation_split(
 9600        &mut self,
 9601        _: &GoToImplementationSplit,
 9602        cx: &mut ViewContext<Self>,
 9603    ) -> Task<Result<Navigated>> {
 9604        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 9605    }
 9606
 9607    pub fn go_to_type_definition(
 9608        &mut self,
 9609        _: &GoToTypeDefinition,
 9610        cx: &mut ViewContext<Self>,
 9611    ) -> Task<Result<Navigated>> {
 9612        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 9613    }
 9614
 9615    pub fn go_to_definition_split(
 9616        &mut self,
 9617        _: &GoToDefinitionSplit,
 9618        cx: &mut ViewContext<Self>,
 9619    ) -> Task<Result<Navigated>> {
 9620        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 9621    }
 9622
 9623    pub fn go_to_type_definition_split(
 9624        &mut self,
 9625        _: &GoToTypeDefinitionSplit,
 9626        cx: &mut ViewContext<Self>,
 9627    ) -> Task<Result<Navigated>> {
 9628        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 9629    }
 9630
 9631    fn go_to_definition_of_kind(
 9632        &mut self,
 9633        kind: GotoDefinitionKind,
 9634        split: bool,
 9635        cx: &mut ViewContext<Self>,
 9636    ) -> Task<Result<Navigated>> {
 9637        let Some(provider) = self.semantics_provider.clone() else {
 9638            return Task::ready(Ok(Navigated::No));
 9639        };
 9640        let buffer = self.buffer.read(cx);
 9641        let head = self.selections.newest::<usize>(cx).head();
 9642        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 9643            text_anchor
 9644        } else {
 9645            return Task::ready(Ok(Navigated::No));
 9646        };
 9647
 9648        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
 9649            return Task::ready(Ok(Navigated::No));
 9650        };
 9651
 9652        cx.spawn(|editor, mut cx| async move {
 9653            let definitions = definitions.await?;
 9654            let navigated = editor
 9655                .update(&mut cx, |editor, cx| {
 9656                    editor.navigate_to_hover_links(
 9657                        Some(kind),
 9658                        definitions
 9659                            .into_iter()
 9660                            .filter(|location| {
 9661                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 9662                            })
 9663                            .map(HoverLink::Text)
 9664                            .collect::<Vec<_>>(),
 9665                        split,
 9666                        cx,
 9667                    )
 9668                })?
 9669                .await?;
 9670            anyhow::Ok(navigated)
 9671        })
 9672    }
 9673
 9674    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 9675        let position = self.selections.newest_anchor().head();
 9676        let Some((buffer, buffer_position)) =
 9677            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9678        else {
 9679            return;
 9680        };
 9681
 9682        cx.spawn(|editor, mut cx| async move {
 9683            if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
 9684                editor.update(&mut cx, |_, cx| {
 9685                    cx.open_url(&url);
 9686                })
 9687            } else {
 9688                Ok(())
 9689            }
 9690        })
 9691        .detach();
 9692    }
 9693
 9694    pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
 9695        let Some(workspace) = self.workspace() else {
 9696            return;
 9697        };
 9698
 9699        let position = self.selections.newest_anchor().head();
 9700
 9701        let Some((buffer, buffer_position)) =
 9702            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9703        else {
 9704            return;
 9705        };
 9706
 9707        let project = self.project.clone();
 9708
 9709        cx.spawn(|_, mut cx| async move {
 9710            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
 9711
 9712            if let Some((_, path)) = result {
 9713                workspace
 9714                    .update(&mut cx, |workspace, cx| {
 9715                        workspace.open_resolved_path(path, cx)
 9716                    })?
 9717                    .await?;
 9718            }
 9719            anyhow::Ok(())
 9720        })
 9721        .detach();
 9722    }
 9723
 9724    pub(crate) fn navigate_to_hover_links(
 9725        &mut self,
 9726        kind: Option<GotoDefinitionKind>,
 9727        mut definitions: Vec<HoverLink>,
 9728        split: bool,
 9729        cx: &mut ViewContext<Editor>,
 9730    ) -> Task<Result<Navigated>> {
 9731        // If there is one definition, just open it directly
 9732        if definitions.len() == 1 {
 9733            let definition = definitions.pop().unwrap();
 9734
 9735            enum TargetTaskResult {
 9736                Location(Option<Location>),
 9737                AlreadyNavigated,
 9738            }
 9739
 9740            let target_task = match definition {
 9741                HoverLink::Text(link) => {
 9742                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
 9743                }
 9744                HoverLink::InlayHint(lsp_location, server_id) => {
 9745                    let computation = self.compute_target_location(lsp_location, server_id, cx);
 9746                    cx.background_executor().spawn(async move {
 9747                        let location = computation.await?;
 9748                        Ok(TargetTaskResult::Location(location))
 9749                    })
 9750                }
 9751                HoverLink::Url(url) => {
 9752                    cx.open_url(&url);
 9753                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
 9754                }
 9755                HoverLink::File(path) => {
 9756                    if let Some(workspace) = self.workspace() {
 9757                        cx.spawn(|_, mut cx| async move {
 9758                            workspace
 9759                                .update(&mut cx, |workspace, cx| {
 9760                                    workspace.open_resolved_path(path, cx)
 9761                                })?
 9762                                .await
 9763                                .map(|_| TargetTaskResult::AlreadyNavigated)
 9764                        })
 9765                    } else {
 9766                        Task::ready(Ok(TargetTaskResult::Location(None)))
 9767                    }
 9768                }
 9769            };
 9770            cx.spawn(|editor, mut cx| async move {
 9771                let target = match target_task.await.context("target resolution task")? {
 9772                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
 9773                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
 9774                    TargetTaskResult::Location(Some(target)) => target,
 9775                };
 9776
 9777                editor.update(&mut cx, |editor, cx| {
 9778                    let Some(workspace) = editor.workspace() else {
 9779                        return Navigated::No;
 9780                    };
 9781                    let pane = workspace.read(cx).active_pane().clone();
 9782
 9783                    let range = target.range.to_offset(target.buffer.read(cx));
 9784                    let range = editor.range_for_match(&range);
 9785
 9786                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 9787                        let buffer = target.buffer.read(cx);
 9788                        let range = check_multiline_range(buffer, range);
 9789                        editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9790                            s.select_ranges([range]);
 9791                        });
 9792                    } else {
 9793                        cx.window_context().defer(move |cx| {
 9794                            let target_editor: View<Self> =
 9795                                workspace.update(cx, |workspace, cx| {
 9796                                    let pane = if split {
 9797                                        workspace.adjacent_pane(cx)
 9798                                    } else {
 9799                                        workspace.active_pane().clone()
 9800                                    };
 9801
 9802                                    workspace.open_project_item(
 9803                                        pane,
 9804                                        target.buffer.clone(),
 9805                                        true,
 9806                                        true,
 9807                                        cx,
 9808                                    )
 9809                                });
 9810                            target_editor.update(cx, |target_editor, cx| {
 9811                                // When selecting a definition in a different buffer, disable the nav history
 9812                                // to avoid creating a history entry at the previous cursor location.
 9813                                pane.update(cx, |pane, _| pane.disable_history());
 9814                                let buffer = target.buffer.read(cx);
 9815                                let range = check_multiline_range(buffer, range);
 9816                                target_editor.change_selections(
 9817                                    Some(Autoscroll::focused()),
 9818                                    cx,
 9819                                    |s| {
 9820                                        s.select_ranges([range]);
 9821                                    },
 9822                                );
 9823                                pane.update(cx, |pane, _| pane.enable_history());
 9824                            });
 9825                        });
 9826                    }
 9827                    Navigated::Yes
 9828                })
 9829            })
 9830        } else if !definitions.is_empty() {
 9831            cx.spawn(|editor, mut cx| async move {
 9832                let (title, location_tasks, workspace) = editor
 9833                    .update(&mut cx, |editor, cx| {
 9834                        let tab_kind = match kind {
 9835                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 9836                            _ => "Definitions",
 9837                        };
 9838                        let title = definitions
 9839                            .iter()
 9840                            .find_map(|definition| match definition {
 9841                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 9842                                    let buffer = origin.buffer.read(cx);
 9843                                    format!(
 9844                                        "{} for {}",
 9845                                        tab_kind,
 9846                                        buffer
 9847                                            .text_for_range(origin.range.clone())
 9848                                            .collect::<String>()
 9849                                    )
 9850                                }),
 9851                                HoverLink::InlayHint(_, _) => None,
 9852                                HoverLink::Url(_) => None,
 9853                                HoverLink::File(_) => None,
 9854                            })
 9855                            .unwrap_or(tab_kind.to_string());
 9856                        let location_tasks = definitions
 9857                            .into_iter()
 9858                            .map(|definition| match definition {
 9859                                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 9860                                HoverLink::InlayHint(lsp_location, server_id) => {
 9861                                    editor.compute_target_location(lsp_location, server_id, cx)
 9862                                }
 9863                                HoverLink::Url(_) => Task::ready(Ok(None)),
 9864                                HoverLink::File(_) => Task::ready(Ok(None)),
 9865                            })
 9866                            .collect::<Vec<_>>();
 9867                        (title, location_tasks, editor.workspace().clone())
 9868                    })
 9869                    .context("location tasks preparation")?;
 9870
 9871                let locations = future::join_all(location_tasks)
 9872                    .await
 9873                    .into_iter()
 9874                    .filter_map(|location| location.transpose())
 9875                    .collect::<Result<_>>()
 9876                    .context("location tasks")?;
 9877
 9878                let Some(workspace) = workspace else {
 9879                    return Ok(Navigated::No);
 9880                };
 9881                let opened = workspace
 9882                    .update(&mut cx, |workspace, cx| {
 9883                        Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
 9884                    })
 9885                    .ok();
 9886
 9887                anyhow::Ok(Navigated::from_bool(opened.is_some()))
 9888            })
 9889        } else {
 9890            Task::ready(Ok(Navigated::No))
 9891        }
 9892    }
 9893
 9894    fn compute_target_location(
 9895        &self,
 9896        lsp_location: lsp::Location,
 9897        server_id: LanguageServerId,
 9898        cx: &mut ViewContext<Self>,
 9899    ) -> Task<anyhow::Result<Option<Location>>> {
 9900        let Some(project) = self.project.clone() else {
 9901            return Task::Ready(Some(Ok(None)));
 9902        };
 9903
 9904        cx.spawn(move |editor, mut cx| async move {
 9905            let location_task = editor.update(&mut cx, |_, cx| {
 9906                project.update(cx, |project, cx| {
 9907                    let language_server_name = project
 9908                        .language_server_statuses(cx)
 9909                        .find(|(id, _)| server_id == *id)
 9910                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
 9911                    language_server_name.map(|language_server_name| {
 9912                        project.open_local_buffer_via_lsp(
 9913                            lsp_location.uri.clone(),
 9914                            server_id,
 9915                            language_server_name,
 9916                            cx,
 9917                        )
 9918                    })
 9919                })
 9920            })?;
 9921            let location = match location_task {
 9922                Some(task) => Some({
 9923                    let target_buffer_handle = task.await.context("open local buffer")?;
 9924                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
 9925                        let target_start = target_buffer
 9926                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
 9927                        let target_end = target_buffer
 9928                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
 9929                        target_buffer.anchor_after(target_start)
 9930                            ..target_buffer.anchor_before(target_end)
 9931                    })?;
 9932                    Location {
 9933                        buffer: target_buffer_handle,
 9934                        range,
 9935                    }
 9936                }),
 9937                None => None,
 9938            };
 9939            Ok(location)
 9940        })
 9941    }
 9942
 9943    pub fn find_all_references(
 9944        &mut self,
 9945        _: &FindAllReferences,
 9946        cx: &mut ViewContext<Self>,
 9947    ) -> Option<Task<Result<Navigated>>> {
 9948        let multi_buffer = self.buffer.read(cx);
 9949        let selection = self.selections.newest::<usize>(cx);
 9950        let head = selection.head();
 9951
 9952        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 9953        let head_anchor = multi_buffer_snapshot.anchor_at(
 9954            head,
 9955            if head < selection.tail() {
 9956                Bias::Right
 9957            } else {
 9958                Bias::Left
 9959            },
 9960        );
 9961
 9962        match self
 9963            .find_all_references_task_sources
 9964            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
 9965        {
 9966            Ok(_) => {
 9967                log::info!(
 9968                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
 9969                );
 9970                return None;
 9971            }
 9972            Err(i) => {
 9973                self.find_all_references_task_sources.insert(i, head_anchor);
 9974            }
 9975        }
 9976
 9977        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
 9978        let workspace = self.workspace()?;
 9979        let project = workspace.read(cx).project().clone();
 9980        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
 9981        Some(cx.spawn(|editor, mut cx| async move {
 9982            let _cleanup = defer({
 9983                let mut cx = cx.clone();
 9984                move || {
 9985                    let _ = editor.update(&mut cx, |editor, _| {
 9986                        if let Ok(i) =
 9987                            editor
 9988                                .find_all_references_task_sources
 9989                                .binary_search_by(|anchor| {
 9990                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
 9991                                })
 9992                        {
 9993                            editor.find_all_references_task_sources.remove(i);
 9994                        }
 9995                    });
 9996                }
 9997            });
 9998
 9999            let locations = references.await?;
10000            if locations.is_empty() {
10001                return anyhow::Ok(Navigated::No);
10002            }
10003
10004            workspace.update(&mut cx, |workspace, cx| {
10005                let title = locations
10006                    .first()
10007                    .as_ref()
10008                    .map(|location| {
10009                        let buffer = location.buffer.read(cx);
10010                        format!(
10011                            "References to `{}`",
10012                            buffer
10013                                .text_for_range(location.range.clone())
10014                                .collect::<String>()
10015                        )
10016                    })
10017                    .unwrap();
10018                Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
10019                Navigated::Yes
10020            })
10021        }))
10022    }
10023
10024    /// Opens a multibuffer with the given project locations in it
10025    pub fn open_locations_in_multibuffer(
10026        workspace: &mut Workspace,
10027        mut locations: Vec<Location>,
10028        title: String,
10029        split: bool,
10030        cx: &mut ViewContext<Workspace>,
10031    ) {
10032        // If there are multiple definitions, open them in a multibuffer
10033        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10034        let mut locations = locations.into_iter().peekable();
10035        let mut ranges_to_highlight = Vec::new();
10036        let capability = workspace.project().read(cx).capability();
10037
10038        let excerpt_buffer = cx.new_model(|cx| {
10039            let mut multibuffer = MultiBuffer::new(capability);
10040            while let Some(location) = locations.next() {
10041                let buffer = location.buffer.read(cx);
10042                let mut ranges_for_buffer = Vec::new();
10043                let range = location.range.to_offset(buffer);
10044                ranges_for_buffer.push(range.clone());
10045
10046                while let Some(next_location) = locations.peek() {
10047                    if next_location.buffer == location.buffer {
10048                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
10049                        locations.next();
10050                    } else {
10051                        break;
10052                    }
10053                }
10054
10055                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10056                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
10057                    location.buffer.clone(),
10058                    ranges_for_buffer,
10059                    DEFAULT_MULTIBUFFER_CONTEXT,
10060                    cx,
10061                ))
10062            }
10063
10064            multibuffer.with_title(title)
10065        });
10066
10067        let editor = cx.new_view(|cx| {
10068            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
10069        });
10070        editor.update(cx, |editor, cx| {
10071            if let Some(first_range) = ranges_to_highlight.first() {
10072                editor.change_selections(None, cx, |selections| {
10073                    selections.clear_disjoint();
10074                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10075                });
10076            }
10077            editor.highlight_background::<Self>(
10078                &ranges_to_highlight,
10079                |theme| theme.editor_highlighted_line_background,
10080                cx,
10081            );
10082        });
10083
10084        let item = Box::new(editor);
10085        let item_id = item.item_id();
10086
10087        if split {
10088            workspace.split_item(SplitDirection::Right, item.clone(), cx);
10089        } else {
10090            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10091                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10092                    pane.close_current_preview_item(cx)
10093                } else {
10094                    None
10095                }
10096            });
10097            workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
10098        }
10099        workspace.active_pane().update(cx, |pane, cx| {
10100            pane.set_preview_item_id(Some(item_id), cx);
10101        });
10102    }
10103
10104    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10105        use language::ToOffset as _;
10106
10107        let provider = self.semantics_provider.clone()?;
10108        let selection = self.selections.newest_anchor().clone();
10109        let (cursor_buffer, cursor_buffer_position) = self
10110            .buffer
10111            .read(cx)
10112            .text_anchor_for_position(selection.head(), cx)?;
10113        let (tail_buffer, cursor_buffer_position_end) = self
10114            .buffer
10115            .read(cx)
10116            .text_anchor_for_position(selection.tail(), cx)?;
10117        if tail_buffer != cursor_buffer {
10118            return None;
10119        }
10120
10121        let snapshot = cursor_buffer.read(cx).snapshot();
10122        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10123        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10124        let prepare_rename = provider
10125            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10126            .unwrap_or_else(|| Task::ready(Ok(None)));
10127        drop(snapshot);
10128
10129        Some(cx.spawn(|this, mut cx| async move {
10130            let rename_range = if let Some(range) = prepare_rename.await? {
10131                Some(range)
10132            } else {
10133                this.update(&mut cx, |this, cx| {
10134                    let buffer = this.buffer.read(cx).snapshot(cx);
10135                    let mut buffer_highlights = this
10136                        .document_highlights_for_position(selection.head(), &buffer)
10137                        .filter(|highlight| {
10138                            highlight.start.excerpt_id == selection.head().excerpt_id
10139                                && highlight.end.excerpt_id == selection.head().excerpt_id
10140                        });
10141                    buffer_highlights
10142                        .next()
10143                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10144                })?
10145            };
10146            if let Some(rename_range) = rename_range {
10147                this.update(&mut cx, |this, cx| {
10148                    let snapshot = cursor_buffer.read(cx).snapshot();
10149                    let rename_buffer_range = rename_range.to_offset(&snapshot);
10150                    let cursor_offset_in_rename_range =
10151                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10152                    let cursor_offset_in_rename_range_end =
10153                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10154
10155                    this.take_rename(false, cx);
10156                    let buffer = this.buffer.read(cx).read(cx);
10157                    let cursor_offset = selection.head().to_offset(&buffer);
10158                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10159                    let rename_end = rename_start + rename_buffer_range.len();
10160                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10161                    let mut old_highlight_id = None;
10162                    let old_name: Arc<str> = buffer
10163                        .chunks(rename_start..rename_end, true)
10164                        .map(|chunk| {
10165                            if old_highlight_id.is_none() {
10166                                old_highlight_id = chunk.syntax_highlight_id;
10167                            }
10168                            chunk.text
10169                        })
10170                        .collect::<String>()
10171                        .into();
10172
10173                    drop(buffer);
10174
10175                    // Position the selection in the rename editor so that it matches the current selection.
10176                    this.show_local_selections = false;
10177                    let rename_editor = cx.new_view(|cx| {
10178                        let mut editor = Editor::single_line(cx);
10179                        editor.buffer.update(cx, |buffer, cx| {
10180                            buffer.edit([(0..0, old_name.clone())], None, cx)
10181                        });
10182                        let rename_selection_range = match cursor_offset_in_rename_range
10183                            .cmp(&cursor_offset_in_rename_range_end)
10184                        {
10185                            Ordering::Equal => {
10186                                editor.select_all(&SelectAll, cx);
10187                                return editor;
10188                            }
10189                            Ordering::Less => {
10190                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10191                            }
10192                            Ordering::Greater => {
10193                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10194                            }
10195                        };
10196                        if rename_selection_range.end > old_name.len() {
10197                            editor.select_all(&SelectAll, cx);
10198                        } else {
10199                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10200                                s.select_ranges([rename_selection_range]);
10201                            });
10202                        }
10203                        editor
10204                    });
10205                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10206                        if e == &EditorEvent::Focused {
10207                            cx.emit(EditorEvent::FocusedIn)
10208                        }
10209                    })
10210                    .detach();
10211
10212                    let write_highlights =
10213                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10214                    let read_highlights =
10215                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
10216                    let ranges = write_highlights
10217                        .iter()
10218                        .flat_map(|(_, ranges)| ranges.iter())
10219                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10220                        .cloned()
10221                        .collect();
10222
10223                    this.highlight_text::<Rename>(
10224                        ranges,
10225                        HighlightStyle {
10226                            fade_out: Some(0.6),
10227                            ..Default::default()
10228                        },
10229                        cx,
10230                    );
10231                    let rename_focus_handle = rename_editor.focus_handle(cx);
10232                    cx.focus(&rename_focus_handle);
10233                    let block_id = this.insert_blocks(
10234                        [BlockProperties {
10235                            style: BlockStyle::Flex,
10236                            position: range.start,
10237                            height: 1,
10238                            render: Box::new({
10239                                let rename_editor = rename_editor.clone();
10240                                move |cx: &mut BlockContext| {
10241                                    let mut text_style = cx.editor_style.text.clone();
10242                                    if let Some(highlight_style) = old_highlight_id
10243                                        .and_then(|h| h.style(&cx.editor_style.syntax))
10244                                    {
10245                                        text_style = text_style.highlight(highlight_style);
10246                                    }
10247                                    div()
10248                                        .pl(cx.anchor_x)
10249                                        .child(EditorElement::new(
10250                                            &rename_editor,
10251                                            EditorStyle {
10252                                                background: cx.theme().system().transparent,
10253                                                local_player: cx.editor_style.local_player,
10254                                                text: text_style,
10255                                                scrollbar_width: cx.editor_style.scrollbar_width,
10256                                                syntax: cx.editor_style.syntax.clone(),
10257                                                status: cx.editor_style.status.clone(),
10258                                                inlay_hints_style: HighlightStyle {
10259                                                    font_weight: Some(FontWeight::BOLD),
10260                                                    ..make_inlay_hints_style(cx)
10261                                                },
10262                                                suggestions_style: HighlightStyle {
10263                                                    color: Some(cx.theme().status().predictive),
10264                                                    ..HighlightStyle::default()
10265                                                },
10266                                                ..EditorStyle::default()
10267                                            },
10268                                        ))
10269                                        .into_any_element()
10270                                }
10271                            }),
10272                            disposition: BlockDisposition::Below,
10273                            priority: 0,
10274                        }],
10275                        Some(Autoscroll::fit()),
10276                        cx,
10277                    )[0];
10278                    this.pending_rename = Some(RenameState {
10279                        range,
10280                        old_name,
10281                        editor: rename_editor,
10282                        block_id,
10283                    });
10284                })?;
10285            }
10286
10287            Ok(())
10288        }))
10289    }
10290
10291    pub fn confirm_rename(
10292        &mut self,
10293        _: &ConfirmRename,
10294        cx: &mut ViewContext<Self>,
10295    ) -> Option<Task<Result<()>>> {
10296        let rename = self.take_rename(false, cx)?;
10297        let workspace = self.workspace()?.downgrade();
10298        let (buffer, start) = self
10299            .buffer
10300            .read(cx)
10301            .text_anchor_for_position(rename.range.start, cx)?;
10302        let (end_buffer, _) = self
10303            .buffer
10304            .read(cx)
10305            .text_anchor_for_position(rename.range.end, cx)?;
10306        if buffer != end_buffer {
10307            return None;
10308        }
10309
10310        let old_name = rename.old_name;
10311        let new_name = rename.editor.read(cx).text(cx);
10312
10313        let rename = self.semantics_provider.as_ref()?.perform_rename(
10314            &buffer,
10315            start,
10316            new_name.clone(),
10317            cx,
10318        )?;
10319
10320        Some(cx.spawn(|editor, mut cx| async move {
10321            let project_transaction = rename.await?;
10322            Self::open_project_transaction(
10323                &editor,
10324                workspace,
10325                project_transaction,
10326                format!("Rename: {}{}", old_name, new_name),
10327                cx.clone(),
10328            )
10329            .await?;
10330
10331            editor.update(&mut cx, |editor, cx| {
10332                editor.refresh_document_highlights(cx);
10333            })?;
10334            Ok(())
10335        }))
10336    }
10337
10338    fn take_rename(
10339        &mut self,
10340        moving_cursor: bool,
10341        cx: &mut ViewContext<Self>,
10342    ) -> Option<RenameState> {
10343        let rename = self.pending_rename.take()?;
10344        if rename.editor.focus_handle(cx).is_focused(cx) {
10345            cx.focus(&self.focus_handle);
10346        }
10347
10348        self.remove_blocks(
10349            [rename.block_id].into_iter().collect(),
10350            Some(Autoscroll::fit()),
10351            cx,
10352        );
10353        self.clear_highlights::<Rename>(cx);
10354        self.show_local_selections = true;
10355
10356        if moving_cursor {
10357            let rename_editor = rename.editor.read(cx);
10358            let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
10359
10360            // Update the selection to match the position of the selection inside
10361            // the rename editor.
10362            let snapshot = self.buffer.read(cx).read(cx);
10363            let rename_range = rename.range.to_offset(&snapshot);
10364            let cursor_in_editor = snapshot
10365                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10366                .min(rename_range.end);
10367            drop(snapshot);
10368
10369            self.change_selections(None, cx, |s| {
10370                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10371            });
10372        } else {
10373            self.refresh_document_highlights(cx);
10374        }
10375
10376        Some(rename)
10377    }
10378
10379    pub fn pending_rename(&self) -> Option<&RenameState> {
10380        self.pending_rename.as_ref()
10381    }
10382
10383    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10384        let project = match &self.project {
10385            Some(project) => project.clone(),
10386            None => return None,
10387        };
10388
10389        Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10390    }
10391
10392    fn format_selections(
10393        &mut self,
10394        _: &FormatSelections,
10395        cx: &mut ViewContext<Self>,
10396    ) -> Option<Task<Result<()>>> {
10397        let project = match &self.project {
10398            Some(project) => project.clone(),
10399            None => return None,
10400        };
10401
10402        let selections = self
10403            .selections
10404            .all_adjusted(cx)
10405            .into_iter()
10406            .filter(|s| !s.is_empty())
10407            .collect_vec();
10408
10409        Some(self.perform_format(
10410            project,
10411            FormatTrigger::Manual,
10412            FormatTarget::Ranges(selections),
10413            cx,
10414        ))
10415    }
10416
10417    fn perform_format(
10418        &mut self,
10419        project: Model<Project>,
10420        trigger: FormatTrigger,
10421        target: FormatTarget,
10422        cx: &mut ViewContext<Self>,
10423    ) -> Task<Result<()>> {
10424        let buffer = self.buffer().clone();
10425        let mut buffers = buffer.read(cx).all_buffers();
10426        if trigger == FormatTrigger::Save {
10427            buffers.retain(|buffer| buffer.read(cx).is_dirty());
10428        }
10429
10430        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10431        let format = project.update(cx, |project, cx| {
10432            project.format(buffers, true, trigger, target, cx)
10433        });
10434
10435        cx.spawn(|_, mut cx| async move {
10436            let transaction = futures::select_biased! {
10437                () = timeout => {
10438                    log::warn!("timed out waiting for formatting");
10439                    None
10440                }
10441                transaction = format.log_err().fuse() => transaction,
10442            };
10443
10444            buffer
10445                .update(&mut cx, |buffer, cx| {
10446                    if let Some(transaction) = transaction {
10447                        if !buffer.is_singleton() {
10448                            buffer.push_transaction(&transaction.0, cx);
10449                        }
10450                    }
10451
10452                    cx.notify();
10453                })
10454                .ok();
10455
10456            Ok(())
10457        })
10458    }
10459
10460    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10461        if let Some(project) = self.project.clone() {
10462            self.buffer.update(cx, |multi_buffer, cx| {
10463                project.update(cx, |project, cx| {
10464                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10465                });
10466            })
10467        }
10468    }
10469
10470    fn cancel_language_server_work(
10471        &mut self,
10472        _: &CancelLanguageServerWork,
10473        cx: &mut ViewContext<Self>,
10474    ) {
10475        if let Some(project) = self.project.clone() {
10476            self.buffer.update(cx, |multi_buffer, cx| {
10477                project.update(cx, |project, cx| {
10478                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10479                });
10480            })
10481        }
10482    }
10483
10484    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10485        cx.show_character_palette();
10486    }
10487
10488    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10489        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10490            let buffer = self.buffer.read(cx).snapshot(cx);
10491            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10492            let is_valid = buffer
10493                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10494                .any(|entry| {
10495                    entry.diagnostic.is_primary
10496                        && !entry.range.is_empty()
10497                        && entry.range.start == primary_range_start
10498                        && entry.diagnostic.message == active_diagnostics.primary_message
10499                });
10500
10501            if is_valid != active_diagnostics.is_valid {
10502                active_diagnostics.is_valid = is_valid;
10503                let mut new_styles = HashMap::default();
10504                for (block_id, diagnostic) in &active_diagnostics.blocks {
10505                    new_styles.insert(
10506                        *block_id,
10507                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10508                    );
10509                }
10510                self.display_map.update(cx, |display_map, _cx| {
10511                    display_map.replace_blocks(new_styles)
10512                });
10513            }
10514        }
10515    }
10516
10517    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10518        self.dismiss_diagnostics(cx);
10519        let snapshot = self.snapshot(cx);
10520        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10521            let buffer = self.buffer.read(cx).snapshot(cx);
10522
10523            let mut primary_range = None;
10524            let mut primary_message = None;
10525            let mut group_end = Point::zero();
10526            let diagnostic_group = buffer
10527                .diagnostic_group::<MultiBufferPoint>(group_id)
10528                .filter_map(|entry| {
10529                    if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10530                        && (entry.range.start.row == entry.range.end.row
10531                            || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10532                    {
10533                        return None;
10534                    }
10535                    if entry.range.end > group_end {
10536                        group_end = entry.range.end;
10537                    }
10538                    if entry.diagnostic.is_primary {
10539                        primary_range = Some(entry.range.clone());
10540                        primary_message = Some(entry.diagnostic.message.clone());
10541                    }
10542                    Some(entry)
10543                })
10544                .collect::<Vec<_>>();
10545            let primary_range = primary_range?;
10546            let primary_message = primary_message?;
10547            let primary_range =
10548                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10549
10550            let blocks = display_map
10551                .insert_blocks(
10552                    diagnostic_group.iter().map(|entry| {
10553                        let diagnostic = entry.diagnostic.clone();
10554                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10555                        BlockProperties {
10556                            style: BlockStyle::Fixed,
10557                            position: buffer.anchor_after(entry.range.start),
10558                            height: message_height,
10559                            render: diagnostic_block_renderer(diagnostic, None, true, true),
10560                            disposition: BlockDisposition::Below,
10561                            priority: 0,
10562                        }
10563                    }),
10564                    cx,
10565                )
10566                .into_iter()
10567                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10568                .collect();
10569
10570            Some(ActiveDiagnosticGroup {
10571                primary_range,
10572                primary_message,
10573                group_id,
10574                blocks,
10575                is_valid: true,
10576            })
10577        });
10578        self.active_diagnostics.is_some()
10579    }
10580
10581    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10582        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10583            self.display_map.update(cx, |display_map, cx| {
10584                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10585            });
10586            cx.notify();
10587        }
10588    }
10589
10590    pub fn set_selections_from_remote(
10591        &mut self,
10592        selections: Vec<Selection<Anchor>>,
10593        pending_selection: Option<Selection<Anchor>>,
10594        cx: &mut ViewContext<Self>,
10595    ) {
10596        let old_cursor_position = self.selections.newest_anchor().head();
10597        self.selections.change_with(cx, |s| {
10598            s.select_anchors(selections);
10599            if let Some(pending_selection) = pending_selection {
10600                s.set_pending(pending_selection, SelectMode::Character);
10601            } else {
10602                s.clear_pending();
10603            }
10604        });
10605        self.selections_did_change(false, &old_cursor_position, true, cx);
10606    }
10607
10608    fn push_to_selection_history(&mut self) {
10609        self.selection_history.push(SelectionHistoryEntry {
10610            selections: self.selections.disjoint_anchors(),
10611            select_next_state: self.select_next_state.clone(),
10612            select_prev_state: self.select_prev_state.clone(),
10613            add_selections_state: self.add_selections_state.clone(),
10614        });
10615    }
10616
10617    pub fn transact(
10618        &mut self,
10619        cx: &mut ViewContext<Self>,
10620        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10621    ) -> Option<TransactionId> {
10622        self.start_transaction_at(Instant::now(), cx);
10623        update(self, cx);
10624        self.end_transaction_at(Instant::now(), cx)
10625    }
10626
10627    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10628        self.end_selection(cx);
10629        if let Some(tx_id) = self
10630            .buffer
10631            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10632        {
10633            self.selection_history
10634                .insert_transaction(tx_id, self.selections.disjoint_anchors());
10635            cx.emit(EditorEvent::TransactionBegun {
10636                transaction_id: tx_id,
10637            })
10638        }
10639    }
10640
10641    fn end_transaction_at(
10642        &mut self,
10643        now: Instant,
10644        cx: &mut ViewContext<Self>,
10645    ) -> Option<TransactionId> {
10646        if let Some(transaction_id) = self
10647            .buffer
10648            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10649        {
10650            if let Some((_, end_selections)) =
10651                self.selection_history.transaction_mut(transaction_id)
10652            {
10653                *end_selections = Some(self.selections.disjoint_anchors());
10654            } else {
10655                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10656            }
10657
10658            cx.emit(EditorEvent::Edited { transaction_id });
10659            Some(transaction_id)
10660        } else {
10661            None
10662        }
10663    }
10664
10665    pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10666        let selection = self.selections.newest::<Point>(cx);
10667
10668        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10669        let range = if selection.is_empty() {
10670            let point = selection.head().to_display_point(&display_map);
10671            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10672            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10673                .to_point(&display_map);
10674            start..end
10675        } else {
10676            selection.range()
10677        };
10678        if display_map.folds_in_range(range).next().is_some() {
10679            self.unfold_lines(&Default::default(), cx)
10680        } else {
10681            self.fold(&Default::default(), cx)
10682        }
10683    }
10684
10685    pub fn toggle_fold_recursive(
10686        &mut self,
10687        _: &actions::ToggleFoldRecursive,
10688        cx: &mut ViewContext<Self>,
10689    ) {
10690        let selection = self.selections.newest::<Point>(cx);
10691
10692        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10693        let range = if selection.is_empty() {
10694            let point = selection.head().to_display_point(&display_map);
10695            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10696            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10697                .to_point(&display_map);
10698            start..end
10699        } else {
10700            selection.range()
10701        };
10702        if display_map.folds_in_range(range).next().is_some() {
10703            self.unfold_recursive(&Default::default(), cx)
10704        } else {
10705            self.fold_recursive(&Default::default(), cx)
10706        }
10707    }
10708
10709    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10710        let mut fold_ranges = Vec::new();
10711        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10712        let selections = self.selections.all_adjusted(cx);
10713
10714        for selection in selections {
10715            let range = selection.range().sorted();
10716            let buffer_start_row = range.start.row;
10717
10718            if range.start.row != range.end.row {
10719                let mut found = false;
10720                let mut row = range.start.row;
10721                while row <= range.end.row {
10722                    if let Some((foldable_range, fold_text)) =
10723                        { display_map.foldable_range(MultiBufferRow(row)) }
10724                    {
10725                        found = true;
10726                        row = foldable_range.end.row + 1;
10727                        fold_ranges.push((foldable_range, fold_text));
10728                    } else {
10729                        row += 1
10730                    }
10731                }
10732                if found {
10733                    continue;
10734                }
10735            }
10736
10737            for row in (0..=range.start.row).rev() {
10738                if let Some((foldable_range, fold_text)) =
10739                    display_map.foldable_range(MultiBufferRow(row))
10740                {
10741                    if foldable_range.end.row >= buffer_start_row {
10742                        fold_ranges.push((foldable_range, fold_text));
10743                        if row <= range.start.row {
10744                            break;
10745                        }
10746                    }
10747                }
10748            }
10749        }
10750
10751        self.fold_ranges(fold_ranges, true, cx);
10752    }
10753
10754    pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10755        let mut fold_ranges = Vec::new();
10756        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10757
10758        for row in 0..display_map.max_buffer_row().0 {
10759            if let Some((foldable_range, fold_text)) =
10760                display_map.foldable_range(MultiBufferRow(row))
10761            {
10762                fold_ranges.push((foldable_range, fold_text));
10763            }
10764        }
10765
10766        self.fold_ranges(fold_ranges, true, cx);
10767    }
10768
10769    pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10770        let mut fold_ranges = Vec::new();
10771        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10772        let selections = self.selections.all_adjusted(cx);
10773
10774        for selection in selections {
10775            let range = selection.range().sorted();
10776            let buffer_start_row = range.start.row;
10777
10778            if range.start.row != range.end.row {
10779                let mut found = false;
10780                for row in range.start.row..=range.end.row {
10781                    if let Some((foldable_range, fold_text)) =
10782                        { display_map.foldable_range(MultiBufferRow(row)) }
10783                    {
10784                        found = true;
10785                        fold_ranges.push((foldable_range, fold_text));
10786                    }
10787                }
10788                if found {
10789                    continue;
10790                }
10791            }
10792
10793            for row in (0..=range.start.row).rev() {
10794                if let Some((foldable_range, fold_text)) =
10795                    display_map.foldable_range(MultiBufferRow(row))
10796                {
10797                    if foldable_range.end.row >= buffer_start_row {
10798                        fold_ranges.push((foldable_range, fold_text));
10799                    } else {
10800                        break;
10801                    }
10802                }
10803            }
10804        }
10805
10806        self.fold_ranges(fold_ranges, true, cx);
10807    }
10808
10809    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10810        let buffer_row = fold_at.buffer_row;
10811        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10812
10813        if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
10814            let autoscroll = self
10815                .selections
10816                .all::<Point>(cx)
10817                .iter()
10818                .any(|selection| fold_range.overlaps(&selection.range()));
10819
10820            self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
10821        }
10822    }
10823
10824    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10825        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10826        let buffer = &display_map.buffer_snapshot;
10827        let selections = self.selections.all::<Point>(cx);
10828        let ranges = selections
10829            .iter()
10830            .map(|s| {
10831                let range = s.display_range(&display_map).sorted();
10832                let mut start = range.start.to_point(&display_map);
10833                let mut end = range.end.to_point(&display_map);
10834                start.column = 0;
10835                end.column = buffer.line_len(MultiBufferRow(end.row));
10836                start..end
10837            })
10838            .collect::<Vec<_>>();
10839
10840        self.unfold_ranges(ranges, true, true, cx);
10841    }
10842
10843    pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10844        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10845        let selections = self.selections.all::<Point>(cx);
10846        let ranges = selections
10847            .iter()
10848            .map(|s| {
10849                let mut range = s.display_range(&display_map).sorted();
10850                *range.start.column_mut() = 0;
10851                *range.end.column_mut() = display_map.line_len(range.end.row());
10852                let start = range.start.to_point(&display_map);
10853                let end = range.end.to_point(&display_map);
10854                start..end
10855            })
10856            .collect::<Vec<_>>();
10857
10858        self.unfold_ranges(ranges, true, true, cx);
10859    }
10860
10861    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10862        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10863
10864        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10865            ..Point::new(
10866                unfold_at.buffer_row.0,
10867                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10868            );
10869
10870        let autoscroll = self
10871            .selections
10872            .all::<Point>(cx)
10873            .iter()
10874            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10875
10876        self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
10877    }
10878
10879    pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10880        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10881        self.unfold_ranges(
10882            [Point::zero()..display_map.max_point().to_point(&display_map)],
10883            true,
10884            true,
10885            cx,
10886        );
10887    }
10888
10889    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10890        let selections = self.selections.all::<Point>(cx);
10891        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10892        let line_mode = self.selections.line_mode;
10893        let ranges = selections.into_iter().map(|s| {
10894            if line_mode {
10895                let start = Point::new(s.start.row, 0);
10896                let end = Point::new(
10897                    s.end.row,
10898                    display_map
10899                        .buffer_snapshot
10900                        .line_len(MultiBufferRow(s.end.row)),
10901                );
10902                (start..end, display_map.fold_placeholder.clone())
10903            } else {
10904                (s.start..s.end, display_map.fold_placeholder.clone())
10905            }
10906        });
10907        self.fold_ranges(ranges, true, cx);
10908    }
10909
10910    pub fn fold_ranges<T: ToOffset + Clone>(
10911        &mut self,
10912        ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
10913        auto_scroll: bool,
10914        cx: &mut ViewContext<Self>,
10915    ) {
10916        let mut fold_ranges = Vec::new();
10917        let mut buffers_affected = HashMap::default();
10918        let multi_buffer = self.buffer().read(cx);
10919        for (fold_range, fold_text) in ranges {
10920            if let Some((_, buffer, _)) =
10921                multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
10922            {
10923                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10924            };
10925            fold_ranges.push((fold_range, fold_text));
10926        }
10927
10928        let mut ranges = fold_ranges.into_iter().peekable();
10929        if ranges.peek().is_some() {
10930            self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
10931
10932            if auto_scroll {
10933                self.request_autoscroll(Autoscroll::fit(), cx);
10934            }
10935
10936            for buffer in buffers_affected.into_values() {
10937                self.sync_expanded_diff_hunks(buffer, cx);
10938            }
10939
10940            cx.notify();
10941
10942            if let Some(active_diagnostics) = self.active_diagnostics.take() {
10943                // Clear diagnostics block when folding a range that contains it.
10944                let snapshot = self.snapshot(cx);
10945                if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10946                    drop(snapshot);
10947                    self.active_diagnostics = Some(active_diagnostics);
10948                    self.dismiss_diagnostics(cx);
10949                } else {
10950                    self.active_diagnostics = Some(active_diagnostics);
10951                }
10952            }
10953
10954            self.scrollbar_marker_state.dirty = true;
10955        }
10956    }
10957
10958    pub fn unfold_ranges<T: ToOffset + Clone>(
10959        &mut self,
10960        ranges: impl IntoIterator<Item = Range<T>>,
10961        inclusive: bool,
10962        auto_scroll: bool,
10963        cx: &mut ViewContext<Self>,
10964    ) {
10965        let mut unfold_ranges = Vec::new();
10966        let mut buffers_affected = HashMap::default();
10967        let multi_buffer = self.buffer().read(cx);
10968        for range in ranges {
10969            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10970                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10971            };
10972            unfold_ranges.push(range);
10973        }
10974
10975        let mut ranges = unfold_ranges.into_iter().peekable();
10976        if ranges.peek().is_some() {
10977            self.display_map
10978                .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
10979            if auto_scroll {
10980                self.request_autoscroll(Autoscroll::fit(), cx);
10981            }
10982
10983            for buffer in buffers_affected.into_values() {
10984                self.sync_expanded_diff_hunks(buffer, cx);
10985            }
10986
10987            cx.notify();
10988            self.scrollbar_marker_state.dirty = true;
10989            self.active_indent_guides_state.dirty = true;
10990        }
10991    }
10992
10993    pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
10994        self.display_map.read(cx).fold_placeholder.clone()
10995    }
10996
10997    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10998        if hovered != self.gutter_hovered {
10999            self.gutter_hovered = hovered;
11000            cx.notify();
11001        }
11002    }
11003
11004    pub fn insert_blocks(
11005        &mut self,
11006        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11007        autoscroll: Option<Autoscroll>,
11008        cx: &mut ViewContext<Self>,
11009    ) -> Vec<CustomBlockId> {
11010        let blocks = self
11011            .display_map
11012            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11013        if let Some(autoscroll) = autoscroll {
11014            self.request_autoscroll(autoscroll, cx);
11015        }
11016        cx.notify();
11017        blocks
11018    }
11019
11020    pub fn resize_blocks(
11021        &mut self,
11022        heights: HashMap<CustomBlockId, u32>,
11023        autoscroll: Option<Autoscroll>,
11024        cx: &mut ViewContext<Self>,
11025    ) {
11026        self.display_map
11027            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11028        if let Some(autoscroll) = autoscroll {
11029            self.request_autoscroll(autoscroll, cx);
11030        }
11031        cx.notify();
11032    }
11033
11034    pub fn replace_blocks(
11035        &mut self,
11036        renderers: HashMap<CustomBlockId, RenderBlock>,
11037        autoscroll: Option<Autoscroll>,
11038        cx: &mut ViewContext<Self>,
11039    ) {
11040        self.display_map
11041            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11042        if let Some(autoscroll) = autoscroll {
11043            self.request_autoscroll(autoscroll, cx);
11044        }
11045        cx.notify();
11046    }
11047
11048    pub fn remove_blocks(
11049        &mut self,
11050        block_ids: HashSet<CustomBlockId>,
11051        autoscroll: Option<Autoscroll>,
11052        cx: &mut ViewContext<Self>,
11053    ) {
11054        self.display_map.update(cx, |display_map, cx| {
11055            display_map.remove_blocks(block_ids, cx)
11056        });
11057        if let Some(autoscroll) = autoscroll {
11058            self.request_autoscroll(autoscroll, cx);
11059        }
11060        cx.notify();
11061    }
11062
11063    pub fn row_for_block(
11064        &self,
11065        block_id: CustomBlockId,
11066        cx: &mut ViewContext<Self>,
11067    ) -> Option<DisplayRow> {
11068        self.display_map
11069            .update(cx, |map, cx| map.row_for_block(block_id, cx))
11070    }
11071
11072    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11073        self.focused_block = Some(focused_block);
11074    }
11075
11076    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11077        self.focused_block.take()
11078    }
11079
11080    pub fn insert_creases(
11081        &mut self,
11082        creases: impl IntoIterator<Item = Crease>,
11083        cx: &mut ViewContext<Self>,
11084    ) -> Vec<CreaseId> {
11085        self.display_map
11086            .update(cx, |map, cx| map.insert_creases(creases, cx))
11087    }
11088
11089    pub fn remove_creases(
11090        &mut self,
11091        ids: impl IntoIterator<Item = CreaseId>,
11092        cx: &mut ViewContext<Self>,
11093    ) {
11094        self.display_map
11095            .update(cx, |map, cx| map.remove_creases(ids, cx));
11096    }
11097
11098    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11099        self.display_map
11100            .update(cx, |map, cx| map.snapshot(cx))
11101            .longest_row()
11102    }
11103
11104    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11105        self.display_map
11106            .update(cx, |map, cx| map.snapshot(cx))
11107            .max_point()
11108    }
11109
11110    pub fn text(&self, cx: &AppContext) -> String {
11111        self.buffer.read(cx).read(cx).text()
11112    }
11113
11114    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11115        let text = self.text(cx);
11116        let text = text.trim();
11117
11118        if text.is_empty() {
11119            return None;
11120        }
11121
11122        Some(text.to_string())
11123    }
11124
11125    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11126        self.transact(cx, |this, cx| {
11127            this.buffer
11128                .read(cx)
11129                .as_singleton()
11130                .expect("you can only call set_text on editors for singleton buffers")
11131                .update(cx, |buffer, cx| buffer.set_text(text, cx));
11132        });
11133    }
11134
11135    pub fn display_text(&self, cx: &mut AppContext) -> String {
11136        self.display_map
11137            .update(cx, |map, cx| map.snapshot(cx))
11138            .text()
11139    }
11140
11141    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11142        let mut wrap_guides = smallvec::smallvec![];
11143
11144        if self.show_wrap_guides == Some(false) {
11145            return wrap_guides;
11146        }
11147
11148        let settings = self.buffer.read(cx).settings_at(0, cx);
11149        if settings.show_wrap_guides {
11150            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11151                wrap_guides.push((soft_wrap as usize, true));
11152            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11153                wrap_guides.push((soft_wrap as usize, true));
11154            }
11155            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11156        }
11157
11158        wrap_guides
11159    }
11160
11161    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11162        let settings = self.buffer.read(cx).settings_at(0, cx);
11163        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11164        match mode {
11165            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11166                SoftWrap::None
11167            }
11168            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11169            language_settings::SoftWrap::PreferredLineLength => {
11170                SoftWrap::Column(settings.preferred_line_length)
11171            }
11172            language_settings::SoftWrap::Bounded => {
11173                SoftWrap::Bounded(settings.preferred_line_length)
11174            }
11175        }
11176    }
11177
11178    pub fn set_soft_wrap_mode(
11179        &mut self,
11180        mode: language_settings::SoftWrap,
11181        cx: &mut ViewContext<Self>,
11182    ) {
11183        self.soft_wrap_mode_override = Some(mode);
11184        cx.notify();
11185    }
11186
11187    pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11188        let rem_size = cx.rem_size();
11189        self.display_map.update(cx, |map, cx| {
11190            map.set_font(
11191                style.text.font(),
11192                style.text.font_size.to_pixels(rem_size),
11193                cx,
11194            )
11195        });
11196        self.style = Some(style);
11197    }
11198
11199    pub fn style(&self) -> Option<&EditorStyle> {
11200        self.style.as_ref()
11201    }
11202
11203    // Called by the element. This method is not designed to be called outside of the editor
11204    // element's layout code because it does not notify when rewrapping is computed synchronously.
11205    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11206        self.display_map
11207            .update(cx, |map, cx| map.set_wrap_width(width, cx))
11208    }
11209
11210    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11211        if self.soft_wrap_mode_override.is_some() {
11212            self.soft_wrap_mode_override.take();
11213        } else {
11214            let soft_wrap = match self.soft_wrap_mode(cx) {
11215                SoftWrap::GitDiff => return,
11216                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11217                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11218                    language_settings::SoftWrap::None
11219                }
11220            };
11221            self.soft_wrap_mode_override = Some(soft_wrap);
11222        }
11223        cx.notify();
11224    }
11225
11226    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11227        let Some(workspace) = self.workspace() else {
11228            return;
11229        };
11230        let fs = workspace.read(cx).app_state().fs.clone();
11231        let current_show = TabBarSettings::get_global(cx).show;
11232        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11233            setting.show = Some(!current_show);
11234        });
11235    }
11236
11237    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11238        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11239            self.buffer
11240                .read(cx)
11241                .settings_at(0, cx)
11242                .indent_guides
11243                .enabled
11244        });
11245        self.show_indent_guides = Some(!currently_enabled);
11246        cx.notify();
11247    }
11248
11249    fn should_show_indent_guides(&self) -> Option<bool> {
11250        self.show_indent_guides
11251    }
11252
11253    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11254        let mut editor_settings = EditorSettings::get_global(cx).clone();
11255        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11256        EditorSettings::override_global(editor_settings, cx);
11257    }
11258
11259    pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11260        self.use_relative_line_numbers
11261            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11262    }
11263
11264    pub fn toggle_relative_line_numbers(
11265        &mut self,
11266        _: &ToggleRelativeLineNumbers,
11267        cx: &mut ViewContext<Self>,
11268    ) {
11269        let is_relative = self.should_use_relative_line_numbers(cx);
11270        self.set_relative_line_number(Some(!is_relative), cx)
11271    }
11272
11273    pub fn set_relative_line_number(
11274        &mut self,
11275        is_relative: Option<bool>,
11276        cx: &mut ViewContext<Self>,
11277    ) {
11278        self.use_relative_line_numbers = is_relative;
11279        cx.notify();
11280    }
11281
11282    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11283        self.show_gutter = show_gutter;
11284        cx.notify();
11285    }
11286
11287    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11288        self.show_line_numbers = Some(show_line_numbers);
11289        cx.notify();
11290    }
11291
11292    pub fn set_show_git_diff_gutter(
11293        &mut self,
11294        show_git_diff_gutter: bool,
11295        cx: &mut ViewContext<Self>,
11296    ) {
11297        self.show_git_diff_gutter = Some(show_git_diff_gutter);
11298        cx.notify();
11299    }
11300
11301    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11302        self.show_code_actions = Some(show_code_actions);
11303        cx.notify();
11304    }
11305
11306    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11307        self.show_runnables = Some(show_runnables);
11308        cx.notify();
11309    }
11310
11311    pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11312        if self.display_map.read(cx).masked != masked {
11313            self.display_map.update(cx, |map, _| map.masked = masked);
11314        }
11315        cx.notify()
11316    }
11317
11318    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11319        self.show_wrap_guides = Some(show_wrap_guides);
11320        cx.notify();
11321    }
11322
11323    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11324        self.show_indent_guides = Some(show_indent_guides);
11325        cx.notify();
11326    }
11327
11328    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11329        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11330            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11331                if let Some(dir) = file.abs_path(cx).parent() {
11332                    return Some(dir.to_owned());
11333                }
11334            }
11335
11336            if let Some(project_path) = buffer.read(cx).project_path(cx) {
11337                return Some(project_path.path.to_path_buf());
11338            }
11339        }
11340
11341        None
11342    }
11343
11344    fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11345        self.active_excerpt(cx)?
11346            .1
11347            .read(cx)
11348            .file()
11349            .and_then(|f| f.as_local())
11350    }
11351
11352    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11353        if let Some(target) = self.target_file(cx) {
11354            cx.reveal_path(&target.abs_path(cx));
11355        }
11356    }
11357
11358    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11359        if let Some(file) = self.target_file(cx) {
11360            if let Some(path) = file.abs_path(cx).to_str() {
11361                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11362            }
11363        }
11364    }
11365
11366    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11367        if let Some(file) = self.target_file(cx) {
11368            if let Some(path) = file.path().to_str() {
11369                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11370            }
11371        }
11372    }
11373
11374    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11375        self.show_git_blame_gutter = !self.show_git_blame_gutter;
11376
11377        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11378            self.start_git_blame(true, cx);
11379        }
11380
11381        cx.notify();
11382    }
11383
11384    pub fn toggle_git_blame_inline(
11385        &mut self,
11386        _: &ToggleGitBlameInline,
11387        cx: &mut ViewContext<Self>,
11388    ) {
11389        self.toggle_git_blame_inline_internal(true, cx);
11390        cx.notify();
11391    }
11392
11393    pub fn git_blame_inline_enabled(&self) -> bool {
11394        self.git_blame_inline_enabled
11395    }
11396
11397    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11398        self.show_selection_menu = self
11399            .show_selection_menu
11400            .map(|show_selections_menu| !show_selections_menu)
11401            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11402
11403        cx.notify();
11404    }
11405
11406    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11407        self.show_selection_menu
11408            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11409    }
11410
11411    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11412        if let Some(project) = self.project.as_ref() {
11413            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11414                return;
11415            };
11416
11417            if buffer.read(cx).file().is_none() {
11418                return;
11419            }
11420
11421            let focused = self.focus_handle(cx).contains_focused(cx);
11422
11423            let project = project.clone();
11424            let blame =
11425                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11426            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11427            self.blame = Some(blame);
11428        }
11429    }
11430
11431    fn toggle_git_blame_inline_internal(
11432        &mut self,
11433        user_triggered: bool,
11434        cx: &mut ViewContext<Self>,
11435    ) {
11436        if self.git_blame_inline_enabled {
11437            self.git_blame_inline_enabled = false;
11438            self.show_git_blame_inline = false;
11439            self.show_git_blame_inline_delay_task.take();
11440        } else {
11441            self.git_blame_inline_enabled = true;
11442            self.start_git_blame_inline(user_triggered, cx);
11443        }
11444
11445        cx.notify();
11446    }
11447
11448    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11449        self.start_git_blame(user_triggered, cx);
11450
11451        if ProjectSettings::get_global(cx)
11452            .git
11453            .inline_blame_delay()
11454            .is_some()
11455        {
11456            self.start_inline_blame_timer(cx);
11457        } else {
11458            self.show_git_blame_inline = true
11459        }
11460    }
11461
11462    pub fn blame(&self) -> Option<&Model<GitBlame>> {
11463        self.blame.as_ref()
11464    }
11465
11466    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11467        self.show_git_blame_gutter && self.has_blame_entries(cx)
11468    }
11469
11470    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11471        self.show_git_blame_inline
11472            && self.focus_handle.is_focused(cx)
11473            && !self.newest_selection_head_on_empty_line(cx)
11474            && self.has_blame_entries(cx)
11475    }
11476
11477    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11478        self.blame()
11479            .map_or(false, |blame| blame.read(cx).has_generated_entries())
11480    }
11481
11482    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11483        let cursor_anchor = self.selections.newest_anchor().head();
11484
11485        let snapshot = self.buffer.read(cx).snapshot(cx);
11486        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11487
11488        snapshot.line_len(buffer_row) == 0
11489    }
11490
11491    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
11492        let (path, selection, repo) = maybe!({
11493            let project_handle = self.project.as_ref()?.clone();
11494            let project = project_handle.read(cx);
11495
11496            let selection = self.selections.newest::<Point>(cx);
11497            let selection_range = selection.range();
11498
11499            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11500                (buffer, selection_range.start.row..selection_range.end.row)
11501            } else {
11502                let buffer_ranges = self
11503                    .buffer()
11504                    .read(cx)
11505                    .range_to_buffer_ranges(selection_range, cx);
11506
11507                let (buffer, range, _) = if selection.reversed {
11508                    buffer_ranges.first()
11509                } else {
11510                    buffer_ranges.last()
11511                }?;
11512
11513                let snapshot = buffer.read(cx).snapshot();
11514                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11515                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
11516                (buffer.clone(), selection)
11517            };
11518
11519            let path = buffer
11520                .read(cx)
11521                .file()?
11522                .as_local()?
11523                .path()
11524                .to_str()?
11525                .to_string();
11526            let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
11527            Some((path, selection, repo))
11528        })
11529        .ok_or_else(|| anyhow!("unable to open git repository"))?;
11530
11531        const REMOTE_NAME: &str = "origin";
11532        let origin_url = repo
11533            .remote_url(REMOTE_NAME)
11534            .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
11535        let sha = repo
11536            .head_sha()
11537            .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
11538
11539        let (provider, remote) =
11540            parse_git_remote_url(GitHostingProviderRegistry::default_global(cx), &origin_url)
11541                .ok_or_else(|| anyhow!("failed to parse Git remote URL"))?;
11542
11543        Ok(provider.build_permalink(
11544            remote,
11545            BuildPermalinkParams {
11546                sha: &sha,
11547                path: &path,
11548                selection: Some(selection),
11549            },
11550        ))
11551    }
11552
11553    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11554        let permalink = self.get_permalink_to_line(cx);
11555
11556        match permalink {
11557            Ok(permalink) => {
11558                cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11559            }
11560            Err(err) => {
11561                let message = format!("Failed to copy permalink: {err}");
11562
11563                Err::<(), anyhow::Error>(err).log_err();
11564
11565                if let Some(workspace) = self.workspace() {
11566                    workspace.update(cx, |workspace, cx| {
11567                        struct CopyPermalinkToLine;
11568
11569                        workspace.show_toast(
11570                            Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
11571                            cx,
11572                        )
11573                    })
11574                }
11575            }
11576        }
11577    }
11578
11579    pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11580        if let Some(file) = self.target_file(cx) {
11581            if let Some(path) = file.path().to_str() {
11582                let selection = self.selections.newest::<Point>(cx).start.row + 1;
11583                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11584            }
11585        }
11586    }
11587
11588    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11589        let permalink = self.get_permalink_to_line(cx);
11590
11591        match permalink {
11592            Ok(permalink) => {
11593                cx.open_url(permalink.as_ref());
11594            }
11595            Err(err) => {
11596                let message = format!("Failed to open permalink: {err}");
11597
11598                Err::<(), anyhow::Error>(err).log_err();
11599
11600                if let Some(workspace) = self.workspace() {
11601                    workspace.update(cx, |workspace, cx| {
11602                        struct OpenPermalinkToLine;
11603
11604                        workspace.show_toast(
11605                            Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
11606                            cx,
11607                        )
11608                    })
11609                }
11610            }
11611        }
11612    }
11613
11614    /// Adds a row highlight for the given range. If a row has multiple highlights, the
11615    /// last highlight added will be used.
11616    ///
11617    /// If the range ends at the beginning of a line, then that line will not be highlighted.
11618    pub fn highlight_rows<T: 'static>(
11619        &mut self,
11620        range: Range<Anchor>,
11621        color: Hsla,
11622        should_autoscroll: bool,
11623        cx: &mut ViewContext<Self>,
11624    ) {
11625        let snapshot = self.buffer().read(cx).snapshot(cx);
11626        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11627        let ix = row_highlights.binary_search_by(|highlight| {
11628            Ordering::Equal
11629                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11630                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11631        });
11632
11633        if let Err(mut ix) = ix {
11634            let index = post_inc(&mut self.highlight_order);
11635
11636            // If this range intersects with the preceding highlight, then merge it with
11637            // the preceding highlight. Otherwise insert a new highlight.
11638            let mut merged = false;
11639            if ix > 0 {
11640                let prev_highlight = &mut row_highlights[ix - 1];
11641                if prev_highlight
11642                    .range
11643                    .end
11644                    .cmp(&range.start, &snapshot)
11645                    .is_ge()
11646                {
11647                    ix -= 1;
11648                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11649                        prev_highlight.range.end = range.end;
11650                    }
11651                    merged = true;
11652                    prev_highlight.index = index;
11653                    prev_highlight.color = color;
11654                    prev_highlight.should_autoscroll = should_autoscroll;
11655                }
11656            }
11657
11658            if !merged {
11659                row_highlights.insert(
11660                    ix,
11661                    RowHighlight {
11662                        range: range.clone(),
11663                        index,
11664                        color,
11665                        should_autoscroll,
11666                    },
11667                );
11668            }
11669
11670            // If any of the following highlights intersect with this one, merge them.
11671            while let Some(next_highlight) = row_highlights.get(ix + 1) {
11672                let highlight = &row_highlights[ix];
11673                if next_highlight
11674                    .range
11675                    .start
11676                    .cmp(&highlight.range.end, &snapshot)
11677                    .is_le()
11678                {
11679                    if next_highlight
11680                        .range
11681                        .end
11682                        .cmp(&highlight.range.end, &snapshot)
11683                        .is_gt()
11684                    {
11685                        row_highlights[ix].range.end = next_highlight.range.end;
11686                    }
11687                    row_highlights.remove(ix + 1);
11688                } else {
11689                    break;
11690                }
11691            }
11692        }
11693    }
11694
11695    /// Remove any highlighted row ranges of the given type that intersect the
11696    /// given ranges.
11697    pub fn remove_highlighted_rows<T: 'static>(
11698        &mut self,
11699        ranges_to_remove: Vec<Range<Anchor>>,
11700        cx: &mut ViewContext<Self>,
11701    ) {
11702        let snapshot = self.buffer().read(cx).snapshot(cx);
11703        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11704        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11705        row_highlights.retain(|highlight| {
11706            while let Some(range_to_remove) = ranges_to_remove.peek() {
11707                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11708                    Ordering::Less | Ordering::Equal => {
11709                        ranges_to_remove.next();
11710                    }
11711                    Ordering::Greater => {
11712                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11713                            Ordering::Less | Ordering::Equal => {
11714                                return false;
11715                            }
11716                            Ordering::Greater => break,
11717                        }
11718                    }
11719                }
11720            }
11721
11722            true
11723        })
11724    }
11725
11726    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11727    pub fn clear_row_highlights<T: 'static>(&mut self) {
11728        self.highlighted_rows.remove(&TypeId::of::<T>());
11729    }
11730
11731    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11732    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11733        self.highlighted_rows
11734            .get(&TypeId::of::<T>())
11735            .map_or(&[] as &[_], |vec| vec.as_slice())
11736            .iter()
11737            .map(|highlight| (highlight.range.clone(), highlight.color))
11738    }
11739
11740    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11741    /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11742    /// Allows to ignore certain kinds of highlights.
11743    pub fn highlighted_display_rows(
11744        &mut self,
11745        cx: &mut WindowContext,
11746    ) -> BTreeMap<DisplayRow, Hsla> {
11747        let snapshot = self.snapshot(cx);
11748        let mut used_highlight_orders = HashMap::default();
11749        self.highlighted_rows
11750            .iter()
11751            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11752            .fold(
11753                BTreeMap::<DisplayRow, Hsla>::new(),
11754                |mut unique_rows, highlight| {
11755                    let start = highlight.range.start.to_display_point(&snapshot);
11756                    let end = highlight.range.end.to_display_point(&snapshot);
11757                    let start_row = start.row().0;
11758                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11759                        && end.column() == 0
11760                    {
11761                        end.row().0.saturating_sub(1)
11762                    } else {
11763                        end.row().0
11764                    };
11765                    for row in start_row..=end_row {
11766                        let used_index =
11767                            used_highlight_orders.entry(row).or_insert(highlight.index);
11768                        if highlight.index >= *used_index {
11769                            *used_index = highlight.index;
11770                            unique_rows.insert(DisplayRow(row), highlight.color);
11771                        }
11772                    }
11773                    unique_rows
11774                },
11775            )
11776    }
11777
11778    pub fn highlighted_display_row_for_autoscroll(
11779        &self,
11780        snapshot: &DisplaySnapshot,
11781    ) -> Option<DisplayRow> {
11782        self.highlighted_rows
11783            .values()
11784            .flat_map(|highlighted_rows| highlighted_rows.iter())
11785            .filter_map(|highlight| {
11786                if highlight.should_autoscroll {
11787                    Some(highlight.range.start.to_display_point(snapshot).row())
11788                } else {
11789                    None
11790                }
11791            })
11792            .min()
11793    }
11794
11795    pub fn set_search_within_ranges(
11796        &mut self,
11797        ranges: &[Range<Anchor>],
11798        cx: &mut ViewContext<Self>,
11799    ) {
11800        self.highlight_background::<SearchWithinRange>(
11801            ranges,
11802            |colors| colors.editor_document_highlight_read_background,
11803            cx,
11804        )
11805    }
11806
11807    pub fn set_breadcrumb_header(&mut self, new_header: String) {
11808        self.breadcrumb_header = Some(new_header);
11809    }
11810
11811    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11812        self.clear_background_highlights::<SearchWithinRange>(cx);
11813    }
11814
11815    pub fn highlight_background<T: 'static>(
11816        &mut self,
11817        ranges: &[Range<Anchor>],
11818        color_fetcher: fn(&ThemeColors) -> Hsla,
11819        cx: &mut ViewContext<Self>,
11820    ) {
11821        self.background_highlights
11822            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11823        self.scrollbar_marker_state.dirty = true;
11824        cx.notify();
11825    }
11826
11827    pub fn clear_background_highlights<T: 'static>(
11828        &mut self,
11829        cx: &mut ViewContext<Self>,
11830    ) -> Option<BackgroundHighlight> {
11831        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11832        if !text_highlights.1.is_empty() {
11833            self.scrollbar_marker_state.dirty = true;
11834            cx.notify();
11835        }
11836        Some(text_highlights)
11837    }
11838
11839    pub fn highlight_gutter<T: 'static>(
11840        &mut self,
11841        ranges: &[Range<Anchor>],
11842        color_fetcher: fn(&AppContext) -> Hsla,
11843        cx: &mut ViewContext<Self>,
11844    ) {
11845        self.gutter_highlights
11846            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11847        cx.notify();
11848    }
11849
11850    pub fn clear_gutter_highlights<T: 'static>(
11851        &mut self,
11852        cx: &mut ViewContext<Self>,
11853    ) -> Option<GutterHighlight> {
11854        cx.notify();
11855        self.gutter_highlights.remove(&TypeId::of::<T>())
11856    }
11857
11858    #[cfg(feature = "test-support")]
11859    pub fn all_text_background_highlights(
11860        &mut self,
11861        cx: &mut ViewContext<Self>,
11862    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11863        let snapshot = self.snapshot(cx);
11864        let buffer = &snapshot.buffer_snapshot;
11865        let start = buffer.anchor_before(0);
11866        let end = buffer.anchor_after(buffer.len());
11867        let theme = cx.theme().colors();
11868        self.background_highlights_in_range(start..end, &snapshot, theme)
11869    }
11870
11871    #[cfg(feature = "test-support")]
11872    pub fn search_background_highlights(
11873        &mut self,
11874        cx: &mut ViewContext<Self>,
11875    ) -> Vec<Range<Point>> {
11876        let snapshot = self.buffer().read(cx).snapshot(cx);
11877
11878        let highlights = self
11879            .background_highlights
11880            .get(&TypeId::of::<items::BufferSearchHighlights>());
11881
11882        if let Some((_color, ranges)) = highlights {
11883            ranges
11884                .iter()
11885                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11886                .collect_vec()
11887        } else {
11888            vec![]
11889        }
11890    }
11891
11892    fn document_highlights_for_position<'a>(
11893        &'a self,
11894        position: Anchor,
11895        buffer: &'a MultiBufferSnapshot,
11896    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
11897        let read_highlights = self
11898            .background_highlights
11899            .get(&TypeId::of::<DocumentHighlightRead>())
11900            .map(|h| &h.1);
11901        let write_highlights = self
11902            .background_highlights
11903            .get(&TypeId::of::<DocumentHighlightWrite>())
11904            .map(|h| &h.1);
11905        let left_position = position.bias_left(buffer);
11906        let right_position = position.bias_right(buffer);
11907        read_highlights
11908            .into_iter()
11909            .chain(write_highlights)
11910            .flat_map(move |ranges| {
11911                let start_ix = match ranges.binary_search_by(|probe| {
11912                    let cmp = probe.end.cmp(&left_position, buffer);
11913                    if cmp.is_ge() {
11914                        Ordering::Greater
11915                    } else {
11916                        Ordering::Less
11917                    }
11918                }) {
11919                    Ok(i) | Err(i) => i,
11920                };
11921
11922                ranges[start_ix..]
11923                    .iter()
11924                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11925            })
11926    }
11927
11928    pub fn has_background_highlights<T: 'static>(&self) -> bool {
11929        self.background_highlights
11930            .get(&TypeId::of::<T>())
11931            .map_or(false, |(_, highlights)| !highlights.is_empty())
11932    }
11933
11934    pub fn background_highlights_in_range(
11935        &self,
11936        search_range: Range<Anchor>,
11937        display_snapshot: &DisplaySnapshot,
11938        theme: &ThemeColors,
11939    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11940        let mut results = Vec::new();
11941        for (color_fetcher, ranges) in self.background_highlights.values() {
11942            let color = color_fetcher(theme);
11943            let start_ix = match ranges.binary_search_by(|probe| {
11944                let cmp = probe
11945                    .end
11946                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11947                if cmp.is_gt() {
11948                    Ordering::Greater
11949                } else {
11950                    Ordering::Less
11951                }
11952            }) {
11953                Ok(i) | Err(i) => i,
11954            };
11955            for range in &ranges[start_ix..] {
11956                if range
11957                    .start
11958                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11959                    .is_ge()
11960                {
11961                    break;
11962                }
11963
11964                let start = range.start.to_display_point(display_snapshot);
11965                let end = range.end.to_display_point(display_snapshot);
11966                results.push((start..end, color))
11967            }
11968        }
11969        results
11970    }
11971
11972    pub fn background_highlight_row_ranges<T: 'static>(
11973        &self,
11974        search_range: Range<Anchor>,
11975        display_snapshot: &DisplaySnapshot,
11976        count: usize,
11977    ) -> Vec<RangeInclusive<DisplayPoint>> {
11978        let mut results = Vec::new();
11979        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11980            return vec![];
11981        };
11982
11983        let start_ix = match ranges.binary_search_by(|probe| {
11984            let cmp = probe
11985                .end
11986                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11987            if cmp.is_gt() {
11988                Ordering::Greater
11989            } else {
11990                Ordering::Less
11991            }
11992        }) {
11993            Ok(i) | Err(i) => i,
11994        };
11995        let mut push_region = |start: Option<Point>, end: Option<Point>| {
11996            if let (Some(start_display), Some(end_display)) = (start, end) {
11997                results.push(
11998                    start_display.to_display_point(display_snapshot)
11999                        ..=end_display.to_display_point(display_snapshot),
12000                );
12001            }
12002        };
12003        let mut start_row: Option<Point> = None;
12004        let mut end_row: Option<Point> = None;
12005        if ranges.len() > count {
12006            return Vec::new();
12007        }
12008        for range in &ranges[start_ix..] {
12009            if range
12010                .start
12011                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12012                .is_ge()
12013            {
12014                break;
12015            }
12016            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12017            if let Some(current_row) = &end_row {
12018                if end.row == current_row.row {
12019                    continue;
12020                }
12021            }
12022            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12023            if start_row.is_none() {
12024                assert_eq!(end_row, None);
12025                start_row = Some(start);
12026                end_row = Some(end);
12027                continue;
12028            }
12029            if let Some(current_end) = end_row.as_mut() {
12030                if start.row > current_end.row + 1 {
12031                    push_region(start_row, end_row);
12032                    start_row = Some(start);
12033                    end_row = Some(end);
12034                } else {
12035                    // Merge two hunks.
12036                    *current_end = end;
12037                }
12038            } else {
12039                unreachable!();
12040            }
12041        }
12042        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12043        push_region(start_row, end_row);
12044        results
12045    }
12046
12047    pub fn gutter_highlights_in_range(
12048        &self,
12049        search_range: Range<Anchor>,
12050        display_snapshot: &DisplaySnapshot,
12051        cx: &AppContext,
12052    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12053        let mut results = Vec::new();
12054        for (color_fetcher, ranges) in self.gutter_highlights.values() {
12055            let color = color_fetcher(cx);
12056            let start_ix = match ranges.binary_search_by(|probe| {
12057                let cmp = probe
12058                    .end
12059                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12060                if cmp.is_gt() {
12061                    Ordering::Greater
12062                } else {
12063                    Ordering::Less
12064                }
12065            }) {
12066                Ok(i) | Err(i) => i,
12067            };
12068            for range in &ranges[start_ix..] {
12069                if range
12070                    .start
12071                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12072                    .is_ge()
12073                {
12074                    break;
12075                }
12076
12077                let start = range.start.to_display_point(display_snapshot);
12078                let end = range.end.to_display_point(display_snapshot);
12079                results.push((start..end, color))
12080            }
12081        }
12082        results
12083    }
12084
12085    /// Get the text ranges corresponding to the redaction query
12086    pub fn redacted_ranges(
12087        &self,
12088        search_range: Range<Anchor>,
12089        display_snapshot: &DisplaySnapshot,
12090        cx: &WindowContext,
12091    ) -> Vec<Range<DisplayPoint>> {
12092        display_snapshot
12093            .buffer_snapshot
12094            .redacted_ranges(search_range, |file| {
12095                if let Some(file) = file {
12096                    file.is_private()
12097                        && EditorSettings::get(
12098                            Some(SettingsLocation {
12099                                worktree_id: file.worktree_id(cx),
12100                                path: file.path().as_ref(),
12101                            }),
12102                            cx,
12103                        )
12104                        .redact_private_values
12105                } else {
12106                    false
12107                }
12108            })
12109            .map(|range| {
12110                range.start.to_display_point(display_snapshot)
12111                    ..range.end.to_display_point(display_snapshot)
12112            })
12113            .collect()
12114    }
12115
12116    pub fn highlight_text<T: 'static>(
12117        &mut self,
12118        ranges: Vec<Range<Anchor>>,
12119        style: HighlightStyle,
12120        cx: &mut ViewContext<Self>,
12121    ) {
12122        self.display_map.update(cx, |map, _| {
12123            map.highlight_text(TypeId::of::<T>(), ranges, style)
12124        });
12125        cx.notify();
12126    }
12127
12128    pub(crate) fn highlight_inlays<T: 'static>(
12129        &mut self,
12130        highlights: Vec<InlayHighlight>,
12131        style: HighlightStyle,
12132        cx: &mut ViewContext<Self>,
12133    ) {
12134        self.display_map.update(cx, |map, _| {
12135            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12136        });
12137        cx.notify();
12138    }
12139
12140    pub fn text_highlights<'a, T: 'static>(
12141        &'a self,
12142        cx: &'a AppContext,
12143    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12144        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12145    }
12146
12147    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12148        let cleared = self
12149            .display_map
12150            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12151        if cleared {
12152            cx.notify();
12153        }
12154    }
12155
12156    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12157        (self.read_only(cx) || self.blink_manager.read(cx).visible())
12158            && self.focus_handle.is_focused(cx)
12159    }
12160
12161    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12162        self.show_cursor_when_unfocused = is_enabled;
12163        cx.notify();
12164    }
12165
12166    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12167        cx.notify();
12168    }
12169
12170    fn on_buffer_event(
12171        &mut self,
12172        multibuffer: Model<MultiBuffer>,
12173        event: &multi_buffer::Event,
12174        cx: &mut ViewContext<Self>,
12175    ) {
12176        match event {
12177            multi_buffer::Event::Edited {
12178                singleton_buffer_edited,
12179            } => {
12180                self.scrollbar_marker_state.dirty = true;
12181                self.active_indent_guides_state.dirty = true;
12182                self.refresh_active_diagnostics(cx);
12183                self.refresh_code_actions(cx);
12184                if self.has_active_inline_completion(cx) {
12185                    self.update_visible_inline_completion(cx);
12186                }
12187                cx.emit(EditorEvent::BufferEdited);
12188                cx.emit(SearchEvent::MatchesInvalidated);
12189                if *singleton_buffer_edited {
12190                    if let Some(project) = &self.project {
12191                        let project = project.read(cx);
12192                        #[allow(clippy::mutable_key_type)]
12193                        let languages_affected = multibuffer
12194                            .read(cx)
12195                            .all_buffers()
12196                            .into_iter()
12197                            .filter_map(|buffer| {
12198                                let buffer = buffer.read(cx);
12199                                let language = buffer.language()?;
12200                                if project.is_local()
12201                                    && project.language_servers_for_buffer(buffer, cx).count() == 0
12202                                {
12203                                    None
12204                                } else {
12205                                    Some(language)
12206                                }
12207                            })
12208                            .cloned()
12209                            .collect::<HashSet<_>>();
12210                        if !languages_affected.is_empty() {
12211                            self.refresh_inlay_hints(
12212                                InlayHintRefreshReason::BufferEdited(languages_affected),
12213                                cx,
12214                            );
12215                        }
12216                    }
12217                }
12218
12219                let Some(project) = &self.project else { return };
12220                let (telemetry, is_via_ssh) = {
12221                    let project = project.read(cx);
12222                    let telemetry = project.client().telemetry().clone();
12223                    let is_via_ssh = project.is_via_ssh();
12224                    (telemetry, is_via_ssh)
12225                };
12226                refresh_linked_ranges(self, cx);
12227                telemetry.log_edit_event("editor", is_via_ssh);
12228            }
12229            multi_buffer::Event::ExcerptsAdded {
12230                buffer,
12231                predecessor,
12232                excerpts,
12233            } => {
12234                self.tasks_update_task = Some(self.refresh_runnables(cx));
12235                cx.emit(EditorEvent::ExcerptsAdded {
12236                    buffer: buffer.clone(),
12237                    predecessor: *predecessor,
12238                    excerpts: excerpts.clone(),
12239                });
12240                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12241            }
12242            multi_buffer::Event::ExcerptsRemoved { ids } => {
12243                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12244                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12245            }
12246            multi_buffer::Event::ExcerptsEdited { ids } => {
12247                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12248            }
12249            multi_buffer::Event::ExcerptsExpanded { ids } => {
12250                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12251            }
12252            multi_buffer::Event::Reparsed(buffer_id) => {
12253                self.tasks_update_task = Some(self.refresh_runnables(cx));
12254
12255                cx.emit(EditorEvent::Reparsed(*buffer_id));
12256            }
12257            multi_buffer::Event::LanguageChanged(buffer_id) => {
12258                linked_editing_ranges::refresh_linked_ranges(self, cx);
12259                cx.emit(EditorEvent::Reparsed(*buffer_id));
12260                cx.notify();
12261            }
12262            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12263            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12264            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12265                cx.emit(EditorEvent::TitleChanged)
12266            }
12267            multi_buffer::Event::DiffBaseChanged => {
12268                self.scrollbar_marker_state.dirty = true;
12269                cx.emit(EditorEvent::DiffBaseChanged);
12270                cx.notify();
12271            }
12272            multi_buffer::Event::DiffUpdated { buffer } => {
12273                self.sync_expanded_diff_hunks(buffer.clone(), cx);
12274                cx.notify();
12275            }
12276            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12277            multi_buffer::Event::DiagnosticsUpdated => {
12278                self.refresh_active_diagnostics(cx);
12279                self.scrollbar_marker_state.dirty = true;
12280                cx.notify();
12281            }
12282            _ => {}
12283        };
12284    }
12285
12286    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12287        cx.notify();
12288    }
12289
12290    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12291        self.tasks_update_task = Some(self.refresh_runnables(cx));
12292        self.refresh_inline_completion(true, false, cx);
12293        self.refresh_inlay_hints(
12294            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12295                self.selections.newest_anchor().head(),
12296                &self.buffer.read(cx).snapshot(cx),
12297                cx,
12298            )),
12299            cx,
12300        );
12301
12302        let old_cursor_shape = self.cursor_shape;
12303
12304        {
12305            let editor_settings = EditorSettings::get_global(cx);
12306            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12307            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12308            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12309        }
12310
12311        if old_cursor_shape != self.cursor_shape {
12312            cx.emit(EditorEvent::CursorShapeChanged);
12313        }
12314
12315        let project_settings = ProjectSettings::get_global(cx);
12316        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12317
12318        if self.mode == EditorMode::Full {
12319            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12320            if self.git_blame_inline_enabled != inline_blame_enabled {
12321                self.toggle_git_blame_inline_internal(false, cx);
12322            }
12323        }
12324
12325        cx.notify();
12326    }
12327
12328    pub fn set_searchable(&mut self, searchable: bool) {
12329        self.searchable = searchable;
12330    }
12331
12332    pub fn searchable(&self) -> bool {
12333        self.searchable
12334    }
12335
12336    fn open_proposed_changes_editor(
12337        &mut self,
12338        _: &OpenProposedChangesEditor,
12339        cx: &mut ViewContext<Self>,
12340    ) {
12341        let Some(workspace) = self.workspace() else {
12342            cx.propagate();
12343            return;
12344        };
12345
12346        let buffer = self.buffer.read(cx);
12347        let mut new_selections_by_buffer = HashMap::default();
12348        for selection in self.selections.all::<usize>(cx) {
12349            for (buffer, range, _) in
12350                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12351            {
12352                let mut range = range.to_point(buffer.read(cx));
12353                range.start.column = 0;
12354                range.end.column = buffer.read(cx).line_len(range.end.row);
12355                new_selections_by_buffer
12356                    .entry(buffer)
12357                    .or_insert(Vec::new())
12358                    .push(range)
12359            }
12360        }
12361
12362        let proposed_changes_buffers = new_selections_by_buffer
12363            .into_iter()
12364            .map(|(buffer, ranges)| ProposedChangesBuffer { buffer, ranges })
12365            .collect::<Vec<_>>();
12366        let proposed_changes_editor = cx.new_view(|cx| {
12367            ProposedChangesEditor::new(proposed_changes_buffers, self.project.clone(), cx)
12368        });
12369
12370        cx.window_context().defer(move |cx| {
12371            workspace.update(cx, |workspace, cx| {
12372                workspace.active_pane().update(cx, |pane, cx| {
12373                    pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12374                });
12375            });
12376        });
12377    }
12378
12379    fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12380        self.open_excerpts_common(true, cx)
12381    }
12382
12383    fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12384        self.open_excerpts_common(false, cx)
12385    }
12386
12387    fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
12388        let buffer = self.buffer.read(cx);
12389        if buffer.is_singleton() {
12390            cx.propagate();
12391            return;
12392        }
12393
12394        let Some(workspace) = self.workspace() else {
12395            cx.propagate();
12396            return;
12397        };
12398
12399        let mut new_selections_by_buffer = HashMap::default();
12400        for selection in self.selections.all::<usize>(cx) {
12401            for (mut buffer_handle, mut range, _) in
12402                buffer.range_to_buffer_ranges(selection.range(), cx)
12403            {
12404                // When editing branch buffers, jump to the corresponding location
12405                // in their base buffer.
12406                let buffer = buffer_handle.read(cx);
12407                if let Some(base_buffer) = buffer.diff_base_buffer() {
12408                    range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12409                    buffer_handle = base_buffer;
12410                }
12411
12412                if selection.reversed {
12413                    mem::swap(&mut range.start, &mut range.end);
12414                }
12415                new_selections_by_buffer
12416                    .entry(buffer_handle)
12417                    .or_insert(Vec::new())
12418                    .push(range)
12419            }
12420        }
12421
12422        // We defer the pane interaction because we ourselves are a workspace item
12423        // and activating a new item causes the pane to call a method on us reentrantly,
12424        // which panics if we're on the stack.
12425        cx.window_context().defer(move |cx| {
12426            workspace.update(cx, |workspace, cx| {
12427                let pane = if split {
12428                    workspace.adjacent_pane(cx)
12429                } else {
12430                    workspace.active_pane().clone()
12431                };
12432
12433                for (buffer, ranges) in new_selections_by_buffer {
12434                    let editor =
12435                        workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
12436                    editor.update(cx, |editor, cx| {
12437                        editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
12438                            s.select_ranges(ranges);
12439                        });
12440                    });
12441                }
12442            })
12443        });
12444    }
12445
12446    fn jump(
12447        &mut self,
12448        path: ProjectPath,
12449        position: Point,
12450        anchor: language::Anchor,
12451        offset_from_top: u32,
12452        cx: &mut ViewContext<Self>,
12453    ) {
12454        let workspace = self.workspace();
12455        cx.spawn(|_, mut cx| async move {
12456            let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
12457            let editor = workspace.update(&mut cx, |workspace, cx| {
12458                // Reset the preview item id before opening the new item
12459                workspace.active_pane().update(cx, |pane, cx| {
12460                    pane.set_preview_item_id(None, cx);
12461                });
12462                workspace.open_path_preview(path, None, true, true, cx)
12463            })?;
12464            let editor = editor
12465                .await?
12466                .downcast::<Editor>()
12467                .ok_or_else(|| anyhow!("opened item was not an editor"))?
12468                .downgrade();
12469            editor.update(&mut cx, |editor, cx| {
12470                let buffer = editor
12471                    .buffer()
12472                    .read(cx)
12473                    .as_singleton()
12474                    .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
12475                let buffer = buffer.read(cx);
12476                let cursor = if buffer.can_resolve(&anchor) {
12477                    language::ToPoint::to_point(&anchor, buffer)
12478                } else {
12479                    buffer.clip_point(position, Bias::Left)
12480                };
12481
12482                let nav_history = editor.nav_history.take();
12483                editor.change_selections(
12484                    Some(Autoscroll::top_relative(offset_from_top as usize)),
12485                    cx,
12486                    |s| {
12487                        s.select_ranges([cursor..cursor]);
12488                    },
12489                );
12490                editor.nav_history = nav_history;
12491
12492                anyhow::Ok(())
12493            })??;
12494
12495            anyhow::Ok(())
12496        })
12497        .detach_and_log_err(cx);
12498    }
12499
12500    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12501        let snapshot = self.buffer.read(cx).read(cx);
12502        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12503        Some(
12504            ranges
12505                .iter()
12506                .map(move |range| {
12507                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12508                })
12509                .collect(),
12510        )
12511    }
12512
12513    fn selection_replacement_ranges(
12514        &self,
12515        range: Range<OffsetUtf16>,
12516        cx: &AppContext,
12517    ) -> Vec<Range<OffsetUtf16>> {
12518        let selections = self.selections.all::<OffsetUtf16>(cx);
12519        let newest_selection = selections
12520            .iter()
12521            .max_by_key(|selection| selection.id)
12522            .unwrap();
12523        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12524        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12525        let snapshot = self.buffer.read(cx).read(cx);
12526        selections
12527            .into_iter()
12528            .map(|mut selection| {
12529                selection.start.0 =
12530                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
12531                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12532                snapshot.clip_offset_utf16(selection.start, Bias::Left)
12533                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12534            })
12535            .collect()
12536    }
12537
12538    fn report_editor_event(
12539        &self,
12540        operation: &'static str,
12541        file_extension: Option<String>,
12542        cx: &AppContext,
12543    ) {
12544        if cfg!(any(test, feature = "test-support")) {
12545            return;
12546        }
12547
12548        let Some(project) = &self.project else { return };
12549
12550        // If None, we are in a file without an extension
12551        let file = self
12552            .buffer
12553            .read(cx)
12554            .as_singleton()
12555            .and_then(|b| b.read(cx).file());
12556        let file_extension = file_extension.or(file
12557            .as_ref()
12558            .and_then(|file| Path::new(file.file_name(cx)).extension())
12559            .and_then(|e| e.to_str())
12560            .map(|a| a.to_string()));
12561
12562        let vim_mode = cx
12563            .global::<SettingsStore>()
12564            .raw_user_settings()
12565            .get("vim_mode")
12566            == Some(&serde_json::Value::Bool(true));
12567
12568        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12569            == language::language_settings::InlineCompletionProvider::Copilot;
12570        let copilot_enabled_for_language = self
12571            .buffer
12572            .read(cx)
12573            .settings_at(0, cx)
12574            .show_inline_completions;
12575
12576        let project = project.read(cx);
12577        let telemetry = project.client().telemetry().clone();
12578        telemetry.report_editor_event(
12579            file_extension,
12580            vim_mode,
12581            operation,
12582            copilot_enabled,
12583            copilot_enabled_for_language,
12584            project.is_via_ssh(),
12585        )
12586    }
12587
12588    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12589    /// with each line being an array of {text, highlight} objects.
12590    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12591        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12592            return;
12593        };
12594
12595        #[derive(Serialize)]
12596        struct Chunk<'a> {
12597            text: String,
12598            highlight: Option<&'a str>,
12599        }
12600
12601        let snapshot = buffer.read(cx).snapshot();
12602        let range = self
12603            .selected_text_range(false, cx)
12604            .and_then(|selection| {
12605                if selection.range.is_empty() {
12606                    None
12607                } else {
12608                    Some(selection.range)
12609                }
12610            })
12611            .unwrap_or_else(|| 0..snapshot.len());
12612
12613        let chunks = snapshot.chunks(range, true);
12614        let mut lines = Vec::new();
12615        let mut line: VecDeque<Chunk> = VecDeque::new();
12616
12617        let Some(style) = self.style.as_ref() else {
12618            return;
12619        };
12620
12621        for chunk in chunks {
12622            let highlight = chunk
12623                .syntax_highlight_id
12624                .and_then(|id| id.name(&style.syntax));
12625            let mut chunk_lines = chunk.text.split('\n').peekable();
12626            while let Some(text) = chunk_lines.next() {
12627                let mut merged_with_last_token = false;
12628                if let Some(last_token) = line.back_mut() {
12629                    if last_token.highlight == highlight {
12630                        last_token.text.push_str(text);
12631                        merged_with_last_token = true;
12632                    }
12633                }
12634
12635                if !merged_with_last_token {
12636                    line.push_back(Chunk {
12637                        text: text.into(),
12638                        highlight,
12639                    });
12640                }
12641
12642                if chunk_lines.peek().is_some() {
12643                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
12644                        line.pop_front();
12645                    }
12646                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
12647                        line.pop_back();
12648                    }
12649
12650                    lines.push(mem::take(&mut line));
12651                }
12652            }
12653        }
12654
12655        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12656            return;
12657        };
12658        cx.write_to_clipboard(ClipboardItem::new_string(lines));
12659    }
12660
12661    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12662        &self.inlay_hint_cache
12663    }
12664
12665    pub fn replay_insert_event(
12666        &mut self,
12667        text: &str,
12668        relative_utf16_range: Option<Range<isize>>,
12669        cx: &mut ViewContext<Self>,
12670    ) {
12671        if !self.input_enabled {
12672            cx.emit(EditorEvent::InputIgnored { text: text.into() });
12673            return;
12674        }
12675        if let Some(relative_utf16_range) = relative_utf16_range {
12676            let selections = self.selections.all::<OffsetUtf16>(cx);
12677            self.change_selections(None, cx, |s| {
12678                let new_ranges = selections.into_iter().map(|range| {
12679                    let start = OffsetUtf16(
12680                        range
12681                            .head()
12682                            .0
12683                            .saturating_add_signed(relative_utf16_range.start),
12684                    );
12685                    let end = OffsetUtf16(
12686                        range
12687                            .head()
12688                            .0
12689                            .saturating_add_signed(relative_utf16_range.end),
12690                    );
12691                    start..end
12692                });
12693                s.select_ranges(new_ranges);
12694            });
12695        }
12696
12697        self.handle_input(text, cx);
12698    }
12699
12700    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12701        let Some(provider) = self.semantics_provider.as_ref() else {
12702            return false;
12703        };
12704
12705        let mut supports = false;
12706        self.buffer().read(cx).for_each_buffer(|buffer| {
12707            supports |= provider.supports_inlay_hints(buffer, cx);
12708        });
12709        supports
12710    }
12711
12712    pub fn focus(&self, cx: &mut WindowContext) {
12713        cx.focus(&self.focus_handle)
12714    }
12715
12716    pub fn is_focused(&self, cx: &WindowContext) -> bool {
12717        self.focus_handle.is_focused(cx)
12718    }
12719
12720    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12721        cx.emit(EditorEvent::Focused);
12722
12723        if let Some(descendant) = self
12724            .last_focused_descendant
12725            .take()
12726            .and_then(|descendant| descendant.upgrade())
12727        {
12728            cx.focus(&descendant);
12729        } else {
12730            if let Some(blame) = self.blame.as_ref() {
12731                blame.update(cx, GitBlame::focus)
12732            }
12733
12734            self.blink_manager.update(cx, BlinkManager::enable);
12735            self.show_cursor_names(cx);
12736            self.buffer.update(cx, |buffer, cx| {
12737                buffer.finalize_last_transaction(cx);
12738                if self.leader_peer_id.is_none() {
12739                    buffer.set_active_selections(
12740                        &self.selections.disjoint_anchors(),
12741                        self.selections.line_mode,
12742                        self.cursor_shape,
12743                        cx,
12744                    );
12745                }
12746            });
12747        }
12748    }
12749
12750    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12751        cx.emit(EditorEvent::FocusedIn)
12752    }
12753
12754    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12755        if event.blurred != self.focus_handle {
12756            self.last_focused_descendant = Some(event.blurred);
12757        }
12758    }
12759
12760    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12761        self.blink_manager.update(cx, BlinkManager::disable);
12762        self.buffer
12763            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12764
12765        if let Some(blame) = self.blame.as_ref() {
12766            blame.update(cx, GitBlame::blur)
12767        }
12768        if !self.hover_state.focused(cx) {
12769            hide_hover(self, cx);
12770        }
12771
12772        self.hide_context_menu(cx);
12773        cx.emit(EditorEvent::Blurred);
12774        cx.notify();
12775    }
12776
12777    pub fn register_action<A: Action>(
12778        &mut self,
12779        listener: impl Fn(&A, &mut WindowContext) + 'static,
12780    ) -> Subscription {
12781        let id = self.next_editor_action_id.post_inc();
12782        let listener = Arc::new(listener);
12783        self.editor_actions.borrow_mut().insert(
12784            id,
12785            Box::new(move |cx| {
12786                let cx = cx.window_context();
12787                let listener = listener.clone();
12788                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12789                    let action = action.downcast_ref().unwrap();
12790                    if phase == DispatchPhase::Bubble {
12791                        listener(action, cx)
12792                    }
12793                })
12794            }),
12795        );
12796
12797        let editor_actions = self.editor_actions.clone();
12798        Subscription::new(move || {
12799            editor_actions.borrow_mut().remove(&id);
12800        })
12801    }
12802
12803    pub fn file_header_size(&self) -> u32 {
12804        self.file_header_size
12805    }
12806
12807    pub fn revert(
12808        &mut self,
12809        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12810        cx: &mut ViewContext<Self>,
12811    ) {
12812        self.buffer().update(cx, |multi_buffer, cx| {
12813            for (buffer_id, changes) in revert_changes {
12814                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12815                    buffer.update(cx, |buffer, cx| {
12816                        buffer.edit(
12817                            changes.into_iter().map(|(range, text)| {
12818                                (range, text.to_string().map(Arc::<str>::from))
12819                            }),
12820                            None,
12821                            cx,
12822                        );
12823                    });
12824                }
12825            }
12826        });
12827        self.change_selections(None, cx, |selections| selections.refresh());
12828    }
12829
12830    pub fn to_pixel_point(
12831        &mut self,
12832        source: multi_buffer::Anchor,
12833        editor_snapshot: &EditorSnapshot,
12834        cx: &mut ViewContext<Self>,
12835    ) -> Option<gpui::Point<Pixels>> {
12836        let source_point = source.to_display_point(editor_snapshot);
12837        self.display_to_pixel_point(source_point, editor_snapshot, cx)
12838    }
12839
12840    pub fn display_to_pixel_point(
12841        &mut self,
12842        source: DisplayPoint,
12843        editor_snapshot: &EditorSnapshot,
12844        cx: &mut ViewContext<Self>,
12845    ) -> Option<gpui::Point<Pixels>> {
12846        let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12847        let text_layout_details = self.text_layout_details(cx);
12848        let scroll_top = text_layout_details
12849            .scroll_anchor
12850            .scroll_position(editor_snapshot)
12851            .y;
12852
12853        if source.row().as_f32() < scroll_top.floor() {
12854            return None;
12855        }
12856        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12857        let source_y = line_height * (source.row().as_f32() - scroll_top);
12858        Some(gpui::Point::new(source_x, source_y))
12859    }
12860
12861    pub fn has_active_completions_menu(&self) -> bool {
12862        self.context_menu.read().as_ref().map_or(false, |menu| {
12863            menu.visible() && matches!(menu, ContextMenu::Completions(_))
12864        })
12865    }
12866
12867    pub fn register_addon<T: Addon>(&mut self, instance: T) {
12868        self.addons
12869            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12870    }
12871
12872    pub fn unregister_addon<T: Addon>(&mut self) {
12873        self.addons.remove(&std::any::TypeId::of::<T>());
12874    }
12875
12876    pub fn addon<T: Addon>(&self) -> Option<&T> {
12877        let type_id = std::any::TypeId::of::<T>();
12878        self.addons
12879            .get(&type_id)
12880            .and_then(|item| item.to_any().downcast_ref::<T>())
12881    }
12882}
12883
12884fn hunks_for_selections(
12885    multi_buffer_snapshot: &MultiBufferSnapshot,
12886    selections: &[Selection<Anchor>],
12887) -> Vec<MultiBufferDiffHunk> {
12888    let buffer_rows_for_selections = selections.iter().map(|selection| {
12889        let head = selection.head();
12890        let tail = selection.tail();
12891        let start = MultiBufferRow(tail.to_point(multi_buffer_snapshot).row);
12892        let end = MultiBufferRow(head.to_point(multi_buffer_snapshot).row);
12893        if start > end {
12894            end..start
12895        } else {
12896            start..end
12897        }
12898    });
12899
12900    hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
12901}
12902
12903pub fn hunks_for_rows(
12904    rows: impl Iterator<Item = Range<MultiBufferRow>>,
12905    multi_buffer_snapshot: &MultiBufferSnapshot,
12906) -> Vec<MultiBufferDiffHunk> {
12907    let mut hunks = Vec::new();
12908    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
12909        HashMap::default();
12910    for selected_multi_buffer_rows in rows {
12911        let query_rows =
12912            selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
12913        for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
12914            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
12915            // when the caret is just above or just below the deleted hunk.
12916            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
12917            let related_to_selection = if allow_adjacent {
12918                hunk.row_range.overlaps(&query_rows)
12919                    || hunk.row_range.start == query_rows.end
12920                    || hunk.row_range.end == query_rows.start
12921            } else {
12922                // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
12923                // `hunk.row_range` is exclusive (e.g. [2..3] means 2nd row is selected)
12924                hunk.row_range.overlaps(&selected_multi_buffer_rows)
12925                    || selected_multi_buffer_rows.end == hunk.row_range.start
12926            };
12927            if related_to_selection {
12928                if !processed_buffer_rows
12929                    .entry(hunk.buffer_id)
12930                    .or_default()
12931                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
12932                {
12933                    continue;
12934                }
12935                hunks.push(hunk);
12936            }
12937        }
12938    }
12939
12940    hunks
12941}
12942
12943pub trait CollaborationHub {
12944    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
12945    fn user_participant_indices<'a>(
12946        &self,
12947        cx: &'a AppContext,
12948    ) -> &'a HashMap<u64, ParticipantIndex>;
12949    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
12950}
12951
12952impl CollaborationHub for Model<Project> {
12953    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
12954        self.read(cx).collaborators()
12955    }
12956
12957    fn user_participant_indices<'a>(
12958        &self,
12959        cx: &'a AppContext,
12960    ) -> &'a HashMap<u64, ParticipantIndex> {
12961        self.read(cx).user_store().read(cx).participant_indices()
12962    }
12963
12964    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
12965        let this = self.read(cx);
12966        let user_ids = this.collaborators().values().map(|c| c.user_id);
12967        this.user_store().read_with(cx, |user_store, cx| {
12968            user_store.participant_names(user_ids, cx)
12969        })
12970    }
12971}
12972
12973pub trait SemanticsProvider {
12974    fn hover(
12975        &self,
12976        buffer: &Model<Buffer>,
12977        position: text::Anchor,
12978        cx: &mut AppContext,
12979    ) -> Option<Task<Vec<project::Hover>>>;
12980
12981    fn inlay_hints(
12982        &self,
12983        buffer_handle: Model<Buffer>,
12984        range: Range<text::Anchor>,
12985        cx: &mut AppContext,
12986    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
12987
12988    fn resolve_inlay_hint(
12989        &self,
12990        hint: InlayHint,
12991        buffer_handle: Model<Buffer>,
12992        server_id: LanguageServerId,
12993        cx: &mut AppContext,
12994    ) -> Option<Task<anyhow::Result<InlayHint>>>;
12995
12996    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
12997
12998    fn document_highlights(
12999        &self,
13000        buffer: &Model<Buffer>,
13001        position: text::Anchor,
13002        cx: &mut AppContext,
13003    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13004
13005    fn definitions(
13006        &self,
13007        buffer: &Model<Buffer>,
13008        position: text::Anchor,
13009        kind: GotoDefinitionKind,
13010        cx: &mut AppContext,
13011    ) -> Option<Task<Result<Vec<LocationLink>>>>;
13012
13013    fn range_for_rename(
13014        &self,
13015        buffer: &Model<Buffer>,
13016        position: text::Anchor,
13017        cx: &mut AppContext,
13018    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13019
13020    fn perform_rename(
13021        &self,
13022        buffer: &Model<Buffer>,
13023        position: text::Anchor,
13024        new_name: String,
13025        cx: &mut AppContext,
13026    ) -> Option<Task<Result<ProjectTransaction>>>;
13027}
13028
13029pub trait CompletionProvider {
13030    fn completions(
13031        &self,
13032        buffer: &Model<Buffer>,
13033        buffer_position: text::Anchor,
13034        trigger: CompletionContext,
13035        cx: &mut ViewContext<Editor>,
13036    ) -> Task<Result<Vec<Completion>>>;
13037
13038    fn resolve_completions(
13039        &self,
13040        buffer: Model<Buffer>,
13041        completion_indices: Vec<usize>,
13042        completions: Arc<RwLock<Box<[Completion]>>>,
13043        cx: &mut ViewContext<Editor>,
13044    ) -> Task<Result<bool>>;
13045
13046    fn apply_additional_edits_for_completion(
13047        &self,
13048        buffer: Model<Buffer>,
13049        completion: Completion,
13050        push_to_history: bool,
13051        cx: &mut ViewContext<Editor>,
13052    ) -> Task<Result<Option<language::Transaction>>>;
13053
13054    fn is_completion_trigger(
13055        &self,
13056        buffer: &Model<Buffer>,
13057        position: language::Anchor,
13058        text: &str,
13059        trigger_in_words: bool,
13060        cx: &mut ViewContext<Editor>,
13061    ) -> bool;
13062
13063    fn sort_completions(&self) -> bool {
13064        true
13065    }
13066}
13067
13068pub trait CodeActionProvider {
13069    fn code_actions(
13070        &self,
13071        buffer: &Model<Buffer>,
13072        range: Range<text::Anchor>,
13073        cx: &mut WindowContext,
13074    ) -> Task<Result<Vec<CodeAction>>>;
13075
13076    fn apply_code_action(
13077        &self,
13078        buffer_handle: Model<Buffer>,
13079        action: CodeAction,
13080        excerpt_id: ExcerptId,
13081        push_to_history: bool,
13082        cx: &mut WindowContext,
13083    ) -> Task<Result<ProjectTransaction>>;
13084}
13085
13086impl CodeActionProvider for Model<Project> {
13087    fn code_actions(
13088        &self,
13089        buffer: &Model<Buffer>,
13090        range: Range<text::Anchor>,
13091        cx: &mut WindowContext,
13092    ) -> Task<Result<Vec<CodeAction>>> {
13093        self.update(cx, |project, cx| project.code_actions(buffer, range, cx))
13094    }
13095
13096    fn apply_code_action(
13097        &self,
13098        buffer_handle: Model<Buffer>,
13099        action: CodeAction,
13100        _excerpt_id: ExcerptId,
13101        push_to_history: bool,
13102        cx: &mut WindowContext,
13103    ) -> Task<Result<ProjectTransaction>> {
13104        self.update(cx, |project, cx| {
13105            project.apply_code_action(buffer_handle, action, push_to_history, cx)
13106        })
13107    }
13108}
13109
13110fn snippet_completions(
13111    project: &Project,
13112    buffer: &Model<Buffer>,
13113    buffer_position: text::Anchor,
13114    cx: &mut AppContext,
13115) -> Vec<Completion> {
13116    let language = buffer.read(cx).language_at(buffer_position);
13117    let language_name = language.as_ref().map(|language| language.lsp_id());
13118    let snippet_store = project.snippets().read(cx);
13119    let snippets = snippet_store.snippets_for(language_name, cx);
13120
13121    if snippets.is_empty() {
13122        return vec![];
13123    }
13124    let snapshot = buffer.read(cx).text_snapshot();
13125    let chars = snapshot.reversed_chars_for_range(text::Anchor::MIN..buffer_position);
13126
13127    let scope = language.map(|language| language.default_scope());
13128    let classifier = CharClassifier::new(scope).for_completion(true);
13129    let mut last_word = chars
13130        .take_while(|c| classifier.is_word(*c))
13131        .collect::<String>();
13132    last_word = last_word.chars().rev().collect();
13133    let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13134    let to_lsp = |point: &text::Anchor| {
13135        let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13136        point_to_lsp(end)
13137    };
13138    let lsp_end = to_lsp(&buffer_position);
13139    snippets
13140        .into_iter()
13141        .filter_map(|snippet| {
13142            let matching_prefix = snippet
13143                .prefix
13144                .iter()
13145                .find(|prefix| prefix.starts_with(&last_word))?;
13146            let start = as_offset - last_word.len();
13147            let start = snapshot.anchor_before(start);
13148            let range = start..buffer_position;
13149            let lsp_start = to_lsp(&start);
13150            let lsp_range = lsp::Range {
13151                start: lsp_start,
13152                end: lsp_end,
13153            };
13154            Some(Completion {
13155                old_range: range,
13156                new_text: snippet.body.clone(),
13157                label: CodeLabel {
13158                    text: matching_prefix.clone(),
13159                    runs: vec![],
13160                    filter_range: 0..matching_prefix.len(),
13161                },
13162                server_id: LanguageServerId(usize::MAX),
13163                documentation: snippet.description.clone().map(Documentation::SingleLine),
13164                lsp_completion: lsp::CompletionItem {
13165                    label: snippet.prefix.first().unwrap().clone(),
13166                    kind: Some(CompletionItemKind::SNIPPET),
13167                    label_details: snippet.description.as_ref().map(|description| {
13168                        lsp::CompletionItemLabelDetails {
13169                            detail: Some(description.clone()),
13170                            description: None,
13171                        }
13172                    }),
13173                    insert_text_format: Some(InsertTextFormat::SNIPPET),
13174                    text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13175                        lsp::InsertReplaceEdit {
13176                            new_text: snippet.body.clone(),
13177                            insert: lsp_range,
13178                            replace: lsp_range,
13179                        },
13180                    )),
13181                    filter_text: Some(snippet.body.clone()),
13182                    sort_text: Some(char::MAX.to_string()),
13183                    ..Default::default()
13184                },
13185                confirm: None,
13186            })
13187        })
13188        .collect()
13189}
13190
13191impl CompletionProvider for Model<Project> {
13192    fn completions(
13193        &self,
13194        buffer: &Model<Buffer>,
13195        buffer_position: text::Anchor,
13196        options: CompletionContext,
13197        cx: &mut ViewContext<Editor>,
13198    ) -> Task<Result<Vec<Completion>>> {
13199        self.update(cx, |project, cx| {
13200            let snippets = snippet_completions(project, buffer, buffer_position, cx);
13201            let project_completions = project.completions(buffer, buffer_position, options, cx);
13202            cx.background_executor().spawn(async move {
13203                let mut completions = project_completions.await?;
13204                //let snippets = snippets.into_iter().;
13205                completions.extend(snippets);
13206                Ok(completions)
13207            })
13208        })
13209    }
13210
13211    fn resolve_completions(
13212        &self,
13213        buffer: Model<Buffer>,
13214        completion_indices: Vec<usize>,
13215        completions: Arc<RwLock<Box<[Completion]>>>,
13216        cx: &mut ViewContext<Editor>,
13217    ) -> Task<Result<bool>> {
13218        self.update(cx, |project, cx| {
13219            project.resolve_completions(buffer, completion_indices, completions, cx)
13220        })
13221    }
13222
13223    fn apply_additional_edits_for_completion(
13224        &self,
13225        buffer: Model<Buffer>,
13226        completion: Completion,
13227        push_to_history: bool,
13228        cx: &mut ViewContext<Editor>,
13229    ) -> Task<Result<Option<language::Transaction>>> {
13230        self.update(cx, |project, cx| {
13231            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13232        })
13233    }
13234
13235    fn is_completion_trigger(
13236        &self,
13237        buffer: &Model<Buffer>,
13238        position: language::Anchor,
13239        text: &str,
13240        trigger_in_words: bool,
13241        cx: &mut ViewContext<Editor>,
13242    ) -> bool {
13243        if !EditorSettings::get_global(cx).show_completions_on_input {
13244            return false;
13245        }
13246
13247        let mut chars = text.chars();
13248        let char = if let Some(char) = chars.next() {
13249            char
13250        } else {
13251            return false;
13252        };
13253        if chars.next().is_some() {
13254            return false;
13255        }
13256
13257        let buffer = buffer.read(cx);
13258        let classifier = buffer
13259            .snapshot()
13260            .char_classifier_at(position)
13261            .for_completion(true);
13262        if trigger_in_words && classifier.is_word(char) {
13263            return true;
13264        }
13265
13266        buffer
13267            .completion_triggers()
13268            .iter()
13269            .any(|string| string == text)
13270    }
13271}
13272
13273impl SemanticsProvider for Model<Project> {
13274    fn hover(
13275        &self,
13276        buffer: &Model<Buffer>,
13277        position: text::Anchor,
13278        cx: &mut AppContext,
13279    ) -> Option<Task<Vec<project::Hover>>> {
13280        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13281    }
13282
13283    fn document_highlights(
13284        &self,
13285        buffer: &Model<Buffer>,
13286        position: text::Anchor,
13287        cx: &mut AppContext,
13288    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13289        Some(self.update(cx, |project, cx| {
13290            project.document_highlights(buffer, position, cx)
13291        }))
13292    }
13293
13294    fn definitions(
13295        &self,
13296        buffer: &Model<Buffer>,
13297        position: text::Anchor,
13298        kind: GotoDefinitionKind,
13299        cx: &mut AppContext,
13300    ) -> Option<Task<Result<Vec<LocationLink>>>> {
13301        Some(self.update(cx, |project, cx| match kind {
13302            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13303            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13304            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13305            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13306        }))
13307    }
13308
13309    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13310        // TODO: make this work for remote projects
13311        self.read(cx)
13312            .language_servers_for_buffer(buffer.read(cx), cx)
13313            .any(
13314                |(_, server)| match server.capabilities().inlay_hint_provider {
13315                    Some(lsp::OneOf::Left(enabled)) => enabled,
13316                    Some(lsp::OneOf::Right(_)) => true,
13317                    None => false,
13318                },
13319            )
13320    }
13321
13322    fn inlay_hints(
13323        &self,
13324        buffer_handle: Model<Buffer>,
13325        range: Range<text::Anchor>,
13326        cx: &mut AppContext,
13327    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13328        Some(self.update(cx, |project, cx| {
13329            project.inlay_hints(buffer_handle, range, cx)
13330        }))
13331    }
13332
13333    fn resolve_inlay_hint(
13334        &self,
13335        hint: InlayHint,
13336        buffer_handle: Model<Buffer>,
13337        server_id: LanguageServerId,
13338        cx: &mut AppContext,
13339    ) -> Option<Task<anyhow::Result<InlayHint>>> {
13340        Some(self.update(cx, |project, cx| {
13341            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13342        }))
13343    }
13344
13345    fn range_for_rename(
13346        &self,
13347        buffer: &Model<Buffer>,
13348        position: text::Anchor,
13349        cx: &mut AppContext,
13350    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13351        Some(self.update(cx, |project, cx| {
13352            project.prepare_rename(buffer.clone(), position, cx)
13353        }))
13354    }
13355
13356    fn perform_rename(
13357        &self,
13358        buffer: &Model<Buffer>,
13359        position: text::Anchor,
13360        new_name: String,
13361        cx: &mut AppContext,
13362    ) -> Option<Task<Result<ProjectTransaction>>> {
13363        Some(self.update(cx, |project, cx| {
13364            project.perform_rename(buffer.clone(), position, new_name, cx)
13365        }))
13366    }
13367}
13368
13369fn inlay_hint_settings(
13370    location: Anchor,
13371    snapshot: &MultiBufferSnapshot,
13372    cx: &mut ViewContext<'_, Editor>,
13373) -> InlayHintSettings {
13374    let file = snapshot.file_at(location);
13375    let language = snapshot.language_at(location);
13376    let settings = all_language_settings(file, cx);
13377    settings
13378        .language(language.map(|l| l.name()).as_ref())
13379        .inlay_hints
13380}
13381
13382fn consume_contiguous_rows(
13383    contiguous_row_selections: &mut Vec<Selection<Point>>,
13384    selection: &Selection<Point>,
13385    display_map: &DisplaySnapshot,
13386    selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
13387) -> (MultiBufferRow, MultiBufferRow) {
13388    contiguous_row_selections.push(selection.clone());
13389    let start_row = MultiBufferRow(selection.start.row);
13390    let mut end_row = ending_row(selection, display_map);
13391
13392    while let Some(next_selection) = selections.peek() {
13393        if next_selection.start.row <= end_row.0 {
13394            end_row = ending_row(next_selection, display_map);
13395            contiguous_row_selections.push(selections.next().unwrap().clone());
13396        } else {
13397            break;
13398        }
13399    }
13400    (start_row, end_row)
13401}
13402
13403fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13404    if next_selection.end.column > 0 || next_selection.is_empty() {
13405        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13406    } else {
13407        MultiBufferRow(next_selection.end.row)
13408    }
13409}
13410
13411impl EditorSnapshot {
13412    pub fn remote_selections_in_range<'a>(
13413        &'a self,
13414        range: &'a Range<Anchor>,
13415        collaboration_hub: &dyn CollaborationHub,
13416        cx: &'a AppContext,
13417    ) -> impl 'a + Iterator<Item = RemoteSelection> {
13418        let participant_names = collaboration_hub.user_names(cx);
13419        let participant_indices = collaboration_hub.user_participant_indices(cx);
13420        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
13421        let collaborators_by_replica_id = collaborators_by_peer_id
13422            .iter()
13423            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
13424            .collect::<HashMap<_, _>>();
13425        self.buffer_snapshot
13426            .selections_in_range(range, false)
13427            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
13428                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
13429                let participant_index = participant_indices.get(&collaborator.user_id).copied();
13430                let user_name = participant_names.get(&collaborator.user_id).cloned();
13431                Some(RemoteSelection {
13432                    replica_id,
13433                    selection,
13434                    cursor_shape,
13435                    line_mode,
13436                    participant_index,
13437                    peer_id: collaborator.peer_id,
13438                    user_name,
13439                })
13440            })
13441    }
13442
13443    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
13444        self.display_snapshot.buffer_snapshot.language_at(position)
13445    }
13446
13447    pub fn is_focused(&self) -> bool {
13448        self.is_focused
13449    }
13450
13451    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
13452        self.placeholder_text.as_ref()
13453    }
13454
13455    pub fn scroll_position(&self) -> gpui::Point<f32> {
13456        self.scroll_anchor.scroll_position(&self.display_snapshot)
13457    }
13458
13459    fn gutter_dimensions(
13460        &self,
13461        font_id: FontId,
13462        font_size: Pixels,
13463        em_width: Pixels,
13464        em_advance: Pixels,
13465        max_line_number_width: Pixels,
13466        cx: &AppContext,
13467    ) -> GutterDimensions {
13468        if !self.show_gutter {
13469            return GutterDimensions::default();
13470        }
13471        let descent = cx.text_system().descent(font_id, font_size);
13472
13473        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
13474            matches!(
13475                ProjectSettings::get_global(cx).git.git_gutter,
13476                Some(GitGutterSetting::TrackedFiles)
13477            )
13478        });
13479        let gutter_settings = EditorSettings::get_global(cx).gutter;
13480        let show_line_numbers = self
13481            .show_line_numbers
13482            .unwrap_or(gutter_settings.line_numbers);
13483        let line_gutter_width = if show_line_numbers {
13484            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
13485            let min_width_for_number_on_gutter = em_advance * 4.0;
13486            max_line_number_width.max(min_width_for_number_on_gutter)
13487        } else {
13488            0.0.into()
13489        };
13490
13491        let show_code_actions = self
13492            .show_code_actions
13493            .unwrap_or(gutter_settings.code_actions);
13494
13495        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
13496
13497        let git_blame_entries_width =
13498            self.git_blame_gutter_max_author_length
13499                .map(|max_author_length| {
13500                    // Length of the author name, but also space for the commit hash,
13501                    // the spacing and the timestamp.
13502                    let max_char_count = max_author_length
13503                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
13504                        + 7 // length of commit sha
13505                        + 14 // length of max relative timestamp ("60 minutes ago")
13506                        + 4; // gaps and margins
13507
13508                    em_advance * max_char_count
13509                });
13510
13511        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
13512        left_padding += if show_code_actions || show_runnables {
13513            em_width * 3.0
13514        } else if show_git_gutter && show_line_numbers {
13515            em_width * 2.0
13516        } else if show_git_gutter || show_line_numbers {
13517            em_width
13518        } else {
13519            px(0.)
13520        };
13521
13522        let right_padding = if gutter_settings.folds && show_line_numbers {
13523            em_width * 4.0
13524        } else if gutter_settings.folds {
13525            em_width * 3.0
13526        } else if show_line_numbers {
13527            em_width
13528        } else {
13529            px(0.)
13530        };
13531
13532        GutterDimensions {
13533            left_padding,
13534            right_padding,
13535            width: line_gutter_width + left_padding + right_padding,
13536            margin: -descent,
13537            git_blame_entries_width,
13538        }
13539    }
13540
13541    pub fn render_fold_toggle(
13542        &self,
13543        buffer_row: MultiBufferRow,
13544        row_contains_cursor: bool,
13545        editor: View<Editor>,
13546        cx: &mut WindowContext,
13547    ) -> Option<AnyElement> {
13548        let folded = self.is_line_folded(buffer_row);
13549
13550        if let Some(crease) = self
13551            .crease_snapshot
13552            .query_row(buffer_row, &self.buffer_snapshot)
13553        {
13554            let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
13555                if folded {
13556                    editor.update(cx, |editor, cx| {
13557                        editor.fold_at(&crate::FoldAt { buffer_row }, cx)
13558                    });
13559                } else {
13560                    editor.update(cx, |editor, cx| {
13561                        editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
13562                    });
13563                }
13564            });
13565
13566            Some((crease.render_toggle)(
13567                buffer_row,
13568                folded,
13569                toggle_callback,
13570                cx,
13571            ))
13572        } else if folded
13573            || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
13574        {
13575            Some(
13576                Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
13577                    .selected(folded)
13578                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
13579                        if folded {
13580                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
13581                        } else {
13582                            this.fold_at(&FoldAt { buffer_row }, cx);
13583                        }
13584                    }))
13585                    .into_any_element(),
13586            )
13587        } else {
13588            None
13589        }
13590    }
13591
13592    pub fn render_crease_trailer(
13593        &self,
13594        buffer_row: MultiBufferRow,
13595        cx: &mut WindowContext,
13596    ) -> Option<AnyElement> {
13597        let folded = self.is_line_folded(buffer_row);
13598        let crease = self
13599            .crease_snapshot
13600            .query_row(buffer_row, &self.buffer_snapshot)?;
13601        Some((crease.render_trailer)(buffer_row, folded, cx))
13602    }
13603}
13604
13605impl Deref for EditorSnapshot {
13606    type Target = DisplaySnapshot;
13607
13608    fn deref(&self) -> &Self::Target {
13609        &self.display_snapshot
13610    }
13611}
13612
13613#[derive(Clone, Debug, PartialEq, Eq)]
13614pub enum EditorEvent {
13615    InputIgnored {
13616        text: Arc<str>,
13617    },
13618    InputHandled {
13619        utf16_range_to_replace: Option<Range<isize>>,
13620        text: Arc<str>,
13621    },
13622    ExcerptsAdded {
13623        buffer: Model<Buffer>,
13624        predecessor: ExcerptId,
13625        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
13626    },
13627    ExcerptsRemoved {
13628        ids: Vec<ExcerptId>,
13629    },
13630    ExcerptsEdited {
13631        ids: Vec<ExcerptId>,
13632    },
13633    ExcerptsExpanded {
13634        ids: Vec<ExcerptId>,
13635    },
13636    BufferEdited,
13637    Edited {
13638        transaction_id: clock::Lamport,
13639    },
13640    Reparsed(BufferId),
13641    Focused,
13642    FocusedIn,
13643    Blurred,
13644    DirtyChanged,
13645    Saved,
13646    TitleChanged,
13647    DiffBaseChanged,
13648    SelectionsChanged {
13649        local: bool,
13650    },
13651    ScrollPositionChanged {
13652        local: bool,
13653        autoscroll: bool,
13654    },
13655    Closed,
13656    TransactionUndone {
13657        transaction_id: clock::Lamport,
13658    },
13659    TransactionBegun {
13660        transaction_id: clock::Lamport,
13661    },
13662    Reloaded,
13663    CursorShapeChanged,
13664}
13665
13666impl EventEmitter<EditorEvent> for Editor {}
13667
13668impl FocusableView for Editor {
13669    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
13670        self.focus_handle.clone()
13671    }
13672}
13673
13674impl Render for Editor {
13675    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
13676        let settings = ThemeSettings::get_global(cx);
13677
13678        let text_style = match self.mode {
13679            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
13680                color: cx.theme().colors().editor_foreground,
13681                font_family: settings.ui_font.family.clone(),
13682                font_features: settings.ui_font.features.clone(),
13683                font_fallbacks: settings.ui_font.fallbacks.clone(),
13684                font_size: rems(0.875).into(),
13685                font_weight: settings.ui_font.weight,
13686                line_height: relative(settings.buffer_line_height.value()),
13687                ..Default::default()
13688            },
13689            EditorMode::Full => TextStyle {
13690                color: cx.theme().colors().editor_foreground,
13691                font_family: settings.buffer_font.family.clone(),
13692                font_features: settings.buffer_font.features.clone(),
13693                font_fallbacks: settings.buffer_font.fallbacks.clone(),
13694                font_size: settings.buffer_font_size(cx).into(),
13695                font_weight: settings.buffer_font.weight,
13696                line_height: relative(settings.buffer_line_height.value()),
13697                ..Default::default()
13698            },
13699        };
13700
13701        let background = match self.mode {
13702            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
13703            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
13704            EditorMode::Full => cx.theme().colors().editor_background,
13705        };
13706
13707        EditorElement::new(
13708            cx.view(),
13709            EditorStyle {
13710                background,
13711                local_player: cx.theme().players().local(),
13712                text: text_style,
13713                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
13714                syntax: cx.theme().syntax().clone(),
13715                status: cx.theme().status().clone(),
13716                inlay_hints_style: make_inlay_hints_style(cx),
13717                suggestions_style: HighlightStyle {
13718                    color: Some(cx.theme().status().predictive),
13719                    ..HighlightStyle::default()
13720                },
13721                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
13722            },
13723        )
13724    }
13725}
13726
13727impl ViewInputHandler for Editor {
13728    fn text_for_range(
13729        &mut self,
13730        range_utf16: Range<usize>,
13731        cx: &mut ViewContext<Self>,
13732    ) -> Option<String> {
13733        Some(
13734            self.buffer
13735                .read(cx)
13736                .read(cx)
13737                .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
13738                .collect(),
13739        )
13740    }
13741
13742    fn selected_text_range(
13743        &mut self,
13744        ignore_disabled_input: bool,
13745        cx: &mut ViewContext<Self>,
13746    ) -> Option<UTF16Selection> {
13747        // Prevent the IME menu from appearing when holding down an alphabetic key
13748        // while input is disabled.
13749        if !ignore_disabled_input && !self.input_enabled {
13750            return None;
13751        }
13752
13753        let selection = self.selections.newest::<OffsetUtf16>(cx);
13754        let range = selection.range();
13755
13756        Some(UTF16Selection {
13757            range: range.start.0..range.end.0,
13758            reversed: selection.reversed,
13759        })
13760    }
13761
13762    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
13763        let snapshot = self.buffer.read(cx).read(cx);
13764        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
13765        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
13766    }
13767
13768    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
13769        self.clear_highlights::<InputComposition>(cx);
13770        self.ime_transaction.take();
13771    }
13772
13773    fn replace_text_in_range(
13774        &mut self,
13775        range_utf16: Option<Range<usize>>,
13776        text: &str,
13777        cx: &mut ViewContext<Self>,
13778    ) {
13779        if !self.input_enabled {
13780            cx.emit(EditorEvent::InputIgnored { text: text.into() });
13781            return;
13782        }
13783
13784        self.transact(cx, |this, cx| {
13785            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
13786                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13787                Some(this.selection_replacement_ranges(range_utf16, cx))
13788            } else {
13789                this.marked_text_ranges(cx)
13790            };
13791
13792            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
13793                let newest_selection_id = this.selections.newest_anchor().id;
13794                this.selections
13795                    .all::<OffsetUtf16>(cx)
13796                    .iter()
13797                    .zip(ranges_to_replace.iter())
13798                    .find_map(|(selection, range)| {
13799                        if selection.id == newest_selection_id {
13800                            Some(
13801                                (range.start.0 as isize - selection.head().0 as isize)
13802                                    ..(range.end.0 as isize - selection.head().0 as isize),
13803                            )
13804                        } else {
13805                            None
13806                        }
13807                    })
13808            });
13809
13810            cx.emit(EditorEvent::InputHandled {
13811                utf16_range_to_replace: range_to_replace,
13812                text: text.into(),
13813            });
13814
13815            if let Some(new_selected_ranges) = new_selected_ranges {
13816                this.change_selections(None, cx, |selections| {
13817                    selections.select_ranges(new_selected_ranges)
13818                });
13819                this.backspace(&Default::default(), cx);
13820            }
13821
13822            this.handle_input(text, cx);
13823        });
13824
13825        if let Some(transaction) = self.ime_transaction {
13826            self.buffer.update(cx, |buffer, cx| {
13827                buffer.group_until_transaction(transaction, cx);
13828            });
13829        }
13830
13831        self.unmark_text(cx);
13832    }
13833
13834    fn replace_and_mark_text_in_range(
13835        &mut self,
13836        range_utf16: Option<Range<usize>>,
13837        text: &str,
13838        new_selected_range_utf16: Option<Range<usize>>,
13839        cx: &mut ViewContext<Self>,
13840    ) {
13841        if !self.input_enabled {
13842            return;
13843        }
13844
13845        let transaction = self.transact(cx, |this, cx| {
13846            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
13847                let snapshot = this.buffer.read(cx).read(cx);
13848                if let Some(relative_range_utf16) = range_utf16.as_ref() {
13849                    for marked_range in &mut marked_ranges {
13850                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
13851                        marked_range.start.0 += relative_range_utf16.start;
13852                        marked_range.start =
13853                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
13854                        marked_range.end =
13855                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
13856                    }
13857                }
13858                Some(marked_ranges)
13859            } else if let Some(range_utf16) = range_utf16 {
13860                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13861                Some(this.selection_replacement_ranges(range_utf16, cx))
13862            } else {
13863                None
13864            };
13865
13866            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
13867                let newest_selection_id = this.selections.newest_anchor().id;
13868                this.selections
13869                    .all::<OffsetUtf16>(cx)
13870                    .iter()
13871                    .zip(ranges_to_replace.iter())
13872                    .find_map(|(selection, range)| {
13873                        if selection.id == newest_selection_id {
13874                            Some(
13875                                (range.start.0 as isize - selection.head().0 as isize)
13876                                    ..(range.end.0 as isize - selection.head().0 as isize),
13877                            )
13878                        } else {
13879                            None
13880                        }
13881                    })
13882            });
13883
13884            cx.emit(EditorEvent::InputHandled {
13885                utf16_range_to_replace: range_to_replace,
13886                text: text.into(),
13887            });
13888
13889            if let Some(ranges) = ranges_to_replace {
13890                this.change_selections(None, cx, |s| s.select_ranges(ranges));
13891            }
13892
13893            let marked_ranges = {
13894                let snapshot = this.buffer.read(cx).read(cx);
13895                this.selections
13896                    .disjoint_anchors()
13897                    .iter()
13898                    .map(|selection| {
13899                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
13900                    })
13901                    .collect::<Vec<_>>()
13902            };
13903
13904            if text.is_empty() {
13905                this.unmark_text(cx);
13906            } else {
13907                this.highlight_text::<InputComposition>(
13908                    marked_ranges.clone(),
13909                    HighlightStyle {
13910                        underline: Some(UnderlineStyle {
13911                            thickness: px(1.),
13912                            color: None,
13913                            wavy: false,
13914                        }),
13915                        ..Default::default()
13916                    },
13917                    cx,
13918                );
13919            }
13920
13921            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
13922            let use_autoclose = this.use_autoclose;
13923            let use_auto_surround = this.use_auto_surround;
13924            this.set_use_autoclose(false);
13925            this.set_use_auto_surround(false);
13926            this.handle_input(text, cx);
13927            this.set_use_autoclose(use_autoclose);
13928            this.set_use_auto_surround(use_auto_surround);
13929
13930            if let Some(new_selected_range) = new_selected_range_utf16 {
13931                let snapshot = this.buffer.read(cx).read(cx);
13932                let new_selected_ranges = marked_ranges
13933                    .into_iter()
13934                    .map(|marked_range| {
13935                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
13936                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
13937                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
13938                        snapshot.clip_offset_utf16(new_start, Bias::Left)
13939                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
13940                    })
13941                    .collect::<Vec<_>>();
13942
13943                drop(snapshot);
13944                this.change_selections(None, cx, |selections| {
13945                    selections.select_ranges(new_selected_ranges)
13946                });
13947            }
13948        });
13949
13950        self.ime_transaction = self.ime_transaction.or(transaction);
13951        if let Some(transaction) = self.ime_transaction {
13952            self.buffer.update(cx, |buffer, cx| {
13953                buffer.group_until_transaction(transaction, cx);
13954            });
13955        }
13956
13957        if self.text_highlights::<InputComposition>(cx).is_none() {
13958            self.ime_transaction.take();
13959        }
13960    }
13961
13962    fn bounds_for_range(
13963        &mut self,
13964        range_utf16: Range<usize>,
13965        element_bounds: gpui::Bounds<Pixels>,
13966        cx: &mut ViewContext<Self>,
13967    ) -> Option<gpui::Bounds<Pixels>> {
13968        let text_layout_details = self.text_layout_details(cx);
13969        let style = &text_layout_details.editor_style;
13970        let font_id = cx.text_system().resolve_font(&style.text.font());
13971        let font_size = style.text.font_size.to_pixels(cx.rem_size());
13972        let line_height = style.text.line_height_in_pixels(cx.rem_size());
13973
13974        let em_width = cx
13975            .text_system()
13976            .typographic_bounds(font_id, font_size, 'm')
13977            .unwrap()
13978            .size
13979            .width;
13980
13981        let snapshot = self.snapshot(cx);
13982        let scroll_position = snapshot.scroll_position();
13983        let scroll_left = scroll_position.x * em_width;
13984
13985        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
13986        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
13987            + self.gutter_dimensions.width;
13988        let y = line_height * (start.row().as_f32() - scroll_position.y);
13989
13990        Some(Bounds {
13991            origin: element_bounds.origin + point(x, y),
13992            size: size(em_width, line_height),
13993        })
13994    }
13995}
13996
13997trait SelectionExt {
13998    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
13999    fn spanned_rows(
14000        &self,
14001        include_end_if_at_line_start: bool,
14002        map: &DisplaySnapshot,
14003    ) -> Range<MultiBufferRow>;
14004}
14005
14006impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14007    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14008        let start = self
14009            .start
14010            .to_point(&map.buffer_snapshot)
14011            .to_display_point(map);
14012        let end = self
14013            .end
14014            .to_point(&map.buffer_snapshot)
14015            .to_display_point(map);
14016        if self.reversed {
14017            end..start
14018        } else {
14019            start..end
14020        }
14021    }
14022
14023    fn spanned_rows(
14024        &self,
14025        include_end_if_at_line_start: bool,
14026        map: &DisplaySnapshot,
14027    ) -> Range<MultiBufferRow> {
14028        let start = self.start.to_point(&map.buffer_snapshot);
14029        let mut end = self.end.to_point(&map.buffer_snapshot);
14030        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14031            end.row -= 1;
14032        }
14033
14034        let buffer_start = map.prev_line_boundary(start).0;
14035        let buffer_end = map.next_line_boundary(end).0;
14036        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14037    }
14038}
14039
14040impl<T: InvalidationRegion> InvalidationStack<T> {
14041    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14042    where
14043        S: Clone + ToOffset,
14044    {
14045        while let Some(region) = self.last() {
14046            let all_selections_inside_invalidation_ranges =
14047                if selections.len() == region.ranges().len() {
14048                    selections
14049                        .iter()
14050                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14051                        .all(|(selection, invalidation_range)| {
14052                            let head = selection.head().to_offset(buffer);
14053                            invalidation_range.start <= head && invalidation_range.end >= head
14054                        })
14055                } else {
14056                    false
14057                };
14058
14059            if all_selections_inside_invalidation_ranges {
14060                break;
14061            } else {
14062                self.pop();
14063            }
14064        }
14065    }
14066}
14067
14068impl<T> Default for InvalidationStack<T> {
14069    fn default() -> Self {
14070        Self(Default::default())
14071    }
14072}
14073
14074impl<T> Deref for InvalidationStack<T> {
14075    type Target = Vec<T>;
14076
14077    fn deref(&self) -> &Self::Target {
14078        &self.0
14079    }
14080}
14081
14082impl<T> DerefMut for InvalidationStack<T> {
14083    fn deref_mut(&mut self) -> &mut Self::Target {
14084        &mut self.0
14085    }
14086}
14087
14088impl InvalidationRegion for SnippetState {
14089    fn ranges(&self) -> &[Range<Anchor>] {
14090        &self.ranges[self.active_index]
14091    }
14092}
14093
14094pub fn diagnostic_block_renderer(
14095    diagnostic: Diagnostic,
14096    max_message_rows: Option<u8>,
14097    allow_closing: bool,
14098    _is_valid: bool,
14099) -> RenderBlock {
14100    let (text_without_backticks, code_ranges) =
14101        highlight_diagnostic_message(&diagnostic, max_message_rows);
14102
14103    Box::new(move |cx: &mut BlockContext| {
14104        let group_id: SharedString = cx.block_id.to_string().into();
14105
14106        let mut text_style = cx.text_style().clone();
14107        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14108        let theme_settings = ThemeSettings::get_global(cx);
14109        text_style.font_family = theme_settings.buffer_font.family.clone();
14110        text_style.font_style = theme_settings.buffer_font.style;
14111        text_style.font_features = theme_settings.buffer_font.features.clone();
14112        text_style.font_weight = theme_settings.buffer_font.weight;
14113
14114        let multi_line_diagnostic = diagnostic.message.contains('\n');
14115
14116        let buttons = |diagnostic: &Diagnostic, block_id: BlockId| {
14117            if multi_line_diagnostic {
14118                v_flex()
14119            } else {
14120                h_flex()
14121            }
14122            .when(allow_closing, |div| {
14123                div.children(diagnostic.is_primary.then(|| {
14124                    IconButton::new(("close-block", EntityId::from(block_id)), IconName::XCircle)
14125                        .icon_color(Color::Muted)
14126                        .size(ButtonSize::Compact)
14127                        .style(ButtonStyle::Transparent)
14128                        .visible_on_hover(group_id.clone())
14129                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14130                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14131                }))
14132            })
14133            .child(
14134                IconButton::new(("copy-block", EntityId::from(block_id)), IconName::Copy)
14135                    .icon_color(Color::Muted)
14136                    .size(ButtonSize::Compact)
14137                    .style(ButtonStyle::Transparent)
14138                    .visible_on_hover(group_id.clone())
14139                    .on_click({
14140                        let message = diagnostic.message.clone();
14141                        move |_click, cx| {
14142                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14143                        }
14144                    })
14145                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14146            )
14147        };
14148
14149        let icon_size = buttons(&diagnostic, cx.block_id)
14150            .into_any_element()
14151            .layout_as_root(AvailableSpace::min_size(), cx);
14152
14153        h_flex()
14154            .id(cx.block_id)
14155            .group(group_id.clone())
14156            .relative()
14157            .size_full()
14158            .pl(cx.gutter_dimensions.width)
14159            .w(cx.max_width + cx.gutter_dimensions.width)
14160            .child(
14161                div()
14162                    .flex()
14163                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14164                    .flex_shrink(),
14165            )
14166            .child(buttons(&diagnostic, cx.block_id))
14167            .child(div().flex().flex_shrink_0().child(
14168                StyledText::new(text_without_backticks.clone()).with_highlights(
14169                    &text_style,
14170                    code_ranges.iter().map(|range| {
14171                        (
14172                            range.clone(),
14173                            HighlightStyle {
14174                                font_weight: Some(FontWeight::BOLD),
14175                                ..Default::default()
14176                            },
14177                        )
14178                    }),
14179                ),
14180            ))
14181            .into_any_element()
14182    })
14183}
14184
14185pub fn highlight_diagnostic_message(
14186    diagnostic: &Diagnostic,
14187    mut max_message_rows: Option<u8>,
14188) -> (SharedString, Vec<Range<usize>>) {
14189    let mut text_without_backticks = String::new();
14190    let mut code_ranges = Vec::new();
14191
14192    if let Some(source) = &diagnostic.source {
14193        text_without_backticks.push_str(source);
14194        code_ranges.push(0..source.len());
14195        text_without_backticks.push_str(": ");
14196    }
14197
14198    let mut prev_offset = 0;
14199    let mut in_code_block = false;
14200    let has_row_limit = max_message_rows.is_some();
14201    let mut newline_indices = diagnostic
14202        .message
14203        .match_indices('\n')
14204        .filter(|_| has_row_limit)
14205        .map(|(ix, _)| ix)
14206        .fuse()
14207        .peekable();
14208
14209    for (quote_ix, _) in diagnostic
14210        .message
14211        .match_indices('`')
14212        .chain([(diagnostic.message.len(), "")])
14213    {
14214        let mut first_newline_ix = None;
14215        let mut last_newline_ix = None;
14216        while let Some(newline_ix) = newline_indices.peek() {
14217            if *newline_ix < quote_ix {
14218                if first_newline_ix.is_none() {
14219                    first_newline_ix = Some(*newline_ix);
14220                }
14221                last_newline_ix = Some(*newline_ix);
14222
14223                if let Some(rows_left) = &mut max_message_rows {
14224                    if *rows_left == 0 {
14225                        break;
14226                    } else {
14227                        *rows_left -= 1;
14228                    }
14229                }
14230                let _ = newline_indices.next();
14231            } else {
14232                break;
14233            }
14234        }
14235        let prev_len = text_without_backticks.len();
14236        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14237        text_without_backticks.push_str(new_text);
14238        if in_code_block {
14239            code_ranges.push(prev_len..text_without_backticks.len());
14240        }
14241        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14242        in_code_block = !in_code_block;
14243        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14244            text_without_backticks.push_str("...");
14245            break;
14246        }
14247    }
14248
14249    (text_without_backticks.into(), code_ranges)
14250}
14251
14252fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14253    match severity {
14254        DiagnosticSeverity::ERROR => colors.error,
14255        DiagnosticSeverity::WARNING => colors.warning,
14256        DiagnosticSeverity::INFORMATION => colors.info,
14257        DiagnosticSeverity::HINT => colors.info,
14258        _ => colors.ignored,
14259    }
14260}
14261
14262pub fn styled_runs_for_code_label<'a>(
14263    label: &'a CodeLabel,
14264    syntax_theme: &'a theme::SyntaxTheme,
14265) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14266    let fade_out = HighlightStyle {
14267        fade_out: Some(0.35),
14268        ..Default::default()
14269    };
14270
14271    let mut prev_end = label.filter_range.end;
14272    label
14273        .runs
14274        .iter()
14275        .enumerate()
14276        .flat_map(move |(ix, (range, highlight_id))| {
14277            let style = if let Some(style) = highlight_id.style(syntax_theme) {
14278                style
14279            } else {
14280                return Default::default();
14281            };
14282            let mut muted_style = style;
14283            muted_style.highlight(fade_out);
14284
14285            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14286            if range.start >= label.filter_range.end {
14287                if range.start > prev_end {
14288                    runs.push((prev_end..range.start, fade_out));
14289                }
14290                runs.push((range.clone(), muted_style));
14291            } else if range.end <= label.filter_range.end {
14292                runs.push((range.clone(), style));
14293            } else {
14294                runs.push((range.start..label.filter_range.end, style));
14295                runs.push((label.filter_range.end..range.end, muted_style));
14296            }
14297            prev_end = cmp::max(prev_end, range.end);
14298
14299            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14300                runs.push((prev_end..label.text.len(), fade_out));
14301            }
14302
14303            runs
14304        })
14305}
14306
14307pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14308    let mut prev_index = 0;
14309    let mut prev_codepoint: Option<char> = None;
14310    text.char_indices()
14311        .chain([(text.len(), '\0')])
14312        .filter_map(move |(index, codepoint)| {
14313            let prev_codepoint = prev_codepoint.replace(codepoint)?;
14314            let is_boundary = index == text.len()
14315                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14316                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14317            if is_boundary {
14318                let chunk = &text[prev_index..index];
14319                prev_index = index;
14320                Some(chunk)
14321            } else {
14322                None
14323            }
14324        })
14325}
14326
14327pub trait RangeToAnchorExt: Sized {
14328    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14329
14330    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14331        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14332        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14333    }
14334}
14335
14336impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14337    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14338        let start_offset = self.start.to_offset(snapshot);
14339        let end_offset = self.end.to_offset(snapshot);
14340        if start_offset == end_offset {
14341            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14342        } else {
14343            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14344        }
14345    }
14346}
14347
14348pub trait RowExt {
14349    fn as_f32(&self) -> f32;
14350
14351    fn next_row(&self) -> Self;
14352
14353    fn previous_row(&self) -> Self;
14354
14355    fn minus(&self, other: Self) -> u32;
14356}
14357
14358impl RowExt for DisplayRow {
14359    fn as_f32(&self) -> f32 {
14360        self.0 as f32
14361    }
14362
14363    fn next_row(&self) -> Self {
14364        Self(self.0 + 1)
14365    }
14366
14367    fn previous_row(&self) -> Self {
14368        Self(self.0.saturating_sub(1))
14369    }
14370
14371    fn minus(&self, other: Self) -> u32 {
14372        self.0 - other.0
14373    }
14374}
14375
14376impl RowExt for MultiBufferRow {
14377    fn as_f32(&self) -> f32 {
14378        self.0 as f32
14379    }
14380
14381    fn next_row(&self) -> Self {
14382        Self(self.0 + 1)
14383    }
14384
14385    fn previous_row(&self) -> Self {
14386        Self(self.0.saturating_sub(1))
14387    }
14388
14389    fn minus(&self, other: Self) -> u32 {
14390        self.0 - other.0
14391    }
14392}
14393
14394trait RowRangeExt {
14395    type Row;
14396
14397    fn len(&self) -> usize;
14398
14399    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
14400}
14401
14402impl RowRangeExt for Range<MultiBufferRow> {
14403    type Row = MultiBufferRow;
14404
14405    fn len(&self) -> usize {
14406        (self.end.0 - self.start.0) as usize
14407    }
14408
14409    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
14410        (self.start.0..self.end.0).map(MultiBufferRow)
14411    }
14412}
14413
14414impl RowRangeExt for Range<DisplayRow> {
14415    type Row = DisplayRow;
14416
14417    fn len(&self) -> usize {
14418        (self.end.0 - self.start.0) as usize
14419    }
14420
14421    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
14422        (self.start.0..self.end.0).map(DisplayRow)
14423    }
14424}
14425
14426fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
14427    if hunk.diff_base_byte_range.is_empty() {
14428        DiffHunkStatus::Added
14429    } else if hunk.row_range.is_empty() {
14430        DiffHunkStatus::Removed
14431    } else {
14432        DiffHunkStatus::Modified
14433    }
14434}
14435
14436/// If select range has more than one line, we
14437/// just point the cursor to range.start.
14438fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
14439    if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
14440        range
14441    } else {
14442        range.start..range.start
14443    }
14444}