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 behaviour.
   15pub mod actions;
   16mod blame_entry_tooltip;
   17mod blink_manager;
   18pub mod display_map;
   19mod editor_settings;
   20mod element;
   21mod hunk_diff;
   22mod inlay_hint_cache;
   23
   24mod debounced_delay;
   25mod git;
   26mod highlight_matching_bracket;
   27mod hover_links;
   28mod hover_popover;
   29mod inline_completion_provider;
   30pub mod items;
   31mod mouse_context_menu;
   32pub mod movement;
   33mod persistence;
   34mod rust_analyzer_ext;
   35pub mod scroll;
   36mod selections_collection;
   37pub mod tasks;
   38
   39#[cfg(test)]
   40mod editor_tests;
   41#[cfg(any(test, feature = "test-support"))]
   42pub mod test;
   43use ::git::diff::{DiffHunk, DiffHunkStatus};
   44use ::git::{parse_git_remote_url, BuildPermalinkParams, GitHostingProviderRegistry};
   45pub(crate) use actions::*;
   46use aho_corasick::AhoCorasick;
   47use anyhow::{anyhow, Context as _, Result};
   48use blink_manager::BlinkManager;
   49use client::{Collaborator, ParticipantIndex};
   50use clock::ReplicaId;
   51use collections::{hash_map, BTreeMap, Bound, HashMap, HashSet, VecDeque};
   52use convert_case::{Case, Casing};
   53use debounced_delay::DebouncedDelay;
   54pub use display_map::DisplayPoint;
   55use display_map::*;
   56pub use editor_settings::EditorSettings;
   57use element::LineWithInvisibles;
   58pub use element::{
   59    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   60};
   61use futures::FutureExt;
   62use fuzzy::{StringMatch, StringMatchCandidate};
   63use git::blame::GitBlame;
   64use git::diff_hunk_to_display;
   65use gpui::{
   66    div, impl_actions, point, prelude::*, px, relative, size, uniform_list, Action, AnyElement,
   67    AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds, ClipboardItem,
   68    Context, DispatchPhase, ElementId, EventEmitter, FocusHandle, FocusableView, FontId, FontStyle,
   69    FontWeight, HighlightStyle, Hsla, InteractiveText, KeyContext, Model, MouseButton, PaintQuad,
   70    ParentElement, Pixels, Render, SharedString, Size, StrikethroughStyle, Styled, StyledText,
   71    Subscription, Task, TextStyle, UnderlineStyle, UniformListScrollHandle, View, ViewContext,
   72    ViewInputHandler, VisualContext, WeakView, WhiteSpace, WindowContext,
   73};
   74use highlight_matching_bracket::refresh_matching_bracket_highlights;
   75use hover_popover::{hide_hover, HoverState};
   76use hunk_diff::ExpandedHunks;
   77pub(crate) use hunk_diff::HunkToExpand;
   78use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   79pub use inline_completion_provider::*;
   80pub use items::MAX_TAB_TITLE_LEN;
   81use itertools::Itertools;
   82use language::{
   83    char_kind,
   84    language_settings::{self, all_language_settings, InlayHintSettings},
   85    markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
   86    CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
   87    Point, Selection, SelectionGoal, TransactionId,
   88};
   89use language::{BufferRow, Runnable, RunnableRange};
   90use task::{ResolvedTask, TaskTemplate, TaskVariables};
   91
   92use hover_links::{HoverLink, HoveredLinkState, InlayHighlight};
   93use lsp::{DiagnosticSeverity, LanguageServerId};
   94use mouse_context_menu::MouseContextMenu;
   95use movement::TextLayoutDetails;
   96pub use multi_buffer::{
   97    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
   98    ToPoint,
   99};
  100use multi_buffer::{MultiBufferPoint, MultiBufferRow, ToOffsetUtf16};
  101use ordered_float::OrderedFloat;
  102use parking_lot::{Mutex, RwLock};
  103use project::project_settings::{GitGutterSetting, ProjectSettings};
  104use project::{
  105    CodeAction, Completion, FormatTrigger, Item, Location, Project, ProjectPath,
  106    ProjectTransaction, TaskSourceKind, WorktreeId,
  107};
  108use rand::prelude::*;
  109use rpc::{proto::*, ErrorExt};
  110use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  111use selections_collection::{resolve_multiple, MutableSelectionsCollection, SelectionsCollection};
  112use serde::{Deserialize, Serialize};
  113use settings::{Settings, SettingsStore};
  114use smallvec::SmallVec;
  115use snippet::Snippet;
  116use std::ops::Not as _;
  117use std::{
  118    any::TypeId,
  119    borrow::Cow,
  120    cmp::{self, Ordering, Reverse},
  121    mem,
  122    num::NonZeroU32,
  123    ops::{ControlFlow, Deref, DerefMut, Range, RangeInclusive},
  124    path::Path,
  125    sync::Arc,
  126    time::{Duration, Instant},
  127};
  128pub use sum_tree::Bias;
  129use sum_tree::TreeMap;
  130use text::{BufferId, OffsetUtf16, Rope};
  131use theme::{
  132    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  133    ThemeColors, ThemeSettings,
  134};
  135use ui::{
  136    h_flex, prelude::*, ButtonSize, ButtonStyle, IconButton, IconName, IconSize, ListItem, Popover,
  137    Tooltip,
  138};
  139use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  140use workspace::item::{ItemHandle, PreviewTabsSettings};
  141use workspace::notifications::{DetachAndPromptErr, NotificationId};
  142use workspace::{
  143    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  144};
  145use workspace::{OpenInTerminal, OpenTerminal, Toast};
  146
  147use crate::hover_links::find_url;
  148
  149pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  150const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  151const MAX_LINE_LEN: usize = 1024;
  152const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  153const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  154pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  155#[doc(hidden)]
  156pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  157#[doc(hidden)]
  158pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
  159
  160pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  161
  162pub fn render_parsed_markdown(
  163    element_id: impl Into<ElementId>,
  164    parsed: &language::ParsedMarkdown,
  165    editor_style: &EditorStyle,
  166    workspace: Option<WeakView<Workspace>>,
  167    cx: &mut WindowContext,
  168) -> InteractiveText {
  169    let code_span_background_color = cx
  170        .theme()
  171        .colors()
  172        .editor_document_highlight_read_background;
  173
  174    let highlights = gpui::combine_highlights(
  175        parsed.highlights.iter().filter_map(|(range, highlight)| {
  176            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  177            Some((range.clone(), highlight))
  178        }),
  179        parsed
  180            .regions
  181            .iter()
  182            .zip(&parsed.region_ranges)
  183            .filter_map(|(region, range)| {
  184                if region.code {
  185                    Some((
  186                        range.clone(),
  187                        HighlightStyle {
  188                            background_color: Some(code_span_background_color),
  189                            ..Default::default()
  190                        },
  191                    ))
  192                } else {
  193                    None
  194                }
  195            }),
  196    );
  197
  198    let mut links = Vec::new();
  199    let mut link_ranges = Vec::new();
  200    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  201        if let Some(link) = region.link.clone() {
  202            links.push(link);
  203            link_ranges.push(range.clone());
  204        }
  205    }
  206
  207    InteractiveText::new(
  208        element_id,
  209        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  210    )
  211    .on_click(link_ranges, move |clicked_range_ix, cx| {
  212        match &links[clicked_range_ix] {
  213            markdown::Link::Web { url } => cx.open_url(url),
  214            markdown::Link::Path { path } => {
  215                if let Some(workspace) = &workspace {
  216                    _ = workspace.update(cx, |workspace, cx| {
  217                        workspace.open_abs_path(path.clone(), false, cx).detach();
  218                    });
  219                }
  220            }
  221        }
  222    })
  223}
  224
  225#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  226pub(crate) enum InlayId {
  227    Suggestion(usize),
  228    Hint(usize),
  229}
  230
  231impl InlayId {
  232    fn id(&self) -> usize {
  233        match self {
  234            Self::Suggestion(id) => *id,
  235            Self::Hint(id) => *id,
  236        }
  237    }
  238}
  239
  240enum DiffRowHighlight {}
  241enum DocumentHighlightRead {}
  242enum DocumentHighlightWrite {}
  243enum InputComposition {}
  244
  245#[derive(Copy, Clone, PartialEq, Eq)]
  246pub enum Direction {
  247    Prev,
  248    Next,
  249}
  250
  251pub fn init_settings(cx: &mut AppContext) {
  252    EditorSettings::register(cx);
  253}
  254
  255pub fn init(cx: &mut AppContext) {
  256    init_settings(cx);
  257
  258    workspace::register_project_item::<Editor>(cx);
  259    workspace::register_followable_item::<Editor>(cx);
  260    workspace::register_deserializable_item::<Editor>(cx);
  261    cx.observe_new_views(
  262        |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
  263            workspace.register_action(Editor::new_file);
  264            workspace.register_action(Editor::new_file_in_direction);
  265        },
  266    )
  267    .detach();
  268
  269    cx.on_action(move |_: &workspace::NewFile, cx| {
  270        let app_state = workspace::AppState::global(cx);
  271        if let Some(app_state) = app_state.upgrade() {
  272            workspace::open_new(app_state, cx, |workspace, cx| {
  273                Editor::new_file(workspace, &Default::default(), cx)
  274            })
  275            .detach();
  276        }
  277    });
  278    cx.on_action(move |_: &workspace::NewWindow, cx| {
  279        let app_state = workspace::AppState::global(cx);
  280        if let Some(app_state) = app_state.upgrade() {
  281            workspace::open_new(app_state, cx, |workspace, cx| {
  282                Editor::new_file(workspace, &Default::default(), cx)
  283            })
  284            .detach();
  285        }
  286    });
  287}
  288
  289pub struct SearchWithinRange;
  290
  291trait InvalidationRegion {
  292    fn ranges(&self) -> &[Range<Anchor>];
  293}
  294
  295#[derive(Clone, Debug, PartialEq)]
  296pub enum SelectPhase {
  297    Begin {
  298        position: DisplayPoint,
  299        add: bool,
  300        click_count: usize,
  301    },
  302    BeginColumnar {
  303        position: DisplayPoint,
  304        goal_column: u32,
  305    },
  306    Extend {
  307        position: DisplayPoint,
  308        click_count: usize,
  309    },
  310    Update {
  311        position: DisplayPoint,
  312        goal_column: u32,
  313        scroll_delta: gpui::Point<f32>,
  314    },
  315    End,
  316}
  317
  318#[derive(Clone, Debug)]
  319pub enum SelectMode {
  320    Character,
  321    Word(Range<Anchor>),
  322    Line(Range<Anchor>),
  323    All,
  324}
  325
  326#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  327pub enum EditorMode {
  328    SingleLine,
  329    AutoHeight { max_lines: usize },
  330    Full,
  331}
  332
  333#[derive(Clone, Debug)]
  334pub enum SoftWrap {
  335    None,
  336    PreferLine,
  337    EditorWidth,
  338    Column(u32),
  339}
  340
  341#[derive(Clone)]
  342pub struct EditorStyle {
  343    pub background: Hsla,
  344    pub local_player: PlayerColor,
  345    pub text: TextStyle,
  346    pub scrollbar_width: Pixels,
  347    pub syntax: Arc<SyntaxTheme>,
  348    pub status: StatusColors,
  349    pub inlay_hints_style: HighlightStyle,
  350    pub suggestions_style: HighlightStyle,
  351}
  352
  353impl Default for EditorStyle {
  354    fn default() -> Self {
  355        Self {
  356            background: Hsla::default(),
  357            local_player: PlayerColor::default(),
  358            text: TextStyle::default(),
  359            scrollbar_width: Pixels::default(),
  360            syntax: Default::default(),
  361            // HACK: Status colors don't have a real default.
  362            // We should look into removing the status colors from the editor
  363            // style and retrieve them directly from the theme.
  364            status: StatusColors::dark(),
  365            inlay_hints_style: HighlightStyle::default(),
  366            suggestions_style: HighlightStyle::default(),
  367        }
  368    }
  369}
  370
  371type CompletionId = usize;
  372
  373// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  374// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  375
  376type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  377
  378struct ScrollbarMarkerState {
  379    scrollbar_size: Size<Pixels>,
  380    dirty: bool,
  381    markers: Arc<[PaintQuad]>,
  382    pending_refresh: Option<Task<Result<()>>>,
  383}
  384
  385impl ScrollbarMarkerState {
  386    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  387        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  388    }
  389}
  390
  391impl Default for ScrollbarMarkerState {
  392    fn default() -> Self {
  393        Self {
  394            scrollbar_size: Size::default(),
  395            dirty: false,
  396            markers: Arc::from([]),
  397            pending_refresh: None,
  398        }
  399    }
  400}
  401
  402#[derive(Clone, Debug)]
  403struct RunnableTasks {
  404    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  405    // We need the column at which the task context evaluation should take place.
  406    column: u32,
  407    extra_variables: HashMap<String, String>,
  408}
  409
  410#[derive(Clone)]
  411struct ResolvedTasks {
  412    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  413    position: Anchor,
  414}
  415
  416/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
  417///
  418/// See the [module level documentation](self) for more information.
  419pub struct Editor {
  420    focus_handle: FocusHandle,
  421    /// The text buffer being edited
  422    buffer: Model<MultiBuffer>,
  423    /// Map of how text in the buffer should be displayed.
  424    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  425    pub display_map: Model<DisplayMap>,
  426    pub selections: SelectionsCollection,
  427    pub scroll_manager: ScrollManager,
  428    columnar_selection_tail: Option<Anchor>,
  429    add_selections_state: Option<AddSelectionsState>,
  430    select_next_state: Option<SelectNextState>,
  431    select_prev_state: Option<SelectNextState>,
  432    selection_history: SelectionHistory,
  433    autoclose_regions: Vec<AutocloseRegion>,
  434    snippet_stack: InvalidationStack<SnippetState>,
  435    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  436    ime_transaction: Option<TransactionId>,
  437    active_diagnostics: Option<ActiveDiagnosticGroup>,
  438    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  439    project: Option<Model<Project>>,
  440    completion_provider: Option<Box<dyn CompletionProvider>>,
  441    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  442    blink_manager: Model<BlinkManager>,
  443    show_cursor_names: bool,
  444    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  445    pub show_local_selections: bool,
  446    mode: EditorMode,
  447    show_breadcrumbs: bool,
  448    show_gutter: bool,
  449    show_wrap_guides: Option<bool>,
  450    placeholder_text: Option<Arc<str>>,
  451    highlight_order: usize,
  452    highlighted_rows: HashMap<TypeId, Vec<(usize, RangeInclusive<Anchor>, Option<Hsla>)>>,
  453    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  454    scrollbar_marker_state: ScrollbarMarkerState,
  455    nav_history: Option<ItemNavHistory>,
  456    context_menu: RwLock<Option<ContextMenu>>,
  457    mouse_context_menu: Option<MouseContextMenu>,
  458    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  459    find_all_references_task_sources: Vec<Anchor>,
  460    next_completion_id: CompletionId,
  461    completion_documentation_pre_resolve_debounce: DebouncedDelay,
  462    available_code_actions: Option<(Location, Arc<[CodeAction]>)>,
  463    code_actions_task: Option<Task<()>>,
  464    document_highlights_task: Option<Task<()>>,
  465    pending_rename: Option<RenameState>,
  466    searchable: bool,
  467    cursor_shape: CursorShape,
  468    collapse_matches: bool,
  469    autoindent_mode: Option<AutoindentMode>,
  470    workspace: Option<(WeakView<Workspace>, WorkspaceId)>,
  471    keymap_context_layers: BTreeMap<TypeId, KeyContext>,
  472    input_enabled: bool,
  473    use_modal_editing: bool,
  474    read_only: bool,
  475    leader_peer_id: Option<PeerId>,
  476    remote_id: Option<ViewId>,
  477    hover_state: HoverState,
  478    gutter_hovered: bool,
  479    hovered_link_state: Option<HoveredLinkState>,
  480    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  481    active_inline_completion: Option<Inlay>,
  482    show_inline_completions: bool,
  483    inlay_hint_cache: InlayHintCache,
  484    expanded_hunks: ExpandedHunks,
  485    next_inlay_id: usize,
  486    _subscriptions: Vec<Subscription>,
  487    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  488    gutter_dimensions: GutterDimensions,
  489    pub vim_replace_map: HashMap<Range<usize>, String>,
  490    style: Option<EditorStyle>,
  491    editor_actions: Vec<Box<dyn Fn(&mut ViewContext<Self>)>>,
  492    use_autoclose: bool,
  493    auto_replace_emoji_shortcode: bool,
  494    show_git_blame_gutter: bool,
  495    show_git_blame_inline: bool,
  496    show_git_blame_inline_delay_task: Option<Task<()>>,
  497    git_blame_inline_enabled: bool,
  498    blame: Option<Model<GitBlame>>,
  499    blame_subscription: Option<Subscription>,
  500    custom_context_menu: Option<
  501        Box<
  502            dyn 'static
  503                + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
  504        >,
  505    >,
  506    last_bounds: Option<Bounds<Pixels>>,
  507    expect_bounds_change: Option<Bounds<Pixels>>,
  508    tasks: HashMap<(BufferId, BufferRow), (usize, RunnableTasks)>,
  509    tasks_update_task: Option<Task<()>>,
  510}
  511
  512#[derive(Clone)]
  513pub struct EditorSnapshot {
  514    pub mode: EditorMode,
  515    show_gutter: bool,
  516    render_git_blame_gutter: bool,
  517    pub display_snapshot: DisplaySnapshot,
  518    pub placeholder_text: Option<Arc<str>>,
  519    is_focused: bool,
  520    scroll_anchor: ScrollAnchor,
  521    ongoing_scroll: OngoingScroll,
  522}
  523
  524const GIT_BLAME_GUTTER_WIDTH_CHARS: f32 = 53.;
  525
  526#[derive(Debug, Clone, Copy)]
  527pub struct GutterDimensions {
  528    pub left_padding: Pixels,
  529    pub right_padding: Pixels,
  530    pub width: Pixels,
  531    pub margin: Pixels,
  532    pub git_blame_entries_width: Option<Pixels>,
  533}
  534
  535impl Default for GutterDimensions {
  536    fn default() -> Self {
  537        Self {
  538            left_padding: Pixels::ZERO,
  539            right_padding: Pixels::ZERO,
  540            width: Pixels::ZERO,
  541            margin: Pixels::ZERO,
  542            git_blame_entries_width: None,
  543        }
  544    }
  545}
  546
  547#[derive(Debug)]
  548pub struct RemoteSelection {
  549    pub replica_id: ReplicaId,
  550    pub selection: Selection<Anchor>,
  551    pub cursor_shape: CursorShape,
  552    pub peer_id: PeerId,
  553    pub line_mode: bool,
  554    pub participant_index: Option<ParticipantIndex>,
  555    pub user_name: Option<SharedString>,
  556}
  557
  558#[derive(Clone, Debug)]
  559struct SelectionHistoryEntry {
  560    selections: Arc<[Selection<Anchor>]>,
  561    select_next_state: Option<SelectNextState>,
  562    select_prev_state: Option<SelectNextState>,
  563    add_selections_state: Option<AddSelectionsState>,
  564}
  565
  566enum SelectionHistoryMode {
  567    Normal,
  568    Undoing,
  569    Redoing,
  570}
  571
  572#[derive(Clone, PartialEq, Eq, Hash)]
  573struct HoveredCursor {
  574    replica_id: u16,
  575    selection_id: usize,
  576}
  577
  578impl Default for SelectionHistoryMode {
  579    fn default() -> Self {
  580        Self::Normal
  581    }
  582}
  583
  584#[derive(Default)]
  585struct SelectionHistory {
  586    #[allow(clippy::type_complexity)]
  587    selections_by_transaction:
  588        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  589    mode: SelectionHistoryMode,
  590    undo_stack: VecDeque<SelectionHistoryEntry>,
  591    redo_stack: VecDeque<SelectionHistoryEntry>,
  592}
  593
  594impl SelectionHistory {
  595    fn insert_transaction(
  596        &mut self,
  597        transaction_id: TransactionId,
  598        selections: Arc<[Selection<Anchor>]>,
  599    ) {
  600        self.selections_by_transaction
  601            .insert(transaction_id, (selections, None));
  602    }
  603
  604    #[allow(clippy::type_complexity)]
  605    fn transaction(
  606        &self,
  607        transaction_id: TransactionId,
  608    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  609        self.selections_by_transaction.get(&transaction_id)
  610    }
  611
  612    #[allow(clippy::type_complexity)]
  613    fn transaction_mut(
  614        &mut self,
  615        transaction_id: TransactionId,
  616    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  617        self.selections_by_transaction.get_mut(&transaction_id)
  618    }
  619
  620    fn push(&mut self, entry: SelectionHistoryEntry) {
  621        if !entry.selections.is_empty() {
  622            match self.mode {
  623                SelectionHistoryMode::Normal => {
  624                    self.push_undo(entry);
  625                    self.redo_stack.clear();
  626                }
  627                SelectionHistoryMode::Undoing => self.push_redo(entry),
  628                SelectionHistoryMode::Redoing => self.push_undo(entry),
  629            }
  630        }
  631    }
  632
  633    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  634        if self
  635            .undo_stack
  636            .back()
  637            .map_or(true, |e| e.selections != entry.selections)
  638        {
  639            self.undo_stack.push_back(entry);
  640            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  641                self.undo_stack.pop_front();
  642            }
  643        }
  644    }
  645
  646    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  647        if self
  648            .redo_stack
  649            .back()
  650            .map_or(true, |e| e.selections != entry.selections)
  651        {
  652            self.redo_stack.push_back(entry);
  653            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  654                self.redo_stack.pop_front();
  655            }
  656        }
  657    }
  658}
  659
  660#[derive(Clone, Debug)]
  661struct AddSelectionsState {
  662    above: bool,
  663    stack: Vec<usize>,
  664}
  665
  666#[derive(Clone)]
  667struct SelectNextState {
  668    query: AhoCorasick,
  669    wordwise: bool,
  670    done: bool,
  671}
  672
  673impl std::fmt::Debug for SelectNextState {
  674    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  675        f.debug_struct(std::any::type_name::<Self>())
  676            .field("wordwise", &self.wordwise)
  677            .field("done", &self.done)
  678            .finish()
  679    }
  680}
  681
  682#[derive(Debug)]
  683struct AutocloseRegion {
  684    selection_id: usize,
  685    range: Range<Anchor>,
  686    pair: BracketPair,
  687}
  688
  689#[derive(Debug)]
  690struct SnippetState {
  691    ranges: Vec<Vec<Range<Anchor>>>,
  692    active_index: usize,
  693}
  694
  695#[doc(hidden)]
  696pub struct RenameState {
  697    pub range: Range<Anchor>,
  698    pub old_name: Arc<str>,
  699    pub editor: View<Editor>,
  700    block_id: BlockId,
  701}
  702
  703struct InvalidationStack<T>(Vec<T>);
  704
  705struct RegisteredInlineCompletionProvider {
  706    provider: Arc<dyn InlineCompletionProviderHandle>,
  707    _subscription: Subscription,
  708}
  709
  710enum ContextMenu {
  711    Completions(CompletionsMenu),
  712    CodeActions(CodeActionsMenu),
  713}
  714
  715impl ContextMenu {
  716    fn select_first(
  717        &mut self,
  718        project: Option<&Model<Project>>,
  719        cx: &mut ViewContext<Editor>,
  720    ) -> bool {
  721        if self.visible() {
  722            match self {
  723                ContextMenu::Completions(menu) => menu.select_first(project, cx),
  724                ContextMenu::CodeActions(menu) => menu.select_first(cx),
  725            }
  726            true
  727        } else {
  728            false
  729        }
  730    }
  731
  732    fn select_prev(
  733        &mut self,
  734        project: Option<&Model<Project>>,
  735        cx: &mut ViewContext<Editor>,
  736    ) -> bool {
  737        if self.visible() {
  738            match self {
  739                ContextMenu::Completions(menu) => menu.select_prev(project, cx),
  740                ContextMenu::CodeActions(menu) => menu.select_prev(cx),
  741            }
  742            true
  743        } else {
  744            false
  745        }
  746    }
  747
  748    fn select_next(
  749        &mut self,
  750        project: Option<&Model<Project>>,
  751        cx: &mut ViewContext<Editor>,
  752    ) -> bool {
  753        if self.visible() {
  754            match self {
  755                ContextMenu::Completions(menu) => menu.select_next(project, cx),
  756                ContextMenu::CodeActions(menu) => menu.select_next(cx),
  757            }
  758            true
  759        } else {
  760            false
  761        }
  762    }
  763
  764    fn select_last(
  765        &mut self,
  766        project: Option<&Model<Project>>,
  767        cx: &mut ViewContext<Editor>,
  768    ) -> bool {
  769        if self.visible() {
  770            match self {
  771                ContextMenu::Completions(menu) => menu.select_last(project, cx),
  772                ContextMenu::CodeActions(menu) => menu.select_last(cx),
  773            }
  774            true
  775        } else {
  776            false
  777        }
  778    }
  779
  780    fn visible(&self) -> bool {
  781        match self {
  782            ContextMenu::Completions(menu) => menu.visible(),
  783            ContextMenu::CodeActions(menu) => menu.visible(),
  784        }
  785    }
  786
  787    fn render(
  788        &self,
  789        cursor_position: DisplayPoint,
  790        style: &EditorStyle,
  791        max_height: Pixels,
  792        workspace: Option<WeakView<Workspace>>,
  793        cx: &mut ViewContext<Editor>,
  794    ) -> (ContextMenuOrigin, AnyElement) {
  795        match self {
  796            ContextMenu::Completions(menu) => (
  797                ContextMenuOrigin::EditorPoint(cursor_position),
  798                menu.render(style, max_height, workspace, cx),
  799            ),
  800            ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
  801        }
  802    }
  803}
  804
  805enum ContextMenuOrigin {
  806    EditorPoint(DisplayPoint),
  807    GutterIndicator(DisplayRow),
  808}
  809
  810#[derive(Clone)]
  811struct CompletionsMenu {
  812    id: CompletionId,
  813    initial_position: Anchor,
  814    buffer: Model<Buffer>,
  815    completions: Arc<RwLock<Box<[Completion]>>>,
  816    match_candidates: Arc<[StringMatchCandidate]>,
  817    matches: Arc<[StringMatch]>,
  818    selected_item: usize,
  819    scroll_handle: UniformListScrollHandle,
  820    selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
  821}
  822
  823impl CompletionsMenu {
  824    fn select_first(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
  825        self.selected_item = 0;
  826        self.scroll_handle.scroll_to_item(self.selected_item);
  827        self.attempt_resolve_selected_completion_documentation(project, cx);
  828        cx.notify();
  829    }
  830
  831    fn select_prev(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
  832        if self.selected_item > 0 {
  833            self.selected_item -= 1;
  834        } else {
  835            self.selected_item = self.matches.len() - 1;
  836        }
  837        self.scroll_handle.scroll_to_item(self.selected_item);
  838        self.attempt_resolve_selected_completion_documentation(project, cx);
  839        cx.notify();
  840    }
  841
  842    fn select_next(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
  843        if self.selected_item + 1 < self.matches.len() {
  844            self.selected_item += 1;
  845        } else {
  846            self.selected_item = 0;
  847        }
  848        self.scroll_handle.scroll_to_item(self.selected_item);
  849        self.attempt_resolve_selected_completion_documentation(project, cx);
  850        cx.notify();
  851    }
  852
  853    fn select_last(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
  854        self.selected_item = self.matches.len() - 1;
  855        self.scroll_handle.scroll_to_item(self.selected_item);
  856        self.attempt_resolve_selected_completion_documentation(project, cx);
  857        cx.notify();
  858    }
  859
  860    fn pre_resolve_completion_documentation(
  861        buffer: Model<Buffer>,
  862        completions: Arc<RwLock<Box<[Completion]>>>,
  863        matches: Arc<[StringMatch]>,
  864        editor: &Editor,
  865        cx: &mut ViewContext<Editor>,
  866    ) -> Task<()> {
  867        let settings = EditorSettings::get_global(cx);
  868        if !settings.show_completion_documentation {
  869            return Task::ready(());
  870        }
  871
  872        let Some(provider) = editor.completion_provider.as_ref() else {
  873            return Task::ready(());
  874        };
  875
  876        let resolve_task = provider.resolve_completions(
  877            buffer,
  878            matches.iter().map(|m| m.candidate_id).collect(),
  879            completions.clone(),
  880            cx,
  881        );
  882
  883        return cx.spawn(move |this, mut cx| async move {
  884            if let Some(true) = resolve_task.await.log_err() {
  885                this.update(&mut cx, |_, cx| cx.notify()).ok();
  886            }
  887        });
  888    }
  889
  890    fn attempt_resolve_selected_completion_documentation(
  891        &mut self,
  892        project: Option<&Model<Project>>,
  893        cx: &mut ViewContext<Editor>,
  894    ) {
  895        let settings = EditorSettings::get_global(cx);
  896        if !settings.show_completion_documentation {
  897            return;
  898        }
  899
  900        let completion_index = self.matches[self.selected_item].candidate_id;
  901        let Some(project) = project else {
  902            return;
  903        };
  904
  905        let resolve_task = project.update(cx, |project, cx| {
  906            project.resolve_completions(
  907                self.buffer.clone(),
  908                vec![completion_index],
  909                self.completions.clone(),
  910                cx,
  911            )
  912        });
  913
  914        let delay_ms =
  915            EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
  916        let delay = Duration::from_millis(delay_ms);
  917
  918        self.selected_completion_documentation_resolve_debounce
  919            .lock()
  920            .fire_new(delay, cx, |_, cx| {
  921                cx.spawn(move |this, mut cx| async move {
  922                    if let Some(true) = resolve_task.await.log_err() {
  923                        this.update(&mut cx, |_, cx| cx.notify()).ok();
  924                    }
  925                })
  926            });
  927    }
  928
  929    fn visible(&self) -> bool {
  930        !self.matches.is_empty()
  931    }
  932
  933    fn render(
  934        &self,
  935        style: &EditorStyle,
  936        max_height: Pixels,
  937        workspace: Option<WeakView<Workspace>>,
  938        cx: &mut ViewContext<Editor>,
  939    ) -> AnyElement {
  940        let settings = EditorSettings::get_global(cx);
  941        let show_completion_documentation = settings.show_completion_documentation;
  942
  943        let widest_completion_ix = self
  944            .matches
  945            .iter()
  946            .enumerate()
  947            .max_by_key(|(_, mat)| {
  948                let completions = self.completions.read();
  949                let completion = &completions[mat.candidate_id];
  950                let documentation = &completion.documentation;
  951
  952                let mut len = completion.label.text.chars().count();
  953                if let Some(Documentation::SingleLine(text)) = documentation {
  954                    if show_completion_documentation {
  955                        len += text.chars().count();
  956                    }
  957                }
  958
  959                len
  960            })
  961            .map(|(ix, _)| ix);
  962
  963        let completions = self.completions.clone();
  964        let matches = self.matches.clone();
  965        let selected_item = self.selected_item;
  966        let style = style.clone();
  967
  968        let multiline_docs = if show_completion_documentation {
  969            let mat = &self.matches[selected_item];
  970            let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
  971                Some(Documentation::MultiLinePlainText(text)) => {
  972                    Some(div().child(SharedString::from(text.clone())))
  973                }
  974                Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
  975                    Some(div().child(render_parsed_markdown(
  976                        "completions_markdown",
  977                        parsed,
  978                        &style,
  979                        workspace,
  980                        cx,
  981                    )))
  982                }
  983                _ => None,
  984            };
  985            multiline_docs.map(|div| {
  986                div.id("multiline_docs")
  987                    .max_h(max_height)
  988                    .flex_1()
  989                    .px_1p5()
  990                    .py_1()
  991                    .min_w(px(260.))
  992                    .max_w(px(640.))
  993                    .w(px(500.))
  994                    .overflow_y_scroll()
  995                    .occlude()
  996            })
  997        } else {
  998            None
  999        };
 1000
 1001        let list = uniform_list(
 1002            cx.view().clone(),
 1003            "completions",
 1004            matches.len(),
 1005            move |_editor, range, cx| {
 1006                let start_ix = range.start;
 1007                let completions_guard = completions.read();
 1008
 1009                matches[range]
 1010                    .iter()
 1011                    .enumerate()
 1012                    .map(|(ix, mat)| {
 1013                        let item_ix = start_ix + ix;
 1014                        let candidate_id = mat.candidate_id;
 1015                        let completion = &completions_guard[candidate_id];
 1016
 1017                        let documentation = if show_completion_documentation {
 1018                            &completion.documentation
 1019                        } else {
 1020                            &None
 1021                        };
 1022
 1023                        let highlights = gpui::combine_highlights(
 1024                            mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
 1025                            styled_runs_for_code_label(&completion.label, &style.syntax).map(
 1026                                |(range, mut highlight)| {
 1027                                    // Ignore font weight for syntax highlighting, as we'll use it
 1028                                    // for fuzzy matches.
 1029                                    highlight.font_weight = None;
 1030
 1031                                    if completion.lsp_completion.deprecated.unwrap_or(false) {
 1032                                        highlight.strikethrough = Some(StrikethroughStyle {
 1033                                            thickness: 1.0.into(),
 1034                                            ..Default::default()
 1035                                        });
 1036                                        highlight.color = Some(cx.theme().colors().text_muted);
 1037                                    }
 1038
 1039                                    (range, highlight)
 1040                                },
 1041                            ),
 1042                        );
 1043                        let completion_label = StyledText::new(completion.label.text.clone())
 1044                            .with_highlights(&style.text, highlights);
 1045                        let documentation_label =
 1046                            if let Some(Documentation::SingleLine(text)) = documentation {
 1047                                if text.trim().is_empty() {
 1048                                    None
 1049                                } else {
 1050                                    Some(
 1051                                        h_flex().ml_4().child(
 1052                                            Label::new(text.clone())
 1053                                                .size(LabelSize::Small)
 1054                                                .color(Color::Muted),
 1055                                        ),
 1056                                    )
 1057                                }
 1058                            } else {
 1059                                None
 1060                            };
 1061
 1062                        div().min_w(px(220.)).max_w(px(540.)).child(
 1063                            ListItem::new(mat.candidate_id)
 1064                                .inset(true)
 1065                                .selected(item_ix == selected_item)
 1066                                .on_click(cx.listener(move |editor, _event, cx| {
 1067                                    cx.stop_propagation();
 1068                                    if let Some(task) = editor.confirm_completion(
 1069                                        &ConfirmCompletion {
 1070                                            item_ix: Some(item_ix),
 1071                                        },
 1072                                        cx,
 1073                                    ) {
 1074                                        task.detach_and_log_err(cx)
 1075                                    }
 1076                                }))
 1077                                .child(h_flex().overflow_hidden().child(completion_label))
 1078                                .end_slot::<Div>(documentation_label),
 1079                        )
 1080                    })
 1081                    .collect()
 1082            },
 1083        )
 1084        .occlude()
 1085        .max_h(max_height)
 1086        .track_scroll(self.scroll_handle.clone())
 1087        .with_width_from_item(widest_completion_ix);
 1088
 1089        Popover::new()
 1090            .child(list)
 1091            .when_some(multiline_docs, |popover, multiline_docs| {
 1092                popover.aside(multiline_docs)
 1093            })
 1094            .into_any_element()
 1095    }
 1096
 1097    pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
 1098        let mut matches = if let Some(query) = query {
 1099            fuzzy::match_strings(
 1100                &self.match_candidates,
 1101                query,
 1102                query.chars().any(|c| c.is_uppercase()),
 1103                100,
 1104                &Default::default(),
 1105                executor,
 1106            )
 1107            .await
 1108        } else {
 1109            self.match_candidates
 1110                .iter()
 1111                .enumerate()
 1112                .map(|(candidate_id, candidate)| StringMatch {
 1113                    candidate_id,
 1114                    score: Default::default(),
 1115                    positions: Default::default(),
 1116                    string: candidate.string.clone(),
 1117                })
 1118                .collect()
 1119        };
 1120
 1121        // Remove all candidates where the query's start does not match the start of any word in the candidate
 1122        if let Some(query) = query {
 1123            if let Some(query_start) = query.chars().next() {
 1124                matches.retain(|string_match| {
 1125                    split_words(&string_match.string).any(|word| {
 1126                        // Check that the first codepoint of the word as lowercase matches the first
 1127                        // codepoint of the query as lowercase
 1128                        word.chars()
 1129                            .flat_map(|codepoint| codepoint.to_lowercase())
 1130                            .zip(query_start.to_lowercase())
 1131                            .all(|(word_cp, query_cp)| word_cp == query_cp)
 1132                    })
 1133                });
 1134            }
 1135        }
 1136
 1137        let completions = self.completions.read();
 1138        matches.sort_unstable_by_key(|mat| {
 1139            // We do want to strike a balance here between what the language server tells us
 1140            // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
 1141            // `Creat` and there is a local variable called `CreateComponent`).
 1142            // So what we do is: we bucket all matches into two buckets
 1143            // - Strong matches
 1144            // - Weak matches
 1145            // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
 1146            // and the Weak matches are the rest.
 1147            //
 1148            // For the strong matches, we sort by the language-servers score first and for the weak
 1149            // matches, we prefer our fuzzy finder first.
 1150            //
 1151            // The thinking behind that: it's useless to take the sort_text the language-server gives
 1152            // us into account when it's obviously a bad match.
 1153
 1154            #[derive(PartialEq, Eq, PartialOrd, Ord)]
 1155            enum MatchScore<'a> {
 1156                Strong {
 1157                    sort_text: Option<&'a str>,
 1158                    score: Reverse<OrderedFloat<f64>>,
 1159                    sort_key: (usize, &'a str),
 1160                },
 1161                Weak {
 1162                    score: Reverse<OrderedFloat<f64>>,
 1163                    sort_text: Option<&'a str>,
 1164                    sort_key: (usize, &'a str),
 1165                },
 1166            }
 1167
 1168            let completion = &completions[mat.candidate_id];
 1169            let sort_key = completion.sort_key();
 1170            let sort_text = completion.lsp_completion.sort_text.as_deref();
 1171            let score = Reverse(OrderedFloat(mat.score));
 1172
 1173            if mat.score >= 0.2 {
 1174                MatchScore::Strong {
 1175                    sort_text,
 1176                    score,
 1177                    sort_key,
 1178                }
 1179            } else {
 1180                MatchScore::Weak {
 1181                    score,
 1182                    sort_text,
 1183                    sort_key,
 1184                }
 1185            }
 1186        });
 1187
 1188        for mat in &mut matches {
 1189            let completion = &completions[mat.candidate_id];
 1190            mat.string.clone_from(&completion.label.text);
 1191            for position in &mut mat.positions {
 1192                *position += completion.label.filter_range.start;
 1193            }
 1194        }
 1195        drop(completions);
 1196
 1197        self.matches = matches.into();
 1198        self.selected_item = 0;
 1199    }
 1200}
 1201
 1202#[derive(Clone)]
 1203struct CodeActionContents {
 1204    tasks: Option<Arc<ResolvedTasks>>,
 1205    actions: Option<Arc<[CodeAction]>>,
 1206}
 1207
 1208impl CodeActionContents {
 1209    fn len(&self) -> usize {
 1210        match (&self.tasks, &self.actions) {
 1211            (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
 1212            (Some(tasks), None) => tasks.templates.len(),
 1213            (None, Some(actions)) => actions.len(),
 1214            (None, None) => 0,
 1215        }
 1216    }
 1217
 1218    fn is_empty(&self) -> bool {
 1219        match (&self.tasks, &self.actions) {
 1220            (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
 1221            (Some(tasks), None) => tasks.templates.is_empty(),
 1222            (None, Some(actions)) => actions.is_empty(),
 1223            (None, None) => true,
 1224        }
 1225    }
 1226
 1227    fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
 1228        self.tasks
 1229            .iter()
 1230            .flat_map(|tasks| {
 1231                tasks
 1232                    .templates
 1233                    .iter()
 1234                    .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
 1235            })
 1236            .chain(self.actions.iter().flat_map(|actions| {
 1237                actions
 1238                    .iter()
 1239                    .map(|action| CodeActionsItem::CodeAction(action.clone()))
 1240            }))
 1241    }
 1242    fn get(&self, index: usize) -> Option<CodeActionsItem> {
 1243        match (&self.tasks, &self.actions) {
 1244            (Some(tasks), Some(actions)) => {
 1245                if index < tasks.templates.len() {
 1246                    tasks
 1247                        .templates
 1248                        .get(index)
 1249                        .cloned()
 1250                        .map(|(kind, task)| CodeActionsItem::Task(kind, task))
 1251                } else {
 1252                    actions
 1253                        .get(index - tasks.templates.len())
 1254                        .cloned()
 1255                        .map(CodeActionsItem::CodeAction)
 1256                }
 1257            }
 1258            (Some(tasks), None) => tasks
 1259                .templates
 1260                .get(index)
 1261                .cloned()
 1262                .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
 1263            (None, Some(actions)) => actions.get(index).cloned().map(CodeActionsItem::CodeAction),
 1264            (None, None) => None,
 1265        }
 1266    }
 1267}
 1268
 1269#[allow(clippy::large_enum_variant)]
 1270#[derive(Clone)]
 1271enum CodeActionsItem {
 1272    Task(TaskSourceKind, ResolvedTask),
 1273    CodeAction(CodeAction),
 1274}
 1275
 1276impl CodeActionsItem {
 1277    fn as_task(&self) -> Option<&ResolvedTask> {
 1278        let Self::Task(_, task) = self else {
 1279            return None;
 1280        };
 1281        Some(task)
 1282    }
 1283    fn as_code_action(&self) -> Option<&CodeAction> {
 1284        let Self::CodeAction(action) = self else {
 1285            return None;
 1286        };
 1287        Some(action)
 1288    }
 1289    fn label(&self) -> String {
 1290        match self {
 1291            Self::CodeAction(action) => action.lsp_action.title.clone(),
 1292            Self::Task(_, task) => task.resolved_label.clone(),
 1293        }
 1294    }
 1295}
 1296
 1297struct CodeActionsMenu {
 1298    actions: CodeActionContents,
 1299    buffer: Model<Buffer>,
 1300    selected_item: usize,
 1301    scroll_handle: UniformListScrollHandle,
 1302    deployed_from_indicator: Option<DisplayRow>,
 1303}
 1304
 1305impl CodeActionsMenu {
 1306    fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
 1307        self.selected_item = 0;
 1308        self.scroll_handle.scroll_to_item(self.selected_item);
 1309        cx.notify()
 1310    }
 1311
 1312    fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
 1313        if self.selected_item > 0 {
 1314            self.selected_item -= 1;
 1315        } else {
 1316            self.selected_item = self.actions.len() - 1;
 1317        }
 1318        self.scroll_handle.scroll_to_item(self.selected_item);
 1319        cx.notify();
 1320    }
 1321
 1322    fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
 1323        if self.selected_item + 1 < self.actions.len() {
 1324            self.selected_item += 1;
 1325        } else {
 1326            self.selected_item = 0;
 1327        }
 1328        self.scroll_handle.scroll_to_item(self.selected_item);
 1329        cx.notify();
 1330    }
 1331
 1332    fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
 1333        self.selected_item = self.actions.len() - 1;
 1334        self.scroll_handle.scroll_to_item(self.selected_item);
 1335        cx.notify()
 1336    }
 1337
 1338    fn visible(&self) -> bool {
 1339        !self.actions.is_empty()
 1340    }
 1341
 1342    fn render(
 1343        &self,
 1344        cursor_position: DisplayPoint,
 1345        _style: &EditorStyle,
 1346        max_height: Pixels,
 1347        cx: &mut ViewContext<Editor>,
 1348    ) -> (ContextMenuOrigin, AnyElement) {
 1349        let actions = self.actions.clone();
 1350        let selected_item = self.selected_item;
 1351        let element = uniform_list(
 1352            cx.view().clone(),
 1353            "code_actions_menu",
 1354            self.actions.len(),
 1355            move |_this, range, cx| {
 1356                actions
 1357                    .iter()
 1358                    .skip(range.start)
 1359                    .take(range.end - range.start)
 1360                    .enumerate()
 1361                    .map(|(ix, action)| {
 1362                        let item_ix = range.start + ix;
 1363                        let selected = selected_item == item_ix;
 1364                        let colors = cx.theme().colors();
 1365                        div()
 1366                            .px_2()
 1367                            .text_color(colors.text)
 1368                            .when(selected, |style| {
 1369                                style
 1370                                    .bg(colors.element_active)
 1371                                    .text_color(colors.text_accent)
 1372                            })
 1373                            .hover(|style| {
 1374                                style
 1375                                    .bg(colors.element_hover)
 1376                                    .text_color(colors.text_accent)
 1377                            })
 1378                            .whitespace_nowrap()
 1379                            .when_some(action.as_code_action(), |this, action| {
 1380                                this.on_mouse_down(
 1381                                    MouseButton::Left,
 1382                                    cx.listener(move |editor, _, cx| {
 1383                                        cx.stop_propagation();
 1384                                        if let Some(task) = editor.confirm_code_action(
 1385                                            &ConfirmCodeAction {
 1386                                                item_ix: Some(item_ix),
 1387                                            },
 1388                                            cx,
 1389                                        ) {
 1390                                            task.detach_and_log_err(cx)
 1391                                        }
 1392                                    }),
 1393                                )
 1394                                // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
 1395                                .child(SharedString::from(action.lsp_action.title.clone()))
 1396                            })
 1397                            .when_some(action.as_task(), |this, task| {
 1398                                this.on_mouse_down(
 1399                                    MouseButton::Left,
 1400                                    cx.listener(move |editor, _, cx| {
 1401                                        cx.stop_propagation();
 1402                                        if let Some(task) = editor.confirm_code_action(
 1403                                            &ConfirmCodeAction {
 1404                                                item_ix: Some(item_ix),
 1405                                            },
 1406                                            cx,
 1407                                        ) {
 1408                                            task.detach_and_log_err(cx)
 1409                                        }
 1410                                    }),
 1411                                )
 1412                                .child(SharedString::from(task.resolved_label.clone()))
 1413                            })
 1414                    })
 1415                    .collect()
 1416            },
 1417        )
 1418        .elevation_1(cx)
 1419        .px_2()
 1420        .py_1()
 1421        .max_h(max_height)
 1422        .occlude()
 1423        .track_scroll(self.scroll_handle.clone())
 1424        .with_width_from_item(
 1425            self.actions
 1426                .iter()
 1427                .enumerate()
 1428                .max_by_key(|(_, action)| match action {
 1429                    CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
 1430                    CodeActionsItem::CodeAction(action) => action.lsp_action.title.chars().count(),
 1431                })
 1432                .map(|(ix, _)| ix),
 1433        )
 1434        .into_any_element();
 1435
 1436        let cursor_position = if let Some(row) = self.deployed_from_indicator {
 1437            ContextMenuOrigin::GutterIndicator(row)
 1438        } else {
 1439            ContextMenuOrigin::EditorPoint(cursor_position)
 1440        };
 1441
 1442        (cursor_position, element)
 1443    }
 1444}
 1445
 1446#[derive(Debug)]
 1447struct ActiveDiagnosticGroup {
 1448    primary_range: Range<Anchor>,
 1449    primary_message: String,
 1450    group_id: usize,
 1451    blocks: HashMap<BlockId, Diagnostic>,
 1452    is_valid: bool,
 1453}
 1454
 1455#[derive(Serialize, Deserialize)]
 1456pub struct ClipboardSelection {
 1457    pub len: usize,
 1458    pub is_entire_line: bool,
 1459    pub first_line_indent: u32,
 1460}
 1461
 1462#[derive(Debug)]
 1463pub(crate) struct NavigationData {
 1464    cursor_anchor: Anchor,
 1465    cursor_position: Point,
 1466    scroll_anchor: ScrollAnchor,
 1467    scroll_top_row: u32,
 1468}
 1469
 1470enum GotoDefinitionKind {
 1471    Symbol,
 1472    Type,
 1473    Implementation,
 1474}
 1475
 1476#[derive(Debug, Clone)]
 1477enum InlayHintRefreshReason {
 1478    Toggle(bool),
 1479    SettingsChange(InlayHintSettings),
 1480    NewLinesShown,
 1481    BufferEdited(HashSet<Arc<Language>>),
 1482    RefreshRequested,
 1483    ExcerptsRemoved(Vec<ExcerptId>),
 1484}
 1485
 1486impl InlayHintRefreshReason {
 1487    fn description(&self) -> &'static str {
 1488        match self {
 1489            Self::Toggle(_) => "toggle",
 1490            Self::SettingsChange(_) => "settings change",
 1491            Self::NewLinesShown => "new lines shown",
 1492            Self::BufferEdited(_) => "buffer edited",
 1493            Self::RefreshRequested => "refresh requested",
 1494            Self::ExcerptsRemoved(_) => "excerpts removed",
 1495        }
 1496    }
 1497}
 1498
 1499impl Editor {
 1500    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
 1501        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1502        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1503        Self::new(EditorMode::SingleLine, buffer, None, cx)
 1504    }
 1505
 1506    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
 1507        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1508        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1509        Self::new(EditorMode::Full, buffer, None, cx)
 1510    }
 1511
 1512    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
 1513        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1514        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1515        Self::new(EditorMode::AutoHeight { max_lines }, buffer, None, cx)
 1516    }
 1517
 1518    pub fn for_buffer(
 1519        buffer: Model<Buffer>,
 1520        project: Option<Model<Project>>,
 1521        cx: &mut ViewContext<Self>,
 1522    ) -> Self {
 1523        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1524        Self::new(EditorMode::Full, buffer, project, cx)
 1525    }
 1526
 1527    pub fn for_multibuffer(
 1528        buffer: Model<MultiBuffer>,
 1529        project: Option<Model<Project>>,
 1530        cx: &mut ViewContext<Self>,
 1531    ) -> Self {
 1532        Self::new(EditorMode::Full, buffer, project, cx)
 1533    }
 1534
 1535    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 1536        let mut clone = Self::new(self.mode, self.buffer.clone(), self.project.clone(), cx);
 1537        self.display_map.update(cx, |display_map, cx| {
 1538            let snapshot = display_map.snapshot(cx);
 1539            clone.display_map.update(cx, |display_map, cx| {
 1540                display_map.set_state(&snapshot, cx);
 1541            });
 1542        });
 1543        clone.selections.clone_state(&self.selections);
 1544        clone.scroll_manager.clone_state(&self.scroll_manager);
 1545        clone.searchable = self.searchable;
 1546        clone
 1547    }
 1548
 1549    fn new(
 1550        mode: EditorMode,
 1551        buffer: Model<MultiBuffer>,
 1552        project: Option<Model<Project>>,
 1553        cx: &mut ViewContext<Self>,
 1554    ) -> Self {
 1555        let style = cx.text_style();
 1556        let font_size = style.font_size.to_pixels(cx.rem_size());
 1557        let display_map = cx.new_model(|cx| {
 1558            DisplayMap::new(buffer.clone(), style.font(), font_size, None, 2, 1, cx)
 1559        });
 1560
 1561        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1562
 1563        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1564
 1565        let soft_wrap_mode_override =
 1566            (mode == EditorMode::SingleLine).then(|| language_settings::SoftWrap::PreferLine);
 1567
 1568        let mut project_subscriptions = Vec::new();
 1569        if mode == EditorMode::Full {
 1570            if let Some(project) = project.as_ref() {
 1571                if buffer.read(cx).is_singleton() {
 1572                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
 1573                        cx.emit(EditorEvent::TitleChanged);
 1574                    }));
 1575                }
 1576                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
 1577                    if let project::Event::RefreshInlayHints = event {
 1578                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1579                    };
 1580                }));
 1581            }
 1582        }
 1583
 1584        let inlay_hint_settings = inlay_hint_settings(
 1585            selections.newest_anchor().head(),
 1586            &buffer.read(cx).snapshot(cx),
 1587            cx,
 1588        );
 1589
 1590        let focus_handle = cx.focus_handle();
 1591        cx.on_focus(&focus_handle, Self::handle_focus).detach();
 1592        cx.on_blur(&focus_handle, Self::handle_blur).detach();
 1593
 1594        let mut this = Self {
 1595            focus_handle,
 1596            buffer: buffer.clone(),
 1597            display_map: display_map.clone(),
 1598            selections,
 1599            scroll_manager: ScrollManager::new(cx),
 1600            columnar_selection_tail: None,
 1601            add_selections_state: None,
 1602            select_next_state: None,
 1603            select_prev_state: None,
 1604            selection_history: Default::default(),
 1605            autoclose_regions: Default::default(),
 1606            snippet_stack: Default::default(),
 1607            select_larger_syntax_node_stack: Vec::new(),
 1608            ime_transaction: Default::default(),
 1609            active_diagnostics: None,
 1610            soft_wrap_mode_override,
 1611            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1612            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1613            project,
 1614            blink_manager: blink_manager.clone(),
 1615            show_local_selections: true,
 1616            mode,
 1617            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1618            show_gutter: mode == EditorMode::Full,
 1619            show_wrap_guides: None,
 1620            placeholder_text: None,
 1621            highlight_order: 0,
 1622            highlighted_rows: HashMap::default(),
 1623            background_highlights: Default::default(),
 1624            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1625            nav_history: None,
 1626            context_menu: RwLock::new(None),
 1627            mouse_context_menu: None,
 1628            completion_tasks: Default::default(),
 1629            find_all_references_task_sources: Vec::new(),
 1630            next_completion_id: 0,
 1631            completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
 1632            next_inlay_id: 0,
 1633            available_code_actions: Default::default(),
 1634            code_actions_task: Default::default(),
 1635            document_highlights_task: Default::default(),
 1636            pending_rename: Default::default(),
 1637            searchable: true,
 1638            cursor_shape: Default::default(),
 1639            autoindent_mode: Some(AutoindentMode::EachLine),
 1640            collapse_matches: false,
 1641            workspace: None,
 1642            keymap_context_layers: Default::default(),
 1643            input_enabled: true,
 1644            use_modal_editing: mode == EditorMode::Full,
 1645            read_only: false,
 1646            use_autoclose: true,
 1647            auto_replace_emoji_shortcode: false,
 1648            leader_peer_id: None,
 1649            remote_id: None,
 1650            hover_state: Default::default(),
 1651            hovered_link_state: Default::default(),
 1652            inline_completion_provider: None,
 1653            active_inline_completion: None,
 1654            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1655            expanded_hunks: ExpandedHunks::default(),
 1656            gutter_hovered: false,
 1657            pixel_position_of_newest_cursor: None,
 1658            last_bounds: None,
 1659            expect_bounds_change: None,
 1660            gutter_dimensions: GutterDimensions::default(),
 1661            style: None,
 1662            show_cursor_names: false,
 1663            hovered_cursors: Default::default(),
 1664            editor_actions: Default::default(),
 1665            vim_replace_map: Default::default(),
 1666            show_inline_completions: mode == EditorMode::Full,
 1667            custom_context_menu: None,
 1668            show_git_blame_gutter: false,
 1669            show_git_blame_inline: false,
 1670            show_git_blame_inline_delay_task: None,
 1671            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1672            blame: None,
 1673            blame_subscription: None,
 1674            tasks: Default::default(),
 1675            _subscriptions: vec![
 1676                cx.observe(&buffer, Self::on_buffer_changed),
 1677                cx.subscribe(&buffer, Self::on_buffer_event),
 1678                cx.observe(&display_map, Self::on_display_map_changed),
 1679                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1680                cx.observe_global::<SettingsStore>(Self::settings_changed),
 1681                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1682                cx.observe_window_activation(|editor, cx| {
 1683                    let active = cx.is_window_active();
 1684                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1685                        if active {
 1686                            blink_manager.enable(cx);
 1687                        } else {
 1688                            blink_manager.show_cursor(cx);
 1689                            blink_manager.disable(cx);
 1690                        }
 1691                    });
 1692                }),
 1693            ],
 1694            tasks_update_task: None,
 1695        };
 1696        this.tasks_update_task = Some(this.refresh_runnables(cx));
 1697        this._subscriptions.extend(project_subscriptions);
 1698
 1699        this.end_selection(cx);
 1700        this.scroll_manager.show_scrollbar(cx);
 1701
 1702        if mode == EditorMode::Full {
 1703            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1704            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1705
 1706            if this.git_blame_inline_enabled {
 1707                this.git_blame_inline_enabled = true;
 1708                this.start_git_blame_inline(false, cx);
 1709            }
 1710        }
 1711
 1712        this.report_editor_event("open", None, cx);
 1713        this
 1714    }
 1715
 1716    fn key_context(&self, cx: &AppContext) -> KeyContext {
 1717        let mut key_context = KeyContext::new_with_defaults();
 1718        key_context.add("Editor");
 1719        let mode = match self.mode {
 1720            EditorMode::SingleLine => "single_line",
 1721            EditorMode::AutoHeight { .. } => "auto_height",
 1722            EditorMode::Full => "full",
 1723        };
 1724        key_context.set("mode", mode);
 1725        if self.pending_rename.is_some() {
 1726            key_context.add("renaming");
 1727        }
 1728        if self.context_menu_visible() {
 1729            match self.context_menu.read().as_ref() {
 1730                Some(ContextMenu::Completions(_)) => {
 1731                    key_context.add("menu");
 1732                    key_context.add("showing_completions")
 1733                }
 1734                Some(ContextMenu::CodeActions(_)) => {
 1735                    key_context.add("menu");
 1736                    key_context.add("showing_code_actions")
 1737                }
 1738                None => {}
 1739            }
 1740        }
 1741
 1742        for layer in self.keymap_context_layers.values() {
 1743            key_context.extend(layer);
 1744        }
 1745
 1746        if let Some(extension) = self
 1747            .buffer
 1748            .read(cx)
 1749            .as_singleton()
 1750            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1751        {
 1752            key_context.set("extension", extension.to_string());
 1753        }
 1754
 1755        if self.has_active_inline_completion(cx) {
 1756            key_context.add("copilot_suggestion");
 1757            key_context.add("inline_completion");
 1758        }
 1759
 1760        key_context
 1761    }
 1762
 1763    pub fn new_file(
 1764        workspace: &mut Workspace,
 1765        _: &workspace::NewFile,
 1766        cx: &mut ViewContext<Workspace>,
 1767    ) {
 1768        let project = workspace.project().clone();
 1769        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1770
 1771        cx.spawn(|workspace, mut cx| async move {
 1772            let buffer = create.await?;
 1773            workspace.update(&mut cx, |workspace, cx| {
 1774                workspace.add_item_to_active_pane(
 1775                    Box::new(
 1776                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 1777                    ),
 1778                    None,
 1779                    cx,
 1780                )
 1781            })
 1782        })
 1783        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 1784            ErrorCode::RemoteUpgradeRequired => Some(format!(
 1785                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1786                e.error_tag("required").unwrap_or("the latest version")
 1787            )),
 1788            _ => None,
 1789        });
 1790    }
 1791
 1792    pub fn new_file_in_direction(
 1793        workspace: &mut Workspace,
 1794        action: &workspace::NewFileInDirection,
 1795        cx: &mut ViewContext<Workspace>,
 1796    ) {
 1797        let project = workspace.project().clone();
 1798        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1799        let direction = action.0;
 1800
 1801        cx.spawn(|workspace, mut cx| async move {
 1802            let buffer = create.await?;
 1803            workspace.update(&mut cx, move |workspace, cx| {
 1804                workspace.split_item(
 1805                    direction,
 1806                    Box::new(
 1807                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 1808                    ),
 1809                    cx,
 1810                )
 1811            })?;
 1812            anyhow::Ok(())
 1813        })
 1814        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 1815            ErrorCode::RemoteUpgradeRequired => Some(format!(
 1816                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1817                e.error_tag("required").unwrap_or("the latest version")
 1818            )),
 1819            _ => None,
 1820        });
 1821    }
 1822
 1823    pub fn replica_id(&self, cx: &AppContext) -> ReplicaId {
 1824        self.buffer.read(cx).replica_id()
 1825    }
 1826
 1827    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1828        self.leader_peer_id
 1829    }
 1830
 1831    pub fn buffer(&self) -> &Model<MultiBuffer> {
 1832        &self.buffer
 1833    }
 1834
 1835    pub fn workspace(&self) -> Option<View<Workspace>> {
 1836        self.workspace.as_ref()?.0.upgrade()
 1837    }
 1838
 1839    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
 1840        self.buffer().read(cx).title(cx)
 1841    }
 1842
 1843    pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
 1844        EditorSnapshot {
 1845            mode: self.mode,
 1846            show_gutter: self.show_gutter,
 1847            render_git_blame_gutter: self.render_git_blame_gutter(cx),
 1848            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1849            scroll_anchor: self.scroll_manager.anchor(),
 1850            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1851            placeholder_text: self.placeholder_text.clone(),
 1852            is_focused: self.focus_handle.is_focused(cx),
 1853        }
 1854    }
 1855
 1856    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
 1857        self.buffer.read(cx).language_at(point, cx)
 1858    }
 1859
 1860    pub fn file_at<T: ToOffset>(
 1861        &self,
 1862        point: T,
 1863        cx: &AppContext,
 1864    ) -> Option<Arc<dyn language::File>> {
 1865        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1866    }
 1867
 1868    pub fn active_excerpt(
 1869        &self,
 1870        cx: &AppContext,
 1871    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
 1872        self.buffer
 1873            .read(cx)
 1874            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1875    }
 1876
 1877    pub fn mode(&self) -> EditorMode {
 1878        self.mode
 1879    }
 1880
 1881    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1882        self.collaboration_hub.as_deref()
 1883    }
 1884
 1885    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1886        self.collaboration_hub = Some(hub);
 1887    }
 1888
 1889    pub fn set_custom_context_menu(
 1890        &mut self,
 1891        f: impl 'static
 1892            + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
 1893    ) {
 1894        self.custom_context_menu = Some(Box::new(f))
 1895    }
 1896
 1897    pub fn set_completion_provider(&mut self, hub: Box<dyn CompletionProvider>) {
 1898        self.completion_provider = Some(hub);
 1899    }
 1900
 1901    pub fn set_inline_completion_provider<T>(
 1902        &mut self,
 1903        provider: Option<Model<T>>,
 1904        cx: &mut ViewContext<Self>,
 1905    ) where
 1906        T: InlineCompletionProvider,
 1907    {
 1908        self.inline_completion_provider =
 1909            provider.map(|provider| RegisteredInlineCompletionProvider {
 1910                _subscription: cx.observe(&provider, |this, _, cx| {
 1911                    if this.focus_handle.is_focused(cx) {
 1912                        this.update_visible_inline_completion(cx);
 1913                    }
 1914                }),
 1915                provider: Arc::new(provider),
 1916            });
 1917        self.refresh_inline_completion(false, cx);
 1918    }
 1919
 1920    pub fn placeholder_text(&self, _cx: &mut WindowContext) -> Option<&str> {
 1921        self.placeholder_text.as_deref()
 1922    }
 1923
 1924    pub fn set_placeholder_text(
 1925        &mut self,
 1926        placeholder_text: impl Into<Arc<str>>,
 1927        cx: &mut ViewContext<Self>,
 1928    ) {
 1929        let placeholder_text = Some(placeholder_text.into());
 1930        if self.placeholder_text != placeholder_text {
 1931            self.placeholder_text = placeholder_text;
 1932            cx.notify();
 1933        }
 1934    }
 1935
 1936    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
 1937        self.cursor_shape = cursor_shape;
 1938        cx.notify();
 1939    }
 1940
 1941    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1942        self.collapse_matches = collapse_matches;
 1943    }
 1944
 1945    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1946        if self.collapse_matches {
 1947            return range.start..range.start;
 1948        }
 1949        range.clone()
 1950    }
 1951
 1952    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
 1953        if self.display_map.read(cx).clip_at_line_ends != clip {
 1954            self.display_map
 1955                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1956        }
 1957    }
 1958
 1959    pub fn set_keymap_context_layer<Tag: 'static>(
 1960        &mut self,
 1961        context: KeyContext,
 1962        cx: &mut ViewContext<Self>,
 1963    ) {
 1964        self.keymap_context_layers
 1965            .insert(TypeId::of::<Tag>(), context);
 1966        cx.notify();
 1967    }
 1968
 1969    pub fn remove_keymap_context_layer<Tag: 'static>(&mut self, cx: &mut ViewContext<Self>) {
 1970        self.keymap_context_layers.remove(&TypeId::of::<Tag>());
 1971        cx.notify();
 1972    }
 1973
 1974    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1975        self.input_enabled = input_enabled;
 1976    }
 1977
 1978    pub fn set_autoindent(&mut self, autoindent: bool) {
 1979        if autoindent {
 1980            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1981        } else {
 1982            self.autoindent_mode = None;
 1983        }
 1984    }
 1985
 1986    pub fn read_only(&self, cx: &AppContext) -> bool {
 1987        self.read_only || self.buffer.read(cx).read_only()
 1988    }
 1989
 1990    pub fn set_read_only(&mut self, read_only: bool) {
 1991        self.read_only = read_only;
 1992    }
 1993
 1994    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1995        self.use_autoclose = autoclose;
 1996    }
 1997
 1998    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1999        self.auto_replace_emoji_shortcode = auto_replace;
 2000    }
 2001
 2002    pub fn set_show_inline_completions(&mut self, show_inline_completions: bool) {
 2003        self.show_inline_completions = show_inline_completions;
 2004    }
 2005
 2006    pub fn set_use_modal_editing(&mut self, to: bool) {
 2007        self.use_modal_editing = to;
 2008    }
 2009
 2010    pub fn use_modal_editing(&self) -> bool {
 2011        self.use_modal_editing
 2012    }
 2013
 2014    fn selections_did_change(
 2015        &mut self,
 2016        local: bool,
 2017        old_cursor_position: &Anchor,
 2018        cx: &mut ViewContext<Self>,
 2019    ) {
 2020        // Copy selections to primary selection buffer
 2021        #[cfg(target_os = "linux")]
 2022        if local {
 2023            let selections = self.selections.all::<usize>(cx);
 2024            let buffer_handle = self.buffer.read(cx).read(cx);
 2025
 2026            let mut text = String::new();
 2027            for (index, selection) in selections.iter().enumerate() {
 2028                let text_for_selection = buffer_handle
 2029                    .text_for_range(selection.start..selection.end)
 2030                    .collect::<String>();
 2031
 2032                text.push_str(&text_for_selection);
 2033                if index != selections.len() - 1 {
 2034                    text.push('\n');
 2035                }
 2036            }
 2037
 2038            if !text.is_empty() {
 2039                cx.write_to_primary(ClipboardItem::new(text));
 2040            }
 2041        }
 2042
 2043        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
 2044            self.buffer.update(cx, |buffer, cx| {
 2045                buffer.set_active_selections(
 2046                    &self.selections.disjoint_anchors(),
 2047                    self.selections.line_mode,
 2048                    self.cursor_shape,
 2049                    cx,
 2050                )
 2051            });
 2052        }
 2053
 2054        let display_map = self
 2055            .display_map
 2056            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2057        let buffer = &display_map.buffer_snapshot;
 2058        self.add_selections_state = None;
 2059        self.select_next_state = None;
 2060        self.select_prev_state = None;
 2061        self.select_larger_syntax_node_stack.clear();
 2062        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2063        self.snippet_stack
 2064            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2065        self.take_rename(false, cx);
 2066
 2067        let new_cursor_position = self.selections.newest_anchor().head();
 2068
 2069        self.push_to_nav_history(
 2070            *old_cursor_position,
 2071            Some(new_cursor_position.to_point(buffer)),
 2072            cx,
 2073        );
 2074
 2075        if local {
 2076            let new_cursor_position = self.selections.newest_anchor().head();
 2077            let mut context_menu = self.context_menu.write();
 2078            let completion_menu = match context_menu.as_ref() {
 2079                Some(ContextMenu::Completions(menu)) => Some(menu),
 2080
 2081                _ => {
 2082                    *context_menu = None;
 2083                    None
 2084                }
 2085            };
 2086
 2087            if let Some(completion_menu) = completion_menu {
 2088                let cursor_position = new_cursor_position.to_offset(buffer);
 2089                let (word_range, kind) = buffer.surrounding_word(completion_menu.initial_position);
 2090                if kind == Some(CharKind::Word)
 2091                    && word_range.to_inclusive().contains(&cursor_position)
 2092                {
 2093                    let mut completion_menu = completion_menu.clone();
 2094                    drop(context_menu);
 2095
 2096                    let query = Self::completion_query(buffer, cursor_position);
 2097                    cx.spawn(move |this, mut cx| async move {
 2098                        completion_menu
 2099                            .filter(query.as_deref(), cx.background_executor().clone())
 2100                            .await;
 2101
 2102                        this.update(&mut cx, |this, cx| {
 2103                            let mut context_menu = this.context_menu.write();
 2104                            let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
 2105                                return;
 2106                            };
 2107
 2108                            if menu.id > completion_menu.id {
 2109                                return;
 2110                            }
 2111
 2112                            *context_menu = Some(ContextMenu::Completions(completion_menu));
 2113                            drop(context_menu);
 2114                            cx.notify();
 2115                        })
 2116                    })
 2117                    .detach();
 2118
 2119                    self.show_completions(&ShowCompletions, cx);
 2120                } else {
 2121                    drop(context_menu);
 2122                    self.hide_context_menu(cx);
 2123                }
 2124            } else {
 2125                drop(context_menu);
 2126            }
 2127
 2128            hide_hover(self, cx);
 2129
 2130            if old_cursor_position.to_display_point(&display_map).row()
 2131                != new_cursor_position.to_display_point(&display_map).row()
 2132            {
 2133                self.available_code_actions.take();
 2134            }
 2135            self.refresh_code_actions(cx);
 2136            self.refresh_document_highlights(cx);
 2137            refresh_matching_bracket_highlights(self, cx);
 2138            self.discard_inline_completion(cx);
 2139            if self.git_blame_inline_enabled {
 2140                self.start_inline_blame_timer(cx);
 2141            }
 2142        }
 2143
 2144        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2145        cx.emit(EditorEvent::SelectionsChanged { local });
 2146
 2147        if self.selections.disjoint_anchors().len() == 1 {
 2148            cx.emit(SearchEvent::ActiveMatchChanged)
 2149        }
 2150
 2151        cx.notify();
 2152    }
 2153
 2154    pub fn change_selections<R>(
 2155        &mut self,
 2156        autoscroll: Option<Autoscroll>,
 2157        cx: &mut ViewContext<Self>,
 2158        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2159    ) -> R {
 2160        let old_cursor_position = self.selections.newest_anchor().head();
 2161        self.push_to_selection_history();
 2162
 2163        let (changed, result) = self.selections.change_with(cx, change);
 2164
 2165        if changed {
 2166            if let Some(autoscroll) = autoscroll {
 2167                self.request_autoscroll(autoscroll, cx);
 2168            }
 2169            self.selections_did_change(true, &old_cursor_position, cx);
 2170        }
 2171
 2172        result
 2173    }
 2174
 2175    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2176    where
 2177        I: IntoIterator<Item = (Range<S>, T)>,
 2178        S: ToOffset,
 2179        T: Into<Arc<str>>,
 2180    {
 2181        if self.read_only(cx) {
 2182            return;
 2183        }
 2184
 2185        self.buffer
 2186            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2187    }
 2188
 2189    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2190    where
 2191        I: IntoIterator<Item = (Range<S>, T)>,
 2192        S: ToOffset,
 2193        T: Into<Arc<str>>,
 2194    {
 2195        if self.read_only(cx) {
 2196            return;
 2197        }
 2198
 2199        self.buffer.update(cx, |buffer, cx| {
 2200            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2201        });
 2202    }
 2203
 2204    pub fn edit_with_block_indent<I, S, T>(
 2205        &mut self,
 2206        edits: I,
 2207        original_indent_columns: Vec<u32>,
 2208        cx: &mut ViewContext<Self>,
 2209    ) where
 2210        I: IntoIterator<Item = (Range<S>, T)>,
 2211        S: ToOffset,
 2212        T: Into<Arc<str>>,
 2213    {
 2214        if self.read_only(cx) {
 2215            return;
 2216        }
 2217
 2218        self.buffer.update(cx, |buffer, cx| {
 2219            buffer.edit(
 2220                edits,
 2221                Some(AutoindentMode::Block {
 2222                    original_indent_columns,
 2223                }),
 2224                cx,
 2225            )
 2226        });
 2227    }
 2228
 2229    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
 2230        self.hide_context_menu(cx);
 2231
 2232        match phase {
 2233            SelectPhase::Begin {
 2234                position,
 2235                add,
 2236                click_count,
 2237            } => self.begin_selection(position, add, click_count, cx),
 2238            SelectPhase::BeginColumnar {
 2239                position,
 2240                goal_column,
 2241            } => self.begin_columnar_selection(position, goal_column, cx),
 2242            SelectPhase::Extend {
 2243                position,
 2244                click_count,
 2245            } => self.extend_selection(position, click_count, cx),
 2246            SelectPhase::Update {
 2247                position,
 2248                goal_column,
 2249                scroll_delta,
 2250            } => self.update_selection(position, goal_column, scroll_delta, cx),
 2251            SelectPhase::End => self.end_selection(cx),
 2252        }
 2253    }
 2254
 2255    fn extend_selection(
 2256        &mut self,
 2257        position: DisplayPoint,
 2258        click_count: usize,
 2259        cx: &mut ViewContext<Self>,
 2260    ) {
 2261        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2262        let tail = self.selections.newest::<usize>(cx).tail();
 2263        self.begin_selection(position, false, click_count, cx);
 2264
 2265        let position = position.to_offset(&display_map, Bias::Left);
 2266        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2267
 2268        let mut pending_selection = self
 2269            .selections
 2270            .pending_anchor()
 2271            .expect("extend_selection not called with pending selection");
 2272        if position >= tail {
 2273            pending_selection.start = tail_anchor;
 2274        } else {
 2275            pending_selection.end = tail_anchor;
 2276            pending_selection.reversed = true;
 2277        }
 2278
 2279        let mut pending_mode = self.selections.pending_mode().unwrap();
 2280        match &mut pending_mode {
 2281            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2282            _ => {}
 2283        }
 2284
 2285        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 2286            s.set_pending(pending_selection, pending_mode)
 2287        });
 2288    }
 2289
 2290    fn begin_selection(
 2291        &mut self,
 2292        position: DisplayPoint,
 2293        add: bool,
 2294        click_count: usize,
 2295        cx: &mut ViewContext<Self>,
 2296    ) {
 2297        if !self.focus_handle.is_focused(cx) {
 2298            cx.focus(&self.focus_handle);
 2299        }
 2300
 2301        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2302        let buffer = &display_map.buffer_snapshot;
 2303        let newest_selection = self.selections.newest_anchor().clone();
 2304        let position = display_map.clip_point(position, Bias::Left);
 2305
 2306        let start;
 2307        let end;
 2308        let mode;
 2309        let auto_scroll;
 2310        match click_count {
 2311            1 => {
 2312                start = buffer.anchor_before(position.to_point(&display_map));
 2313                end = start;
 2314                mode = SelectMode::Character;
 2315                auto_scroll = true;
 2316            }
 2317            2 => {
 2318                let range = movement::surrounding_word(&display_map, position);
 2319                start = buffer.anchor_before(range.start.to_point(&display_map));
 2320                end = buffer.anchor_before(range.end.to_point(&display_map));
 2321                mode = SelectMode::Word(start..end);
 2322                auto_scroll = true;
 2323            }
 2324            3 => {
 2325                let position = display_map
 2326                    .clip_point(position, Bias::Left)
 2327                    .to_point(&display_map);
 2328                let line_start = display_map.prev_line_boundary(position).0;
 2329                let next_line_start = buffer.clip_point(
 2330                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2331                    Bias::Left,
 2332                );
 2333                start = buffer.anchor_before(line_start);
 2334                end = buffer.anchor_before(next_line_start);
 2335                mode = SelectMode::Line(start..end);
 2336                auto_scroll = true;
 2337            }
 2338            _ => {
 2339                start = buffer.anchor_before(0);
 2340                end = buffer.anchor_before(buffer.len());
 2341                mode = SelectMode::All;
 2342                auto_scroll = false;
 2343            }
 2344        }
 2345
 2346        self.change_selections(auto_scroll.then(|| Autoscroll::newest()), cx, |s| {
 2347            if !add {
 2348                s.clear_disjoint();
 2349            } else if click_count > 1 {
 2350                s.delete(newest_selection.id)
 2351            }
 2352
 2353            s.set_pending_anchor_range(start..end, mode);
 2354        });
 2355    }
 2356
 2357    fn begin_columnar_selection(
 2358        &mut self,
 2359        position: DisplayPoint,
 2360        goal_column: u32,
 2361        cx: &mut ViewContext<Self>,
 2362    ) {
 2363        if !self.focus_handle.is_focused(cx) {
 2364            cx.focus(&self.focus_handle);
 2365        }
 2366
 2367        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2368        let tail = self.selections.newest::<Point>(cx).tail();
 2369        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2370
 2371        self.select_columns(
 2372            tail.to_display_point(&display_map),
 2373            position,
 2374            goal_column,
 2375            &display_map,
 2376            cx,
 2377        );
 2378    }
 2379
 2380    fn update_selection(
 2381        &mut self,
 2382        position: DisplayPoint,
 2383        goal_column: u32,
 2384        scroll_delta: gpui::Point<f32>,
 2385        cx: &mut ViewContext<Self>,
 2386    ) {
 2387        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2388
 2389        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2390            let tail = tail.to_display_point(&display_map);
 2391            self.select_columns(tail, position, goal_column, &display_map, cx);
 2392        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2393            let buffer = self.buffer.read(cx).snapshot(cx);
 2394            let head;
 2395            let tail;
 2396            let mode = self.selections.pending_mode().unwrap();
 2397            match &mode {
 2398                SelectMode::Character => {
 2399                    head = position.to_point(&display_map);
 2400                    tail = pending.tail().to_point(&buffer);
 2401                }
 2402                SelectMode::Word(original_range) => {
 2403                    let original_display_range = original_range.start.to_display_point(&display_map)
 2404                        ..original_range.end.to_display_point(&display_map);
 2405                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2406                        ..original_display_range.end.to_point(&display_map);
 2407                    if movement::is_inside_word(&display_map, position)
 2408                        || original_display_range.contains(&position)
 2409                    {
 2410                        let word_range = movement::surrounding_word(&display_map, position);
 2411                        if word_range.start < original_display_range.start {
 2412                            head = word_range.start.to_point(&display_map);
 2413                        } else {
 2414                            head = word_range.end.to_point(&display_map);
 2415                        }
 2416                    } else {
 2417                        head = position.to_point(&display_map);
 2418                    }
 2419
 2420                    if head <= original_buffer_range.start {
 2421                        tail = original_buffer_range.end;
 2422                    } else {
 2423                        tail = original_buffer_range.start;
 2424                    }
 2425                }
 2426                SelectMode::Line(original_range) => {
 2427                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2428
 2429                    let position = display_map
 2430                        .clip_point(position, Bias::Left)
 2431                        .to_point(&display_map);
 2432                    let line_start = display_map.prev_line_boundary(position).0;
 2433                    let next_line_start = buffer.clip_point(
 2434                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2435                        Bias::Left,
 2436                    );
 2437
 2438                    if line_start < original_range.start {
 2439                        head = line_start
 2440                    } else {
 2441                        head = next_line_start
 2442                    }
 2443
 2444                    if head <= original_range.start {
 2445                        tail = original_range.end;
 2446                    } else {
 2447                        tail = original_range.start;
 2448                    }
 2449                }
 2450                SelectMode::All => {
 2451                    return;
 2452                }
 2453            };
 2454
 2455            if head < tail {
 2456                pending.start = buffer.anchor_before(head);
 2457                pending.end = buffer.anchor_before(tail);
 2458                pending.reversed = true;
 2459            } else {
 2460                pending.start = buffer.anchor_before(tail);
 2461                pending.end = buffer.anchor_before(head);
 2462                pending.reversed = false;
 2463            }
 2464
 2465            self.change_selections(None, cx, |s| {
 2466                s.set_pending(pending, mode);
 2467            });
 2468        } else {
 2469            log::error!("update_selection dispatched with no pending selection");
 2470            return;
 2471        }
 2472
 2473        self.apply_scroll_delta(scroll_delta, cx);
 2474        cx.notify();
 2475    }
 2476
 2477    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 2478        self.columnar_selection_tail.take();
 2479        if self.selections.pending_anchor().is_some() {
 2480            let selections = self.selections.all::<usize>(cx);
 2481            self.change_selections(None, cx, |s| {
 2482                s.select(selections);
 2483                s.clear_pending();
 2484            });
 2485        }
 2486    }
 2487
 2488    fn select_columns(
 2489        &mut self,
 2490        tail: DisplayPoint,
 2491        head: DisplayPoint,
 2492        goal_column: u32,
 2493        display_map: &DisplaySnapshot,
 2494        cx: &mut ViewContext<Self>,
 2495    ) {
 2496        let start_row = cmp::min(tail.row(), head.row());
 2497        let end_row = cmp::max(tail.row(), head.row());
 2498        let start_column = cmp::min(tail.column(), goal_column);
 2499        let end_column = cmp::max(tail.column(), goal_column);
 2500        let reversed = start_column < tail.column();
 2501
 2502        let selection_ranges = (start_row.0..=end_row.0)
 2503            .map(DisplayRow)
 2504            .filter_map(|row| {
 2505                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2506                    let start = display_map
 2507                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2508                        .to_point(display_map);
 2509                    let end = display_map
 2510                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2511                        .to_point(display_map);
 2512                    if reversed {
 2513                        Some(end..start)
 2514                    } else {
 2515                        Some(start..end)
 2516                    }
 2517                } else {
 2518                    None
 2519                }
 2520            })
 2521            .collect::<Vec<_>>();
 2522
 2523        self.change_selections(None, cx, |s| {
 2524            s.select_ranges(selection_ranges);
 2525        });
 2526        cx.notify();
 2527    }
 2528
 2529    pub fn has_pending_nonempty_selection(&self) -> bool {
 2530        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2531            Some(Selection { start, end, .. }) => start != end,
 2532            None => false,
 2533        };
 2534        pending_nonempty_selection || self.columnar_selection_tail.is_some()
 2535    }
 2536
 2537    pub fn has_pending_selection(&self) -> bool {
 2538        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2539    }
 2540
 2541    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 2542        self.clear_expanded_diff_hunks(cx);
 2543        if self.dismiss_menus_and_popups(cx) {
 2544            return;
 2545        }
 2546
 2547        if self.mode == EditorMode::Full {
 2548            if self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel()) {
 2549                return;
 2550            }
 2551        }
 2552
 2553        cx.propagate();
 2554    }
 2555
 2556    pub fn dismiss_menus_and_popups(&mut self, cx: &mut ViewContext<Self>) -> bool {
 2557        if self.take_rename(false, cx).is_some() {
 2558            return true;
 2559        }
 2560
 2561        if hide_hover(self, cx) {
 2562            return true;
 2563        }
 2564
 2565        if self.hide_context_menu(cx).is_some() {
 2566            return true;
 2567        }
 2568
 2569        if self.discard_inline_completion(cx) {
 2570            return true;
 2571        }
 2572
 2573        if self.snippet_stack.pop().is_some() {
 2574            return true;
 2575        }
 2576
 2577        if self.mode == EditorMode::Full {
 2578            if self.active_diagnostics.is_some() {
 2579                self.dismiss_diagnostics(cx);
 2580                return true;
 2581            }
 2582        }
 2583
 2584        false
 2585    }
 2586
 2587    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 2588        let text: Arc<str> = text.into();
 2589
 2590        if self.read_only(cx) {
 2591            return;
 2592        }
 2593
 2594        let selections = self.selections.all_adjusted(cx);
 2595        let mut brace_inserted = false;
 2596        let mut edits = Vec::new();
 2597        let mut new_selections = Vec::with_capacity(selections.len());
 2598        let mut new_autoclose_regions = Vec::new();
 2599        let snapshot = self.buffer.read(cx).read(cx);
 2600
 2601        for (selection, autoclose_region) in
 2602            self.selections_with_autoclose_regions(selections, &snapshot)
 2603        {
 2604            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2605                // Determine if the inserted text matches the opening or closing
 2606                // bracket of any of this language's bracket pairs.
 2607                let mut bracket_pair = None;
 2608                let mut is_bracket_pair_start = false;
 2609                let mut is_bracket_pair_end = false;
 2610                if !text.is_empty() {
 2611                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2612                    //  and they are removing the character that triggered IME popup.
 2613                    for (pair, enabled) in scope.brackets() {
 2614                        if !pair.close {
 2615                            continue;
 2616                        }
 2617
 2618                        if enabled && pair.start.ends_with(text.as_ref()) {
 2619                            bracket_pair = Some(pair.clone());
 2620                            is_bracket_pair_start = true;
 2621                            break;
 2622                        }
 2623                        if pair.end.as_str() == text.as_ref() {
 2624                            bracket_pair = Some(pair.clone());
 2625                            is_bracket_pair_end = true;
 2626                            break;
 2627                        }
 2628                    }
 2629                }
 2630
 2631                if let Some(bracket_pair) = bracket_pair {
 2632                    if selection.is_empty() {
 2633                        if is_bracket_pair_start {
 2634                            let prefix_len = bracket_pair.start.len() - text.len();
 2635
 2636                            // If the inserted text is a suffix of an opening bracket and the
 2637                            // selection is preceded by the rest of the opening bracket, then
 2638                            // insert the closing bracket.
 2639                            let following_text_allows_autoclose = snapshot
 2640                                .chars_at(selection.start)
 2641                                .next()
 2642                                .map_or(true, |c| scope.should_autoclose_before(c));
 2643                            let preceding_text_matches_prefix = prefix_len == 0
 2644                                || (selection.start.column >= (prefix_len as u32)
 2645                                    && snapshot.contains_str_at(
 2646                                        Point::new(
 2647                                            selection.start.row,
 2648                                            selection.start.column - (prefix_len as u32),
 2649                                        ),
 2650                                        &bracket_pair.start[..prefix_len],
 2651                                    ));
 2652                            let autoclose = self.use_autoclose
 2653                                && snapshot.settings_at(selection.start, cx).use_autoclose;
 2654                            if autoclose
 2655                                && following_text_allows_autoclose
 2656                                && preceding_text_matches_prefix
 2657                            {
 2658                                let anchor = snapshot.anchor_before(selection.end);
 2659                                new_selections.push((selection.map(|_| anchor), text.len()));
 2660                                new_autoclose_regions.push((
 2661                                    anchor,
 2662                                    text.len(),
 2663                                    selection.id,
 2664                                    bracket_pair.clone(),
 2665                                ));
 2666                                edits.push((
 2667                                    selection.range(),
 2668                                    format!("{}{}", text, bracket_pair.end).into(),
 2669                                ));
 2670                                brace_inserted = true;
 2671                                continue;
 2672                            }
 2673                        }
 2674
 2675                        if let Some(region) = autoclose_region {
 2676                            // If the selection is followed by an auto-inserted closing bracket,
 2677                            // then don't insert that closing bracket again; just move the selection
 2678                            // past the closing bracket.
 2679                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2680                                && text.as_ref() == region.pair.end.as_str();
 2681                            if should_skip {
 2682                                let anchor = snapshot.anchor_after(selection.end);
 2683                                new_selections
 2684                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2685                                continue;
 2686                            }
 2687                        }
 2688
 2689                        let always_treat_brackets_as_autoclosed = snapshot
 2690                            .settings_at(selection.start, cx)
 2691                            .always_treat_brackets_as_autoclosed;
 2692                        if always_treat_brackets_as_autoclosed
 2693                            && is_bracket_pair_end
 2694                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2695                        {
 2696                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2697                            // and the inserted text is a closing bracket and the selection is followed
 2698                            // by the closing bracket then move the selection past the closing bracket.
 2699                            let anchor = snapshot.anchor_after(selection.end);
 2700                            new_selections.push((selection.map(|_| anchor), text.len()));
 2701                            continue;
 2702                        }
 2703                    }
 2704                    // If an opening bracket is 1 character long and is typed while
 2705                    // text is selected, then surround that text with the bracket pair.
 2706                    else if is_bracket_pair_start && bracket_pair.start.chars().count() == 1 {
 2707                        edits.push((selection.start..selection.start, text.clone()));
 2708                        edits.push((
 2709                            selection.end..selection.end,
 2710                            bracket_pair.end.as_str().into(),
 2711                        ));
 2712                        brace_inserted = true;
 2713                        new_selections.push((
 2714                            Selection {
 2715                                id: selection.id,
 2716                                start: snapshot.anchor_after(selection.start),
 2717                                end: snapshot.anchor_before(selection.end),
 2718                                reversed: selection.reversed,
 2719                                goal: selection.goal,
 2720                            },
 2721                            0,
 2722                        ));
 2723                        continue;
 2724                    }
 2725                }
 2726            }
 2727
 2728            if self.auto_replace_emoji_shortcode
 2729                && selection.is_empty()
 2730                && text.as_ref().ends_with(':')
 2731            {
 2732                if let Some(possible_emoji_short_code) =
 2733                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 2734                {
 2735                    if !possible_emoji_short_code.is_empty() {
 2736                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 2737                            let emoji_shortcode_start = Point::new(
 2738                                selection.start.row,
 2739                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 2740                            );
 2741
 2742                            // Remove shortcode from buffer
 2743                            edits.push((
 2744                                emoji_shortcode_start..selection.start,
 2745                                "".to_string().into(),
 2746                            ));
 2747                            new_selections.push((
 2748                                Selection {
 2749                                    id: selection.id,
 2750                                    start: snapshot.anchor_after(emoji_shortcode_start),
 2751                                    end: snapshot.anchor_before(selection.start),
 2752                                    reversed: selection.reversed,
 2753                                    goal: selection.goal,
 2754                                },
 2755                                0,
 2756                            ));
 2757
 2758                            // Insert emoji
 2759                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 2760                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 2761                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 2762
 2763                            continue;
 2764                        }
 2765                    }
 2766                }
 2767            }
 2768
 2769            // If not handling any auto-close operation, then just replace the selected
 2770            // text with the given input and move the selection to the end of the
 2771            // newly inserted text.
 2772            let anchor = snapshot.anchor_after(selection.end);
 2773            new_selections.push((selection.map(|_| anchor), 0));
 2774            edits.push((selection.start..selection.end, text.clone()));
 2775        }
 2776
 2777        drop(snapshot);
 2778        self.transact(cx, |this, cx| {
 2779            this.buffer.update(cx, |buffer, cx| {
 2780                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 2781            });
 2782
 2783            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 2784            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 2785            let snapshot = this.buffer.read(cx).read(cx);
 2786            let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
 2787                .zip(new_selection_deltas)
 2788                .map(|(selection, delta)| Selection {
 2789                    id: selection.id,
 2790                    start: selection.start + delta,
 2791                    end: selection.end + delta,
 2792                    reversed: selection.reversed,
 2793                    goal: SelectionGoal::None,
 2794                })
 2795                .collect::<Vec<_>>();
 2796
 2797            let mut i = 0;
 2798            for (position, delta, selection_id, pair) in new_autoclose_regions {
 2799                let position = position.to_offset(&snapshot) + delta;
 2800                let start = snapshot.anchor_before(position);
 2801                let end = snapshot.anchor_after(position);
 2802                while let Some(existing_state) = this.autoclose_regions.get(i) {
 2803                    match existing_state.range.start.cmp(&start, &snapshot) {
 2804                        Ordering::Less => i += 1,
 2805                        Ordering::Greater => break,
 2806                        Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
 2807                            Ordering::Less => i += 1,
 2808                            Ordering::Equal => break,
 2809                            Ordering::Greater => break,
 2810                        },
 2811                    }
 2812                }
 2813                this.autoclose_regions.insert(
 2814                    i,
 2815                    AutocloseRegion {
 2816                        selection_id,
 2817                        range: start..end,
 2818                        pair,
 2819                    },
 2820                );
 2821            }
 2822
 2823            drop(snapshot);
 2824            let had_active_inline_completion = this.has_active_inline_completion(cx);
 2825            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 2826
 2827            if brace_inserted {
 2828                // If we inserted a brace while composing text (i.e. typing `"` on a
 2829                // Brazilian keyboard), exit the composing state because most likely
 2830                // the user wanted to surround the selection.
 2831                this.unmark_text(cx);
 2832            } else if EditorSettings::get_global(cx).use_on_type_format {
 2833                if let Some(on_type_format_task) =
 2834                    this.trigger_on_type_formatting(text.to_string(), cx)
 2835                {
 2836                    on_type_format_task.detach_and_log_err(cx);
 2837                }
 2838            }
 2839
 2840            let trigger_in_words = !had_active_inline_completion;
 2841            this.trigger_completion_on_input(&text, trigger_in_words, cx);
 2842            this.refresh_inline_completion(true, cx);
 2843        });
 2844    }
 2845
 2846    fn find_possible_emoji_shortcode_at_position(
 2847        snapshot: &MultiBufferSnapshot,
 2848        position: Point,
 2849    ) -> Option<String> {
 2850        let mut chars = Vec::new();
 2851        let mut found_colon = false;
 2852        for char in snapshot.reversed_chars_at(position).take(100) {
 2853            // Found a possible emoji shortcode in the middle of the buffer
 2854            if found_colon {
 2855                if char.is_whitespace() {
 2856                    chars.reverse();
 2857                    return Some(chars.iter().collect());
 2858                }
 2859                // If the previous character is not a whitespace, we are in the middle of a word
 2860                // and we only want to complete the shortcode if the word is made up of other emojis
 2861                let mut containing_word = String::new();
 2862                for ch in snapshot
 2863                    .reversed_chars_at(position)
 2864                    .skip(chars.len() + 1)
 2865                    .take(100)
 2866                {
 2867                    if ch.is_whitespace() {
 2868                        break;
 2869                    }
 2870                    containing_word.push(ch);
 2871                }
 2872                let containing_word = containing_word.chars().rev().collect::<String>();
 2873                if util::word_consists_of_emojis(containing_word.as_str()) {
 2874                    chars.reverse();
 2875                    return Some(chars.iter().collect());
 2876                }
 2877            }
 2878
 2879            if char.is_whitespace() || !char.is_ascii() {
 2880                return None;
 2881            }
 2882            if char == ':' {
 2883                found_colon = true;
 2884            } else {
 2885                chars.push(char);
 2886            }
 2887        }
 2888        // Found a possible emoji shortcode at the beginning of the buffer
 2889        chars.reverse();
 2890        Some(chars.iter().collect())
 2891    }
 2892
 2893    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 2894        self.transact(cx, |this, cx| {
 2895            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 2896                let selections = this.selections.all::<usize>(cx);
 2897                let multi_buffer = this.buffer.read(cx);
 2898                let buffer = multi_buffer.snapshot(cx);
 2899                selections
 2900                    .iter()
 2901                    .map(|selection| {
 2902                        let start_point = selection.start.to_point(&buffer);
 2903                        let mut indent =
 2904                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 2905                        indent.len = cmp::min(indent.len, start_point.column);
 2906                        let start = selection.start;
 2907                        let end = selection.end;
 2908                        let selection_is_empty = start == end;
 2909                        let language_scope = buffer.language_scope_at(start);
 2910                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 2911                            &language_scope
 2912                        {
 2913                            let leading_whitespace_len = buffer
 2914                                .reversed_chars_at(start)
 2915                                .take_while(|c| c.is_whitespace() && *c != '\n')
 2916                                .map(|c| c.len_utf8())
 2917                                .sum::<usize>();
 2918
 2919                            let trailing_whitespace_len = buffer
 2920                                .chars_at(end)
 2921                                .take_while(|c| c.is_whitespace() && *c != '\n')
 2922                                .map(|c| c.len_utf8())
 2923                                .sum::<usize>();
 2924
 2925                            let insert_extra_newline =
 2926                                language.brackets().any(|(pair, enabled)| {
 2927                                    let pair_start = pair.start.trim_end();
 2928                                    let pair_end = pair.end.trim_start();
 2929
 2930                                    enabled
 2931                                        && pair.newline
 2932                                        && buffer.contains_str_at(
 2933                                            end + trailing_whitespace_len,
 2934                                            pair_end,
 2935                                        )
 2936                                        && buffer.contains_str_at(
 2937                                            (start - leading_whitespace_len)
 2938                                                .saturating_sub(pair_start.len()),
 2939                                            pair_start,
 2940                                        )
 2941                                });
 2942
 2943                            // Comment extension on newline is allowed only for cursor selections
 2944                            let comment_delimiter = maybe!({
 2945                                if !selection_is_empty {
 2946                                    return None;
 2947                                }
 2948
 2949                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 2950                                    return None;
 2951                                }
 2952
 2953                                let delimiters = language.line_comment_prefixes();
 2954                                let max_len_of_delimiter =
 2955                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 2956                                let (snapshot, range) =
 2957                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 2958
 2959                                let mut index_of_first_non_whitespace = 0;
 2960                                let comment_candidate = snapshot
 2961                                    .chars_for_range(range)
 2962                                    .skip_while(|c| {
 2963                                        let should_skip = c.is_whitespace();
 2964                                        if should_skip {
 2965                                            index_of_first_non_whitespace += 1;
 2966                                        }
 2967                                        should_skip
 2968                                    })
 2969                                    .take(max_len_of_delimiter)
 2970                                    .collect::<String>();
 2971                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 2972                                    comment_candidate.starts_with(comment_prefix.as_ref())
 2973                                })?;
 2974                                let cursor_is_placed_after_comment_marker =
 2975                                    index_of_first_non_whitespace + comment_prefix.len()
 2976                                        <= start_point.column as usize;
 2977                                if cursor_is_placed_after_comment_marker {
 2978                                    Some(comment_prefix.clone())
 2979                                } else {
 2980                                    None
 2981                                }
 2982                            });
 2983                            (comment_delimiter, insert_extra_newline)
 2984                        } else {
 2985                            (None, false)
 2986                        };
 2987
 2988                        let capacity_for_delimiter = comment_delimiter
 2989                            .as_deref()
 2990                            .map(str::len)
 2991                            .unwrap_or_default();
 2992                        let mut new_text =
 2993                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 2994                        new_text.push_str("\n");
 2995                        new_text.extend(indent.chars());
 2996                        if let Some(delimiter) = &comment_delimiter {
 2997                            new_text.push_str(&delimiter);
 2998                        }
 2999                        if insert_extra_newline {
 3000                            new_text = new_text.repeat(2);
 3001                        }
 3002
 3003                        let anchor = buffer.anchor_after(end);
 3004                        let new_selection = selection.map(|_| anchor);
 3005                        (
 3006                            (start..end, new_text),
 3007                            (insert_extra_newline, new_selection),
 3008                        )
 3009                    })
 3010                    .unzip()
 3011            };
 3012
 3013            this.edit_with_autoindent(edits, cx);
 3014            let buffer = this.buffer.read(cx).snapshot(cx);
 3015            let new_selections = selection_fixup_info
 3016                .into_iter()
 3017                .map(|(extra_newline_inserted, new_selection)| {
 3018                    let mut cursor = new_selection.end.to_point(&buffer);
 3019                    if extra_newline_inserted {
 3020                        cursor.row -= 1;
 3021                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3022                    }
 3023                    new_selection.map(|_| cursor)
 3024                })
 3025                .collect();
 3026
 3027            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3028            this.refresh_inline_completion(true, cx);
 3029        });
 3030    }
 3031
 3032    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3033        let buffer = self.buffer.read(cx);
 3034        let snapshot = buffer.snapshot(cx);
 3035
 3036        let mut edits = Vec::new();
 3037        let mut rows = Vec::new();
 3038
 3039        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3040            let cursor = selection.head();
 3041            let row = cursor.row;
 3042
 3043            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3044
 3045            let newline = "\n".to_string();
 3046            edits.push((start_of_line..start_of_line, newline));
 3047
 3048            rows.push(row + rows_inserted as u32);
 3049        }
 3050
 3051        self.transact(cx, |editor, cx| {
 3052            editor.edit(edits, cx);
 3053
 3054            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3055                let mut index = 0;
 3056                s.move_cursors_with(|map, _, _| {
 3057                    let row = rows[index];
 3058                    index += 1;
 3059
 3060                    let point = Point::new(row, 0);
 3061                    let boundary = map.next_line_boundary(point).1;
 3062                    let clipped = map.clip_point(boundary, Bias::Left);
 3063
 3064                    (clipped, SelectionGoal::None)
 3065                });
 3066            });
 3067
 3068            let mut indent_edits = Vec::new();
 3069            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3070            for row in rows {
 3071                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3072                for (row, indent) in indents {
 3073                    if indent.len == 0 {
 3074                        continue;
 3075                    }
 3076
 3077                    let text = match indent.kind {
 3078                        IndentKind::Space => " ".repeat(indent.len as usize),
 3079                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3080                    };
 3081                    let point = Point::new(row.0, 0);
 3082                    indent_edits.push((point..point, text));
 3083                }
 3084            }
 3085            editor.edit(indent_edits, cx);
 3086        });
 3087    }
 3088
 3089    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3090        let buffer = self.buffer.read(cx);
 3091        let snapshot = buffer.snapshot(cx);
 3092
 3093        let mut edits = Vec::new();
 3094        let mut rows = Vec::new();
 3095        let mut rows_inserted = 0;
 3096
 3097        for selection in self.selections.all_adjusted(cx) {
 3098            let cursor = selection.head();
 3099            let row = cursor.row;
 3100
 3101            let point = Point::new(row + 1, 0);
 3102            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3103
 3104            let newline = "\n".to_string();
 3105            edits.push((start_of_line..start_of_line, newline));
 3106
 3107            rows_inserted += 1;
 3108            rows.push(row + rows_inserted);
 3109        }
 3110
 3111        self.transact(cx, |editor, cx| {
 3112            editor.edit(edits, cx);
 3113
 3114            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3115                let mut index = 0;
 3116                s.move_cursors_with(|map, _, _| {
 3117                    let row = rows[index];
 3118                    index += 1;
 3119
 3120                    let point = Point::new(row, 0);
 3121                    let boundary = map.next_line_boundary(point).1;
 3122                    let clipped = map.clip_point(boundary, Bias::Left);
 3123
 3124                    (clipped, SelectionGoal::None)
 3125                });
 3126            });
 3127
 3128            let mut indent_edits = Vec::new();
 3129            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3130            for row in rows {
 3131                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3132                for (row, indent) in indents {
 3133                    if indent.len == 0 {
 3134                        continue;
 3135                    }
 3136
 3137                    let text = match indent.kind {
 3138                        IndentKind::Space => " ".repeat(indent.len as usize),
 3139                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3140                    };
 3141                    let point = Point::new(row.0, 0);
 3142                    indent_edits.push((point..point, text));
 3143                }
 3144            }
 3145            editor.edit(indent_edits, cx);
 3146        });
 3147    }
 3148
 3149    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3150        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3151            original_indent_columns: Vec::new(),
 3152        });
 3153        self.insert_with_autoindent_mode(text, autoindent, cx);
 3154    }
 3155
 3156    fn insert_with_autoindent_mode(
 3157        &mut self,
 3158        text: &str,
 3159        autoindent_mode: Option<AutoindentMode>,
 3160        cx: &mut ViewContext<Self>,
 3161    ) {
 3162        if self.read_only(cx) {
 3163            return;
 3164        }
 3165
 3166        let text: Arc<str> = text.into();
 3167        self.transact(cx, |this, cx| {
 3168            let old_selections = this.selections.all_adjusted(cx);
 3169            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3170                let anchors = {
 3171                    let snapshot = buffer.read(cx);
 3172                    old_selections
 3173                        .iter()
 3174                        .map(|s| {
 3175                            let anchor = snapshot.anchor_after(s.head());
 3176                            s.map(|_| anchor)
 3177                        })
 3178                        .collect::<Vec<_>>()
 3179                };
 3180                buffer.edit(
 3181                    old_selections
 3182                        .iter()
 3183                        .map(|s| (s.start..s.end, text.clone())),
 3184                    autoindent_mode,
 3185                    cx,
 3186                );
 3187                anchors
 3188            });
 3189
 3190            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3191                s.select_anchors(selection_anchors);
 3192            })
 3193        });
 3194    }
 3195
 3196    fn trigger_completion_on_input(
 3197        &mut self,
 3198        text: &str,
 3199        trigger_in_words: bool,
 3200        cx: &mut ViewContext<Self>,
 3201    ) {
 3202        if !EditorSettings::get_global(cx).show_completions_on_input {
 3203            return;
 3204        }
 3205
 3206        let selection = self.selections.newest_anchor();
 3207        if self
 3208            .buffer
 3209            .read(cx)
 3210            .is_completion_trigger(selection.head(), text, trigger_in_words, cx)
 3211        {
 3212            self.show_completions(&ShowCompletions, cx);
 3213        } else {
 3214            self.hide_context_menu(cx);
 3215        }
 3216    }
 3217
 3218    /// If any empty selections is touching the start of its innermost containing autoclose
 3219    /// region, expand it to select the brackets.
 3220    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 3221        let selections = self.selections.all::<usize>(cx);
 3222        let buffer = self.buffer.read(cx).read(cx);
 3223        let new_selections = self
 3224            .selections_with_autoclose_regions(selections, &buffer)
 3225            .map(|(mut selection, region)| {
 3226                if !selection.is_empty() {
 3227                    return selection;
 3228                }
 3229
 3230                if let Some(region) = region {
 3231                    let mut range = region.range.to_offset(&buffer);
 3232                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3233                        range.start -= region.pair.start.len();
 3234                        if buffer.contains_str_at(range.start, &region.pair.start)
 3235                            && buffer.contains_str_at(range.end, &region.pair.end)
 3236                        {
 3237                            range.end += region.pair.end.len();
 3238                            selection.start = range.start;
 3239                            selection.end = range.end;
 3240
 3241                            return selection;
 3242                        }
 3243                    }
 3244                }
 3245
 3246                let always_treat_brackets_as_autoclosed = buffer
 3247                    .settings_at(selection.start, cx)
 3248                    .always_treat_brackets_as_autoclosed;
 3249
 3250                if !always_treat_brackets_as_autoclosed {
 3251                    return selection;
 3252                }
 3253
 3254                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3255                    for (pair, enabled) in scope.brackets() {
 3256                        if !enabled || !pair.close {
 3257                            continue;
 3258                        }
 3259
 3260                        if buffer.contains_str_at(selection.start, &pair.end) {
 3261                            let pair_start_len = pair.start.len();
 3262                            if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
 3263                            {
 3264                                selection.start -= pair_start_len;
 3265                                selection.end += pair.end.len();
 3266
 3267                                return selection;
 3268                            }
 3269                        }
 3270                    }
 3271                }
 3272
 3273                selection
 3274            })
 3275            .collect();
 3276
 3277        drop(buffer);
 3278        self.change_selections(None, cx, |selections| selections.select(new_selections));
 3279    }
 3280
 3281    /// Iterate the given selections, and for each one, find the smallest surrounding
 3282    /// autoclose region. This uses the ordering of the selections and the autoclose
 3283    /// regions to avoid repeated comparisons.
 3284    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3285        &'a self,
 3286        selections: impl IntoIterator<Item = Selection<D>>,
 3287        buffer: &'a MultiBufferSnapshot,
 3288    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3289        let mut i = 0;
 3290        let mut regions = self.autoclose_regions.as_slice();
 3291        selections.into_iter().map(move |selection| {
 3292            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3293
 3294            let mut enclosing = None;
 3295            while let Some(pair_state) = regions.get(i) {
 3296                if pair_state.range.end.to_offset(buffer) < range.start {
 3297                    regions = &regions[i + 1..];
 3298                    i = 0;
 3299                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3300                    break;
 3301                } else {
 3302                    if pair_state.selection_id == selection.id {
 3303                        enclosing = Some(pair_state);
 3304                    }
 3305                    i += 1;
 3306                }
 3307            }
 3308
 3309            (selection.clone(), enclosing)
 3310        })
 3311    }
 3312
 3313    /// Remove any autoclose regions that no longer contain their selection.
 3314    fn invalidate_autoclose_regions(
 3315        &mut self,
 3316        mut selections: &[Selection<Anchor>],
 3317        buffer: &MultiBufferSnapshot,
 3318    ) {
 3319        self.autoclose_regions.retain(|state| {
 3320            let mut i = 0;
 3321            while let Some(selection) = selections.get(i) {
 3322                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3323                    selections = &selections[1..];
 3324                    continue;
 3325                }
 3326                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3327                    break;
 3328                }
 3329                if selection.id == state.selection_id {
 3330                    return true;
 3331                } else {
 3332                    i += 1;
 3333                }
 3334            }
 3335            false
 3336        });
 3337    }
 3338
 3339    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3340        let offset = position.to_offset(buffer);
 3341        let (word_range, kind) = buffer.surrounding_word(offset);
 3342        if offset > word_range.start && kind == Some(CharKind::Word) {
 3343            Some(
 3344                buffer
 3345                    .text_for_range(word_range.start..offset)
 3346                    .collect::<String>(),
 3347            )
 3348        } else {
 3349            None
 3350        }
 3351    }
 3352
 3353    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 3354        self.refresh_inlay_hints(
 3355            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3356            cx,
 3357        );
 3358    }
 3359
 3360    pub fn inlay_hints_enabled(&self) -> bool {
 3361        self.inlay_hint_cache.enabled
 3362    }
 3363
 3364    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 3365        if self.project.is_none() || self.mode != EditorMode::Full {
 3366            return;
 3367        }
 3368
 3369        let reason_description = reason.description();
 3370        let ignore_debounce = matches!(
 3371            reason,
 3372            InlayHintRefreshReason::SettingsChange(_)
 3373                | InlayHintRefreshReason::Toggle(_)
 3374                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3375        );
 3376        let (invalidate_cache, required_languages) = match reason {
 3377            InlayHintRefreshReason::Toggle(enabled) => {
 3378                self.inlay_hint_cache.enabled = enabled;
 3379                if enabled {
 3380                    (InvalidationStrategy::RefreshRequested, None)
 3381                } else {
 3382                    self.inlay_hint_cache.clear();
 3383                    self.splice_inlays(
 3384                        self.visible_inlay_hints(cx)
 3385                            .iter()
 3386                            .map(|inlay| inlay.id)
 3387                            .collect(),
 3388                        Vec::new(),
 3389                        cx,
 3390                    );
 3391                    return;
 3392                }
 3393            }
 3394            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3395                match self.inlay_hint_cache.update_settings(
 3396                    &self.buffer,
 3397                    new_settings,
 3398                    self.visible_inlay_hints(cx),
 3399                    cx,
 3400                ) {
 3401                    ControlFlow::Break(Some(InlaySplice {
 3402                        to_remove,
 3403                        to_insert,
 3404                    })) => {
 3405                        self.splice_inlays(to_remove, to_insert, cx);
 3406                        return;
 3407                    }
 3408                    ControlFlow::Break(None) => return,
 3409                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3410                }
 3411            }
 3412            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3413                if let Some(InlaySplice {
 3414                    to_remove,
 3415                    to_insert,
 3416                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3417                {
 3418                    self.splice_inlays(to_remove, to_insert, cx);
 3419                }
 3420                return;
 3421            }
 3422            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3423            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3424                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3425            }
 3426            InlayHintRefreshReason::RefreshRequested => {
 3427                (InvalidationStrategy::RefreshRequested, None)
 3428            }
 3429        };
 3430
 3431        if let Some(InlaySplice {
 3432            to_remove,
 3433            to_insert,
 3434        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3435            reason_description,
 3436            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3437            invalidate_cache,
 3438            ignore_debounce,
 3439            cx,
 3440        ) {
 3441            self.splice_inlays(to_remove, to_insert, cx);
 3442        }
 3443    }
 3444
 3445    fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
 3446        self.display_map
 3447            .read(cx)
 3448            .current_inlays()
 3449            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3450            .cloned()
 3451            .collect()
 3452    }
 3453
 3454    pub fn excerpts_for_inlay_hints_query(
 3455        &self,
 3456        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3457        cx: &mut ViewContext<Editor>,
 3458    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 3459        let Some(project) = self.project.as_ref() else {
 3460            return HashMap::default();
 3461        };
 3462        let project = project.read(cx);
 3463        let multi_buffer = self.buffer().read(cx);
 3464        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3465        let multi_buffer_visible_start = self
 3466            .scroll_manager
 3467            .anchor()
 3468            .anchor
 3469            .to_point(&multi_buffer_snapshot);
 3470        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3471            multi_buffer_visible_start
 3472                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3473            Bias::Left,
 3474        );
 3475        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3476        multi_buffer
 3477            .range_to_buffer_ranges(multi_buffer_visible_range, cx)
 3478            .into_iter()
 3479            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3480            .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
 3481                let buffer = buffer_handle.read(cx);
 3482                let buffer_file = project::File::from_dyn(buffer.file())?;
 3483                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3484                let worktree_entry = buffer_worktree
 3485                    .read(cx)
 3486                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3487                if worktree_entry.is_ignored {
 3488                    return None;
 3489                }
 3490
 3491                let language = buffer.language()?;
 3492                if let Some(restrict_to_languages) = restrict_to_languages {
 3493                    if !restrict_to_languages.contains(language) {
 3494                        return None;
 3495                    }
 3496                }
 3497                Some((
 3498                    excerpt_id,
 3499                    (
 3500                        buffer_handle,
 3501                        buffer.version().clone(),
 3502                        excerpt_visible_range,
 3503                    ),
 3504                ))
 3505            })
 3506            .collect()
 3507    }
 3508
 3509    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 3510        TextLayoutDetails {
 3511            text_system: cx.text_system().clone(),
 3512            editor_style: self.style.clone().unwrap(),
 3513            rem_size: cx.rem_size(),
 3514            scroll_anchor: self.scroll_manager.anchor(),
 3515            visible_rows: self.visible_line_count(),
 3516            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3517        }
 3518    }
 3519
 3520    fn splice_inlays(
 3521        &self,
 3522        to_remove: Vec<InlayId>,
 3523        to_insert: Vec<Inlay>,
 3524        cx: &mut ViewContext<Self>,
 3525    ) {
 3526        self.display_map.update(cx, |display_map, cx| {
 3527            display_map.splice_inlays(to_remove, to_insert, cx);
 3528        });
 3529        cx.notify();
 3530    }
 3531
 3532    fn trigger_on_type_formatting(
 3533        &self,
 3534        input: String,
 3535        cx: &mut ViewContext<Self>,
 3536    ) -> Option<Task<Result<()>>> {
 3537        if input.len() != 1 {
 3538            return None;
 3539        }
 3540
 3541        let project = self.project.as_ref()?;
 3542        let position = self.selections.newest_anchor().head();
 3543        let (buffer, buffer_position) = self
 3544            .buffer
 3545            .read(cx)
 3546            .text_anchor_for_position(position, cx)?;
 3547
 3548        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3549        // hence we do LSP request & edit on host side only — add formats to host's history.
 3550        let push_to_lsp_host_history = true;
 3551        // If this is not the host, append its history with new edits.
 3552        let push_to_client_history = project.read(cx).is_remote();
 3553
 3554        let on_type_formatting = project.update(cx, |project, cx| {
 3555            project.on_type_format(
 3556                buffer.clone(),
 3557                buffer_position,
 3558                input,
 3559                push_to_lsp_host_history,
 3560                cx,
 3561            )
 3562        });
 3563        Some(cx.spawn(|editor, mut cx| async move {
 3564            if let Some(transaction) = on_type_formatting.await? {
 3565                if push_to_client_history {
 3566                    buffer
 3567                        .update(&mut cx, |buffer, _| {
 3568                            buffer.push_transaction(transaction, Instant::now());
 3569                        })
 3570                        .ok();
 3571                }
 3572                editor.update(&mut cx, |editor, cx| {
 3573                    editor.refresh_document_highlights(cx);
 3574                })?;
 3575            }
 3576            Ok(())
 3577        }))
 3578    }
 3579
 3580    fn show_completions(&mut self, _: &ShowCompletions, cx: &mut ViewContext<Self>) {
 3581        if self.pending_rename.is_some() {
 3582            return;
 3583        }
 3584
 3585        let Some(provider) = self.completion_provider.as_ref() else {
 3586            return;
 3587        };
 3588
 3589        let position = self.selections.newest_anchor().head();
 3590        let (buffer, buffer_position) =
 3591            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3592                output
 3593            } else {
 3594                return;
 3595            };
 3596
 3597        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 3598        let completions = provider.completions(&buffer, buffer_position, cx);
 3599
 3600        let id = post_inc(&mut self.next_completion_id);
 3601        let task = cx.spawn(|this, mut cx| {
 3602            async move {
 3603                let completions = completions.await.log_err();
 3604                let menu = if let Some(completions) = completions {
 3605                    let mut menu = CompletionsMenu {
 3606                        id,
 3607                        initial_position: position,
 3608                        match_candidates: completions
 3609                            .iter()
 3610                            .enumerate()
 3611                            .map(|(id, completion)| {
 3612                                StringMatchCandidate::new(
 3613                                    id,
 3614                                    completion.label.text[completion.label.filter_range.clone()]
 3615                                        .into(),
 3616                                )
 3617                            })
 3618                            .collect(),
 3619                        buffer: buffer.clone(),
 3620                        completions: Arc::new(RwLock::new(completions.into())),
 3621                        matches: Vec::new().into(),
 3622                        selected_item: 0,
 3623                        scroll_handle: UniformListScrollHandle::new(),
 3624                        selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
 3625                            DebouncedDelay::new(),
 3626                        )),
 3627                    };
 3628                    menu.filter(query.as_deref(), cx.background_executor().clone())
 3629                        .await;
 3630
 3631                    if menu.matches.is_empty() {
 3632                        None
 3633                    } else {
 3634                        this.update(&mut cx, |editor, cx| {
 3635                            let completions = menu.completions.clone();
 3636                            let matches = menu.matches.clone();
 3637
 3638                            let delay_ms = EditorSettings::get_global(cx)
 3639                                .completion_documentation_secondary_query_debounce;
 3640                            let delay = Duration::from_millis(delay_ms);
 3641
 3642                            editor
 3643                                .completion_documentation_pre_resolve_debounce
 3644                                .fire_new(delay, cx, |editor, cx| {
 3645                                    CompletionsMenu::pre_resolve_completion_documentation(
 3646                                        buffer,
 3647                                        completions,
 3648                                        matches,
 3649                                        editor,
 3650                                        cx,
 3651                                    )
 3652                                });
 3653                        })
 3654                        .ok();
 3655                        Some(menu)
 3656                    }
 3657                } else {
 3658                    None
 3659                };
 3660
 3661                this.update(&mut cx, |this, cx| {
 3662                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 3663
 3664                    let mut context_menu = this.context_menu.write();
 3665                    match context_menu.as_ref() {
 3666                        None => {}
 3667
 3668                        Some(ContextMenu::Completions(prev_menu)) => {
 3669                            if prev_menu.id > id {
 3670                                return;
 3671                            }
 3672                        }
 3673
 3674                        _ => return,
 3675                    }
 3676
 3677                    if this.focus_handle.is_focused(cx) && menu.is_some() {
 3678                        let menu = menu.unwrap();
 3679                        *context_menu = Some(ContextMenu::Completions(menu));
 3680                        drop(context_menu);
 3681                        this.discard_inline_completion(cx);
 3682                        cx.notify();
 3683                    } else if this.completion_tasks.len() <= 1 {
 3684                        // If there are no more completion tasks and the last menu was
 3685                        // empty, we should hide it. If it was already hidden, we should
 3686                        // also show the copilot completion when available.
 3687                        drop(context_menu);
 3688                        if this.hide_context_menu(cx).is_none() {
 3689                            this.update_visible_inline_completion(cx);
 3690                        }
 3691                    }
 3692                })?;
 3693
 3694                Ok::<_, anyhow::Error>(())
 3695            }
 3696            .log_err()
 3697        });
 3698
 3699        self.completion_tasks.push((id, task));
 3700    }
 3701
 3702    pub fn confirm_completion(
 3703        &mut self,
 3704        action: &ConfirmCompletion,
 3705        cx: &mut ViewContext<Self>,
 3706    ) -> Option<Task<Result<()>>> {
 3707        use language::ToOffset as _;
 3708
 3709        let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 3710            menu
 3711        } else {
 3712            return None;
 3713        };
 3714
 3715        let mat = completions_menu
 3716            .matches
 3717            .get(action.item_ix.unwrap_or(completions_menu.selected_item))?;
 3718        let buffer_handle = completions_menu.buffer;
 3719        let completions = completions_menu.completions.read();
 3720        let completion = completions.get(mat.candidate_id)?;
 3721        cx.stop_propagation();
 3722
 3723        let snippet;
 3724        let text;
 3725        if completion.is_snippet() {
 3726            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 3727            text = snippet.as_ref().unwrap().text.clone();
 3728        } else {
 3729            snippet = None;
 3730            text = completion.new_text.clone();
 3731        };
 3732        let selections = self.selections.all::<usize>(cx);
 3733        let buffer = buffer_handle.read(cx);
 3734        let old_range = completion.old_range.to_offset(buffer);
 3735        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 3736
 3737        let newest_selection = self.selections.newest_anchor();
 3738        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 3739            return None;
 3740        }
 3741
 3742        let lookbehind = newest_selection
 3743            .start
 3744            .text_anchor
 3745            .to_offset(buffer)
 3746            .saturating_sub(old_range.start);
 3747        let lookahead = old_range
 3748            .end
 3749            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 3750        let mut common_prefix_len = old_text
 3751            .bytes()
 3752            .zip(text.bytes())
 3753            .take_while(|(a, b)| a == b)
 3754            .count();
 3755
 3756        let snapshot = self.buffer.read(cx).snapshot(cx);
 3757        let mut range_to_replace: Option<Range<isize>> = None;
 3758        let mut ranges = Vec::new();
 3759        for selection in &selections {
 3760            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 3761                let start = selection.start.saturating_sub(lookbehind);
 3762                let end = selection.end + lookahead;
 3763                if selection.id == newest_selection.id {
 3764                    range_to_replace = Some(
 3765                        ((start + common_prefix_len) as isize - selection.start as isize)
 3766                            ..(end as isize - selection.start as isize),
 3767                    );
 3768                }
 3769                ranges.push(start + common_prefix_len..end);
 3770            } else {
 3771                common_prefix_len = 0;
 3772                ranges.clear();
 3773                ranges.extend(selections.iter().map(|s| {
 3774                    if s.id == newest_selection.id {
 3775                        range_to_replace = Some(
 3776                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 3777                                - selection.start as isize
 3778                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 3779                                    - selection.start as isize,
 3780                        );
 3781                        old_range.clone()
 3782                    } else {
 3783                        s.start..s.end
 3784                    }
 3785                }));
 3786                break;
 3787            }
 3788        }
 3789        let text = &text[common_prefix_len..];
 3790
 3791        cx.emit(EditorEvent::InputHandled {
 3792            utf16_range_to_replace: range_to_replace,
 3793            text: text.into(),
 3794        });
 3795
 3796        self.transact(cx, |this, cx| {
 3797            if let Some(mut snippet) = snippet {
 3798                snippet.text = text.to_string();
 3799                for tabstop in snippet.tabstops.iter_mut().flatten() {
 3800                    tabstop.start -= common_prefix_len as isize;
 3801                    tabstop.end -= common_prefix_len as isize;
 3802                }
 3803
 3804                this.insert_snippet(&ranges, snippet, cx).log_err();
 3805            } else {
 3806                this.buffer.update(cx, |buffer, cx| {
 3807                    buffer.edit(
 3808                        ranges.iter().map(|range| (range.clone(), text)),
 3809                        this.autoindent_mode.clone(),
 3810                        cx,
 3811                    );
 3812                });
 3813            }
 3814
 3815            this.refresh_inline_completion(true, cx);
 3816        });
 3817
 3818        let provider = self.completion_provider.as_ref()?;
 3819        let apply_edits = provider.apply_additional_edits_for_completion(
 3820            buffer_handle,
 3821            completion.clone(),
 3822            true,
 3823            cx,
 3824        );
 3825        Some(cx.foreground_executor().spawn(async move {
 3826            apply_edits.await?;
 3827            Ok(())
 3828        }))
 3829    }
 3830
 3831    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 3832        let mut context_menu = self.context_menu.write();
 3833        if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 3834            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 3835                // Toggle if we're selecting the same one
 3836                *context_menu = None;
 3837                cx.notify();
 3838                return;
 3839            } else {
 3840                // Otherwise, clear it and start a new one
 3841                *context_menu = None;
 3842                cx.notify();
 3843            }
 3844        }
 3845        drop(context_menu);
 3846        let snapshot = self.snapshot(cx);
 3847        let deployed_from_indicator = action.deployed_from_indicator;
 3848        let mut task = self.code_actions_task.take();
 3849        let action = action.clone();
 3850        cx.spawn(|this, mut cx| async move {
 3851            while let Some(prev_task) = task {
 3852                prev_task.await;
 3853                task = this.update(&mut cx, |this, _| this.code_actions_task.take())?;
 3854            }
 3855
 3856            let spawned_test_task = this.update(&mut cx, |this, cx| {
 3857                if this.focus_handle.is_focused(cx) {
 3858                    let multibuffer_point = action
 3859                        .deployed_from_indicator
 3860                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 3861                        .unwrap_or_else(|| this.selections.newest::<Point>(cx).head());
 3862                    let (buffer, buffer_row) = snapshot
 3863                        .buffer_snapshot
 3864                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 3865                        .and_then(|(buffer_snapshot, range)| {
 3866                            this.buffer
 3867                                .read(cx)
 3868                                .buffer(buffer_snapshot.remote_id())
 3869                                .map(|buffer| (buffer, range.start.row))
 3870                        })?;
 3871                    let (_, code_actions) = this
 3872                        .available_code_actions
 3873                        .clone()
 3874                        .and_then(|(location, code_actions)| {
 3875                            let snapshot = location.buffer.read(cx).snapshot();
 3876                            let point_range = location.range.to_point(&snapshot);
 3877                            let point_range = point_range.start.row..=point_range.end.row;
 3878                            if point_range.contains(&buffer_row) {
 3879                                Some((location, code_actions))
 3880                            } else {
 3881                                None
 3882                            }
 3883                        })
 3884                        .unzip();
 3885                    let buffer_id = buffer.read(cx).remote_id();
 3886                    let tasks = this
 3887                        .tasks
 3888                        .get(&(buffer_id, buffer_row))
 3889                        .map(|t| Arc::new(t.to_owned()));
 3890                    if tasks.is_none() && code_actions.is_none() {
 3891                        return None;
 3892                    }
 3893
 3894                    this.completion_tasks.clear();
 3895                    this.discard_inline_completion(cx);
 3896                    let task_context = tasks.as_ref().zip(this.workspace.clone()).and_then(
 3897                        |(tasks, (workspace, _))| {
 3898                            let position = Point::new(buffer_row, tasks.1.column);
 3899                            let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 3900                            let location = Location {
 3901                                buffer: buffer.clone(),
 3902                                range: range_start..range_start,
 3903                            };
 3904                            workspace
 3905                                .update(cx, |workspace, cx| {
 3906                                    tasks::task_context_for_location(workspace, location, cx)
 3907                                })
 3908                                .ok()
 3909                                .flatten()
 3910                        },
 3911                    );
 3912                    let tasks = tasks.zip(task_context).map(|(tasks, mut task_context)| {
 3913                        // Fill in the environmental variables from the tree-sitter captures
 3914                        let mut additional_task_variables = TaskVariables::default();
 3915                        for (capture_name, value) in tasks.1.extra_variables.clone() {
 3916                            additional_task_variables.insert(
 3917                                task::VariableName::Custom(capture_name.into()),
 3918                                value.clone(),
 3919                            );
 3920                        }
 3921                        task_context
 3922                            .task_variables
 3923                            .extend(additional_task_variables);
 3924
 3925                        Arc::new(ResolvedTasks {
 3926                            templates: tasks
 3927                                .1
 3928                                .templates
 3929                                .iter()
 3930                                .filter_map(|(kind, template)| {
 3931                                    template
 3932                                        .resolve_task(&kind.to_id_base(), &task_context)
 3933                                        .map(|task| (kind.clone(), task))
 3934                                })
 3935                                .collect(),
 3936                            position: snapshot
 3937                                .buffer_snapshot
 3938                                .anchor_before(Point::new(multibuffer_point.row, tasks.1.column)),
 3939                        })
 3940                    });
 3941                    let spawn_straight_away = tasks
 3942                        .as_ref()
 3943                        .map_or(false, |tasks| tasks.templates.len() == 1)
 3944                        && code_actions
 3945                            .as_ref()
 3946                            .map_or(true, |actions| actions.is_empty());
 3947                    *this.context_menu.write() = Some(ContextMenu::CodeActions(CodeActionsMenu {
 3948                        buffer,
 3949                        actions: CodeActionContents {
 3950                            tasks,
 3951                            actions: code_actions,
 3952                        },
 3953                        selected_item: Default::default(),
 3954                        scroll_handle: UniformListScrollHandle::default(),
 3955                        deployed_from_indicator,
 3956                    }));
 3957                    if spawn_straight_away {
 3958                        if let Some(task) =
 3959                            this.confirm_code_action(&ConfirmCodeAction { item_ix: Some(0) }, cx)
 3960                        {
 3961                            cx.notify();
 3962                            return Some(task);
 3963                        }
 3964                    }
 3965                    cx.notify();
 3966                }
 3967                Some(Task::ready(Ok(())))
 3968            })?;
 3969            if let Some(task) = spawned_test_task {
 3970                task.await?;
 3971            }
 3972
 3973            Ok::<_, anyhow::Error>(())
 3974        })
 3975        .detach_and_log_err(cx);
 3976    }
 3977
 3978    pub fn confirm_code_action(
 3979        &mut self,
 3980        action: &ConfirmCodeAction,
 3981        cx: &mut ViewContext<Self>,
 3982    ) -> Option<Task<Result<()>>> {
 3983        let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 3984            menu
 3985        } else {
 3986            return None;
 3987        };
 3988        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 3989        let action = actions_menu.actions.get(action_ix)?;
 3990        let title = action.label();
 3991        let buffer = actions_menu.buffer;
 3992        let workspace = self.workspace()?;
 3993
 3994        match action {
 3995            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 3996                workspace.update(cx, |workspace, cx| {
 3997                    workspace::tasks::schedule_resolved_task(
 3998                        workspace,
 3999                        task_source_kind,
 4000                        resolved_task,
 4001                        false,
 4002                        cx,
 4003                    );
 4004
 4005                    Some(Task::ready(Ok(())))
 4006                })
 4007            }
 4008            CodeActionsItem::CodeAction(action) => {
 4009                let apply_code_actions = workspace
 4010                    .read(cx)
 4011                    .project()
 4012                    .clone()
 4013                    .update(cx, |project, cx| {
 4014                        project.apply_code_action(buffer, action, true, cx)
 4015                    });
 4016                let workspace = workspace.downgrade();
 4017                Some(cx.spawn(|editor, cx| async move {
 4018                    let project_transaction = apply_code_actions.await?;
 4019                    Self::open_project_transaction(
 4020                        &editor,
 4021                        workspace,
 4022                        project_transaction,
 4023                        title,
 4024                        cx,
 4025                    )
 4026                    .await
 4027                }))
 4028            }
 4029        }
 4030    }
 4031
 4032    async fn open_project_transaction(
 4033        this: &WeakView<Editor>,
 4034        workspace: WeakView<Workspace>,
 4035        transaction: ProjectTransaction,
 4036        title: String,
 4037        mut cx: AsyncWindowContext,
 4038    ) -> Result<()> {
 4039        let replica_id = this.update(&mut cx, |this, cx| this.replica_id(cx))?;
 4040
 4041        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4042        cx.update(|cx| {
 4043            entries.sort_unstable_by_key(|(buffer, _)| {
 4044                buffer.read(cx).file().map(|f| f.path().clone())
 4045            });
 4046        })?;
 4047
 4048        // If the project transaction's edits are all contained within this editor, then
 4049        // avoid opening a new editor to display them.
 4050
 4051        if let Some((buffer, transaction)) = entries.first() {
 4052            if entries.len() == 1 {
 4053                let excerpt = this.update(&mut cx, |editor, cx| {
 4054                    editor
 4055                        .buffer()
 4056                        .read(cx)
 4057                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4058                })?;
 4059                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4060                    if excerpted_buffer == *buffer {
 4061                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4062                            let excerpt_range = excerpt_range.to_offset(buffer);
 4063                            buffer
 4064                                .edited_ranges_for_transaction::<usize>(transaction)
 4065                                .all(|range| {
 4066                                    excerpt_range.start <= range.start
 4067                                        && excerpt_range.end >= range.end
 4068                                })
 4069                        })?;
 4070
 4071                        if all_edits_within_excerpt {
 4072                            return Ok(());
 4073                        }
 4074                    }
 4075                }
 4076            }
 4077        } else {
 4078            return Ok(());
 4079        }
 4080
 4081        let mut ranges_to_highlight = Vec::new();
 4082        let excerpt_buffer = cx.new_model(|cx| {
 4083            let mut multibuffer =
 4084                MultiBuffer::new(replica_id, Capability::ReadWrite).with_title(title);
 4085            for (buffer_handle, transaction) in &entries {
 4086                let buffer = buffer_handle.read(cx);
 4087                ranges_to_highlight.extend(
 4088                    multibuffer.push_excerpts_with_context_lines(
 4089                        buffer_handle.clone(),
 4090                        buffer
 4091                            .edited_ranges_for_transaction::<usize>(transaction)
 4092                            .collect(),
 4093                        DEFAULT_MULTIBUFFER_CONTEXT,
 4094                        cx,
 4095                    ),
 4096                );
 4097            }
 4098            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4099            multibuffer
 4100        })?;
 4101
 4102        workspace.update(&mut cx, |workspace, cx| {
 4103            let project = workspace.project().clone();
 4104            let editor =
 4105                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), cx));
 4106            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, cx);
 4107            editor.update(cx, |editor, cx| {
 4108                editor.highlight_background::<Self>(
 4109                    &ranges_to_highlight,
 4110                    |theme| theme.editor_highlighted_line_background,
 4111                    cx,
 4112                );
 4113            });
 4114        })?;
 4115
 4116        Ok(())
 4117    }
 4118
 4119    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4120        let project = self.project.clone()?;
 4121        let buffer = self.buffer.read(cx);
 4122        let newest_selection = self.selections.newest_anchor().clone();
 4123        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4124        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4125        if start_buffer != end_buffer {
 4126            return None;
 4127        }
 4128
 4129        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 4130            cx.background_executor()
 4131                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4132                .await;
 4133
 4134            let actions = if let Ok(code_actions) = project.update(&mut cx, |project, cx| {
 4135                project.code_actions(&start_buffer, start..end, cx)
 4136            }) {
 4137                code_actions.await
 4138            } else {
 4139                Vec::new()
 4140            };
 4141
 4142            this.update(&mut cx, |this, cx| {
 4143                this.available_code_actions = if actions.is_empty() {
 4144                    None
 4145                } else {
 4146                    Some((
 4147                        Location {
 4148                            buffer: start_buffer,
 4149                            range: start..end,
 4150                        },
 4151                        actions.into(),
 4152                    ))
 4153                };
 4154                cx.notify();
 4155            })
 4156            .log_err();
 4157        }));
 4158        None
 4159    }
 4160
 4161    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 4162        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4163            self.show_git_blame_inline = false;
 4164
 4165            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 4166                cx.background_executor().timer(delay).await;
 4167
 4168                this.update(&mut cx, |this, cx| {
 4169                    this.show_git_blame_inline = true;
 4170                    cx.notify();
 4171                })
 4172                .log_err();
 4173            }));
 4174        }
 4175    }
 4176
 4177    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4178        if self.pending_rename.is_some() {
 4179            return None;
 4180        }
 4181
 4182        let project = self.project.clone()?;
 4183        let buffer = self.buffer.read(cx);
 4184        let newest_selection = self.selections.newest_anchor().clone();
 4185        let cursor_position = newest_selection.head();
 4186        let (cursor_buffer, cursor_buffer_position) =
 4187            buffer.text_anchor_for_position(cursor_position, cx)?;
 4188        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4189        if cursor_buffer != tail_buffer {
 4190            return None;
 4191        }
 4192
 4193        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4194            cx.background_executor()
 4195                .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
 4196                .await;
 4197
 4198            let highlights = if let Some(highlights) = project
 4199                .update(&mut cx, |project, cx| {
 4200                    project.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4201                })
 4202                .log_err()
 4203            {
 4204                highlights.await.log_err()
 4205            } else {
 4206                None
 4207            };
 4208
 4209            if let Some(highlights) = highlights {
 4210                this.update(&mut cx, |this, cx| {
 4211                    if this.pending_rename.is_some() {
 4212                        return;
 4213                    }
 4214
 4215                    let buffer_id = cursor_position.buffer_id;
 4216                    let buffer = this.buffer.read(cx);
 4217                    if !buffer
 4218                        .text_anchor_for_position(cursor_position, cx)
 4219                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4220                    {
 4221                        return;
 4222                    }
 4223
 4224                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4225                    let mut write_ranges = Vec::new();
 4226                    let mut read_ranges = Vec::new();
 4227                    for highlight in highlights {
 4228                        for (excerpt_id, excerpt_range) in
 4229                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 4230                        {
 4231                            let start = highlight
 4232                                .range
 4233                                .start
 4234                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4235                            let end = highlight
 4236                                .range
 4237                                .end
 4238                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4239                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4240                                continue;
 4241                            }
 4242
 4243                            let range = Anchor {
 4244                                buffer_id,
 4245                                excerpt_id: excerpt_id,
 4246                                text_anchor: start,
 4247                            }..Anchor {
 4248                                buffer_id,
 4249                                excerpt_id,
 4250                                text_anchor: end,
 4251                            };
 4252                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4253                                write_ranges.push(range);
 4254                            } else {
 4255                                read_ranges.push(range);
 4256                            }
 4257                        }
 4258                    }
 4259
 4260                    this.highlight_background::<DocumentHighlightRead>(
 4261                        &read_ranges,
 4262                        |theme| theme.editor_document_highlight_read_background,
 4263                        cx,
 4264                    );
 4265                    this.highlight_background::<DocumentHighlightWrite>(
 4266                        &write_ranges,
 4267                        |theme| theme.editor_document_highlight_write_background,
 4268                        cx,
 4269                    );
 4270                    cx.notify();
 4271                })
 4272                .log_err();
 4273            }
 4274        }));
 4275        None
 4276    }
 4277
 4278    fn refresh_inline_completion(
 4279        &mut self,
 4280        debounce: bool,
 4281        cx: &mut ViewContext<Self>,
 4282    ) -> Option<()> {
 4283        let provider = self.inline_completion_provider()?;
 4284        let cursor = self.selections.newest_anchor().head();
 4285        let (buffer, cursor_buffer_position) =
 4286            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4287        if !self.show_inline_completions
 4288            || !provider.is_enabled(&buffer, cursor_buffer_position, cx)
 4289        {
 4290            self.discard_inline_completion(cx);
 4291            return None;
 4292        }
 4293
 4294        self.update_visible_inline_completion(cx);
 4295        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 4296        Some(())
 4297    }
 4298
 4299    fn cycle_inline_completion(
 4300        &mut self,
 4301        direction: Direction,
 4302        cx: &mut ViewContext<Self>,
 4303    ) -> Option<()> {
 4304        let provider = self.inline_completion_provider()?;
 4305        let cursor = self.selections.newest_anchor().head();
 4306        let (buffer, cursor_buffer_position) =
 4307            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4308        if !self.show_inline_completions
 4309            || !provider.is_enabled(&buffer, cursor_buffer_position, cx)
 4310        {
 4311            return None;
 4312        }
 4313
 4314        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4315        self.update_visible_inline_completion(cx);
 4316
 4317        Some(())
 4318    }
 4319
 4320    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 4321        if !self.has_active_inline_completion(cx) {
 4322            self.refresh_inline_completion(false, cx);
 4323            return;
 4324        }
 4325
 4326        self.update_visible_inline_completion(cx);
 4327    }
 4328
 4329    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 4330        self.show_cursor_names(cx);
 4331    }
 4332
 4333    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 4334        self.show_cursor_names = true;
 4335        cx.notify();
 4336        cx.spawn(|this, mut cx| async move {
 4337            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 4338            this.update(&mut cx, |this, cx| {
 4339                this.show_cursor_names = false;
 4340                cx.notify()
 4341            })
 4342            .ok()
 4343        })
 4344        .detach();
 4345    }
 4346
 4347    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 4348        if self.has_active_inline_completion(cx) {
 4349            self.cycle_inline_completion(Direction::Next, cx);
 4350        } else {
 4351            let is_copilot_disabled = self.refresh_inline_completion(false, cx).is_none();
 4352            if is_copilot_disabled {
 4353                cx.propagate();
 4354            }
 4355        }
 4356    }
 4357
 4358    pub fn previous_inline_completion(
 4359        &mut self,
 4360        _: &PreviousInlineCompletion,
 4361        cx: &mut ViewContext<Self>,
 4362    ) {
 4363        if self.has_active_inline_completion(cx) {
 4364            self.cycle_inline_completion(Direction::Prev, cx);
 4365        } else {
 4366            let is_copilot_disabled = self.refresh_inline_completion(false, cx).is_none();
 4367            if is_copilot_disabled {
 4368                cx.propagate();
 4369            }
 4370        }
 4371    }
 4372
 4373    fn accept_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> bool {
 4374        if let Some(completion) = self.take_active_inline_completion(cx) {
 4375            if let Some(provider) = self.inline_completion_provider() {
 4376                provider.accept(cx);
 4377            }
 4378
 4379            cx.emit(EditorEvent::InputHandled {
 4380                utf16_range_to_replace: None,
 4381                text: completion.text.to_string().into(),
 4382            });
 4383            self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
 4384            self.refresh_inline_completion(true, cx);
 4385            cx.notify();
 4386            true
 4387        } else {
 4388            false
 4389        }
 4390    }
 4391
 4392    pub fn accept_partial_inline_completion(
 4393        &mut self,
 4394        _: &AcceptPartialInlineCompletion,
 4395        cx: &mut ViewContext<Self>,
 4396    ) {
 4397        if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
 4398            if let Some(completion) = self.take_active_inline_completion(cx) {
 4399                let mut partial_completion = completion
 4400                    .text
 4401                    .chars()
 4402                    .by_ref()
 4403                    .take_while(|c| c.is_alphabetic())
 4404                    .collect::<String>();
 4405                if partial_completion.is_empty() {
 4406                    partial_completion = completion
 4407                        .text
 4408                        .chars()
 4409                        .by_ref()
 4410                        .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 4411                        .collect::<String>();
 4412                }
 4413
 4414                cx.emit(EditorEvent::InputHandled {
 4415                    utf16_range_to_replace: None,
 4416                    text: partial_completion.clone().into(),
 4417                });
 4418                self.insert_with_autoindent_mode(&partial_completion, None, cx);
 4419                self.refresh_inline_completion(true, cx);
 4420                cx.notify();
 4421            }
 4422        }
 4423    }
 4424
 4425    fn discard_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> bool {
 4426        if let Some(provider) = self.inline_completion_provider() {
 4427            provider.discard(cx);
 4428        }
 4429
 4430        self.take_active_inline_completion(cx).is_some()
 4431    }
 4432
 4433    pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
 4434        if let Some(completion) = self.active_inline_completion.as_ref() {
 4435            let buffer = self.buffer.read(cx).read(cx);
 4436            completion.position.is_valid(&buffer)
 4437        } else {
 4438            false
 4439        }
 4440    }
 4441
 4442    fn take_active_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<Inlay> {
 4443        let completion = self.active_inline_completion.take()?;
 4444        self.display_map.update(cx, |map, cx| {
 4445            map.splice_inlays(vec![completion.id], Default::default(), cx);
 4446        });
 4447        let buffer = self.buffer.read(cx).read(cx);
 4448
 4449        if completion.position.is_valid(&buffer) {
 4450            Some(completion)
 4451        } else {
 4452            None
 4453        }
 4454    }
 4455
 4456    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
 4457        let selection = self.selections.newest_anchor();
 4458        let cursor = selection.head();
 4459
 4460        if self.context_menu.read().is_none()
 4461            && self.completion_tasks.is_empty()
 4462            && selection.start == selection.end
 4463        {
 4464            if let Some(provider) = self.inline_completion_provider() {
 4465                if let Some((buffer, cursor_buffer_position)) =
 4466                    self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 4467                {
 4468                    if let Some(text) =
 4469                        provider.active_completion_text(&buffer, cursor_buffer_position, cx)
 4470                    {
 4471                        let text = Rope::from(text);
 4472                        let mut to_remove = Vec::new();
 4473                        if let Some(completion) = self.active_inline_completion.take() {
 4474                            to_remove.push(completion.id);
 4475                        }
 4476
 4477                        let completion_inlay =
 4478                            Inlay::suggestion(post_inc(&mut self.next_inlay_id), cursor, text);
 4479                        self.active_inline_completion = Some(completion_inlay.clone());
 4480                        self.display_map.update(cx, move |map, cx| {
 4481                            map.splice_inlays(to_remove, vec![completion_inlay], cx)
 4482                        });
 4483                        cx.notify();
 4484                        return;
 4485                    }
 4486                }
 4487            }
 4488        }
 4489
 4490        self.discard_inline_completion(cx);
 4491    }
 4492
 4493    fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 4494        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 4495    }
 4496
 4497    fn render_code_actions_indicator(
 4498        &self,
 4499        _style: &EditorStyle,
 4500        row: DisplayRow,
 4501        is_active: bool,
 4502        cx: &mut ViewContext<Self>,
 4503    ) -> Option<IconButton> {
 4504        if self.available_code_actions.is_some() {
 4505            Some(
 4506                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 4507                    .icon_size(IconSize::XSmall)
 4508                    .size(ui::ButtonSize::None)
 4509                    .icon_color(Color::Muted)
 4510                    .selected(is_active)
 4511                    .on_click(cx.listener(move |editor, _e, cx| {
 4512                        editor.focus(cx);
 4513                        editor.toggle_code_actions(
 4514                            &ToggleCodeActions {
 4515                                deployed_from_indicator: Some(row),
 4516                            },
 4517                            cx,
 4518                        );
 4519                    })),
 4520            )
 4521        } else {
 4522            None
 4523        }
 4524    }
 4525
 4526    fn clear_tasks(&mut self) {
 4527        self.tasks.clear()
 4528    }
 4529
 4530    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: (usize, RunnableTasks)) {
 4531        if let Some(_) = self.tasks.insert(key, value) {
 4532            // This case should hopefully be rare, but just in case...
 4533            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 4534        }
 4535    }
 4536
 4537    fn render_run_indicator(
 4538        &self,
 4539        _style: &EditorStyle,
 4540        is_active: bool,
 4541        row: DisplayRow,
 4542        cx: &mut ViewContext<Self>,
 4543    ) -> IconButton {
 4544        IconButton::new("run_indicator", ui::IconName::Play)
 4545            .icon_size(IconSize::XSmall)
 4546            .size(ui::ButtonSize::None)
 4547            .icon_color(Color::Muted)
 4548            .selected(is_active)
 4549            .on_click(cx.listener(move |editor, _e, cx| {
 4550                editor.focus(cx);
 4551                editor.toggle_code_actions(
 4552                    &ToggleCodeActions {
 4553                        deployed_from_indicator: Some(row),
 4554                    },
 4555                    cx,
 4556                );
 4557            }))
 4558    }
 4559
 4560    pub fn render_fold_indicators(
 4561        &mut self,
 4562        fold_data: Vec<Option<(FoldStatus, MultiBufferRow, bool)>>,
 4563        _style: &EditorStyle,
 4564        gutter_hovered: bool,
 4565        _line_height: Pixels,
 4566        _gutter_margin: Pixels,
 4567        cx: &mut ViewContext<Self>,
 4568    ) -> Vec<Option<AnyElement>> {
 4569        fold_data
 4570            .iter()
 4571            .enumerate()
 4572            .map(|(ix, fold_data)| {
 4573                fold_data
 4574                    .map(|(fold_status, buffer_row, active)| {
 4575                        (active || gutter_hovered || fold_status == FoldStatus::Folded).then(|| {
 4576                            IconButton::new(ix, ui::IconName::ChevronDown)
 4577                                .on_click(cx.listener(move |this, _e, cx| match fold_status {
 4578                                    FoldStatus::Folded => {
 4579                                        this.unfold_at(&UnfoldAt { buffer_row }, cx);
 4580                                    }
 4581                                    FoldStatus::Foldable => {
 4582                                        this.fold_at(&FoldAt { buffer_row }, cx);
 4583                                    }
 4584                                }))
 4585                                .icon_color(ui::Color::Muted)
 4586                                .icon_size(ui::IconSize::Small)
 4587                                .selected(fold_status == FoldStatus::Folded)
 4588                                .selected_icon(ui::IconName::ChevronRight)
 4589                                .size(ui::ButtonSize::None)
 4590                                .into_any_element()
 4591                        })
 4592                    })
 4593                    .flatten()
 4594            })
 4595            .collect()
 4596    }
 4597
 4598    pub fn context_menu_visible(&self) -> bool {
 4599        self.context_menu
 4600            .read()
 4601            .as_ref()
 4602            .map_or(false, |menu| menu.visible())
 4603    }
 4604
 4605    fn render_context_menu(
 4606        &self,
 4607        cursor_position: DisplayPoint,
 4608        style: &EditorStyle,
 4609        max_height: Pixels,
 4610        cx: &mut ViewContext<Editor>,
 4611    ) -> Option<(ContextMenuOrigin, AnyElement)> {
 4612        self.context_menu.read().as_ref().map(|menu| {
 4613            menu.render(
 4614                cursor_position,
 4615                style,
 4616                max_height,
 4617                self.workspace.as_ref().map(|(w, _)| w.clone()),
 4618                cx,
 4619            )
 4620        })
 4621    }
 4622
 4623    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
 4624        cx.notify();
 4625        self.completion_tasks.clear();
 4626        let context_menu = self.context_menu.write().take();
 4627        if context_menu.is_some() {
 4628            self.update_visible_inline_completion(cx);
 4629        }
 4630        context_menu
 4631    }
 4632
 4633    pub fn insert_snippet(
 4634        &mut self,
 4635        insertion_ranges: &[Range<usize>],
 4636        snippet: Snippet,
 4637        cx: &mut ViewContext<Self>,
 4638    ) -> Result<()> {
 4639        struct Tabstop<T> {
 4640            is_end_tabstop: bool,
 4641            ranges: Vec<Range<T>>,
 4642        }
 4643
 4644        let tabstops = self.buffer.update(cx, |buffer, cx| {
 4645            let snippet_text: Arc<str> = snippet.text.clone().into();
 4646            buffer.edit(
 4647                insertion_ranges
 4648                    .iter()
 4649                    .cloned()
 4650                    .map(|range| (range, snippet_text.clone())),
 4651                Some(AutoindentMode::EachLine),
 4652                cx,
 4653            );
 4654
 4655            let snapshot = &*buffer.read(cx);
 4656            let snippet = &snippet;
 4657            snippet
 4658                .tabstops
 4659                .iter()
 4660                .map(|tabstop| {
 4661                    let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
 4662                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 4663                    });
 4664                    let mut tabstop_ranges = tabstop
 4665                        .iter()
 4666                        .flat_map(|tabstop_range| {
 4667                            let mut delta = 0_isize;
 4668                            insertion_ranges.iter().map(move |insertion_range| {
 4669                                let insertion_start = insertion_range.start as isize + delta;
 4670                                delta +=
 4671                                    snippet.text.len() as isize - insertion_range.len() as isize;
 4672
 4673                                let start = ((insertion_start + tabstop_range.start) as usize)
 4674                                    .min(snapshot.len());
 4675                                let end = ((insertion_start + tabstop_range.end) as usize)
 4676                                    .min(snapshot.len());
 4677                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 4678                            })
 4679                        })
 4680                        .collect::<Vec<_>>();
 4681                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 4682
 4683                    Tabstop {
 4684                        is_end_tabstop,
 4685                        ranges: tabstop_ranges,
 4686                    }
 4687                })
 4688                .collect::<Vec<_>>()
 4689        });
 4690
 4691        if let Some(tabstop) = tabstops.first() {
 4692            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 4693                s.select_ranges(tabstop.ranges.iter().cloned());
 4694            });
 4695
 4696            // If we're already at the last tabstop and it's at the end of the snippet,
 4697            // we're done, we don't need to keep the state around.
 4698            if !tabstop.is_end_tabstop {
 4699                let ranges = tabstops
 4700                    .into_iter()
 4701                    .map(|tabstop| tabstop.ranges)
 4702                    .collect::<Vec<_>>();
 4703                self.snippet_stack.push(SnippetState {
 4704                    active_index: 0,
 4705                    ranges,
 4706                });
 4707            }
 4708
 4709            // Check whether the just-entered snippet ends with an auto-closable bracket.
 4710            if self.autoclose_regions.is_empty() {
 4711                let snapshot = self.buffer.read(cx).snapshot(cx);
 4712                for selection in &mut self.selections.all::<Point>(cx) {
 4713                    let selection_head = selection.head();
 4714                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 4715                        continue;
 4716                    };
 4717
 4718                    let mut bracket_pair = None;
 4719                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 4720                    let prev_chars = snapshot
 4721                        .reversed_chars_at(selection_head)
 4722                        .collect::<String>();
 4723                    for (pair, enabled) in scope.brackets() {
 4724                        if enabled
 4725                            && pair.close
 4726                            && prev_chars.starts_with(pair.start.as_str())
 4727                            && next_chars.starts_with(pair.end.as_str())
 4728                        {
 4729                            bracket_pair = Some(pair.clone());
 4730                            break;
 4731                        }
 4732                    }
 4733                    if let Some(pair) = bracket_pair {
 4734                        let start = snapshot.anchor_after(selection_head);
 4735                        let end = snapshot.anchor_after(selection_head);
 4736                        self.autoclose_regions.push(AutocloseRegion {
 4737                            selection_id: selection.id,
 4738                            range: start..end,
 4739                            pair,
 4740                        });
 4741                    }
 4742                }
 4743            }
 4744        }
 4745        Ok(())
 4746    }
 4747
 4748    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 4749        self.move_to_snippet_tabstop(Bias::Right, cx)
 4750    }
 4751
 4752    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 4753        self.move_to_snippet_tabstop(Bias::Left, cx)
 4754    }
 4755
 4756    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 4757        if let Some(mut snippet) = self.snippet_stack.pop() {
 4758            match bias {
 4759                Bias::Left => {
 4760                    if snippet.active_index > 0 {
 4761                        snippet.active_index -= 1;
 4762                    } else {
 4763                        self.snippet_stack.push(snippet);
 4764                        return false;
 4765                    }
 4766                }
 4767                Bias::Right => {
 4768                    if snippet.active_index + 1 < snippet.ranges.len() {
 4769                        snippet.active_index += 1;
 4770                    } else {
 4771                        self.snippet_stack.push(snippet);
 4772                        return false;
 4773                    }
 4774                }
 4775            }
 4776            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 4777                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 4778                    s.select_anchor_ranges(current_ranges.iter().cloned())
 4779                });
 4780                // If snippet state is not at the last tabstop, push it back on the stack
 4781                if snippet.active_index + 1 < snippet.ranges.len() {
 4782                    self.snippet_stack.push(snippet);
 4783                }
 4784                return true;
 4785            }
 4786        }
 4787
 4788        false
 4789    }
 4790
 4791    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 4792        self.transact(cx, |this, cx| {
 4793            this.select_all(&SelectAll, cx);
 4794            this.insert("", cx);
 4795        });
 4796    }
 4797
 4798    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 4799        self.transact(cx, |this, cx| {
 4800            this.select_autoclose_pair(cx);
 4801            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 4802            if !this.selections.line_mode {
 4803                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 4804                for selection in &mut selections {
 4805                    if selection.is_empty() {
 4806                        let old_head = selection.head();
 4807                        let mut new_head =
 4808                            movement::left(&display_map, old_head.to_display_point(&display_map))
 4809                                .to_point(&display_map);
 4810                        if let Some((buffer, line_buffer_range)) = display_map
 4811                            .buffer_snapshot
 4812                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 4813                        {
 4814                            let indent_size =
 4815                                buffer.indent_size_for_line(line_buffer_range.start.row);
 4816                            let indent_len = match indent_size.kind {
 4817                                IndentKind::Space => {
 4818                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 4819                                }
 4820                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 4821                            };
 4822                            if old_head.column <= indent_size.len && old_head.column > 0 {
 4823                                let indent_len = indent_len.get();
 4824                                new_head = cmp::min(
 4825                                    new_head,
 4826                                    MultiBufferPoint::new(
 4827                                        old_head.row,
 4828                                        ((old_head.column - 1) / indent_len) * indent_len,
 4829                                    ),
 4830                                );
 4831                            }
 4832                        }
 4833
 4834                        selection.set_head(new_head, SelectionGoal::None);
 4835                    }
 4836                }
 4837            }
 4838
 4839            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 4840            this.insert("", cx);
 4841            this.refresh_inline_completion(true, cx);
 4842        });
 4843    }
 4844
 4845    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 4846        self.transact(cx, |this, cx| {
 4847            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 4848                let line_mode = s.line_mode;
 4849                s.move_with(|map, selection| {
 4850                    if selection.is_empty() && !line_mode {
 4851                        let cursor = movement::right(map, selection.head());
 4852                        selection.end = cursor;
 4853                        selection.reversed = true;
 4854                        selection.goal = SelectionGoal::None;
 4855                    }
 4856                })
 4857            });
 4858            this.insert("", cx);
 4859            this.refresh_inline_completion(true, cx);
 4860        });
 4861    }
 4862
 4863    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 4864        if self.move_to_prev_snippet_tabstop(cx) {
 4865            return;
 4866        }
 4867
 4868        self.outdent(&Outdent, cx);
 4869    }
 4870
 4871    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 4872        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 4873            return;
 4874        }
 4875
 4876        let mut selections = self.selections.all_adjusted(cx);
 4877        let buffer = self.buffer.read(cx);
 4878        let snapshot = buffer.snapshot(cx);
 4879        let rows_iter = selections.iter().map(|s| s.head().row);
 4880        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 4881
 4882        let mut edits = Vec::new();
 4883        let mut prev_edited_row = 0;
 4884        let mut row_delta = 0;
 4885        for selection in &mut selections {
 4886            if selection.start.row != prev_edited_row {
 4887                row_delta = 0;
 4888            }
 4889            prev_edited_row = selection.end.row;
 4890
 4891            // If the selection is non-empty, then increase the indentation of the selected lines.
 4892            if !selection.is_empty() {
 4893                row_delta =
 4894                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 4895                continue;
 4896            }
 4897
 4898            // If the selection is empty and the cursor is in the leading whitespace before the
 4899            // suggested indentation, then auto-indent the line.
 4900            let cursor = selection.head();
 4901            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 4902            if let Some(suggested_indent) =
 4903                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 4904            {
 4905                if cursor.column < suggested_indent.len
 4906                    && cursor.column <= current_indent.len
 4907                    && current_indent.len <= suggested_indent.len
 4908                {
 4909                    selection.start = Point::new(cursor.row, suggested_indent.len);
 4910                    selection.end = selection.start;
 4911                    if row_delta == 0 {
 4912                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 4913                            cursor.row,
 4914                            current_indent,
 4915                            suggested_indent,
 4916                        ));
 4917                        row_delta = suggested_indent.len - current_indent.len;
 4918                    }
 4919                    continue;
 4920                }
 4921            }
 4922
 4923            // Accept copilot completion if there is only one selection and the cursor is not
 4924            // in the leading whitespace.
 4925            if self.selections.count() == 1
 4926                && cursor.column >= current_indent.len
 4927                && self.has_active_inline_completion(cx)
 4928            {
 4929                self.accept_inline_completion(cx);
 4930                return;
 4931            }
 4932
 4933            // Otherwise, insert a hard or soft tab.
 4934            let settings = buffer.settings_at(cursor, cx);
 4935            let tab_size = if settings.hard_tabs {
 4936                IndentSize::tab()
 4937            } else {
 4938                let tab_size = settings.tab_size.get();
 4939                let char_column = snapshot
 4940                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 4941                    .flat_map(str::chars)
 4942                    .count()
 4943                    + row_delta as usize;
 4944                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 4945                IndentSize::spaces(chars_to_next_tab_stop)
 4946            };
 4947            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 4948            selection.end = selection.start;
 4949            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 4950            row_delta += tab_size.len;
 4951        }
 4952
 4953        self.transact(cx, |this, cx| {
 4954            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 4955            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 4956            this.refresh_inline_completion(true, cx);
 4957        });
 4958    }
 4959
 4960    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 4961        if self.read_only(cx) {
 4962            return;
 4963        }
 4964        let mut selections = self.selections.all::<Point>(cx);
 4965        let mut prev_edited_row = 0;
 4966        let mut row_delta = 0;
 4967        let mut edits = Vec::new();
 4968        let buffer = self.buffer.read(cx);
 4969        let snapshot = buffer.snapshot(cx);
 4970        for selection in &mut selections {
 4971            if selection.start.row != prev_edited_row {
 4972                row_delta = 0;
 4973            }
 4974            prev_edited_row = selection.end.row;
 4975
 4976            row_delta =
 4977                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 4978        }
 4979
 4980        self.transact(cx, |this, cx| {
 4981            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 4982            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 4983        });
 4984    }
 4985
 4986    fn indent_selection(
 4987        buffer: &MultiBuffer,
 4988        snapshot: &MultiBufferSnapshot,
 4989        selection: &mut Selection<Point>,
 4990        edits: &mut Vec<(Range<Point>, String)>,
 4991        delta_for_start_row: u32,
 4992        cx: &AppContext,
 4993    ) -> u32 {
 4994        let settings = buffer.settings_at(selection.start, cx);
 4995        let tab_size = settings.tab_size.get();
 4996        let indent_kind = if settings.hard_tabs {
 4997            IndentKind::Tab
 4998        } else {
 4999            IndentKind::Space
 5000        };
 5001        let mut start_row = selection.start.row;
 5002        let mut end_row = selection.end.row + 1;
 5003
 5004        // If a selection ends at the beginning of a line, don't indent
 5005        // that last line.
 5006        if selection.end.column == 0 && selection.end.row > selection.start.row {
 5007            end_row -= 1;
 5008        }
 5009
 5010        // Avoid re-indenting a row that has already been indented by a
 5011        // previous selection, but still update this selection's column
 5012        // to reflect that indentation.
 5013        if delta_for_start_row > 0 {
 5014            start_row += 1;
 5015            selection.start.column += delta_for_start_row;
 5016            if selection.end.row == selection.start.row {
 5017                selection.end.column += delta_for_start_row;
 5018            }
 5019        }
 5020
 5021        let mut delta_for_end_row = 0;
 5022        let has_multiple_rows = start_row + 1 != end_row;
 5023        for row in start_row..end_row {
 5024            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 5025            let indent_delta = match (current_indent.kind, indent_kind) {
 5026                (IndentKind::Space, IndentKind::Space) => {
 5027                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 5028                    IndentSize::spaces(columns_to_next_tab_stop)
 5029                }
 5030                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 5031                (_, IndentKind::Tab) => IndentSize::tab(),
 5032            };
 5033
 5034            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 5035                0
 5036            } else {
 5037                selection.start.column
 5038            };
 5039            let row_start = Point::new(row, start);
 5040            edits.push((
 5041                row_start..row_start,
 5042                indent_delta.chars().collect::<String>(),
 5043            ));
 5044
 5045            // Update this selection's endpoints to reflect the indentation.
 5046            if row == selection.start.row {
 5047                selection.start.column += indent_delta.len;
 5048            }
 5049            if row == selection.end.row {
 5050                selection.end.column += indent_delta.len;
 5051                delta_for_end_row = indent_delta.len;
 5052            }
 5053        }
 5054
 5055        if selection.start.row == selection.end.row {
 5056            delta_for_start_row + delta_for_end_row
 5057        } else {
 5058            delta_for_end_row
 5059        }
 5060    }
 5061
 5062    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 5063        if self.read_only(cx) {
 5064            return;
 5065        }
 5066        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5067        let selections = self.selections.all::<Point>(cx);
 5068        let mut deletion_ranges = Vec::new();
 5069        let mut last_outdent = None;
 5070        {
 5071            let buffer = self.buffer.read(cx);
 5072            let snapshot = buffer.snapshot(cx);
 5073            for selection in &selections {
 5074                let settings = buffer.settings_at(selection.start, cx);
 5075                let tab_size = settings.tab_size.get();
 5076                let mut rows = selection.spanned_rows(false, &display_map);
 5077
 5078                // Avoid re-outdenting a row that has already been outdented by a
 5079                // previous selection.
 5080                if let Some(last_row) = last_outdent {
 5081                    if last_row == rows.start {
 5082                        rows.start = rows.start.next_row();
 5083                    }
 5084                }
 5085                let has_multiple_rows = rows.len() > 1;
 5086                for row in rows.iter_rows() {
 5087                    let indent_size = snapshot.indent_size_for_line(row);
 5088                    if indent_size.len > 0 {
 5089                        let deletion_len = match indent_size.kind {
 5090                            IndentKind::Space => {
 5091                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 5092                                if columns_to_prev_tab_stop == 0 {
 5093                                    tab_size
 5094                                } else {
 5095                                    columns_to_prev_tab_stop
 5096                                }
 5097                            }
 5098                            IndentKind::Tab => 1,
 5099                        };
 5100                        let start = if has_multiple_rows
 5101                            || deletion_len > selection.start.column
 5102                            || indent_size.len < selection.start.column
 5103                        {
 5104                            0
 5105                        } else {
 5106                            selection.start.column - deletion_len
 5107                        };
 5108                        deletion_ranges.push(
 5109                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 5110                        );
 5111                        last_outdent = Some(row);
 5112                    }
 5113                }
 5114            }
 5115        }
 5116
 5117        self.transact(cx, |this, cx| {
 5118            this.buffer.update(cx, |buffer, cx| {
 5119                let empty_str: Arc<str> = "".into();
 5120                buffer.edit(
 5121                    deletion_ranges
 5122                        .into_iter()
 5123                        .map(|range| (range, empty_str.clone())),
 5124                    None,
 5125                    cx,
 5126                );
 5127            });
 5128            let selections = this.selections.all::<usize>(cx);
 5129            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5130        });
 5131    }
 5132
 5133    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 5134        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5135        let selections = self.selections.all::<Point>(cx);
 5136
 5137        let mut new_cursors = Vec::new();
 5138        let mut edit_ranges = Vec::new();
 5139        let mut selections = selections.iter().peekable();
 5140        while let Some(selection) = selections.next() {
 5141            let mut rows = selection.spanned_rows(false, &display_map);
 5142            let goal_display_column = selection.head().to_display_point(&display_map).column();
 5143
 5144            // Accumulate contiguous regions of rows that we want to delete.
 5145            while let Some(next_selection) = selections.peek() {
 5146                let next_rows = next_selection.spanned_rows(false, &display_map);
 5147                if next_rows.start <= rows.end {
 5148                    rows.end = next_rows.end;
 5149                    selections.next().unwrap();
 5150                } else {
 5151                    break;
 5152                }
 5153            }
 5154
 5155            let buffer = &display_map.buffer_snapshot;
 5156            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 5157            let edit_end;
 5158            let cursor_buffer_row;
 5159            if buffer.max_point().row >= rows.end.0 {
 5160                // If there's a line after the range, delete the \n from the end of the row range
 5161                // and position the cursor on the next line.
 5162                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 5163                cursor_buffer_row = rows.end;
 5164            } else {
 5165                // If there isn't a line after the range, delete the \n from the line before the
 5166                // start of the row range and position the cursor there.
 5167                edit_start = edit_start.saturating_sub(1);
 5168                edit_end = buffer.len();
 5169                cursor_buffer_row = rows.start.previous_row();
 5170            }
 5171
 5172            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 5173            *cursor.column_mut() =
 5174                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 5175
 5176            new_cursors.push((
 5177                selection.id,
 5178                buffer.anchor_after(cursor.to_point(&display_map)),
 5179            ));
 5180            edit_ranges.push(edit_start..edit_end);
 5181        }
 5182
 5183        self.transact(cx, |this, cx| {
 5184            let buffer = this.buffer.update(cx, |buffer, cx| {
 5185                let empty_str: Arc<str> = "".into();
 5186                buffer.edit(
 5187                    edit_ranges
 5188                        .into_iter()
 5189                        .map(|range| (range, empty_str.clone())),
 5190                    None,
 5191                    cx,
 5192                );
 5193                buffer.snapshot(cx)
 5194            });
 5195            let new_selections = new_cursors
 5196                .into_iter()
 5197                .map(|(id, cursor)| {
 5198                    let cursor = cursor.to_point(&buffer);
 5199                    Selection {
 5200                        id,
 5201                        start: cursor,
 5202                        end: cursor,
 5203                        reversed: false,
 5204                        goal: SelectionGoal::None,
 5205                    }
 5206                })
 5207                .collect();
 5208
 5209            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5210                s.select(new_selections);
 5211            });
 5212        });
 5213    }
 5214
 5215    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 5216        if self.read_only(cx) {
 5217            return;
 5218        }
 5219        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 5220        for selection in self.selections.all::<Point>(cx) {
 5221            let start = MultiBufferRow(selection.start.row);
 5222            let end = if selection.start.row == selection.end.row {
 5223                MultiBufferRow(selection.start.row + 1)
 5224            } else {
 5225                MultiBufferRow(selection.end.row)
 5226            };
 5227
 5228            if let Some(last_row_range) = row_ranges.last_mut() {
 5229                if start <= last_row_range.end {
 5230                    last_row_range.end = end;
 5231                    continue;
 5232                }
 5233            }
 5234            row_ranges.push(start..end);
 5235        }
 5236
 5237        let snapshot = self.buffer.read(cx).snapshot(cx);
 5238        let mut cursor_positions = Vec::new();
 5239        for row_range in &row_ranges {
 5240            let anchor = snapshot.anchor_before(Point::new(
 5241                row_range.end.previous_row().0,
 5242                snapshot.line_len(row_range.end.previous_row()),
 5243            ));
 5244            cursor_positions.push(anchor..anchor);
 5245        }
 5246
 5247        self.transact(cx, |this, cx| {
 5248            for row_range in row_ranges.into_iter().rev() {
 5249                for row in row_range.iter_rows().rev() {
 5250                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 5251                    let next_line_row = row.next_row();
 5252                    let indent = snapshot.indent_size_for_line(next_line_row);
 5253                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 5254
 5255                    let replace = if snapshot.line_len(next_line_row) > indent.len {
 5256                        " "
 5257                    } else {
 5258                        ""
 5259                    };
 5260
 5261                    this.buffer.update(cx, |buffer, cx| {
 5262                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 5263                    });
 5264                }
 5265            }
 5266
 5267            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5268                s.select_anchor_ranges(cursor_positions)
 5269            });
 5270        });
 5271    }
 5272
 5273    pub fn sort_lines_case_sensitive(
 5274        &mut self,
 5275        _: &SortLinesCaseSensitive,
 5276        cx: &mut ViewContext<Self>,
 5277    ) {
 5278        self.manipulate_lines(cx, |lines| lines.sort())
 5279    }
 5280
 5281    pub fn sort_lines_case_insensitive(
 5282        &mut self,
 5283        _: &SortLinesCaseInsensitive,
 5284        cx: &mut ViewContext<Self>,
 5285    ) {
 5286        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 5287    }
 5288
 5289    pub fn unique_lines_case_insensitive(
 5290        &mut self,
 5291        _: &UniqueLinesCaseInsensitive,
 5292        cx: &mut ViewContext<Self>,
 5293    ) {
 5294        self.manipulate_lines(cx, |lines| {
 5295            let mut seen = HashSet::default();
 5296            lines.retain(|line| seen.insert(line.to_lowercase()));
 5297        })
 5298    }
 5299
 5300    pub fn unique_lines_case_sensitive(
 5301        &mut self,
 5302        _: &UniqueLinesCaseSensitive,
 5303        cx: &mut ViewContext<Self>,
 5304    ) {
 5305        self.manipulate_lines(cx, |lines| {
 5306            let mut seen = HashSet::default();
 5307            lines.retain(|line| seen.insert(*line));
 5308        })
 5309    }
 5310
 5311    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 5312        let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
 5313        if !revert_changes.is_empty() {
 5314            self.transact(cx, |editor, cx| {
 5315                editor.buffer().update(cx, |multi_buffer, cx| {
 5316                    for (buffer_id, changes) in revert_changes {
 5317                        if let Some(buffer) = multi_buffer.buffer(buffer_id) {
 5318                            buffer.update(cx, |buffer, cx| {
 5319                                buffer.edit(
 5320                                    changes.into_iter().map(|(range, text)| {
 5321                                        (range, text.to_string().map(Arc::<str>::from))
 5322                                    }),
 5323                                    None,
 5324                                    cx,
 5325                                );
 5326                            });
 5327                        }
 5328                    }
 5329                });
 5330                editor.change_selections(None, cx, |selections| selections.refresh());
 5331            });
 5332        }
 5333    }
 5334
 5335    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 5336        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 5337            let project_path = buffer.read(cx).project_path(cx)?;
 5338            let project = self.project.as_ref()?.read(cx);
 5339            let entry = project.entry_for_path(&project_path, cx)?;
 5340            let abs_path = project.absolute_path(&project_path, cx)?;
 5341            let parent = if entry.is_symlink {
 5342                abs_path.canonicalize().ok()?
 5343            } else {
 5344                abs_path
 5345            }
 5346            .parent()?
 5347            .to_path_buf();
 5348            Some(parent)
 5349        }) {
 5350            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 5351        }
 5352    }
 5353
 5354    fn gather_revert_changes(
 5355        &mut self,
 5356        selections: &[Selection<Anchor>],
 5357        cx: &mut ViewContext<'_, Editor>,
 5358    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 5359        let mut revert_changes = HashMap::default();
 5360        self.buffer.update(cx, |multi_buffer, cx| {
 5361            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 5362            for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
 5363                Self::prepare_revert_change(&mut revert_changes, &multi_buffer, &hunk, cx);
 5364            }
 5365        });
 5366        revert_changes
 5367    }
 5368
 5369    fn prepare_revert_change(
 5370        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 5371        multi_buffer: &MultiBuffer,
 5372        hunk: &DiffHunk<MultiBufferRow>,
 5373        cx: &mut AppContext,
 5374    ) -> Option<()> {
 5375        let buffer = multi_buffer.buffer(hunk.buffer_id)?;
 5376        let buffer = buffer.read(cx);
 5377        let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
 5378        let buffer_snapshot = buffer.snapshot();
 5379        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 5380        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 5381            probe
 5382                .0
 5383                .start
 5384                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 5385                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 5386        }) {
 5387            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 5388            Some(())
 5389        } else {
 5390            None
 5391        }
 5392    }
 5393
 5394    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 5395        self.manipulate_lines(cx, |lines| lines.reverse())
 5396    }
 5397
 5398    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 5399        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 5400    }
 5401
 5402    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 5403    where
 5404        Fn: FnMut(&mut Vec<&str>),
 5405    {
 5406        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5407        let buffer = self.buffer.read(cx).snapshot(cx);
 5408
 5409        let mut edits = Vec::new();
 5410
 5411        let selections = self.selections.all::<Point>(cx);
 5412        let mut selections = selections.iter().peekable();
 5413        let mut contiguous_row_selections = Vec::new();
 5414        let mut new_selections = Vec::new();
 5415        let mut added_lines = 0;
 5416        let mut removed_lines = 0;
 5417
 5418        while let Some(selection) = selections.next() {
 5419            let (start_row, end_row) = consume_contiguous_rows(
 5420                &mut contiguous_row_selections,
 5421                selection,
 5422                &display_map,
 5423                &mut selections,
 5424            );
 5425
 5426            let start_point = Point::new(start_row.0, 0);
 5427            let end_point = Point::new(
 5428                end_row.previous_row().0,
 5429                buffer.line_len(end_row.previous_row()),
 5430            );
 5431            let text = buffer
 5432                .text_for_range(start_point..end_point)
 5433                .collect::<String>();
 5434
 5435            let mut lines = text.split('\n').collect_vec();
 5436
 5437            let lines_before = lines.len();
 5438            callback(&mut lines);
 5439            let lines_after = lines.len();
 5440
 5441            edits.push((start_point..end_point, lines.join("\n")));
 5442
 5443            // Selections must change based on added and removed line count
 5444            let start_row =
 5445                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 5446            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 5447            new_selections.push(Selection {
 5448                id: selection.id,
 5449                start: start_row,
 5450                end: end_row,
 5451                goal: SelectionGoal::None,
 5452                reversed: selection.reversed,
 5453            });
 5454
 5455            if lines_after > lines_before {
 5456                added_lines += lines_after - lines_before;
 5457            } else if lines_before > lines_after {
 5458                removed_lines += lines_before - lines_after;
 5459            }
 5460        }
 5461
 5462        self.transact(cx, |this, cx| {
 5463            let buffer = this.buffer.update(cx, |buffer, cx| {
 5464                buffer.edit(edits, None, cx);
 5465                buffer.snapshot(cx)
 5466            });
 5467
 5468            // Recalculate offsets on newly edited buffer
 5469            let new_selections = new_selections
 5470                .iter()
 5471                .map(|s| {
 5472                    let start_point = Point::new(s.start.0, 0);
 5473                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 5474                    Selection {
 5475                        id: s.id,
 5476                        start: buffer.point_to_offset(start_point),
 5477                        end: buffer.point_to_offset(end_point),
 5478                        goal: s.goal,
 5479                        reversed: s.reversed,
 5480                    }
 5481                })
 5482                .collect();
 5483
 5484            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5485                s.select(new_selections);
 5486            });
 5487
 5488            this.request_autoscroll(Autoscroll::fit(), cx);
 5489        });
 5490    }
 5491
 5492    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 5493        self.manipulate_text(cx, |text| text.to_uppercase())
 5494    }
 5495
 5496    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 5497        self.manipulate_text(cx, |text| text.to_lowercase())
 5498    }
 5499
 5500    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 5501        self.manipulate_text(cx, |text| {
 5502            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 5503            // https://github.com/rutrum/convert-case/issues/16
 5504            text.split('\n')
 5505                .map(|line| line.to_case(Case::Title))
 5506                .join("\n")
 5507        })
 5508    }
 5509
 5510    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 5511        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 5512    }
 5513
 5514    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 5515        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 5516    }
 5517
 5518    pub fn convert_to_upper_camel_case(
 5519        &mut self,
 5520        _: &ConvertToUpperCamelCase,
 5521        cx: &mut ViewContext<Self>,
 5522    ) {
 5523        self.manipulate_text(cx, |text| {
 5524            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 5525            // https://github.com/rutrum/convert-case/issues/16
 5526            text.split('\n')
 5527                .map(|line| line.to_case(Case::UpperCamel))
 5528                .join("\n")
 5529        })
 5530    }
 5531
 5532    pub fn convert_to_lower_camel_case(
 5533        &mut self,
 5534        _: &ConvertToLowerCamelCase,
 5535        cx: &mut ViewContext<Self>,
 5536    ) {
 5537        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 5538    }
 5539
 5540    pub fn convert_to_opposite_case(
 5541        &mut self,
 5542        _: &ConvertToOppositeCase,
 5543        cx: &mut ViewContext<Self>,
 5544    ) {
 5545        self.manipulate_text(cx, |text| {
 5546            text.chars()
 5547                .fold(String::with_capacity(text.len()), |mut t, c| {
 5548                    if c.is_uppercase() {
 5549                        t.extend(c.to_lowercase());
 5550                    } else {
 5551                        t.extend(c.to_uppercase());
 5552                    }
 5553                    t
 5554                })
 5555        })
 5556    }
 5557
 5558    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 5559    where
 5560        Fn: FnMut(&str) -> String,
 5561    {
 5562        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5563        let buffer = self.buffer.read(cx).snapshot(cx);
 5564
 5565        let mut new_selections = Vec::new();
 5566        let mut edits = Vec::new();
 5567        let mut selection_adjustment = 0i32;
 5568
 5569        for selection in self.selections.all::<usize>(cx) {
 5570            let selection_is_empty = selection.is_empty();
 5571
 5572            let (start, end) = if selection_is_empty {
 5573                let word_range = movement::surrounding_word(
 5574                    &display_map,
 5575                    selection.start.to_display_point(&display_map),
 5576                );
 5577                let start = word_range.start.to_offset(&display_map, Bias::Left);
 5578                let end = word_range.end.to_offset(&display_map, Bias::Left);
 5579                (start, end)
 5580            } else {
 5581                (selection.start, selection.end)
 5582            };
 5583
 5584            let text = buffer.text_for_range(start..end).collect::<String>();
 5585            let old_length = text.len() as i32;
 5586            let text = callback(&text);
 5587
 5588            new_selections.push(Selection {
 5589                start: (start as i32 - selection_adjustment) as usize,
 5590                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 5591                goal: SelectionGoal::None,
 5592                ..selection
 5593            });
 5594
 5595            selection_adjustment += old_length - text.len() as i32;
 5596
 5597            edits.push((start..end, text));
 5598        }
 5599
 5600        self.transact(cx, |this, cx| {
 5601            this.buffer.update(cx, |buffer, cx| {
 5602                buffer.edit(edits, None, cx);
 5603            });
 5604
 5605            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5606                s.select(new_selections);
 5607            });
 5608
 5609            this.request_autoscroll(Autoscroll::fit(), cx);
 5610        });
 5611    }
 5612
 5613    pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
 5614        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5615        let buffer = &display_map.buffer_snapshot;
 5616        let selections = self.selections.all::<Point>(cx);
 5617
 5618        let mut edits = Vec::new();
 5619        let mut selections_iter = selections.iter().peekable();
 5620        while let Some(selection) = selections_iter.next() {
 5621            // Avoid duplicating the same lines twice.
 5622            let mut rows = selection.spanned_rows(false, &display_map);
 5623
 5624            while let Some(next_selection) = selections_iter.peek() {
 5625                let next_rows = next_selection.spanned_rows(false, &display_map);
 5626                if next_rows.start < rows.end {
 5627                    rows.end = next_rows.end;
 5628                    selections_iter.next().unwrap();
 5629                } else {
 5630                    break;
 5631                }
 5632            }
 5633
 5634            // Copy the text from the selected row region and splice it either at the start
 5635            // or end of the region.
 5636            let start = Point::new(rows.start.0, 0);
 5637            let end = Point::new(
 5638                rows.end.previous_row().0,
 5639                buffer.line_len(rows.end.previous_row()),
 5640            );
 5641            let text = buffer
 5642                .text_for_range(start..end)
 5643                .chain(Some("\n"))
 5644                .collect::<String>();
 5645            let insert_location = if upwards {
 5646                Point::new(rows.end.0, 0)
 5647            } else {
 5648                start
 5649            };
 5650            edits.push((insert_location..insert_location, text));
 5651        }
 5652
 5653        self.transact(cx, |this, cx| {
 5654            this.buffer.update(cx, |buffer, cx| {
 5655                buffer.edit(edits, None, cx);
 5656            });
 5657
 5658            this.request_autoscroll(Autoscroll::fit(), cx);
 5659        });
 5660    }
 5661
 5662    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 5663        self.duplicate_line(true, cx);
 5664    }
 5665
 5666    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 5667        self.duplicate_line(false, cx);
 5668    }
 5669
 5670    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 5671        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5672        let buffer = self.buffer.read(cx).snapshot(cx);
 5673
 5674        let mut edits = Vec::new();
 5675        let mut unfold_ranges = Vec::new();
 5676        let mut refold_ranges = Vec::new();
 5677
 5678        let selections = self.selections.all::<Point>(cx);
 5679        let mut selections = selections.iter().peekable();
 5680        let mut contiguous_row_selections = Vec::new();
 5681        let mut new_selections = Vec::new();
 5682
 5683        while let Some(selection) = selections.next() {
 5684            // Find all the selections that span a contiguous row range
 5685            let (start_row, end_row) = consume_contiguous_rows(
 5686                &mut contiguous_row_selections,
 5687                selection,
 5688                &display_map,
 5689                &mut selections,
 5690            );
 5691
 5692            // Move the text spanned by the row range to be before the line preceding the row range
 5693            if start_row.0 > 0 {
 5694                let range_to_move = Point::new(
 5695                    start_row.previous_row().0,
 5696                    buffer.line_len(start_row.previous_row()),
 5697                )
 5698                    ..Point::new(
 5699                        end_row.previous_row().0,
 5700                        buffer.line_len(end_row.previous_row()),
 5701                    );
 5702                let insertion_point = display_map
 5703                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 5704                    .0;
 5705
 5706                // Don't move lines across excerpts
 5707                if buffer
 5708                    .excerpt_boundaries_in_range((
 5709                        Bound::Excluded(insertion_point),
 5710                        Bound::Included(range_to_move.end),
 5711                    ))
 5712                    .next()
 5713                    .is_none()
 5714                {
 5715                    let text = buffer
 5716                        .text_for_range(range_to_move.clone())
 5717                        .flat_map(|s| s.chars())
 5718                        .skip(1)
 5719                        .chain(['\n'])
 5720                        .collect::<String>();
 5721
 5722                    edits.push((
 5723                        buffer.anchor_after(range_to_move.start)
 5724                            ..buffer.anchor_before(range_to_move.end),
 5725                        String::new(),
 5726                    ));
 5727                    let insertion_anchor = buffer.anchor_after(insertion_point);
 5728                    edits.push((insertion_anchor..insertion_anchor, text));
 5729
 5730                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 5731
 5732                    // Move selections up
 5733                    new_selections.extend(contiguous_row_selections.drain(..).map(
 5734                        |mut selection| {
 5735                            selection.start.row -= row_delta;
 5736                            selection.end.row -= row_delta;
 5737                            selection
 5738                        },
 5739                    ));
 5740
 5741                    // Move folds up
 5742                    unfold_ranges.push(range_to_move.clone());
 5743                    for fold in display_map.folds_in_range(
 5744                        buffer.anchor_before(range_to_move.start)
 5745                            ..buffer.anchor_after(range_to_move.end),
 5746                    ) {
 5747                        let mut start = fold.range.start.to_point(&buffer);
 5748                        let mut end = fold.range.end.to_point(&buffer);
 5749                        start.row -= row_delta;
 5750                        end.row -= row_delta;
 5751                        refold_ranges.push(start..end);
 5752                    }
 5753                }
 5754            }
 5755
 5756            // If we didn't move line(s), preserve the existing selections
 5757            new_selections.append(&mut contiguous_row_selections);
 5758        }
 5759
 5760        self.transact(cx, |this, cx| {
 5761            this.unfold_ranges(unfold_ranges, true, true, cx);
 5762            this.buffer.update(cx, |buffer, cx| {
 5763                for (range, text) in edits {
 5764                    buffer.edit([(range, text)], None, cx);
 5765                }
 5766            });
 5767            this.fold_ranges(refold_ranges, true, cx);
 5768            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5769                s.select(new_selections);
 5770            })
 5771        });
 5772    }
 5773
 5774    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 5775        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5776        let buffer = self.buffer.read(cx).snapshot(cx);
 5777
 5778        let mut edits = Vec::new();
 5779        let mut unfold_ranges = Vec::new();
 5780        let mut refold_ranges = Vec::new();
 5781
 5782        let selections = self.selections.all::<Point>(cx);
 5783        let mut selections = selections.iter().peekable();
 5784        let mut contiguous_row_selections = Vec::new();
 5785        let mut new_selections = Vec::new();
 5786
 5787        while let Some(selection) = selections.next() {
 5788            // Find all the selections that span a contiguous row range
 5789            let (start_row, end_row) = consume_contiguous_rows(
 5790                &mut contiguous_row_selections,
 5791                selection,
 5792                &display_map,
 5793                &mut selections,
 5794            );
 5795
 5796            // Move the text spanned by the row range to be after the last line of the row range
 5797            if end_row.0 <= buffer.max_point().row {
 5798                let range_to_move =
 5799                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 5800                let insertion_point = display_map
 5801                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 5802                    .0;
 5803
 5804                // Don't move lines across excerpt boundaries
 5805                if buffer
 5806                    .excerpt_boundaries_in_range((
 5807                        Bound::Excluded(range_to_move.start),
 5808                        Bound::Included(insertion_point),
 5809                    ))
 5810                    .next()
 5811                    .is_none()
 5812                {
 5813                    let mut text = String::from("\n");
 5814                    text.extend(buffer.text_for_range(range_to_move.clone()));
 5815                    text.pop(); // Drop trailing newline
 5816                    edits.push((
 5817                        buffer.anchor_after(range_to_move.start)
 5818                            ..buffer.anchor_before(range_to_move.end),
 5819                        String::new(),
 5820                    ));
 5821                    let insertion_anchor = buffer.anchor_after(insertion_point);
 5822                    edits.push((insertion_anchor..insertion_anchor, text));
 5823
 5824                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 5825
 5826                    // Move selections down
 5827                    new_selections.extend(contiguous_row_selections.drain(..).map(
 5828                        |mut selection| {
 5829                            selection.start.row += row_delta;
 5830                            selection.end.row += row_delta;
 5831                            selection
 5832                        },
 5833                    ));
 5834
 5835                    // Move folds down
 5836                    unfold_ranges.push(range_to_move.clone());
 5837                    for fold in display_map.folds_in_range(
 5838                        buffer.anchor_before(range_to_move.start)
 5839                            ..buffer.anchor_after(range_to_move.end),
 5840                    ) {
 5841                        let mut start = fold.range.start.to_point(&buffer);
 5842                        let mut end = fold.range.end.to_point(&buffer);
 5843                        start.row += row_delta;
 5844                        end.row += row_delta;
 5845                        refold_ranges.push(start..end);
 5846                    }
 5847                }
 5848            }
 5849
 5850            // If we didn't move line(s), preserve the existing selections
 5851            new_selections.append(&mut contiguous_row_selections);
 5852        }
 5853
 5854        self.transact(cx, |this, cx| {
 5855            this.unfold_ranges(unfold_ranges, true, true, cx);
 5856            this.buffer.update(cx, |buffer, cx| {
 5857                for (range, text) in edits {
 5858                    buffer.edit([(range, text)], None, cx);
 5859                }
 5860            });
 5861            this.fold_ranges(refold_ranges, true, cx);
 5862            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 5863        });
 5864    }
 5865
 5866    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 5867        let text_layout_details = &self.text_layout_details(cx);
 5868        self.transact(cx, |this, cx| {
 5869            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5870                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 5871                let line_mode = s.line_mode;
 5872                s.move_with(|display_map, selection| {
 5873                    if !selection.is_empty() || line_mode {
 5874                        return;
 5875                    }
 5876
 5877                    let mut head = selection.head();
 5878                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 5879                    if head.column() == display_map.line_len(head.row()) {
 5880                        transpose_offset = display_map
 5881                            .buffer_snapshot
 5882                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 5883                    }
 5884
 5885                    if transpose_offset == 0 {
 5886                        return;
 5887                    }
 5888
 5889                    *head.column_mut() += 1;
 5890                    head = display_map.clip_point(head, Bias::Right);
 5891                    let goal = SelectionGoal::HorizontalPosition(
 5892                        display_map
 5893                            .x_for_display_point(head, &text_layout_details)
 5894                            .into(),
 5895                    );
 5896                    selection.collapse_to(head, goal);
 5897
 5898                    let transpose_start = display_map
 5899                        .buffer_snapshot
 5900                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 5901                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 5902                        let transpose_end = display_map
 5903                            .buffer_snapshot
 5904                            .clip_offset(transpose_offset + 1, Bias::Right);
 5905                        if let Some(ch) =
 5906                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 5907                        {
 5908                            edits.push((transpose_start..transpose_offset, String::new()));
 5909                            edits.push((transpose_end..transpose_end, ch.to_string()));
 5910                        }
 5911                    }
 5912                });
 5913                edits
 5914            });
 5915            this.buffer
 5916                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 5917            let selections = this.selections.all::<usize>(cx);
 5918            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5919                s.select(selections);
 5920            });
 5921        });
 5922    }
 5923
 5924    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 5925        let mut text = String::new();
 5926        let buffer = self.buffer.read(cx).snapshot(cx);
 5927        let mut selections = self.selections.all::<Point>(cx);
 5928        let mut clipboard_selections = Vec::with_capacity(selections.len());
 5929        {
 5930            let max_point = buffer.max_point();
 5931            let mut is_first = true;
 5932            for selection in &mut selections {
 5933                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 5934                if is_entire_line {
 5935                    selection.start = Point::new(selection.start.row, 0);
 5936                    selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 5937                    selection.goal = SelectionGoal::None;
 5938                }
 5939                if is_first {
 5940                    is_first = false;
 5941                } else {
 5942                    text += "\n";
 5943                }
 5944                let mut len = 0;
 5945                for chunk in buffer.text_for_range(selection.start..selection.end) {
 5946                    text.push_str(chunk);
 5947                    len += chunk.len();
 5948                }
 5949                clipboard_selections.push(ClipboardSelection {
 5950                    len,
 5951                    is_entire_line,
 5952                    first_line_indent: buffer
 5953                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 5954                        .len,
 5955                });
 5956            }
 5957        }
 5958
 5959        self.transact(cx, |this, cx| {
 5960            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5961                s.select(selections);
 5962            });
 5963            this.insert("", cx);
 5964            cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
 5965        });
 5966    }
 5967
 5968    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 5969        let selections = self.selections.all::<Point>(cx);
 5970        let buffer = self.buffer.read(cx).read(cx);
 5971        let mut text = String::new();
 5972
 5973        let mut clipboard_selections = Vec::with_capacity(selections.len());
 5974        {
 5975            let max_point = buffer.max_point();
 5976            let mut is_first = true;
 5977            for selection in selections.iter() {
 5978                let mut start = selection.start;
 5979                let mut end = selection.end;
 5980                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 5981                if is_entire_line {
 5982                    start = Point::new(start.row, 0);
 5983                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 5984                }
 5985                if is_first {
 5986                    is_first = false;
 5987                } else {
 5988                    text += "\n";
 5989                }
 5990                let mut len = 0;
 5991                for chunk in buffer.text_for_range(start..end) {
 5992                    text.push_str(chunk);
 5993                    len += chunk.len();
 5994                }
 5995                clipboard_selections.push(ClipboardSelection {
 5996                    len,
 5997                    is_entire_line,
 5998                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 5999                });
 6000            }
 6001        }
 6002
 6003        cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
 6004    }
 6005
 6006    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 6007        if self.read_only(cx) {
 6008            return;
 6009        }
 6010
 6011        self.transact(cx, |this, cx| {
 6012            if let Some(item) = cx.read_from_clipboard() {
 6013                let clipboard_text = Cow::Borrowed(item.text());
 6014                if let Some(mut clipboard_selections) = item.metadata::<Vec<ClipboardSelection>>() {
 6015                    let old_selections = this.selections.all::<usize>(cx);
 6016                    let all_selections_were_entire_line =
 6017                        clipboard_selections.iter().all(|s| s.is_entire_line);
 6018                    let first_selection_indent_column =
 6019                        clipboard_selections.first().map(|s| s.first_line_indent);
 6020                    if clipboard_selections.len() != old_selections.len() {
 6021                        clipboard_selections.drain(..);
 6022                    }
 6023
 6024                    this.buffer.update(cx, |buffer, cx| {
 6025                        let snapshot = buffer.read(cx);
 6026                        let mut start_offset = 0;
 6027                        let mut edits = Vec::new();
 6028                        let mut original_indent_columns = Vec::new();
 6029                        let line_mode = this.selections.line_mode;
 6030                        for (ix, selection) in old_selections.iter().enumerate() {
 6031                            let to_insert;
 6032                            let entire_line;
 6033                            let original_indent_column;
 6034                            if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 6035                                let end_offset = start_offset + clipboard_selection.len;
 6036                                to_insert = &clipboard_text[start_offset..end_offset];
 6037                                entire_line = clipboard_selection.is_entire_line;
 6038                                start_offset = end_offset + 1;
 6039                                original_indent_column =
 6040                                    Some(clipboard_selection.first_line_indent);
 6041                            } else {
 6042                                to_insert = clipboard_text.as_str();
 6043                                entire_line = all_selections_were_entire_line;
 6044                                original_indent_column = first_selection_indent_column
 6045                            }
 6046
 6047                            // If the corresponding selection was empty when this slice of the
 6048                            // clipboard text was written, then the entire line containing the
 6049                            // selection was copied. If this selection is also currently empty,
 6050                            // then paste the line before the current line of the buffer.
 6051                            let range = if selection.is_empty() && !line_mode && entire_line {
 6052                                let column = selection.start.to_point(&snapshot).column as usize;
 6053                                let line_start = selection.start - column;
 6054                                line_start..line_start
 6055                            } else {
 6056                                selection.range()
 6057                            };
 6058
 6059                            edits.push((range, to_insert));
 6060                            original_indent_columns.extend(original_indent_column);
 6061                        }
 6062                        drop(snapshot);
 6063
 6064                        buffer.edit(
 6065                            edits,
 6066                            Some(AutoindentMode::Block {
 6067                                original_indent_columns,
 6068                            }),
 6069                            cx,
 6070                        );
 6071                    });
 6072
 6073                    let selections = this.selections.all::<usize>(cx);
 6074                    this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6075                } else {
 6076                    this.insert(&clipboard_text, cx);
 6077                }
 6078            }
 6079        });
 6080    }
 6081
 6082    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 6083        if self.read_only(cx) {
 6084            return;
 6085        }
 6086
 6087        if let Some(tx_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 6088            if let Some((selections, _)) = self.selection_history.transaction(tx_id).cloned() {
 6089                self.change_selections(None, cx, |s| {
 6090                    s.select_anchors(selections.to_vec());
 6091                });
 6092            }
 6093            self.request_autoscroll(Autoscroll::fit(), cx);
 6094            self.unmark_text(cx);
 6095            self.refresh_inline_completion(true, cx);
 6096            cx.emit(EditorEvent::Edited);
 6097            cx.emit(EditorEvent::TransactionUndone {
 6098                transaction_id: tx_id,
 6099            });
 6100        }
 6101    }
 6102
 6103    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 6104        if self.read_only(cx) {
 6105            return;
 6106        }
 6107
 6108        if let Some(tx_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 6109            if let Some((_, Some(selections))) = self.selection_history.transaction(tx_id).cloned()
 6110            {
 6111                self.change_selections(None, cx, |s| {
 6112                    s.select_anchors(selections.to_vec());
 6113                });
 6114            }
 6115            self.request_autoscroll(Autoscroll::fit(), cx);
 6116            self.unmark_text(cx);
 6117            self.refresh_inline_completion(true, cx);
 6118            cx.emit(EditorEvent::Edited);
 6119        }
 6120    }
 6121
 6122    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 6123        self.buffer
 6124            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 6125    }
 6126
 6127    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 6128        self.buffer
 6129            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 6130    }
 6131
 6132    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 6133        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6134            let line_mode = s.line_mode;
 6135            s.move_with(|map, selection| {
 6136                let cursor = if selection.is_empty() && !line_mode {
 6137                    movement::left(map, selection.start)
 6138                } else {
 6139                    selection.start
 6140                };
 6141                selection.collapse_to(cursor, SelectionGoal::None);
 6142            });
 6143        })
 6144    }
 6145
 6146    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 6147        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6148            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 6149        })
 6150    }
 6151
 6152    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 6153        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6154            let line_mode = s.line_mode;
 6155            s.move_with(|map, selection| {
 6156                let cursor = if selection.is_empty() && !line_mode {
 6157                    movement::right(map, selection.end)
 6158                } else {
 6159                    selection.end
 6160                };
 6161                selection.collapse_to(cursor, SelectionGoal::None)
 6162            });
 6163        })
 6164    }
 6165
 6166    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 6167        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6168            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 6169        })
 6170    }
 6171
 6172    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 6173        if self.take_rename(true, cx).is_some() {
 6174            return;
 6175        }
 6176
 6177        if matches!(self.mode, EditorMode::SingleLine) {
 6178            cx.propagate();
 6179            return;
 6180        }
 6181
 6182        let text_layout_details = &self.text_layout_details(cx);
 6183
 6184        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6185            let line_mode = s.line_mode;
 6186            s.move_with(|map, selection| {
 6187                if !selection.is_empty() && !line_mode {
 6188                    selection.goal = SelectionGoal::None;
 6189                }
 6190                let (cursor, goal) = movement::up(
 6191                    map,
 6192                    selection.start,
 6193                    selection.goal,
 6194                    false,
 6195                    &text_layout_details,
 6196                );
 6197                selection.collapse_to(cursor, goal);
 6198            });
 6199        })
 6200    }
 6201
 6202    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 6203        if self.take_rename(true, cx).is_some() {
 6204            return;
 6205        }
 6206
 6207        if matches!(self.mode, EditorMode::SingleLine) {
 6208            cx.propagate();
 6209            return;
 6210        }
 6211
 6212        let text_layout_details = &self.text_layout_details(cx);
 6213
 6214        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6215            let line_mode = s.line_mode;
 6216            s.move_with(|map, selection| {
 6217                if !selection.is_empty() && !line_mode {
 6218                    selection.goal = SelectionGoal::None;
 6219                }
 6220                let (cursor, goal) = movement::up_by_rows(
 6221                    map,
 6222                    selection.start,
 6223                    action.lines,
 6224                    selection.goal,
 6225                    false,
 6226                    &text_layout_details,
 6227                );
 6228                selection.collapse_to(cursor, goal);
 6229            });
 6230        })
 6231    }
 6232
 6233    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 6234        if self.take_rename(true, cx).is_some() {
 6235            return;
 6236        }
 6237
 6238        if matches!(self.mode, EditorMode::SingleLine) {
 6239            cx.propagate();
 6240            return;
 6241        }
 6242
 6243        let text_layout_details = &self.text_layout_details(cx);
 6244
 6245        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6246            let line_mode = s.line_mode;
 6247            s.move_with(|map, selection| {
 6248                if !selection.is_empty() && !line_mode {
 6249                    selection.goal = SelectionGoal::None;
 6250                }
 6251                let (cursor, goal) = movement::down_by_rows(
 6252                    map,
 6253                    selection.start,
 6254                    action.lines,
 6255                    selection.goal,
 6256                    false,
 6257                    &text_layout_details,
 6258                );
 6259                selection.collapse_to(cursor, goal);
 6260            });
 6261        })
 6262    }
 6263
 6264    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 6265        let text_layout_details = &self.text_layout_details(cx);
 6266        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6267            s.move_heads_with(|map, head, goal| {
 6268                movement::down_by_rows(map, head, action.lines, goal, false, &text_layout_details)
 6269            })
 6270        })
 6271    }
 6272
 6273    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 6274        let text_layout_details = &self.text_layout_details(cx);
 6275        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6276            s.move_heads_with(|map, head, goal| {
 6277                movement::up_by_rows(map, head, action.lines, goal, false, &text_layout_details)
 6278            })
 6279        })
 6280    }
 6281
 6282    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 6283        if self.take_rename(true, cx).is_some() {
 6284            return;
 6285        }
 6286
 6287        if matches!(self.mode, EditorMode::SingleLine) {
 6288            cx.propagate();
 6289            return;
 6290        }
 6291
 6292        let row_count = if let Some(row_count) = self.visible_line_count() {
 6293            row_count as u32 - 1
 6294        } else {
 6295            return;
 6296        };
 6297
 6298        let autoscroll = if action.center_cursor {
 6299            Autoscroll::center()
 6300        } else {
 6301            Autoscroll::fit()
 6302        };
 6303
 6304        let text_layout_details = &self.text_layout_details(cx);
 6305
 6306        self.change_selections(Some(autoscroll), cx, |s| {
 6307            let line_mode = s.line_mode;
 6308            s.move_with(|map, selection| {
 6309                if !selection.is_empty() && !line_mode {
 6310                    selection.goal = SelectionGoal::None;
 6311                }
 6312                let (cursor, goal) = movement::up_by_rows(
 6313                    map,
 6314                    selection.end,
 6315                    row_count,
 6316                    selection.goal,
 6317                    false,
 6318                    &text_layout_details,
 6319                );
 6320                selection.collapse_to(cursor, goal);
 6321            });
 6322        });
 6323    }
 6324
 6325    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 6326        let text_layout_details = &self.text_layout_details(cx);
 6327        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6328            s.move_heads_with(|map, head, goal| {
 6329                movement::up(map, head, goal, false, &text_layout_details)
 6330            })
 6331        })
 6332    }
 6333
 6334    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 6335        self.take_rename(true, cx);
 6336
 6337        if self.mode == EditorMode::SingleLine {
 6338            cx.propagate();
 6339            return;
 6340        }
 6341
 6342        let text_layout_details = &self.text_layout_details(cx);
 6343        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6344            let line_mode = s.line_mode;
 6345            s.move_with(|map, selection| {
 6346                if !selection.is_empty() && !line_mode {
 6347                    selection.goal = SelectionGoal::None;
 6348                }
 6349                let (cursor, goal) = movement::down(
 6350                    map,
 6351                    selection.end,
 6352                    selection.goal,
 6353                    false,
 6354                    &text_layout_details,
 6355                );
 6356                selection.collapse_to(cursor, goal);
 6357            });
 6358        });
 6359    }
 6360
 6361    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 6362        if self.take_rename(true, cx).is_some() {
 6363            return;
 6364        }
 6365
 6366        if self
 6367            .context_menu
 6368            .write()
 6369            .as_mut()
 6370            .map(|menu| menu.select_last(self.project.as_ref(), cx))
 6371            .unwrap_or(false)
 6372        {
 6373            return;
 6374        }
 6375
 6376        if matches!(self.mode, EditorMode::SingleLine) {
 6377            cx.propagate();
 6378            return;
 6379        }
 6380
 6381        let row_count = if let Some(row_count) = self.visible_line_count() {
 6382            row_count as u32 - 1
 6383        } else {
 6384            return;
 6385        };
 6386
 6387        let autoscroll = if action.center_cursor {
 6388            Autoscroll::center()
 6389        } else {
 6390            Autoscroll::fit()
 6391        };
 6392
 6393        let text_layout_details = &self.text_layout_details(cx);
 6394        self.change_selections(Some(autoscroll), cx, |s| {
 6395            let line_mode = s.line_mode;
 6396            s.move_with(|map, selection| {
 6397                if !selection.is_empty() && !line_mode {
 6398                    selection.goal = SelectionGoal::None;
 6399                }
 6400                let (cursor, goal) = movement::down_by_rows(
 6401                    map,
 6402                    selection.end,
 6403                    row_count,
 6404                    selection.goal,
 6405                    false,
 6406                    &text_layout_details,
 6407                );
 6408                selection.collapse_to(cursor, goal);
 6409            });
 6410        });
 6411    }
 6412
 6413    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 6414        let text_layout_details = &self.text_layout_details(cx);
 6415        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6416            s.move_heads_with(|map, head, goal| {
 6417                movement::down(map, head, goal, false, &text_layout_details)
 6418            })
 6419        });
 6420    }
 6421
 6422    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 6423        if let Some(context_menu) = self.context_menu.write().as_mut() {
 6424            context_menu.select_first(self.project.as_ref(), cx);
 6425        }
 6426    }
 6427
 6428    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 6429        if let Some(context_menu) = self.context_menu.write().as_mut() {
 6430            context_menu.select_prev(self.project.as_ref(), cx);
 6431        }
 6432    }
 6433
 6434    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 6435        if let Some(context_menu) = self.context_menu.write().as_mut() {
 6436            context_menu.select_next(self.project.as_ref(), cx);
 6437        }
 6438    }
 6439
 6440    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 6441        if let Some(context_menu) = self.context_menu.write().as_mut() {
 6442            context_menu.select_last(self.project.as_ref(), cx);
 6443        }
 6444    }
 6445
 6446    pub fn move_to_previous_word_start(
 6447        &mut self,
 6448        _: &MoveToPreviousWordStart,
 6449        cx: &mut ViewContext<Self>,
 6450    ) {
 6451        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6452            s.move_cursors_with(|map, head, _| {
 6453                (
 6454                    movement::previous_word_start(map, head),
 6455                    SelectionGoal::None,
 6456                )
 6457            });
 6458        })
 6459    }
 6460
 6461    pub fn move_to_previous_subword_start(
 6462        &mut self,
 6463        _: &MoveToPreviousSubwordStart,
 6464        cx: &mut ViewContext<Self>,
 6465    ) {
 6466        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6467            s.move_cursors_with(|map, head, _| {
 6468                (
 6469                    movement::previous_subword_start(map, head),
 6470                    SelectionGoal::None,
 6471                )
 6472            });
 6473        })
 6474    }
 6475
 6476    pub fn select_to_previous_word_start(
 6477        &mut self,
 6478        _: &SelectToPreviousWordStart,
 6479        cx: &mut ViewContext<Self>,
 6480    ) {
 6481        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6482            s.move_heads_with(|map, head, _| {
 6483                (
 6484                    movement::previous_word_start(map, head),
 6485                    SelectionGoal::None,
 6486                )
 6487            });
 6488        })
 6489    }
 6490
 6491    pub fn select_to_previous_subword_start(
 6492        &mut self,
 6493        _: &SelectToPreviousSubwordStart,
 6494        cx: &mut ViewContext<Self>,
 6495    ) {
 6496        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6497            s.move_heads_with(|map, head, _| {
 6498                (
 6499                    movement::previous_subword_start(map, head),
 6500                    SelectionGoal::None,
 6501                )
 6502            });
 6503        })
 6504    }
 6505
 6506    pub fn delete_to_previous_word_start(
 6507        &mut self,
 6508        _: &DeleteToPreviousWordStart,
 6509        cx: &mut ViewContext<Self>,
 6510    ) {
 6511        self.transact(cx, |this, cx| {
 6512            this.select_autoclose_pair(cx);
 6513            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6514                let line_mode = s.line_mode;
 6515                s.move_with(|map, selection| {
 6516                    if selection.is_empty() && !line_mode {
 6517                        let cursor = movement::previous_word_start(map, selection.head());
 6518                        selection.set_head(cursor, SelectionGoal::None);
 6519                    }
 6520                });
 6521            });
 6522            this.insert("", cx);
 6523        });
 6524    }
 6525
 6526    pub fn delete_to_previous_subword_start(
 6527        &mut self,
 6528        _: &DeleteToPreviousSubwordStart,
 6529        cx: &mut ViewContext<Self>,
 6530    ) {
 6531        self.transact(cx, |this, cx| {
 6532            this.select_autoclose_pair(cx);
 6533            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6534                let line_mode = s.line_mode;
 6535                s.move_with(|map, selection| {
 6536                    if selection.is_empty() && !line_mode {
 6537                        let cursor = movement::previous_subword_start(map, selection.head());
 6538                        selection.set_head(cursor, SelectionGoal::None);
 6539                    }
 6540                });
 6541            });
 6542            this.insert("", cx);
 6543        });
 6544    }
 6545
 6546    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 6547        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6548            s.move_cursors_with(|map, head, _| {
 6549                (movement::next_word_end(map, head), SelectionGoal::None)
 6550            });
 6551        })
 6552    }
 6553
 6554    pub fn move_to_next_subword_end(
 6555        &mut self,
 6556        _: &MoveToNextSubwordEnd,
 6557        cx: &mut ViewContext<Self>,
 6558    ) {
 6559        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6560            s.move_cursors_with(|map, head, _| {
 6561                (movement::next_subword_end(map, head), SelectionGoal::None)
 6562            });
 6563        })
 6564    }
 6565
 6566    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 6567        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6568            s.move_heads_with(|map, head, _| {
 6569                (movement::next_word_end(map, head), SelectionGoal::None)
 6570            });
 6571        })
 6572    }
 6573
 6574    pub fn select_to_next_subword_end(
 6575        &mut self,
 6576        _: &SelectToNextSubwordEnd,
 6577        cx: &mut ViewContext<Self>,
 6578    ) {
 6579        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6580            s.move_heads_with(|map, head, _| {
 6581                (movement::next_subword_end(map, head), SelectionGoal::None)
 6582            });
 6583        })
 6584    }
 6585
 6586    pub fn delete_to_next_word_end(&mut self, _: &DeleteToNextWordEnd, cx: &mut ViewContext<Self>) {
 6587        self.transact(cx, |this, cx| {
 6588            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6589                let line_mode = s.line_mode;
 6590                s.move_with(|map, selection| {
 6591                    if selection.is_empty() && !line_mode {
 6592                        let cursor = movement::next_word_end(map, selection.head());
 6593                        selection.set_head(cursor, SelectionGoal::None);
 6594                    }
 6595                });
 6596            });
 6597            this.insert("", cx);
 6598        });
 6599    }
 6600
 6601    pub fn delete_to_next_subword_end(
 6602        &mut self,
 6603        _: &DeleteToNextSubwordEnd,
 6604        cx: &mut ViewContext<Self>,
 6605    ) {
 6606        self.transact(cx, |this, cx| {
 6607            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6608                s.move_with(|map, selection| {
 6609                    if selection.is_empty() {
 6610                        let cursor = movement::next_subword_end(map, selection.head());
 6611                        selection.set_head(cursor, SelectionGoal::None);
 6612                    }
 6613                });
 6614            });
 6615            this.insert("", cx);
 6616        });
 6617    }
 6618
 6619    pub fn move_to_beginning_of_line(
 6620        &mut self,
 6621        action: &MoveToBeginningOfLine,
 6622        cx: &mut ViewContext<Self>,
 6623    ) {
 6624        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6625            s.move_cursors_with(|map, head, _| {
 6626                (
 6627                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 6628                    SelectionGoal::None,
 6629                )
 6630            });
 6631        })
 6632    }
 6633
 6634    pub fn select_to_beginning_of_line(
 6635        &mut self,
 6636        action: &SelectToBeginningOfLine,
 6637        cx: &mut ViewContext<Self>,
 6638    ) {
 6639        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6640            s.move_heads_with(|map, head, _| {
 6641                (
 6642                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 6643                    SelectionGoal::None,
 6644                )
 6645            });
 6646        });
 6647    }
 6648
 6649    pub fn delete_to_beginning_of_line(
 6650        &mut self,
 6651        _: &DeleteToBeginningOfLine,
 6652        cx: &mut ViewContext<Self>,
 6653    ) {
 6654        self.transact(cx, |this, cx| {
 6655            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6656                s.move_with(|_, selection| {
 6657                    selection.reversed = true;
 6658                });
 6659            });
 6660
 6661            this.select_to_beginning_of_line(
 6662                &SelectToBeginningOfLine {
 6663                    stop_at_soft_wraps: false,
 6664                },
 6665                cx,
 6666            );
 6667            this.backspace(&Backspace, cx);
 6668        });
 6669    }
 6670
 6671    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 6672        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6673            s.move_cursors_with(|map, head, _| {
 6674                (
 6675                    movement::line_end(map, head, action.stop_at_soft_wraps),
 6676                    SelectionGoal::None,
 6677                )
 6678            });
 6679        })
 6680    }
 6681
 6682    pub fn select_to_end_of_line(
 6683        &mut self,
 6684        action: &SelectToEndOfLine,
 6685        cx: &mut ViewContext<Self>,
 6686    ) {
 6687        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6688            s.move_heads_with(|map, head, _| {
 6689                (
 6690                    movement::line_end(map, head, action.stop_at_soft_wraps),
 6691                    SelectionGoal::None,
 6692                )
 6693            });
 6694        })
 6695    }
 6696
 6697    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 6698        self.transact(cx, |this, cx| {
 6699            this.select_to_end_of_line(
 6700                &SelectToEndOfLine {
 6701                    stop_at_soft_wraps: false,
 6702                },
 6703                cx,
 6704            );
 6705            this.delete(&Delete, cx);
 6706        });
 6707    }
 6708
 6709    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 6710        self.transact(cx, |this, cx| {
 6711            this.select_to_end_of_line(
 6712                &SelectToEndOfLine {
 6713                    stop_at_soft_wraps: false,
 6714                },
 6715                cx,
 6716            );
 6717            this.cut(&Cut, cx);
 6718        });
 6719    }
 6720
 6721    pub fn move_to_start_of_paragraph(
 6722        &mut self,
 6723        _: &MoveToStartOfParagraph,
 6724        cx: &mut ViewContext<Self>,
 6725    ) {
 6726        if matches!(self.mode, EditorMode::SingleLine) {
 6727            cx.propagate();
 6728            return;
 6729        }
 6730
 6731        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6732            s.move_with(|map, selection| {
 6733                selection.collapse_to(
 6734                    movement::start_of_paragraph(map, selection.head(), 1),
 6735                    SelectionGoal::None,
 6736                )
 6737            });
 6738        })
 6739    }
 6740
 6741    pub fn move_to_end_of_paragraph(
 6742        &mut self,
 6743        _: &MoveToEndOfParagraph,
 6744        cx: &mut ViewContext<Self>,
 6745    ) {
 6746        if matches!(self.mode, EditorMode::SingleLine) {
 6747            cx.propagate();
 6748            return;
 6749        }
 6750
 6751        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6752            s.move_with(|map, selection| {
 6753                selection.collapse_to(
 6754                    movement::end_of_paragraph(map, selection.head(), 1),
 6755                    SelectionGoal::None,
 6756                )
 6757            });
 6758        })
 6759    }
 6760
 6761    pub fn select_to_start_of_paragraph(
 6762        &mut self,
 6763        _: &SelectToStartOfParagraph,
 6764        cx: &mut ViewContext<Self>,
 6765    ) {
 6766        if matches!(self.mode, EditorMode::SingleLine) {
 6767            cx.propagate();
 6768            return;
 6769        }
 6770
 6771        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6772            s.move_heads_with(|map, head, _| {
 6773                (
 6774                    movement::start_of_paragraph(map, head, 1),
 6775                    SelectionGoal::None,
 6776                )
 6777            });
 6778        })
 6779    }
 6780
 6781    pub fn select_to_end_of_paragraph(
 6782        &mut self,
 6783        _: &SelectToEndOfParagraph,
 6784        cx: &mut ViewContext<Self>,
 6785    ) {
 6786        if matches!(self.mode, EditorMode::SingleLine) {
 6787            cx.propagate();
 6788            return;
 6789        }
 6790
 6791        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6792            s.move_heads_with(|map, head, _| {
 6793                (
 6794                    movement::end_of_paragraph(map, head, 1),
 6795                    SelectionGoal::None,
 6796                )
 6797            });
 6798        })
 6799    }
 6800
 6801    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 6802        if matches!(self.mode, EditorMode::SingleLine) {
 6803            cx.propagate();
 6804            return;
 6805        }
 6806
 6807        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6808            s.select_ranges(vec![0..0]);
 6809        });
 6810    }
 6811
 6812    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 6813        let mut selection = self.selections.last::<Point>(cx);
 6814        selection.set_head(Point::zero(), SelectionGoal::None);
 6815
 6816        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6817            s.select(vec![selection]);
 6818        });
 6819    }
 6820
 6821    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 6822        if matches!(self.mode, EditorMode::SingleLine) {
 6823            cx.propagate();
 6824            return;
 6825        }
 6826
 6827        let cursor = self.buffer.read(cx).read(cx).len();
 6828        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6829            s.select_ranges(vec![cursor..cursor])
 6830        });
 6831    }
 6832
 6833    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 6834        self.nav_history = nav_history;
 6835    }
 6836
 6837    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 6838        self.nav_history.as_ref()
 6839    }
 6840
 6841    fn push_to_nav_history(
 6842        &mut self,
 6843        cursor_anchor: Anchor,
 6844        new_position: Option<Point>,
 6845        cx: &mut ViewContext<Self>,
 6846    ) {
 6847        if let Some(nav_history) = self.nav_history.as_mut() {
 6848            let buffer = self.buffer.read(cx).read(cx);
 6849            let cursor_position = cursor_anchor.to_point(&buffer);
 6850            let scroll_state = self.scroll_manager.anchor();
 6851            let scroll_top_row = scroll_state.top_row(&buffer);
 6852            drop(buffer);
 6853
 6854            if let Some(new_position) = new_position {
 6855                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 6856                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 6857                    return;
 6858                }
 6859            }
 6860
 6861            nav_history.push(
 6862                Some(NavigationData {
 6863                    cursor_anchor,
 6864                    cursor_position,
 6865                    scroll_anchor: scroll_state,
 6866                    scroll_top_row,
 6867                }),
 6868                cx,
 6869            );
 6870        }
 6871    }
 6872
 6873    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 6874        let buffer = self.buffer.read(cx).snapshot(cx);
 6875        let mut selection = self.selections.first::<usize>(cx);
 6876        selection.set_head(buffer.len(), SelectionGoal::None);
 6877        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6878            s.select(vec![selection]);
 6879        });
 6880    }
 6881
 6882    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 6883        let end = self.buffer.read(cx).read(cx).len();
 6884        self.change_selections(None, cx, |s| {
 6885            s.select_ranges(vec![0..end]);
 6886        });
 6887    }
 6888
 6889    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 6890        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6891        let mut selections = self.selections.all::<Point>(cx);
 6892        let max_point = display_map.buffer_snapshot.max_point();
 6893        for selection in &mut selections {
 6894            let rows = selection.spanned_rows(true, &display_map);
 6895            selection.start = Point::new(rows.start.0, 0);
 6896            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 6897            selection.reversed = false;
 6898        }
 6899        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6900            s.select(selections);
 6901        });
 6902    }
 6903
 6904    pub fn split_selection_into_lines(
 6905        &mut self,
 6906        _: &SplitSelectionIntoLines,
 6907        cx: &mut ViewContext<Self>,
 6908    ) {
 6909        let mut to_unfold = Vec::new();
 6910        let mut new_selection_ranges = Vec::new();
 6911        {
 6912            let selections = self.selections.all::<Point>(cx);
 6913            let buffer = self.buffer.read(cx).read(cx);
 6914            for selection in selections {
 6915                for row in selection.start.row..selection.end.row {
 6916                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 6917                    new_selection_ranges.push(cursor..cursor);
 6918                }
 6919                new_selection_ranges.push(selection.end..selection.end);
 6920                to_unfold.push(selection.start..selection.end);
 6921            }
 6922        }
 6923        self.unfold_ranges(to_unfold, true, true, cx);
 6924        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6925            s.select_ranges(new_selection_ranges);
 6926        });
 6927    }
 6928
 6929    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 6930        self.add_selection(true, cx);
 6931    }
 6932
 6933    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 6934        self.add_selection(false, cx);
 6935    }
 6936
 6937    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 6938        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6939        let mut selections = self.selections.all::<Point>(cx);
 6940        let text_layout_details = self.text_layout_details(cx);
 6941        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 6942            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 6943            let range = oldest_selection.display_range(&display_map).sorted();
 6944
 6945            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 6946            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 6947            let positions = start_x.min(end_x)..start_x.max(end_x);
 6948
 6949            selections.clear();
 6950            let mut stack = Vec::new();
 6951            for row in range.start.row().0..=range.end.row().0 {
 6952                if let Some(selection) = self.selections.build_columnar_selection(
 6953                    &display_map,
 6954                    DisplayRow(row),
 6955                    &positions,
 6956                    oldest_selection.reversed,
 6957                    &text_layout_details,
 6958                ) {
 6959                    stack.push(selection.id);
 6960                    selections.push(selection);
 6961                }
 6962            }
 6963
 6964            if above {
 6965                stack.reverse();
 6966            }
 6967
 6968            AddSelectionsState { above, stack }
 6969        });
 6970
 6971        let last_added_selection = *state.stack.last().unwrap();
 6972        let mut new_selections = Vec::new();
 6973        if above == state.above {
 6974            let end_row = if above {
 6975                DisplayRow(0)
 6976            } else {
 6977                display_map.max_point().row()
 6978            };
 6979
 6980            'outer: for selection in selections {
 6981                if selection.id == last_added_selection {
 6982                    let range = selection.display_range(&display_map).sorted();
 6983                    debug_assert_eq!(range.start.row(), range.end.row());
 6984                    let mut row = range.start.row();
 6985                    let positions =
 6986                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 6987                            px(start)..px(end)
 6988                        } else {
 6989                            let start_x =
 6990                                display_map.x_for_display_point(range.start, &text_layout_details);
 6991                            let end_x =
 6992                                display_map.x_for_display_point(range.end, &text_layout_details);
 6993                            start_x.min(end_x)..start_x.max(end_x)
 6994                        };
 6995
 6996                    while row != end_row {
 6997                        if above {
 6998                            row.0 -= 1;
 6999                        } else {
 7000                            row.0 += 1;
 7001                        }
 7002
 7003                        if let Some(new_selection) = self.selections.build_columnar_selection(
 7004                            &display_map,
 7005                            row,
 7006                            &positions,
 7007                            selection.reversed,
 7008                            &text_layout_details,
 7009                        ) {
 7010                            state.stack.push(new_selection.id);
 7011                            if above {
 7012                                new_selections.push(new_selection);
 7013                                new_selections.push(selection);
 7014                            } else {
 7015                                new_selections.push(selection);
 7016                                new_selections.push(new_selection);
 7017                            }
 7018
 7019                            continue 'outer;
 7020                        }
 7021                    }
 7022                }
 7023
 7024                new_selections.push(selection);
 7025            }
 7026        } else {
 7027            new_selections = selections;
 7028            new_selections.retain(|s| s.id != last_added_selection);
 7029            state.stack.pop();
 7030        }
 7031
 7032        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7033            s.select(new_selections);
 7034        });
 7035        if state.stack.len() > 1 {
 7036            self.add_selections_state = Some(state);
 7037        }
 7038    }
 7039
 7040    pub fn select_next_match_internal(
 7041        &mut self,
 7042        display_map: &DisplaySnapshot,
 7043        replace_newest: bool,
 7044        autoscroll: Option<Autoscroll>,
 7045        cx: &mut ViewContext<Self>,
 7046    ) -> Result<()> {
 7047        fn select_next_match_ranges(
 7048            this: &mut Editor,
 7049            range: Range<usize>,
 7050            replace_newest: bool,
 7051            auto_scroll: Option<Autoscroll>,
 7052            cx: &mut ViewContext<Editor>,
 7053        ) {
 7054            this.unfold_ranges([range.clone()], false, true, cx);
 7055            this.change_selections(auto_scroll, cx, |s| {
 7056                if replace_newest {
 7057                    s.delete(s.newest_anchor().id);
 7058                }
 7059                s.insert_range(range.clone());
 7060            });
 7061        }
 7062
 7063        let buffer = &display_map.buffer_snapshot;
 7064        let mut selections = self.selections.all::<usize>(cx);
 7065        if let Some(mut select_next_state) = self.select_next_state.take() {
 7066            let query = &select_next_state.query;
 7067            if !select_next_state.done {
 7068                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 7069                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 7070                let mut next_selected_range = None;
 7071
 7072                let bytes_after_last_selection =
 7073                    buffer.bytes_in_range(last_selection.end..buffer.len());
 7074                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 7075                let query_matches = query
 7076                    .stream_find_iter(bytes_after_last_selection)
 7077                    .map(|result| (last_selection.end, result))
 7078                    .chain(
 7079                        query
 7080                            .stream_find_iter(bytes_before_first_selection)
 7081                            .map(|result| (0, result)),
 7082                    );
 7083
 7084                for (start_offset, query_match) in query_matches {
 7085                    let query_match = query_match.unwrap(); // can only fail due to I/O
 7086                    let offset_range =
 7087                        start_offset + query_match.start()..start_offset + query_match.end();
 7088                    let display_range = offset_range.start.to_display_point(&display_map)
 7089                        ..offset_range.end.to_display_point(&display_map);
 7090
 7091                    if !select_next_state.wordwise
 7092                        || (!movement::is_inside_word(&display_map, display_range.start)
 7093                            && !movement::is_inside_word(&display_map, display_range.end))
 7094                    {
 7095                        // TODO: This is n^2, because we might check all the selections
 7096                        if !selections
 7097                            .iter()
 7098                            .any(|selection| selection.range().overlaps(&offset_range))
 7099                        {
 7100                            next_selected_range = Some(offset_range);
 7101                            break;
 7102                        }
 7103                    }
 7104                }
 7105
 7106                if let Some(next_selected_range) = next_selected_range {
 7107                    select_next_match_ranges(
 7108                        self,
 7109                        next_selected_range,
 7110                        replace_newest,
 7111                        autoscroll,
 7112                        cx,
 7113                    );
 7114                } else {
 7115                    select_next_state.done = true;
 7116                }
 7117            }
 7118
 7119            self.select_next_state = Some(select_next_state);
 7120        } else {
 7121            let mut only_carets = true;
 7122            let mut same_text_selected = true;
 7123            let mut selected_text = None;
 7124
 7125            let mut selections_iter = selections.iter().peekable();
 7126            while let Some(selection) = selections_iter.next() {
 7127                if selection.start != selection.end {
 7128                    only_carets = false;
 7129                }
 7130
 7131                if same_text_selected {
 7132                    if selected_text.is_none() {
 7133                        selected_text =
 7134                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 7135                    }
 7136
 7137                    if let Some(next_selection) = selections_iter.peek() {
 7138                        if next_selection.range().len() == selection.range().len() {
 7139                            let next_selected_text = buffer
 7140                                .text_for_range(next_selection.range())
 7141                                .collect::<String>();
 7142                            if Some(next_selected_text) != selected_text {
 7143                                same_text_selected = false;
 7144                                selected_text = None;
 7145                            }
 7146                        } else {
 7147                            same_text_selected = false;
 7148                            selected_text = None;
 7149                        }
 7150                    }
 7151                }
 7152            }
 7153
 7154            if only_carets {
 7155                for selection in &mut selections {
 7156                    let word_range = movement::surrounding_word(
 7157                        &display_map,
 7158                        selection.start.to_display_point(&display_map),
 7159                    );
 7160                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 7161                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 7162                    selection.goal = SelectionGoal::None;
 7163                    selection.reversed = false;
 7164                    select_next_match_ranges(
 7165                        self,
 7166                        selection.start..selection.end,
 7167                        replace_newest,
 7168                        autoscroll,
 7169                        cx,
 7170                    );
 7171                }
 7172
 7173                if selections.len() == 1 {
 7174                    let selection = selections
 7175                        .last()
 7176                        .expect("ensured that there's only one selection");
 7177                    let query = buffer
 7178                        .text_for_range(selection.start..selection.end)
 7179                        .collect::<String>();
 7180                    let is_empty = query.is_empty();
 7181                    let select_state = SelectNextState {
 7182                        query: AhoCorasick::new(&[query])?,
 7183                        wordwise: true,
 7184                        done: is_empty,
 7185                    };
 7186                    self.select_next_state = Some(select_state);
 7187                } else {
 7188                    self.select_next_state = None;
 7189                }
 7190            } else if let Some(selected_text) = selected_text {
 7191                self.select_next_state = Some(SelectNextState {
 7192                    query: AhoCorasick::new(&[selected_text])?,
 7193                    wordwise: false,
 7194                    done: false,
 7195                });
 7196                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 7197            }
 7198        }
 7199        Ok(())
 7200    }
 7201
 7202    pub fn select_all_matches(
 7203        &mut self,
 7204        _action: &SelectAllMatches,
 7205        cx: &mut ViewContext<Self>,
 7206    ) -> Result<()> {
 7207        self.push_to_selection_history();
 7208        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7209
 7210        self.select_next_match_internal(&display_map, false, None, cx)?;
 7211        let Some(select_next_state) = self.select_next_state.as_mut() else {
 7212            return Ok(());
 7213        };
 7214        if select_next_state.done {
 7215            return Ok(());
 7216        }
 7217
 7218        let mut new_selections = self.selections.all::<usize>(cx);
 7219
 7220        let buffer = &display_map.buffer_snapshot;
 7221        let query_matches = select_next_state
 7222            .query
 7223            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 7224
 7225        for query_match in query_matches {
 7226            let query_match = query_match.unwrap(); // can only fail due to I/O
 7227            let offset_range = query_match.start()..query_match.end();
 7228            let display_range = offset_range.start.to_display_point(&display_map)
 7229                ..offset_range.end.to_display_point(&display_map);
 7230
 7231            if !select_next_state.wordwise
 7232                || (!movement::is_inside_word(&display_map, display_range.start)
 7233                    && !movement::is_inside_word(&display_map, display_range.end))
 7234            {
 7235                self.selections.change_with(cx, |selections| {
 7236                    new_selections.push(Selection {
 7237                        id: selections.new_selection_id(),
 7238                        start: offset_range.start,
 7239                        end: offset_range.end,
 7240                        reversed: false,
 7241                        goal: SelectionGoal::None,
 7242                    });
 7243                });
 7244            }
 7245        }
 7246
 7247        new_selections.sort_by_key(|selection| selection.start);
 7248        let mut ix = 0;
 7249        while ix + 1 < new_selections.len() {
 7250            let current_selection = &new_selections[ix];
 7251            let next_selection = &new_selections[ix + 1];
 7252            if current_selection.range().overlaps(&next_selection.range()) {
 7253                if current_selection.id < next_selection.id {
 7254                    new_selections.remove(ix + 1);
 7255                } else {
 7256                    new_selections.remove(ix);
 7257                }
 7258            } else {
 7259                ix += 1;
 7260            }
 7261        }
 7262
 7263        select_next_state.done = true;
 7264        self.unfold_ranges(
 7265            new_selections.iter().map(|selection| selection.range()),
 7266            false,
 7267            false,
 7268            cx,
 7269        );
 7270        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 7271            selections.select(new_selections)
 7272        });
 7273
 7274        Ok(())
 7275    }
 7276
 7277    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 7278        self.push_to_selection_history();
 7279        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7280        self.select_next_match_internal(
 7281            &display_map,
 7282            action.replace_newest,
 7283            Some(Autoscroll::newest()),
 7284            cx,
 7285        )?;
 7286        Ok(())
 7287    }
 7288
 7289    pub fn select_previous(
 7290        &mut self,
 7291        action: &SelectPrevious,
 7292        cx: &mut ViewContext<Self>,
 7293    ) -> Result<()> {
 7294        self.push_to_selection_history();
 7295        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7296        let buffer = &display_map.buffer_snapshot;
 7297        let mut selections = self.selections.all::<usize>(cx);
 7298        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 7299            let query = &select_prev_state.query;
 7300            if !select_prev_state.done {
 7301                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 7302                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 7303                let mut next_selected_range = None;
 7304                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 7305                let bytes_before_last_selection =
 7306                    buffer.reversed_bytes_in_range(0..last_selection.start);
 7307                let bytes_after_first_selection =
 7308                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 7309                let query_matches = query
 7310                    .stream_find_iter(bytes_before_last_selection)
 7311                    .map(|result| (last_selection.start, result))
 7312                    .chain(
 7313                        query
 7314                            .stream_find_iter(bytes_after_first_selection)
 7315                            .map(|result| (buffer.len(), result)),
 7316                    );
 7317                for (end_offset, query_match) in query_matches {
 7318                    let query_match = query_match.unwrap(); // can only fail due to I/O
 7319                    let offset_range =
 7320                        end_offset - query_match.end()..end_offset - query_match.start();
 7321                    let display_range = offset_range.start.to_display_point(&display_map)
 7322                        ..offset_range.end.to_display_point(&display_map);
 7323
 7324                    if !select_prev_state.wordwise
 7325                        || (!movement::is_inside_word(&display_map, display_range.start)
 7326                            && !movement::is_inside_word(&display_map, display_range.end))
 7327                    {
 7328                        next_selected_range = Some(offset_range);
 7329                        break;
 7330                    }
 7331                }
 7332
 7333                if let Some(next_selected_range) = next_selected_range {
 7334                    self.unfold_ranges([next_selected_range.clone()], false, true, cx);
 7335                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 7336                        if action.replace_newest {
 7337                            s.delete(s.newest_anchor().id);
 7338                        }
 7339                        s.insert_range(next_selected_range);
 7340                    });
 7341                } else {
 7342                    select_prev_state.done = true;
 7343                }
 7344            }
 7345
 7346            self.select_prev_state = Some(select_prev_state);
 7347        } else {
 7348            let mut only_carets = true;
 7349            let mut same_text_selected = true;
 7350            let mut selected_text = None;
 7351
 7352            let mut selections_iter = selections.iter().peekable();
 7353            while let Some(selection) = selections_iter.next() {
 7354                if selection.start != selection.end {
 7355                    only_carets = false;
 7356                }
 7357
 7358                if same_text_selected {
 7359                    if selected_text.is_none() {
 7360                        selected_text =
 7361                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 7362                    }
 7363
 7364                    if let Some(next_selection) = selections_iter.peek() {
 7365                        if next_selection.range().len() == selection.range().len() {
 7366                            let next_selected_text = buffer
 7367                                .text_for_range(next_selection.range())
 7368                                .collect::<String>();
 7369                            if Some(next_selected_text) != selected_text {
 7370                                same_text_selected = false;
 7371                                selected_text = None;
 7372                            }
 7373                        } else {
 7374                            same_text_selected = false;
 7375                            selected_text = None;
 7376                        }
 7377                    }
 7378                }
 7379            }
 7380
 7381            if only_carets {
 7382                for selection in &mut selections {
 7383                    let word_range = movement::surrounding_word(
 7384                        &display_map,
 7385                        selection.start.to_display_point(&display_map),
 7386                    );
 7387                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 7388                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 7389                    selection.goal = SelectionGoal::None;
 7390                    selection.reversed = false;
 7391                }
 7392                if selections.len() == 1 {
 7393                    let selection = selections
 7394                        .last()
 7395                        .expect("ensured that there's only one selection");
 7396                    let query = buffer
 7397                        .text_for_range(selection.start..selection.end)
 7398                        .collect::<String>();
 7399                    let is_empty = query.is_empty();
 7400                    let select_state = SelectNextState {
 7401                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 7402                        wordwise: true,
 7403                        done: is_empty,
 7404                    };
 7405                    self.select_prev_state = Some(select_state);
 7406                } else {
 7407                    self.select_prev_state = None;
 7408                }
 7409
 7410                self.unfold_ranges(
 7411                    selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 7412                    false,
 7413                    true,
 7414                    cx,
 7415                );
 7416                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 7417                    s.select(selections);
 7418                });
 7419            } else if let Some(selected_text) = selected_text {
 7420                self.select_prev_state = Some(SelectNextState {
 7421                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 7422                    wordwise: false,
 7423                    done: false,
 7424                });
 7425                self.select_previous(action, cx)?;
 7426            }
 7427        }
 7428        Ok(())
 7429    }
 7430
 7431    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 7432        let text_layout_details = &self.text_layout_details(cx);
 7433        self.transact(cx, |this, cx| {
 7434            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 7435            let mut edits = Vec::new();
 7436            let mut selection_edit_ranges = Vec::new();
 7437            let mut last_toggled_row = None;
 7438            let snapshot = this.buffer.read(cx).read(cx);
 7439            let empty_str: Arc<str> = "".into();
 7440            let mut suffixes_inserted = Vec::new();
 7441
 7442            fn comment_prefix_range(
 7443                snapshot: &MultiBufferSnapshot,
 7444                row: MultiBufferRow,
 7445                comment_prefix: &str,
 7446                comment_prefix_whitespace: &str,
 7447            ) -> Range<Point> {
 7448                let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
 7449
 7450                let mut line_bytes = snapshot
 7451                    .bytes_in_range(start..snapshot.max_point())
 7452                    .flatten()
 7453                    .copied();
 7454
 7455                // If this line currently begins with the line comment prefix, then record
 7456                // the range containing the prefix.
 7457                if line_bytes
 7458                    .by_ref()
 7459                    .take(comment_prefix.len())
 7460                    .eq(comment_prefix.bytes())
 7461                {
 7462                    // Include any whitespace that matches the comment prefix.
 7463                    let matching_whitespace_len = line_bytes
 7464                        .zip(comment_prefix_whitespace.bytes())
 7465                        .take_while(|(a, b)| a == b)
 7466                        .count() as u32;
 7467                    let end = Point::new(
 7468                        start.row,
 7469                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 7470                    );
 7471                    start..end
 7472                } else {
 7473                    start..start
 7474                }
 7475            }
 7476
 7477            fn comment_suffix_range(
 7478                snapshot: &MultiBufferSnapshot,
 7479                row: MultiBufferRow,
 7480                comment_suffix: &str,
 7481                comment_suffix_has_leading_space: bool,
 7482            ) -> Range<Point> {
 7483                let end = Point::new(row.0, snapshot.line_len(row));
 7484                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 7485
 7486                let mut line_end_bytes = snapshot
 7487                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 7488                    .flatten()
 7489                    .copied();
 7490
 7491                let leading_space_len = if suffix_start_column > 0
 7492                    && line_end_bytes.next() == Some(b' ')
 7493                    && comment_suffix_has_leading_space
 7494                {
 7495                    1
 7496                } else {
 7497                    0
 7498                };
 7499
 7500                // If this line currently begins with the line comment prefix, then record
 7501                // the range containing the prefix.
 7502                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 7503                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 7504                    start..end
 7505                } else {
 7506                    end..end
 7507                }
 7508            }
 7509
 7510            // TODO: Handle selections that cross excerpts
 7511            for selection in &mut selections {
 7512                let start_column = snapshot
 7513                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 7514                    .len;
 7515                let language = if let Some(language) =
 7516                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 7517                {
 7518                    language
 7519                } else {
 7520                    continue;
 7521                };
 7522
 7523                selection_edit_ranges.clear();
 7524
 7525                // If multiple selections contain a given row, avoid processing that
 7526                // row more than once.
 7527                let mut start_row = MultiBufferRow(selection.start.row);
 7528                if last_toggled_row == Some(start_row) {
 7529                    start_row = start_row.next_row();
 7530                }
 7531                let end_row =
 7532                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 7533                        MultiBufferRow(selection.end.row - 1)
 7534                    } else {
 7535                        MultiBufferRow(selection.end.row)
 7536                    };
 7537                last_toggled_row = Some(end_row);
 7538
 7539                if start_row > end_row {
 7540                    continue;
 7541                }
 7542
 7543                // If the language has line comments, toggle those.
 7544                let full_comment_prefixes = language.line_comment_prefixes();
 7545                if !full_comment_prefixes.is_empty() {
 7546                    let first_prefix = full_comment_prefixes
 7547                        .first()
 7548                        .expect("prefixes is non-empty");
 7549                    let prefix_trimmed_lengths = full_comment_prefixes
 7550                        .iter()
 7551                        .map(|p| p.trim_end_matches(' ').len())
 7552                        .collect::<SmallVec<[usize; 4]>>();
 7553
 7554                    let mut all_selection_lines_are_comments = true;
 7555
 7556                    for row in start_row.0..=end_row.0 {
 7557                        let row = MultiBufferRow(row);
 7558                        if start_row < end_row && snapshot.is_line_blank(row) {
 7559                            continue;
 7560                        }
 7561
 7562                        let prefix_range = full_comment_prefixes
 7563                            .iter()
 7564                            .zip(prefix_trimmed_lengths.iter().copied())
 7565                            .map(|(prefix, trimmed_prefix_len)| {
 7566                                comment_prefix_range(
 7567                                    snapshot.deref(),
 7568                                    row,
 7569                                    &prefix[..trimmed_prefix_len],
 7570                                    &prefix[trimmed_prefix_len..],
 7571                                )
 7572                            })
 7573                            .max_by_key(|range| range.end.column - range.start.column)
 7574                            .expect("prefixes is non-empty");
 7575
 7576                        if prefix_range.is_empty() {
 7577                            all_selection_lines_are_comments = false;
 7578                        }
 7579
 7580                        selection_edit_ranges.push(prefix_range);
 7581                    }
 7582
 7583                    if all_selection_lines_are_comments {
 7584                        edits.extend(
 7585                            selection_edit_ranges
 7586                                .iter()
 7587                                .cloned()
 7588                                .map(|range| (range, empty_str.clone())),
 7589                        );
 7590                    } else {
 7591                        let min_column = selection_edit_ranges
 7592                            .iter()
 7593                            .map(|range| range.start.column)
 7594                            .min()
 7595                            .unwrap_or(0);
 7596                        edits.extend(selection_edit_ranges.iter().map(|range| {
 7597                            let position = Point::new(range.start.row, min_column);
 7598                            (position..position, first_prefix.clone())
 7599                        }));
 7600                    }
 7601                } else if let Some((full_comment_prefix, comment_suffix)) =
 7602                    language.block_comment_delimiters()
 7603                {
 7604                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 7605                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 7606                    let prefix_range = comment_prefix_range(
 7607                        snapshot.deref(),
 7608                        start_row,
 7609                        comment_prefix,
 7610                        comment_prefix_whitespace,
 7611                    );
 7612                    let suffix_range = comment_suffix_range(
 7613                        snapshot.deref(),
 7614                        end_row,
 7615                        comment_suffix.trim_start_matches(' '),
 7616                        comment_suffix.starts_with(' '),
 7617                    );
 7618
 7619                    if prefix_range.is_empty() || suffix_range.is_empty() {
 7620                        edits.push((
 7621                            prefix_range.start..prefix_range.start,
 7622                            full_comment_prefix.clone(),
 7623                        ));
 7624                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 7625                        suffixes_inserted.push((end_row, comment_suffix.len()));
 7626                    } else {
 7627                        edits.push((prefix_range, empty_str.clone()));
 7628                        edits.push((suffix_range, empty_str.clone()));
 7629                    }
 7630                } else {
 7631                    continue;
 7632                }
 7633            }
 7634
 7635            drop(snapshot);
 7636            this.buffer.update(cx, |buffer, cx| {
 7637                buffer.edit(edits, None, cx);
 7638            });
 7639
 7640            // Adjust selections so that they end before any comment suffixes that
 7641            // were inserted.
 7642            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 7643            let mut selections = this.selections.all::<Point>(cx);
 7644            let snapshot = this.buffer.read(cx).read(cx);
 7645            for selection in &mut selections {
 7646                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 7647                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 7648                        Ordering::Less => {
 7649                            suffixes_inserted.next();
 7650                            continue;
 7651                        }
 7652                        Ordering::Greater => break,
 7653                        Ordering::Equal => {
 7654                            if selection.end.column == snapshot.line_len(row) {
 7655                                if selection.is_empty() {
 7656                                    selection.start.column -= suffix_len as u32;
 7657                                }
 7658                                selection.end.column -= suffix_len as u32;
 7659                            }
 7660                            break;
 7661                        }
 7662                    }
 7663                }
 7664            }
 7665
 7666            drop(snapshot);
 7667            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 7668
 7669            let selections = this.selections.all::<Point>(cx);
 7670            let selections_on_single_row = selections.windows(2).all(|selections| {
 7671                selections[0].start.row == selections[1].start.row
 7672                    && selections[0].end.row == selections[1].end.row
 7673                    && selections[0].start.row == selections[0].end.row
 7674            });
 7675            let selections_selecting = selections
 7676                .iter()
 7677                .any(|selection| selection.start != selection.end);
 7678            let advance_downwards = action.advance_downwards
 7679                && selections_on_single_row
 7680                && !selections_selecting
 7681                && this.mode != EditorMode::SingleLine;
 7682
 7683            if advance_downwards {
 7684                let snapshot = this.buffer.read(cx).snapshot(cx);
 7685
 7686                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7687                    s.move_cursors_with(|display_snapshot, display_point, _| {
 7688                        let mut point = display_point.to_point(display_snapshot);
 7689                        point.row += 1;
 7690                        point = snapshot.clip_point(point, Bias::Left);
 7691                        let display_point = point.to_display_point(display_snapshot);
 7692                        let goal = SelectionGoal::HorizontalPosition(
 7693                            display_snapshot
 7694                                .x_for_display_point(display_point, &text_layout_details)
 7695                                .into(),
 7696                        );
 7697                        (display_point, goal)
 7698                    })
 7699                });
 7700            }
 7701        });
 7702    }
 7703
 7704    pub fn select_larger_syntax_node(
 7705        &mut self,
 7706        _: &SelectLargerSyntaxNode,
 7707        cx: &mut ViewContext<Self>,
 7708    ) {
 7709        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7710        let buffer = self.buffer.read(cx).snapshot(cx);
 7711        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 7712
 7713        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 7714        let mut selected_larger_node = false;
 7715        let new_selections = old_selections
 7716            .iter()
 7717            .map(|selection| {
 7718                let old_range = selection.start..selection.end;
 7719                let mut new_range = old_range.clone();
 7720                while let Some(containing_range) =
 7721                    buffer.range_for_syntax_ancestor(new_range.clone())
 7722                {
 7723                    new_range = containing_range;
 7724                    if !display_map.intersects_fold(new_range.start)
 7725                        && !display_map.intersects_fold(new_range.end)
 7726                    {
 7727                        break;
 7728                    }
 7729                }
 7730
 7731                selected_larger_node |= new_range != old_range;
 7732                Selection {
 7733                    id: selection.id,
 7734                    start: new_range.start,
 7735                    end: new_range.end,
 7736                    goal: SelectionGoal::None,
 7737                    reversed: selection.reversed,
 7738                }
 7739            })
 7740            .collect::<Vec<_>>();
 7741
 7742        if selected_larger_node {
 7743            stack.push(old_selections);
 7744            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7745                s.select(new_selections);
 7746            });
 7747        }
 7748        self.select_larger_syntax_node_stack = stack;
 7749    }
 7750
 7751    pub fn select_smaller_syntax_node(
 7752        &mut self,
 7753        _: &SelectSmallerSyntaxNode,
 7754        cx: &mut ViewContext<Self>,
 7755    ) {
 7756        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 7757        if let Some(selections) = stack.pop() {
 7758            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7759                s.select(selections.to_vec());
 7760            });
 7761        }
 7762        self.select_larger_syntax_node_stack = stack;
 7763    }
 7764
 7765    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 7766        let project = self.project.clone();
 7767        cx.spawn(|this, mut cx| async move {
 7768            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 7769                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 7770            }) else {
 7771                return;
 7772            };
 7773
 7774            let Some(project) = project else {
 7775                return;
 7776            };
 7777            if project
 7778                .update(&mut cx, |this, _| this.is_remote())
 7779                .unwrap_or(true)
 7780            {
 7781                // Do not display any test indicators in remote projects.
 7782                return;
 7783            }
 7784            let new_rows =
 7785                cx.background_executor()
 7786                    .spawn({
 7787                        let snapshot = display_snapshot.clone();
 7788                        async move {
 7789                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 7790                        }
 7791                    })
 7792                    .await;
 7793            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 7794
 7795            this.update(&mut cx, |this, _| {
 7796                this.clear_tasks();
 7797                for (key, value) in rows {
 7798                    this.insert_tasks(key, value);
 7799                }
 7800            })
 7801            .ok();
 7802        })
 7803    }
 7804    fn fetch_runnable_ranges(
 7805        snapshot: &DisplaySnapshot,
 7806        range: Range<Anchor>,
 7807    ) -> Vec<language::RunnableRange> {
 7808        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 7809    }
 7810
 7811    fn runnable_rows(
 7812        project: Model<Project>,
 7813        snapshot: DisplaySnapshot,
 7814        runnable_ranges: Vec<RunnableRange>,
 7815        mut cx: AsyncWindowContext,
 7816    ) -> Vec<((BufferId, u32), (usize, RunnableTasks))> {
 7817        runnable_ranges
 7818            .into_iter()
 7819            .filter_map(|mut runnable| {
 7820                let (tasks, _) = cx
 7821                    .update(|cx| {
 7822                        Self::resolve_runnable(project.clone(), &mut runnable.runnable, cx)
 7823                    })
 7824                    .ok()?;
 7825                if tasks.is_empty() {
 7826                    return None;
 7827                }
 7828
 7829                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 7830
 7831                let row = snapshot
 7832                    .buffer_snapshot
 7833                    .buffer_line_for_row(MultiBufferRow(point.row))?
 7834                    .1
 7835                    .start
 7836                    .row;
 7837
 7838                Some((
 7839                    (runnable.buffer_id, row),
 7840                    (
 7841                        runnable.run_range.start,
 7842                        RunnableTasks {
 7843                            templates: tasks,
 7844                            column: point.column,
 7845                            extra_variables: runnable.extra_captures,
 7846                        },
 7847                    ),
 7848                ))
 7849            })
 7850            .collect()
 7851    }
 7852
 7853    fn resolve_runnable(
 7854        project: Model<Project>,
 7855        runnable: &mut Runnable,
 7856        cx: &WindowContext<'_>,
 7857    ) -> (Vec<(TaskSourceKind, TaskTemplate)>, Option<WorktreeId>) {
 7858        let (inventory, worktree_id) = project.read_with(cx, |project, cx| {
 7859            let worktree_id = project
 7860                .buffer_for_id(runnable.buffer)
 7861                .and_then(|buffer| buffer.read(cx).file())
 7862                .map(|file| WorktreeId::from_usize(file.worktree_id()));
 7863
 7864            (project.task_inventory().clone(), worktree_id)
 7865        });
 7866
 7867        let inventory = inventory.read(cx);
 7868        let tags = mem::take(&mut runnable.tags);
 7869        let mut tags: Vec<_> = tags
 7870            .into_iter()
 7871            .flat_map(|tag| {
 7872                let tag = tag.0.clone();
 7873                inventory
 7874                    .list_tasks(Some(runnable.language.clone()), worktree_id)
 7875                    .into_iter()
 7876                    .filter(move |(_, template)| {
 7877                        template.tags.iter().any(|source_tag| source_tag == &tag)
 7878                    })
 7879            })
 7880            .sorted_by_key(|(kind, _)| kind.to_owned())
 7881            .collect();
 7882        if let Some((leading_tag_source, _)) = tags.first() {
 7883            // Strongest source wins; if we have worktree tag binding, prefer that to
 7884            // global and language bindings;
 7885            // if we have a global binding, prefer that to language binding.
 7886            let first_mismatch = tags
 7887                .iter()
 7888                .position(|(tag_source, _)| tag_source != leading_tag_source);
 7889            if let Some(index) = first_mismatch {
 7890                tags.truncate(index);
 7891            }
 7892        }
 7893
 7894        (tags, worktree_id)
 7895    }
 7896
 7897    pub fn move_to_enclosing_bracket(
 7898        &mut self,
 7899        _: &MoveToEnclosingBracket,
 7900        cx: &mut ViewContext<Self>,
 7901    ) {
 7902        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7903            s.move_offsets_with(|snapshot, selection| {
 7904                let Some(enclosing_bracket_ranges) =
 7905                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 7906                else {
 7907                    return;
 7908                };
 7909
 7910                let mut best_length = usize::MAX;
 7911                let mut best_inside = false;
 7912                let mut best_in_bracket_range = false;
 7913                let mut best_destination = None;
 7914                for (open, close) in enclosing_bracket_ranges {
 7915                    let close = close.to_inclusive();
 7916                    let length = close.end() - open.start;
 7917                    let inside = selection.start >= open.end && selection.end <= *close.start();
 7918                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 7919                        || close.contains(&selection.head());
 7920
 7921                    // If best is next to a bracket and current isn't, skip
 7922                    if !in_bracket_range && best_in_bracket_range {
 7923                        continue;
 7924                    }
 7925
 7926                    // Prefer smaller lengths unless best is inside and current isn't
 7927                    if length > best_length && (best_inside || !inside) {
 7928                        continue;
 7929                    }
 7930
 7931                    best_length = length;
 7932                    best_inside = inside;
 7933                    best_in_bracket_range = in_bracket_range;
 7934                    best_destination = Some(
 7935                        if close.contains(&selection.start) && close.contains(&selection.end) {
 7936                            if inside {
 7937                                open.end
 7938                            } else {
 7939                                open.start
 7940                            }
 7941                        } else {
 7942                            if inside {
 7943                                *close.start()
 7944                            } else {
 7945                                *close.end()
 7946                            }
 7947                        },
 7948                    );
 7949                }
 7950
 7951                if let Some(destination) = best_destination {
 7952                    selection.collapse_to(destination, SelectionGoal::None);
 7953                }
 7954            })
 7955        });
 7956    }
 7957
 7958    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 7959        self.end_selection(cx);
 7960        self.selection_history.mode = SelectionHistoryMode::Undoing;
 7961        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 7962            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 7963            self.select_next_state = entry.select_next_state;
 7964            self.select_prev_state = entry.select_prev_state;
 7965            self.add_selections_state = entry.add_selections_state;
 7966            self.request_autoscroll(Autoscroll::newest(), cx);
 7967        }
 7968        self.selection_history.mode = SelectionHistoryMode::Normal;
 7969    }
 7970
 7971    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 7972        self.end_selection(cx);
 7973        self.selection_history.mode = SelectionHistoryMode::Redoing;
 7974        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 7975            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 7976            self.select_next_state = entry.select_next_state;
 7977            self.select_prev_state = entry.select_prev_state;
 7978            self.add_selections_state = entry.add_selections_state;
 7979            self.request_autoscroll(Autoscroll::newest(), cx);
 7980        }
 7981        self.selection_history.mode = SelectionHistoryMode::Normal;
 7982    }
 7983
 7984    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 7985        let selections = self.selections.disjoint_anchors();
 7986
 7987        let lines = if action.lines == 0 { 3 } else { action.lines };
 7988
 7989        self.buffer.update(cx, |buffer, cx| {
 7990            buffer.expand_excerpts(
 7991                selections
 7992                    .into_iter()
 7993                    .map(|selection| selection.head().excerpt_id)
 7994                    .dedup(),
 7995                lines,
 7996                cx,
 7997            )
 7998        })
 7999    }
 8000
 8001    pub fn expand_excerpt(&mut self, excerpt: ExcerptId, cx: &mut ViewContext<Self>) {
 8002        self.buffer
 8003            .update(cx, |buffer, cx| buffer.expand_excerpts([excerpt], 3, cx))
 8004    }
 8005
 8006    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 8007        self.go_to_diagnostic_impl(Direction::Next, cx)
 8008    }
 8009
 8010    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 8011        self.go_to_diagnostic_impl(Direction::Prev, cx)
 8012    }
 8013
 8014    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 8015        let buffer = self.buffer.read(cx).snapshot(cx);
 8016        let selection = self.selections.newest::<usize>(cx);
 8017
 8018        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 8019        if direction == Direction::Next {
 8020            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 8021                let (group_id, jump_to) = popover.activation_info();
 8022                if self.activate_diagnostics(group_id, cx) {
 8023                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8024                        let mut new_selection = s.newest_anchor().clone();
 8025                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 8026                        s.select_anchors(vec![new_selection.clone()]);
 8027                    });
 8028                }
 8029                return;
 8030            }
 8031        }
 8032
 8033        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 8034            active_diagnostics
 8035                .primary_range
 8036                .to_offset(&buffer)
 8037                .to_inclusive()
 8038        });
 8039        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 8040            if active_primary_range.contains(&selection.head()) {
 8041                *active_primary_range.start()
 8042            } else {
 8043                selection.head()
 8044            }
 8045        } else {
 8046            selection.head()
 8047        };
 8048        let snapshot = self.snapshot(cx);
 8049        loop {
 8050            let diagnostics = if direction == Direction::Prev {
 8051                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 8052            } else {
 8053                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 8054            }
 8055            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 8056            let group = diagnostics
 8057                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 8058                // be sorted in a stable way
 8059                // skip until we are at current active diagnostic, if it exists
 8060                .skip_while(|entry| {
 8061                    (match direction {
 8062                        Direction::Prev => entry.range.start >= search_start,
 8063                        Direction::Next => entry.range.start <= search_start,
 8064                    }) && self
 8065                        .active_diagnostics
 8066                        .as_ref()
 8067                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 8068                })
 8069                .find_map(|entry| {
 8070                    if entry.diagnostic.is_primary
 8071                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 8072                        && !entry.range.is_empty()
 8073                        // if we match with the active diagnostic, skip it
 8074                        && Some(entry.diagnostic.group_id)
 8075                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 8076                    {
 8077                        Some((entry.range, entry.diagnostic.group_id))
 8078                    } else {
 8079                        None
 8080                    }
 8081                });
 8082
 8083            if let Some((primary_range, group_id)) = group {
 8084                if self.activate_diagnostics(group_id, cx) {
 8085                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8086                        s.select(vec![Selection {
 8087                            id: selection.id,
 8088                            start: primary_range.start,
 8089                            end: primary_range.start,
 8090                            reversed: false,
 8091                            goal: SelectionGoal::None,
 8092                        }]);
 8093                    });
 8094                }
 8095                break;
 8096            } else {
 8097                // Cycle around to the start of the buffer, potentially moving back to the start of
 8098                // the currently active diagnostic.
 8099                active_primary_range.take();
 8100                if direction == Direction::Prev {
 8101                    if search_start == buffer.len() {
 8102                        break;
 8103                    } else {
 8104                        search_start = buffer.len();
 8105                    }
 8106                } else if search_start == 0 {
 8107                    break;
 8108                } else {
 8109                    search_start = 0;
 8110                }
 8111            }
 8112        }
 8113    }
 8114
 8115    fn go_to_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 8116        let snapshot = self
 8117            .display_map
 8118            .update(cx, |display_map, cx| display_map.snapshot(cx));
 8119        let selection = self.selections.newest::<Point>(cx);
 8120
 8121        if !self.seek_in_direction(
 8122            &snapshot,
 8123            selection.head(),
 8124            false,
 8125            snapshot.buffer_snapshot.git_diff_hunks_in_range(
 8126                MultiBufferRow(selection.head().row + 1)..MultiBufferRow::MAX,
 8127            ),
 8128            cx,
 8129        ) {
 8130            let wrapped_point = Point::zero();
 8131            self.seek_in_direction(
 8132                &snapshot,
 8133                wrapped_point,
 8134                true,
 8135                snapshot.buffer_snapshot.git_diff_hunks_in_range(
 8136                    MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
 8137                ),
 8138                cx,
 8139            );
 8140        }
 8141    }
 8142
 8143    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 8144        let snapshot = self
 8145            .display_map
 8146            .update(cx, |display_map, cx| display_map.snapshot(cx));
 8147        let selection = self.selections.newest::<Point>(cx);
 8148
 8149        if !self.seek_in_direction(
 8150            &snapshot,
 8151            selection.head(),
 8152            false,
 8153            snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
 8154                MultiBufferRow(0)..MultiBufferRow(selection.head().row),
 8155            ),
 8156            cx,
 8157        ) {
 8158            let wrapped_point = snapshot.buffer_snapshot.max_point();
 8159            self.seek_in_direction(
 8160                &snapshot,
 8161                wrapped_point,
 8162                true,
 8163                snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
 8164                    MultiBufferRow(0)..MultiBufferRow(wrapped_point.row),
 8165                ),
 8166                cx,
 8167            );
 8168        }
 8169    }
 8170
 8171    fn seek_in_direction(
 8172        &mut self,
 8173        snapshot: &DisplaySnapshot,
 8174        initial_point: Point,
 8175        is_wrapped: bool,
 8176        hunks: impl Iterator<Item = DiffHunk<MultiBufferRow>>,
 8177        cx: &mut ViewContext<Editor>,
 8178    ) -> bool {
 8179        let display_point = initial_point.to_display_point(snapshot);
 8180        let mut hunks = hunks
 8181            .map(|hunk| diff_hunk_to_display(&hunk, &snapshot))
 8182            .filter(|hunk| {
 8183                if is_wrapped {
 8184                    true
 8185                } else {
 8186                    !hunk.contains_display_row(display_point.row())
 8187                }
 8188            })
 8189            .dedup();
 8190
 8191        if let Some(hunk) = hunks.next() {
 8192            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8193                let row = hunk.start_display_row();
 8194                let point = DisplayPoint::new(row, 0);
 8195                s.select_display_ranges([point..point]);
 8196            });
 8197
 8198            true
 8199        } else {
 8200            false
 8201        }
 8202    }
 8203
 8204    pub fn go_to_definition(
 8205        &mut self,
 8206        _: &GoToDefinition,
 8207        cx: &mut ViewContext<Self>,
 8208    ) -> Task<Result<bool>> {
 8209        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx)
 8210    }
 8211
 8212    pub fn go_to_implementation(
 8213        &mut self,
 8214        _: &GoToImplementation,
 8215        cx: &mut ViewContext<Self>,
 8216    ) -> Task<Result<bool>> {
 8217        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 8218    }
 8219
 8220    pub fn go_to_implementation_split(
 8221        &mut self,
 8222        _: &GoToImplementationSplit,
 8223        cx: &mut ViewContext<Self>,
 8224    ) -> Task<Result<bool>> {
 8225        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 8226    }
 8227
 8228    pub fn go_to_type_definition(
 8229        &mut self,
 8230        _: &GoToTypeDefinition,
 8231        cx: &mut ViewContext<Self>,
 8232    ) -> Task<Result<bool>> {
 8233        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 8234    }
 8235
 8236    pub fn go_to_definition_split(
 8237        &mut self,
 8238        _: &GoToDefinitionSplit,
 8239        cx: &mut ViewContext<Self>,
 8240    ) -> Task<Result<bool>> {
 8241        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 8242    }
 8243
 8244    pub fn go_to_type_definition_split(
 8245        &mut self,
 8246        _: &GoToTypeDefinitionSplit,
 8247        cx: &mut ViewContext<Self>,
 8248    ) -> Task<Result<bool>> {
 8249        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 8250    }
 8251
 8252    fn go_to_definition_of_kind(
 8253        &mut self,
 8254        kind: GotoDefinitionKind,
 8255        split: bool,
 8256        cx: &mut ViewContext<Self>,
 8257    ) -> Task<Result<bool>> {
 8258        let Some(workspace) = self.workspace() else {
 8259            return Task::ready(Ok(false));
 8260        };
 8261        let buffer = self.buffer.read(cx);
 8262        let head = self.selections.newest::<usize>(cx).head();
 8263        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 8264            text_anchor
 8265        } else {
 8266            return Task::ready(Ok(false));
 8267        };
 8268
 8269        let project = workspace.read(cx).project().clone();
 8270        let definitions = project.update(cx, |project, cx| match kind {
 8271            GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
 8272            GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
 8273            GotoDefinitionKind::Implementation => project.implementation(&buffer, head, cx),
 8274        });
 8275
 8276        cx.spawn(|editor, mut cx| async move {
 8277            let definitions = definitions.await?;
 8278            let navigated = editor
 8279                .update(&mut cx, |editor, cx| {
 8280                    editor.navigate_to_hover_links(
 8281                        Some(kind),
 8282                        definitions
 8283                            .into_iter()
 8284                            .filter(|location| {
 8285                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 8286                            })
 8287                            .map(HoverLink::Text)
 8288                            .collect::<Vec<_>>(),
 8289                        split,
 8290                        cx,
 8291                    )
 8292                })?
 8293                .await?;
 8294            anyhow::Ok(navigated)
 8295        })
 8296    }
 8297
 8298    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 8299        let position = self.selections.newest_anchor().head();
 8300        let Some((buffer, buffer_position)) =
 8301            self.buffer.read(cx).text_anchor_for_position(position, cx)
 8302        else {
 8303            return;
 8304        };
 8305
 8306        cx.spawn(|editor, mut cx| async move {
 8307            if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
 8308                editor.update(&mut cx, |_, cx| {
 8309                    cx.open_url(&url);
 8310                })
 8311            } else {
 8312                Ok(())
 8313            }
 8314        })
 8315        .detach();
 8316    }
 8317
 8318    pub(crate) fn navigate_to_hover_links(
 8319        &mut self,
 8320        kind: Option<GotoDefinitionKind>,
 8321        mut definitions: Vec<HoverLink>,
 8322        split: bool,
 8323        cx: &mut ViewContext<Editor>,
 8324    ) -> Task<Result<bool>> {
 8325        // If there is one definition, just open it directly
 8326        if definitions.len() == 1 {
 8327            let definition = definitions.pop().unwrap();
 8328            let target_task = match definition {
 8329                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 8330                HoverLink::InlayHint(lsp_location, server_id) => {
 8331                    self.compute_target_location(lsp_location, server_id, cx)
 8332                }
 8333                HoverLink::Url(url) => {
 8334                    cx.open_url(&url);
 8335                    Task::ready(Ok(None))
 8336                }
 8337            };
 8338            cx.spawn(|editor, mut cx| async move {
 8339                let target = target_task.await.context("target resolution task")?;
 8340                if let Some(target) = target {
 8341                    editor.update(&mut cx, |editor, cx| {
 8342                        let Some(workspace) = editor.workspace() else {
 8343                            return false;
 8344                        };
 8345                        let pane = workspace.read(cx).active_pane().clone();
 8346
 8347                        let range = target.range.to_offset(target.buffer.read(cx));
 8348                        let range = editor.range_for_match(&range);
 8349                        if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 8350                            editor.change_selections(Some(Autoscroll::focused()), cx, |s| {
 8351                                s.select_ranges([range]);
 8352                            });
 8353                        } else {
 8354                            cx.window_context().defer(move |cx| {
 8355                                let target_editor: View<Self> =
 8356                                    workspace.update(cx, |workspace, cx| {
 8357                                        let pane = if split {
 8358                                            workspace.adjacent_pane(cx)
 8359                                        } else {
 8360                                            workspace.active_pane().clone()
 8361                                        };
 8362
 8363                                        workspace.open_project_item(pane, target.buffer.clone(), cx)
 8364                                    });
 8365                                target_editor.update(cx, |target_editor, cx| {
 8366                                    // When selecting a definition in a different buffer, disable the nav history
 8367                                    // to avoid creating a history entry at the previous cursor location.
 8368                                    pane.update(cx, |pane, _| pane.disable_history());
 8369                                    target_editor.change_selections(
 8370                                        Some(Autoscroll::focused()),
 8371                                        cx,
 8372                                        |s| {
 8373                                            s.select_ranges([range]);
 8374                                        },
 8375                                    );
 8376                                    pane.update(cx, |pane, _| pane.enable_history());
 8377                                });
 8378                            });
 8379                        }
 8380                        true
 8381                    })
 8382                } else {
 8383                    Ok(false)
 8384                }
 8385            })
 8386        } else if !definitions.is_empty() {
 8387            let replica_id = self.replica_id(cx);
 8388            cx.spawn(|editor, mut cx| async move {
 8389                let (title, location_tasks, workspace) = editor
 8390                    .update(&mut cx, |editor, cx| {
 8391                        let tab_kind = match kind {
 8392                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 8393                            _ => "Definitions",
 8394                        };
 8395                        let title = definitions
 8396                            .iter()
 8397                            .find_map(|definition| match definition {
 8398                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 8399                                    let buffer = origin.buffer.read(cx);
 8400                                    format!(
 8401                                        "{} for {}",
 8402                                        tab_kind,
 8403                                        buffer
 8404                                            .text_for_range(origin.range.clone())
 8405                                            .collect::<String>()
 8406                                    )
 8407                                }),
 8408                                HoverLink::InlayHint(_, _) => None,
 8409                                HoverLink::Url(_) => None,
 8410                            })
 8411                            .unwrap_or(tab_kind.to_string());
 8412                        let location_tasks = definitions
 8413                            .into_iter()
 8414                            .map(|definition| match definition {
 8415                                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 8416                                HoverLink::InlayHint(lsp_location, server_id) => {
 8417                                    editor.compute_target_location(lsp_location, server_id, cx)
 8418                                }
 8419                                HoverLink::Url(_) => Task::ready(Ok(None)),
 8420                            })
 8421                            .collect::<Vec<_>>();
 8422                        (title, location_tasks, editor.workspace().clone())
 8423                    })
 8424                    .context("location tasks preparation")?;
 8425
 8426                let locations = futures::future::join_all(location_tasks)
 8427                    .await
 8428                    .into_iter()
 8429                    .filter_map(|location| location.transpose())
 8430                    .collect::<Result<_>>()
 8431                    .context("location tasks")?;
 8432
 8433                let Some(workspace) = workspace else {
 8434                    return Ok(false);
 8435                };
 8436                let opened = workspace
 8437                    .update(&mut cx, |workspace, cx| {
 8438                        Self::open_locations_in_multibuffer(
 8439                            workspace, locations, replica_id, title, split, cx,
 8440                        )
 8441                    })
 8442                    .ok();
 8443
 8444                anyhow::Ok(opened.is_some())
 8445            })
 8446        } else {
 8447            Task::ready(Ok(false))
 8448        }
 8449    }
 8450
 8451    fn compute_target_location(
 8452        &self,
 8453        lsp_location: lsp::Location,
 8454        server_id: LanguageServerId,
 8455        cx: &mut ViewContext<Editor>,
 8456    ) -> Task<anyhow::Result<Option<Location>>> {
 8457        let Some(project) = self.project.clone() else {
 8458            return Task::Ready(Some(Ok(None)));
 8459        };
 8460
 8461        cx.spawn(move |editor, mut cx| async move {
 8462            let location_task = editor.update(&mut cx, |editor, cx| {
 8463                project.update(cx, |project, cx| {
 8464                    let language_server_name =
 8465                        editor.buffer.read(cx).as_singleton().and_then(|buffer| {
 8466                            project
 8467                                .language_server_for_buffer(buffer.read(cx), server_id, cx)
 8468                                .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
 8469                        });
 8470                    language_server_name.map(|language_server_name| {
 8471                        project.open_local_buffer_via_lsp(
 8472                            lsp_location.uri.clone(),
 8473                            server_id,
 8474                            language_server_name,
 8475                            cx,
 8476                        )
 8477                    })
 8478                })
 8479            })?;
 8480            let location = match location_task {
 8481                Some(task) => Some({
 8482                    let target_buffer_handle = task.await.context("open local buffer")?;
 8483                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
 8484                        let target_start = target_buffer
 8485                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
 8486                        let target_end = target_buffer
 8487                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
 8488                        target_buffer.anchor_after(target_start)
 8489                            ..target_buffer.anchor_before(target_end)
 8490                    })?;
 8491                    Location {
 8492                        buffer: target_buffer_handle,
 8493                        range,
 8494                    }
 8495                }),
 8496                None => None,
 8497            };
 8498            Ok(location)
 8499        })
 8500    }
 8501
 8502    pub fn find_all_references(
 8503        &mut self,
 8504        _: &FindAllReferences,
 8505        cx: &mut ViewContext<Self>,
 8506    ) -> Option<Task<Result<()>>> {
 8507        let multi_buffer = self.buffer.read(cx);
 8508        let selection = self.selections.newest::<usize>(cx);
 8509        let head = selection.head();
 8510
 8511        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 8512        let head_anchor = multi_buffer_snapshot.anchor_at(
 8513            head,
 8514            if head < selection.tail() {
 8515                Bias::Right
 8516            } else {
 8517                Bias::Left
 8518            },
 8519        );
 8520
 8521        match self
 8522            .find_all_references_task_sources
 8523            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
 8524        {
 8525            Ok(_) => {
 8526                log::info!(
 8527                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
 8528                );
 8529                return None;
 8530            }
 8531            Err(i) => {
 8532                self.find_all_references_task_sources.insert(i, head_anchor);
 8533            }
 8534        }
 8535
 8536        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
 8537        let replica_id = self.replica_id(cx);
 8538        let workspace = self.workspace()?;
 8539        let project = workspace.read(cx).project().clone();
 8540        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
 8541        Some(cx.spawn(|editor, mut cx| async move {
 8542            let _cleanup = defer({
 8543                let mut cx = cx.clone();
 8544                move || {
 8545                    let _ = editor.update(&mut cx, |editor, _| {
 8546                        if let Ok(i) =
 8547                            editor
 8548                                .find_all_references_task_sources
 8549                                .binary_search_by(|anchor| {
 8550                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
 8551                                })
 8552                        {
 8553                            editor.find_all_references_task_sources.remove(i);
 8554                        }
 8555                    });
 8556                }
 8557            });
 8558
 8559            let locations = references.await?;
 8560            if locations.is_empty() {
 8561                return anyhow::Ok(());
 8562            }
 8563
 8564            workspace.update(&mut cx, |workspace, cx| {
 8565                let title = locations
 8566                    .first()
 8567                    .as_ref()
 8568                    .map(|location| {
 8569                        let buffer = location.buffer.read(cx);
 8570                        format!(
 8571                            "References to `{}`",
 8572                            buffer
 8573                                .text_for_range(location.range.clone())
 8574                                .collect::<String>()
 8575                        )
 8576                    })
 8577                    .unwrap();
 8578                Self::open_locations_in_multibuffer(
 8579                    workspace, locations, replica_id, title, false, cx,
 8580                );
 8581            })
 8582        }))
 8583    }
 8584
 8585    /// Opens a multibuffer with the given project locations in it
 8586    pub fn open_locations_in_multibuffer(
 8587        workspace: &mut Workspace,
 8588        mut locations: Vec<Location>,
 8589        replica_id: ReplicaId,
 8590        title: String,
 8591        split: bool,
 8592        cx: &mut ViewContext<Workspace>,
 8593    ) {
 8594        // If there are multiple definitions, open them in a multibuffer
 8595        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
 8596        let mut locations = locations.into_iter().peekable();
 8597        let mut ranges_to_highlight = Vec::new();
 8598        let capability = workspace.project().read(cx).capability();
 8599
 8600        let excerpt_buffer = cx.new_model(|cx| {
 8601            let mut multibuffer = MultiBuffer::new(replica_id, capability);
 8602            while let Some(location) = locations.next() {
 8603                let buffer = location.buffer.read(cx);
 8604                let mut ranges_for_buffer = Vec::new();
 8605                let range = location.range.to_offset(buffer);
 8606                ranges_for_buffer.push(range.clone());
 8607
 8608                while let Some(next_location) = locations.peek() {
 8609                    if next_location.buffer == location.buffer {
 8610                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
 8611                        locations.next();
 8612                    } else {
 8613                        break;
 8614                    }
 8615                }
 8616
 8617                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
 8618                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
 8619                    location.buffer.clone(),
 8620                    ranges_for_buffer,
 8621                    DEFAULT_MULTIBUFFER_CONTEXT,
 8622                    cx,
 8623                ))
 8624            }
 8625
 8626            multibuffer.with_title(title)
 8627        });
 8628
 8629        let editor = cx.new_view(|cx| {
 8630            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), cx)
 8631        });
 8632        editor.update(cx, |editor, cx| {
 8633            editor.highlight_background::<Self>(
 8634                &ranges_to_highlight,
 8635                |theme| theme.editor_highlighted_line_background,
 8636                cx,
 8637            );
 8638        });
 8639
 8640        let item = Box::new(editor);
 8641        let item_id = item.item_id();
 8642
 8643        if split {
 8644            workspace.split_item(SplitDirection::Right, item.clone(), cx);
 8645        } else {
 8646            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
 8647                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
 8648                    pane.close_current_preview_item(cx)
 8649                } else {
 8650                    None
 8651                }
 8652            });
 8653            workspace.add_item_to_active_pane(item.clone(), destination_index, cx);
 8654        }
 8655        workspace.active_pane().update(cx, |pane, cx| {
 8656            pane.set_preview_item_id(Some(item_id), cx);
 8657        });
 8658    }
 8659
 8660    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 8661        use language::ToOffset as _;
 8662
 8663        let project = self.project.clone()?;
 8664        let selection = self.selections.newest_anchor().clone();
 8665        let (cursor_buffer, cursor_buffer_position) = self
 8666            .buffer
 8667            .read(cx)
 8668            .text_anchor_for_position(selection.head(), cx)?;
 8669        let (tail_buffer, cursor_buffer_position_end) = self
 8670            .buffer
 8671            .read(cx)
 8672            .text_anchor_for_position(selection.tail(), cx)?;
 8673        if tail_buffer != cursor_buffer {
 8674            return None;
 8675        }
 8676
 8677        let snapshot = cursor_buffer.read(cx).snapshot();
 8678        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
 8679        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
 8680        let prepare_rename = project.update(cx, |project, cx| {
 8681            project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
 8682        });
 8683        drop(snapshot);
 8684
 8685        Some(cx.spawn(|this, mut cx| async move {
 8686            let rename_range = if let Some(range) = prepare_rename.await? {
 8687                Some(range)
 8688            } else {
 8689                this.update(&mut cx, |this, cx| {
 8690                    let buffer = this.buffer.read(cx).snapshot(cx);
 8691                    let mut buffer_highlights = this
 8692                        .document_highlights_for_position(selection.head(), &buffer)
 8693                        .filter(|highlight| {
 8694                            highlight.start.excerpt_id == selection.head().excerpt_id
 8695                                && highlight.end.excerpt_id == selection.head().excerpt_id
 8696                        });
 8697                    buffer_highlights
 8698                        .next()
 8699                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
 8700                })?
 8701            };
 8702            if let Some(rename_range) = rename_range {
 8703                this.update(&mut cx, |this, cx| {
 8704                    let snapshot = cursor_buffer.read(cx).snapshot();
 8705                    let rename_buffer_range = rename_range.to_offset(&snapshot);
 8706                    let cursor_offset_in_rename_range =
 8707                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
 8708                    let cursor_offset_in_rename_range_end =
 8709                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
 8710
 8711                    this.take_rename(false, cx);
 8712                    let buffer = this.buffer.read(cx).read(cx);
 8713                    let cursor_offset = selection.head().to_offset(&buffer);
 8714                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
 8715                    let rename_end = rename_start + rename_buffer_range.len();
 8716                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
 8717                    let mut old_highlight_id = None;
 8718                    let old_name: Arc<str> = buffer
 8719                        .chunks(rename_start..rename_end, true)
 8720                        .map(|chunk| {
 8721                            if old_highlight_id.is_none() {
 8722                                old_highlight_id = chunk.syntax_highlight_id;
 8723                            }
 8724                            chunk.text
 8725                        })
 8726                        .collect::<String>()
 8727                        .into();
 8728
 8729                    drop(buffer);
 8730
 8731                    // Position the selection in the rename editor so that it matches the current selection.
 8732                    this.show_local_selections = false;
 8733                    let rename_editor = cx.new_view(|cx| {
 8734                        let mut editor = Editor::single_line(cx);
 8735                        editor.buffer.update(cx, |buffer, cx| {
 8736                            buffer.edit([(0..0, old_name.clone())], None, cx)
 8737                        });
 8738                        let rename_selection_range = match cursor_offset_in_rename_range
 8739                            .cmp(&cursor_offset_in_rename_range_end)
 8740                        {
 8741                            Ordering::Equal => {
 8742                                editor.select_all(&SelectAll, cx);
 8743                                return editor;
 8744                            }
 8745                            Ordering::Less => {
 8746                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
 8747                            }
 8748                            Ordering::Greater => {
 8749                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
 8750                            }
 8751                        };
 8752                        if rename_selection_range.end > old_name.len() {
 8753                            editor.select_all(&SelectAll, cx);
 8754                        } else {
 8755                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8756                                s.select_ranges([rename_selection_range]);
 8757                            });
 8758                        }
 8759                        editor
 8760                    });
 8761
 8762                    let write_highlights =
 8763                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
 8764                    let read_highlights =
 8765                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
 8766                    let ranges = write_highlights
 8767                        .iter()
 8768                        .flat_map(|(_, ranges)| ranges.iter())
 8769                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
 8770                        .cloned()
 8771                        .collect();
 8772
 8773                    this.highlight_text::<Rename>(
 8774                        ranges,
 8775                        HighlightStyle {
 8776                            fade_out: Some(0.6),
 8777                            ..Default::default()
 8778                        },
 8779                        cx,
 8780                    );
 8781                    let rename_focus_handle = rename_editor.focus_handle(cx);
 8782                    cx.focus(&rename_focus_handle);
 8783                    let block_id = this.insert_blocks(
 8784                        [BlockProperties {
 8785                            style: BlockStyle::Flex,
 8786                            position: range.start,
 8787                            height: 1,
 8788                            render: Box::new({
 8789                                let rename_editor = rename_editor.clone();
 8790                                move |cx: &mut BlockContext| {
 8791                                    let mut text_style = cx.editor_style.text.clone();
 8792                                    if let Some(highlight_style) = old_highlight_id
 8793                                        .and_then(|h| h.style(&cx.editor_style.syntax))
 8794                                    {
 8795                                        text_style = text_style.highlight(highlight_style);
 8796                                    }
 8797                                    div()
 8798                                        .pl(cx.anchor_x)
 8799                                        .child(EditorElement::new(
 8800                                            &rename_editor,
 8801                                            EditorStyle {
 8802                                                background: cx.theme().system().transparent,
 8803                                                local_player: cx.editor_style.local_player,
 8804                                                text: text_style,
 8805                                                scrollbar_width: cx.editor_style.scrollbar_width,
 8806                                                syntax: cx.editor_style.syntax.clone(),
 8807                                                status: cx.editor_style.status.clone(),
 8808                                                inlay_hints_style: HighlightStyle {
 8809                                                    color: Some(cx.theme().status().hint),
 8810                                                    font_weight: Some(FontWeight::BOLD),
 8811                                                    ..HighlightStyle::default()
 8812                                                },
 8813                                                suggestions_style: HighlightStyle {
 8814                                                    color: Some(cx.theme().status().predictive),
 8815                                                    ..HighlightStyle::default()
 8816                                                },
 8817                                            },
 8818                                        ))
 8819                                        .into_any_element()
 8820                                }
 8821                            }),
 8822                            disposition: BlockDisposition::Below,
 8823                        }],
 8824                        Some(Autoscroll::fit()),
 8825                        cx,
 8826                    )[0];
 8827                    this.pending_rename = Some(RenameState {
 8828                        range,
 8829                        old_name,
 8830                        editor: rename_editor,
 8831                        block_id,
 8832                    });
 8833                })?;
 8834            }
 8835
 8836            Ok(())
 8837        }))
 8838    }
 8839
 8840    pub fn confirm_rename(
 8841        &mut self,
 8842        _: &ConfirmRename,
 8843        cx: &mut ViewContext<Self>,
 8844    ) -> Option<Task<Result<()>>> {
 8845        let rename = self.take_rename(false, cx)?;
 8846        let workspace = self.workspace()?;
 8847        let (start_buffer, start) = self
 8848            .buffer
 8849            .read(cx)
 8850            .text_anchor_for_position(rename.range.start, cx)?;
 8851        let (end_buffer, end) = self
 8852            .buffer
 8853            .read(cx)
 8854            .text_anchor_for_position(rename.range.end, cx)?;
 8855        if start_buffer != end_buffer {
 8856            return None;
 8857        }
 8858
 8859        let buffer = start_buffer;
 8860        let range = start..end;
 8861        let old_name = rename.old_name;
 8862        let new_name = rename.editor.read(cx).text(cx);
 8863
 8864        let rename = workspace
 8865            .read(cx)
 8866            .project()
 8867            .clone()
 8868            .update(cx, |project, cx| {
 8869                project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
 8870            });
 8871        let workspace = workspace.downgrade();
 8872
 8873        Some(cx.spawn(|editor, mut cx| async move {
 8874            let project_transaction = rename.await?;
 8875            Self::open_project_transaction(
 8876                &editor,
 8877                workspace,
 8878                project_transaction,
 8879                format!("Rename: {}{}", old_name, new_name),
 8880                cx.clone(),
 8881            )
 8882            .await?;
 8883
 8884            editor.update(&mut cx, |editor, cx| {
 8885                editor.refresh_document_highlights(cx);
 8886            })?;
 8887            Ok(())
 8888        }))
 8889    }
 8890
 8891    fn take_rename(
 8892        &mut self,
 8893        moving_cursor: bool,
 8894        cx: &mut ViewContext<Self>,
 8895    ) -> Option<RenameState> {
 8896        let rename = self.pending_rename.take()?;
 8897        if rename.editor.focus_handle(cx).is_focused(cx) {
 8898            cx.focus(&self.focus_handle);
 8899        }
 8900
 8901        self.remove_blocks(
 8902            [rename.block_id].into_iter().collect(),
 8903            Some(Autoscroll::fit()),
 8904            cx,
 8905        );
 8906        self.clear_highlights::<Rename>(cx);
 8907        self.show_local_selections = true;
 8908
 8909        if moving_cursor {
 8910            let rename_editor = rename.editor.read(cx);
 8911            let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
 8912
 8913            // Update the selection to match the position of the selection inside
 8914            // the rename editor.
 8915            let snapshot = self.buffer.read(cx).read(cx);
 8916            let rename_range = rename.range.to_offset(&snapshot);
 8917            let cursor_in_editor = snapshot
 8918                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
 8919                .min(rename_range.end);
 8920            drop(snapshot);
 8921
 8922            self.change_selections(None, cx, |s| {
 8923                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
 8924            });
 8925        } else {
 8926            self.refresh_document_highlights(cx);
 8927        }
 8928
 8929        Some(rename)
 8930    }
 8931
 8932    pub fn pending_rename(&self) -> Option<&RenameState> {
 8933        self.pending_rename.as_ref()
 8934    }
 8935
 8936    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 8937        let project = match &self.project {
 8938            Some(project) => project.clone(),
 8939            None => return None,
 8940        };
 8941
 8942        Some(self.perform_format(project, FormatTrigger::Manual, cx))
 8943    }
 8944
 8945    fn perform_format(
 8946        &mut self,
 8947        project: Model<Project>,
 8948        trigger: FormatTrigger,
 8949        cx: &mut ViewContext<Self>,
 8950    ) -> Task<Result<()>> {
 8951        let buffer = self.buffer().clone();
 8952        let mut buffers = buffer.read(cx).all_buffers();
 8953        if trigger == FormatTrigger::Save {
 8954            buffers.retain(|buffer| buffer.read(cx).is_dirty());
 8955        }
 8956
 8957        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
 8958        let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
 8959
 8960        cx.spawn(|_, mut cx| async move {
 8961            let transaction = futures::select_biased! {
 8962                () = timeout => {
 8963                    log::warn!("timed out waiting for formatting");
 8964                    None
 8965                }
 8966                transaction = format.log_err().fuse() => transaction,
 8967            };
 8968
 8969            buffer
 8970                .update(&mut cx, |buffer, cx| {
 8971                    if let Some(transaction) = transaction {
 8972                        if !buffer.is_singleton() {
 8973                            buffer.push_transaction(&transaction.0, cx);
 8974                        }
 8975                    }
 8976
 8977                    cx.notify();
 8978                })
 8979                .ok();
 8980
 8981            Ok(())
 8982        })
 8983    }
 8984
 8985    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
 8986        if let Some(project) = self.project.clone() {
 8987            self.buffer.update(cx, |multi_buffer, cx| {
 8988                project.update(cx, |project, cx| {
 8989                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
 8990                });
 8991            })
 8992        }
 8993    }
 8994
 8995    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
 8996        cx.show_character_palette();
 8997    }
 8998
 8999    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
 9000        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
 9001            let buffer = self.buffer.read(cx).snapshot(cx);
 9002            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
 9003            let is_valid = buffer
 9004                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
 9005                .any(|entry| {
 9006                    entry.diagnostic.is_primary
 9007                        && !entry.range.is_empty()
 9008                        && entry.range.start == primary_range_start
 9009                        && entry.diagnostic.message == active_diagnostics.primary_message
 9010                });
 9011
 9012            if is_valid != active_diagnostics.is_valid {
 9013                active_diagnostics.is_valid = is_valid;
 9014                let mut new_styles = HashMap::default();
 9015                for (block_id, diagnostic) in &active_diagnostics.blocks {
 9016                    new_styles.insert(
 9017                        *block_id,
 9018                        diagnostic_block_renderer(diagnostic.clone(), is_valid),
 9019                    );
 9020                }
 9021                self.display_map
 9022                    .update(cx, |display_map, _| display_map.replace_blocks(new_styles));
 9023            }
 9024        }
 9025    }
 9026
 9027    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
 9028        self.dismiss_diagnostics(cx);
 9029        let snapshot = self.snapshot(cx);
 9030        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
 9031            let buffer = self.buffer.read(cx).snapshot(cx);
 9032
 9033            let mut primary_range = None;
 9034            let mut primary_message = None;
 9035            let mut group_end = Point::zero();
 9036            let diagnostic_group = buffer
 9037                .diagnostic_group::<MultiBufferPoint>(group_id)
 9038                .filter_map(|entry| {
 9039                    if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
 9040                        && (entry.range.start.row == entry.range.end.row
 9041                            || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
 9042                    {
 9043                        return None;
 9044                    }
 9045                    if entry.range.end > group_end {
 9046                        group_end = entry.range.end;
 9047                    }
 9048                    if entry.diagnostic.is_primary {
 9049                        primary_range = Some(entry.range.clone());
 9050                        primary_message = Some(entry.diagnostic.message.clone());
 9051                    }
 9052                    Some(entry)
 9053                })
 9054                .collect::<Vec<_>>();
 9055            let primary_range = primary_range?;
 9056            let primary_message = primary_message?;
 9057            let primary_range =
 9058                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
 9059
 9060            let blocks = display_map
 9061                .insert_blocks(
 9062                    diagnostic_group.iter().map(|entry| {
 9063                        let diagnostic = entry.diagnostic.clone();
 9064                        let message_height = diagnostic.message.matches('\n').count() as u8 + 1;
 9065                        BlockProperties {
 9066                            style: BlockStyle::Fixed,
 9067                            position: buffer.anchor_after(entry.range.start),
 9068                            height: message_height,
 9069                            render: diagnostic_block_renderer(diagnostic, true),
 9070                            disposition: BlockDisposition::Below,
 9071                        }
 9072                    }),
 9073                    cx,
 9074                )
 9075                .into_iter()
 9076                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
 9077                .collect();
 9078
 9079            Some(ActiveDiagnosticGroup {
 9080                primary_range,
 9081                primary_message,
 9082                group_id,
 9083                blocks,
 9084                is_valid: true,
 9085            })
 9086        });
 9087        self.active_diagnostics.is_some()
 9088    }
 9089
 9090    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
 9091        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
 9092            self.display_map.update(cx, |display_map, cx| {
 9093                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
 9094            });
 9095            cx.notify();
 9096        }
 9097    }
 9098
 9099    pub fn set_selections_from_remote(
 9100        &mut self,
 9101        selections: Vec<Selection<Anchor>>,
 9102        pending_selection: Option<Selection<Anchor>>,
 9103        cx: &mut ViewContext<Self>,
 9104    ) {
 9105        let old_cursor_position = self.selections.newest_anchor().head();
 9106        self.selections.change_with(cx, |s| {
 9107            s.select_anchors(selections);
 9108            if let Some(pending_selection) = pending_selection {
 9109                s.set_pending(pending_selection, SelectMode::Character);
 9110            } else {
 9111                s.clear_pending();
 9112            }
 9113        });
 9114        self.selections_did_change(false, &old_cursor_position, cx);
 9115    }
 9116
 9117    fn push_to_selection_history(&mut self) {
 9118        self.selection_history.push(SelectionHistoryEntry {
 9119            selections: self.selections.disjoint_anchors(),
 9120            select_next_state: self.select_next_state.clone(),
 9121            select_prev_state: self.select_prev_state.clone(),
 9122            add_selections_state: self.add_selections_state.clone(),
 9123        });
 9124    }
 9125
 9126    pub fn transact(
 9127        &mut self,
 9128        cx: &mut ViewContext<Self>,
 9129        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
 9130    ) -> Option<TransactionId> {
 9131        self.start_transaction_at(Instant::now(), cx);
 9132        update(self, cx);
 9133        self.end_transaction_at(Instant::now(), cx)
 9134    }
 9135
 9136    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
 9137        self.end_selection(cx);
 9138        if let Some(tx_id) = self
 9139            .buffer
 9140            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
 9141        {
 9142            self.selection_history
 9143                .insert_transaction(tx_id, self.selections.disjoint_anchors());
 9144            cx.emit(EditorEvent::TransactionBegun {
 9145                transaction_id: tx_id,
 9146            })
 9147        }
 9148    }
 9149
 9150    fn end_transaction_at(
 9151        &mut self,
 9152        now: Instant,
 9153        cx: &mut ViewContext<Self>,
 9154    ) -> Option<TransactionId> {
 9155        if let Some(tx_id) = self
 9156            .buffer
 9157            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
 9158        {
 9159            if let Some((_, end_selections)) = self.selection_history.transaction_mut(tx_id) {
 9160                *end_selections = Some(self.selections.disjoint_anchors());
 9161            } else {
 9162                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
 9163            }
 9164
 9165            cx.emit(EditorEvent::Edited);
 9166            Some(tx_id)
 9167        } else {
 9168            None
 9169        }
 9170    }
 9171
 9172    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
 9173        let mut fold_ranges = Vec::new();
 9174
 9175        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9176
 9177        let selections = self.selections.all_adjusted(cx);
 9178        for selection in selections {
 9179            let range = selection.range().sorted();
 9180            let buffer_start_row = range.start.row;
 9181
 9182            for row in (0..=range.end.row).rev() {
 9183                let fold_range = display_map.foldable_range(MultiBufferRow(row));
 9184
 9185                if let Some(fold_range) = fold_range {
 9186                    if fold_range.end.row >= buffer_start_row {
 9187                        fold_ranges.push(fold_range);
 9188                        if row <= range.start.row {
 9189                            break;
 9190                        }
 9191                    }
 9192                }
 9193            }
 9194        }
 9195
 9196        self.fold_ranges(fold_ranges, true, cx);
 9197    }
 9198
 9199    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
 9200        let buffer_row = fold_at.buffer_row;
 9201        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9202
 9203        if let Some(fold_range) = display_map.foldable_range(buffer_row) {
 9204            let autoscroll = self
 9205                .selections
 9206                .all::<Point>(cx)
 9207                .iter()
 9208                .any(|selection| fold_range.overlaps(&selection.range()));
 9209
 9210            self.fold_ranges(std::iter::once(fold_range), autoscroll, cx);
 9211        }
 9212    }
 9213
 9214    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
 9215        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9216        let buffer = &display_map.buffer_snapshot;
 9217        let selections = self.selections.all::<Point>(cx);
 9218        let ranges = selections
 9219            .iter()
 9220            .map(|s| {
 9221                let range = s.display_range(&display_map).sorted();
 9222                let mut start = range.start.to_point(&display_map);
 9223                let mut end = range.end.to_point(&display_map);
 9224                start.column = 0;
 9225                end.column = buffer.line_len(MultiBufferRow(end.row));
 9226                start..end
 9227            })
 9228            .collect::<Vec<_>>();
 9229
 9230        self.unfold_ranges(ranges, true, true, cx);
 9231    }
 9232
 9233    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
 9234        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9235
 9236        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
 9237            ..Point::new(
 9238                unfold_at.buffer_row.0,
 9239                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
 9240            );
 9241
 9242        let autoscroll = self
 9243            .selections
 9244            .all::<Point>(cx)
 9245            .iter()
 9246            .any(|selection| selection.range().overlaps(&intersection_range));
 9247
 9248        self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
 9249    }
 9250
 9251    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
 9252        let selections = self.selections.all::<Point>(cx);
 9253        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9254        let line_mode = self.selections.line_mode;
 9255        let ranges = selections.into_iter().map(|s| {
 9256            if line_mode {
 9257                let start = Point::new(s.start.row, 0);
 9258                let end = Point::new(
 9259                    s.end.row,
 9260                    display_map
 9261                        .buffer_snapshot
 9262                        .line_len(MultiBufferRow(s.end.row)),
 9263                );
 9264                start..end
 9265            } else {
 9266                s.start..s.end
 9267            }
 9268        });
 9269        self.fold_ranges(ranges, true, cx);
 9270    }
 9271
 9272    pub fn fold_ranges<T: ToOffset + Clone>(
 9273        &mut self,
 9274        ranges: impl IntoIterator<Item = Range<T>>,
 9275        auto_scroll: bool,
 9276        cx: &mut ViewContext<Self>,
 9277    ) {
 9278        let mut fold_ranges = Vec::new();
 9279        let mut buffers_affected = HashMap::default();
 9280        let multi_buffer = self.buffer().read(cx);
 9281        for range in ranges {
 9282            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
 9283                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
 9284            };
 9285            fold_ranges.push(range);
 9286        }
 9287
 9288        let mut ranges = fold_ranges.into_iter().peekable();
 9289        if ranges.peek().is_some() {
 9290            self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
 9291
 9292            if auto_scroll {
 9293                self.request_autoscroll(Autoscroll::fit(), cx);
 9294            }
 9295
 9296            for buffer in buffers_affected.into_values() {
 9297                self.sync_expanded_diff_hunks(buffer, cx);
 9298            }
 9299
 9300            cx.notify();
 9301
 9302            if let Some(active_diagnostics) = self.active_diagnostics.take() {
 9303                // Clear diagnostics block when folding a range that contains it.
 9304                let snapshot = self.snapshot(cx);
 9305                if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
 9306                    drop(snapshot);
 9307                    self.active_diagnostics = Some(active_diagnostics);
 9308                    self.dismiss_diagnostics(cx);
 9309                } else {
 9310                    self.active_diagnostics = Some(active_diagnostics);
 9311                }
 9312            }
 9313
 9314            self.scrollbar_marker_state.dirty = true;
 9315        }
 9316    }
 9317
 9318    pub fn unfold_ranges<T: ToOffset + Clone>(
 9319        &mut self,
 9320        ranges: impl IntoIterator<Item = Range<T>>,
 9321        inclusive: bool,
 9322        auto_scroll: bool,
 9323        cx: &mut ViewContext<Self>,
 9324    ) {
 9325        let mut unfold_ranges = Vec::new();
 9326        let mut buffers_affected = HashMap::default();
 9327        let multi_buffer = self.buffer().read(cx);
 9328        for range in ranges {
 9329            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
 9330                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
 9331            };
 9332            unfold_ranges.push(range);
 9333        }
 9334
 9335        let mut ranges = unfold_ranges.into_iter().peekable();
 9336        if ranges.peek().is_some() {
 9337            self.display_map
 9338                .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
 9339            if auto_scroll {
 9340                self.request_autoscroll(Autoscroll::fit(), cx);
 9341            }
 9342
 9343            for buffer in buffers_affected.into_values() {
 9344                self.sync_expanded_diff_hunks(buffer, cx);
 9345            }
 9346
 9347            cx.notify();
 9348            self.scrollbar_marker_state.dirty = true;
 9349        }
 9350    }
 9351
 9352    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
 9353        if hovered != self.gutter_hovered {
 9354            self.gutter_hovered = hovered;
 9355            cx.notify();
 9356        }
 9357    }
 9358
 9359    pub fn insert_blocks(
 9360        &mut self,
 9361        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
 9362        autoscroll: Option<Autoscroll>,
 9363        cx: &mut ViewContext<Self>,
 9364    ) -> Vec<BlockId> {
 9365        let blocks = self
 9366            .display_map
 9367            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
 9368        if let Some(autoscroll) = autoscroll {
 9369            self.request_autoscroll(autoscroll, cx);
 9370        }
 9371        blocks
 9372    }
 9373
 9374    pub fn replace_blocks(
 9375        &mut self,
 9376        blocks: HashMap<BlockId, RenderBlock>,
 9377        autoscroll: Option<Autoscroll>,
 9378        cx: &mut ViewContext<Self>,
 9379    ) {
 9380        self.display_map
 9381            .update(cx, |display_map, _| display_map.replace_blocks(blocks));
 9382        if let Some(autoscroll) = autoscroll {
 9383            self.request_autoscroll(autoscroll, cx);
 9384        }
 9385    }
 9386
 9387    pub fn remove_blocks(
 9388        &mut self,
 9389        block_ids: HashSet<BlockId>,
 9390        autoscroll: Option<Autoscroll>,
 9391        cx: &mut ViewContext<Self>,
 9392    ) {
 9393        self.display_map.update(cx, |display_map, cx| {
 9394            display_map.remove_blocks(block_ids, cx)
 9395        });
 9396        if let Some(autoscroll) = autoscroll {
 9397            self.request_autoscroll(autoscroll, cx);
 9398        }
 9399    }
 9400
 9401    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
 9402        self.display_map
 9403            .update(cx, |map, cx| map.snapshot(cx))
 9404            .longest_row()
 9405    }
 9406
 9407    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
 9408        self.display_map
 9409            .update(cx, |map, cx| map.snapshot(cx))
 9410            .max_point()
 9411    }
 9412
 9413    pub fn text(&self, cx: &AppContext) -> String {
 9414        self.buffer.read(cx).read(cx).text()
 9415    }
 9416
 9417    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
 9418        let text = self.text(cx);
 9419        let text = text.trim();
 9420
 9421        if text.is_empty() {
 9422            return None;
 9423        }
 9424
 9425        Some(text.to_string())
 9426    }
 9427
 9428    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
 9429        self.transact(cx, |this, cx| {
 9430            this.buffer
 9431                .read(cx)
 9432                .as_singleton()
 9433                .expect("you can only call set_text on editors for singleton buffers")
 9434                .update(cx, |buffer, cx| buffer.set_text(text, cx));
 9435        });
 9436    }
 9437
 9438    pub fn display_text(&self, cx: &mut AppContext) -> String {
 9439        self.display_map
 9440            .update(cx, |map, cx| map.snapshot(cx))
 9441            .text()
 9442    }
 9443
 9444    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
 9445        let mut wrap_guides = smallvec::smallvec![];
 9446
 9447        if self.show_wrap_guides == Some(false) {
 9448            return wrap_guides;
 9449        }
 9450
 9451        let settings = self.buffer.read(cx).settings_at(0, cx);
 9452        if settings.show_wrap_guides {
 9453            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
 9454                wrap_guides.push((soft_wrap as usize, true));
 9455            }
 9456            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
 9457        }
 9458
 9459        wrap_guides
 9460    }
 9461
 9462    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
 9463        let settings = self.buffer.read(cx).settings_at(0, cx);
 9464        let mode = self
 9465            .soft_wrap_mode_override
 9466            .unwrap_or_else(|| settings.soft_wrap);
 9467        match mode {
 9468            language_settings::SoftWrap::None => SoftWrap::None,
 9469            language_settings::SoftWrap::PreferLine => SoftWrap::PreferLine,
 9470            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
 9471            language_settings::SoftWrap::PreferredLineLength => {
 9472                SoftWrap::Column(settings.preferred_line_length)
 9473            }
 9474        }
 9475    }
 9476
 9477    pub fn set_soft_wrap_mode(
 9478        &mut self,
 9479        mode: language_settings::SoftWrap,
 9480        cx: &mut ViewContext<Self>,
 9481    ) {
 9482        self.soft_wrap_mode_override = Some(mode);
 9483        cx.notify();
 9484    }
 9485
 9486    pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
 9487        let rem_size = cx.rem_size();
 9488        self.display_map.update(cx, |map, cx| {
 9489            map.set_font(
 9490                style.text.font(),
 9491                style.text.font_size.to_pixels(rem_size),
 9492                cx,
 9493            )
 9494        });
 9495        self.style = Some(style);
 9496    }
 9497
 9498    pub fn style(&self) -> Option<&EditorStyle> {
 9499        self.style.as_ref()
 9500    }
 9501
 9502    // Called by the element. This method is not designed to be called outside of the editor
 9503    // element's layout code because it does not notify when rewrapping is computed synchronously.
 9504    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
 9505        self.display_map
 9506            .update(cx, |map, cx| map.set_wrap_width(width, cx))
 9507    }
 9508
 9509    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
 9510        if self.soft_wrap_mode_override.is_some() {
 9511            self.soft_wrap_mode_override.take();
 9512        } else {
 9513            let soft_wrap = match self.soft_wrap_mode(cx) {
 9514                SoftWrap::None | SoftWrap::PreferLine => language_settings::SoftWrap::EditorWidth,
 9515                SoftWrap::EditorWidth | SoftWrap::Column(_) => {
 9516                    language_settings::SoftWrap::PreferLine
 9517                }
 9518            };
 9519            self.soft_wrap_mode_override = Some(soft_wrap);
 9520        }
 9521        cx.notify();
 9522    }
 9523
 9524    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
 9525        let mut editor_settings = EditorSettings::get_global(cx).clone();
 9526        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
 9527        EditorSettings::override_global(editor_settings, cx);
 9528    }
 9529
 9530    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
 9531        self.show_gutter = show_gutter;
 9532        cx.notify();
 9533    }
 9534
 9535    pub fn set_show_wrap_guides(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
 9536        self.show_wrap_guides = Some(show_gutter);
 9537        cx.notify();
 9538    }
 9539
 9540    pub fn reveal_in_finder(&mut self, _: &RevealInFinder, cx: &mut ViewContext<Self>) {
 9541        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
 9542            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
 9543                cx.reveal_path(&file.abs_path(cx));
 9544            }
 9545        }
 9546    }
 9547
 9548    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
 9549        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
 9550            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
 9551                if let Some(path) = file.abs_path(cx).to_str() {
 9552                    cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
 9553                }
 9554            }
 9555        }
 9556    }
 9557
 9558    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
 9559        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
 9560            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
 9561                if let Some(path) = file.path().to_str() {
 9562                    cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
 9563                }
 9564            }
 9565        }
 9566    }
 9567
 9568    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
 9569        self.show_git_blame_gutter = !self.show_git_blame_gutter;
 9570
 9571        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
 9572            self.start_git_blame(true, cx);
 9573        }
 9574
 9575        cx.notify();
 9576    }
 9577
 9578    pub fn toggle_git_blame_inline(
 9579        &mut self,
 9580        _: &ToggleGitBlameInline,
 9581        cx: &mut ViewContext<Self>,
 9582    ) {
 9583        self.toggle_git_blame_inline_internal(true, cx);
 9584        cx.notify();
 9585    }
 9586
 9587    pub fn git_blame_inline_enabled(&self) -> bool {
 9588        self.git_blame_inline_enabled
 9589    }
 9590
 9591    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
 9592        if let Some(project) = self.project.as_ref() {
 9593            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
 9594                return;
 9595            };
 9596
 9597            if buffer.read(cx).file().is_none() {
 9598                return;
 9599            }
 9600
 9601            let focused = self.focus_handle(cx).contains_focused(cx);
 9602
 9603            let project = project.clone();
 9604            let blame =
 9605                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
 9606            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
 9607            self.blame = Some(blame);
 9608        }
 9609    }
 9610
 9611    fn toggle_git_blame_inline_internal(
 9612        &mut self,
 9613        user_triggered: bool,
 9614        cx: &mut ViewContext<Self>,
 9615    ) {
 9616        if self.git_blame_inline_enabled {
 9617            self.git_blame_inline_enabled = false;
 9618            self.show_git_blame_inline = false;
 9619            self.show_git_blame_inline_delay_task.take();
 9620        } else {
 9621            self.git_blame_inline_enabled = true;
 9622            self.start_git_blame_inline(user_triggered, cx);
 9623        }
 9624
 9625        cx.notify();
 9626    }
 9627
 9628    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
 9629        self.start_git_blame(user_triggered, cx);
 9630
 9631        if ProjectSettings::get_global(cx)
 9632            .git
 9633            .inline_blame_delay()
 9634            .is_some()
 9635        {
 9636            self.start_inline_blame_timer(cx);
 9637        } else {
 9638            self.show_git_blame_inline = true
 9639        }
 9640    }
 9641
 9642    pub fn blame(&self) -> Option<&Model<GitBlame>> {
 9643        self.blame.as_ref()
 9644    }
 9645
 9646    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
 9647        self.show_git_blame_gutter && self.has_blame_entries(cx)
 9648    }
 9649
 9650    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
 9651        self.show_git_blame_inline
 9652            && self.focus_handle.is_focused(cx)
 9653            && !self.newest_selection_head_on_empty_line(cx)
 9654            && self.has_blame_entries(cx)
 9655    }
 9656
 9657    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
 9658        self.blame()
 9659            .map_or(false, |blame| blame.read(cx).has_generated_entries())
 9660    }
 9661
 9662    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
 9663        let cursor_anchor = self.selections.newest_anchor().head();
 9664
 9665        let snapshot = self.buffer.read(cx).snapshot(cx);
 9666        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
 9667
 9668        snapshot.line_len(buffer_row) == 0
 9669    }
 9670
 9671    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
 9672        let (path, repo) = maybe!({
 9673            let project_handle = self.project.as_ref()?.clone();
 9674            let project = project_handle.read(cx);
 9675            let buffer = self.buffer().read(cx).as_singleton()?;
 9676            let path = buffer
 9677                .read(cx)
 9678                .file()?
 9679                .as_local()?
 9680                .path()
 9681                .to_str()?
 9682                .to_string();
 9683            let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
 9684            Some((path, repo))
 9685        })
 9686        .ok_or_else(|| anyhow!("unable to open git repository"))?;
 9687
 9688        const REMOTE_NAME: &str = "origin";
 9689        let origin_url = repo
 9690            .lock()
 9691            .remote_url(REMOTE_NAME)
 9692            .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
 9693        let sha = repo
 9694            .lock()
 9695            .head_sha()
 9696            .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
 9697        let selections = self.selections.all::<Point>(cx);
 9698        let selection = selections.iter().peekable().next();
 9699
 9700        let (provider, remote) =
 9701            parse_git_remote_url(GitHostingProviderRegistry::default_global(cx), &origin_url)
 9702                .ok_or_else(|| anyhow!("failed to parse Git remote URL"))?;
 9703
 9704        Ok(provider.build_permalink(
 9705            remote,
 9706            BuildPermalinkParams {
 9707                sha: &sha,
 9708                path: &path,
 9709                selection: selection.map(|selection| {
 9710                    let range = selection.range();
 9711                    let start = range.start.row;
 9712                    let end = range.end.row;
 9713                    start..end
 9714                }),
 9715            },
 9716        ))
 9717    }
 9718
 9719    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
 9720        let permalink = self.get_permalink_to_line(cx);
 9721
 9722        match permalink {
 9723            Ok(permalink) => {
 9724                cx.write_to_clipboard(ClipboardItem::new(permalink.to_string()));
 9725            }
 9726            Err(err) => {
 9727                let message = format!("Failed to copy permalink: {err}");
 9728
 9729                Err::<(), anyhow::Error>(err).log_err();
 9730
 9731                if let Some(workspace) = self.workspace() {
 9732                    workspace.update(cx, |workspace, cx| {
 9733                        struct CopyPermalinkToLine;
 9734
 9735                        workspace.show_toast(
 9736                            Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
 9737                            cx,
 9738                        )
 9739                    })
 9740                }
 9741            }
 9742        }
 9743    }
 9744
 9745    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
 9746        let permalink = self.get_permalink_to_line(cx);
 9747
 9748        match permalink {
 9749            Ok(permalink) => {
 9750                cx.open_url(permalink.as_ref());
 9751            }
 9752            Err(err) => {
 9753                let message = format!("Failed to open permalink: {err}");
 9754
 9755                Err::<(), anyhow::Error>(err).log_err();
 9756
 9757                if let Some(workspace) = self.workspace() {
 9758                    workspace.update(cx, |workspace, cx| {
 9759                        struct OpenPermalinkToLine;
 9760
 9761                        workspace.show_toast(
 9762                            Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
 9763                            cx,
 9764                        )
 9765                    })
 9766                }
 9767            }
 9768        }
 9769    }
 9770
 9771    /// Adds or removes (on `None` color) a highlight for the rows corresponding to the anchor range given.
 9772    /// On matching anchor range, replaces the old highlight; does not clear the other existing highlights.
 9773    /// If multiple anchor ranges will produce highlights for the same row, the last range added will be used.
 9774    pub fn highlight_rows<T: 'static>(
 9775        &mut self,
 9776        rows: RangeInclusive<Anchor>,
 9777        color: Option<Hsla>,
 9778        cx: &mut ViewContext<Self>,
 9779    ) {
 9780        let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
 9781        match self.highlighted_rows.entry(TypeId::of::<T>()) {
 9782            hash_map::Entry::Occupied(o) => {
 9783                let row_highlights = o.into_mut();
 9784                let existing_highlight_index =
 9785                    row_highlights.binary_search_by(|(_, highlight_range, _)| {
 9786                        highlight_range
 9787                            .start()
 9788                            .cmp(&rows.start(), &multi_buffer_snapshot)
 9789                            .then(
 9790                                highlight_range
 9791                                    .end()
 9792                                    .cmp(&rows.end(), &multi_buffer_snapshot),
 9793                            )
 9794                    });
 9795                match color {
 9796                    Some(color) => {
 9797                        let insert_index = match existing_highlight_index {
 9798                            Ok(i) => i,
 9799                            Err(i) => i,
 9800                        };
 9801                        row_highlights.insert(
 9802                            insert_index,
 9803                            (post_inc(&mut self.highlight_order), rows, Some(color)),
 9804                        );
 9805                    }
 9806                    None => match existing_highlight_index {
 9807                        Ok(i) => {
 9808                            row_highlights.remove(i);
 9809                        }
 9810                        Err(i) => {
 9811                            row_highlights
 9812                                .insert(i, (post_inc(&mut self.highlight_order), rows, None));
 9813                        }
 9814                    },
 9815                }
 9816            }
 9817            hash_map::Entry::Vacant(v) => {
 9818                v.insert(vec![(post_inc(&mut self.highlight_order), rows, color)]);
 9819            }
 9820        }
 9821    }
 9822
 9823    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
 9824    pub fn clear_row_highlights<T: 'static>(&mut self) {
 9825        self.highlighted_rows.remove(&TypeId::of::<T>());
 9826    }
 9827
 9828    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
 9829    pub fn highlighted_rows<T: 'static>(
 9830        &self,
 9831    ) -> Option<impl Iterator<Item = (&RangeInclusive<Anchor>, Option<&Hsla>)>> {
 9832        Some(
 9833            self.highlighted_rows
 9834                .get(&TypeId::of::<T>())?
 9835                .iter()
 9836                .map(|(_, range, color)| (range, color.as_ref())),
 9837        )
 9838    }
 9839
 9840    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
 9841    /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
 9842    /// Allows to ignore certain kinds of highlights.
 9843    pub fn highlighted_display_rows(
 9844        &mut self,
 9845        exclude_highlights: HashSet<TypeId>,
 9846        cx: &mut WindowContext,
 9847    ) -> BTreeMap<DisplayRow, Hsla> {
 9848        let snapshot = self.snapshot(cx);
 9849        let mut used_highlight_orders = HashMap::default();
 9850        self.highlighted_rows
 9851            .iter()
 9852            .filter(|(type_id, _)| !exclude_highlights.contains(type_id))
 9853            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
 9854            .fold(
 9855                BTreeMap::<DisplayRow, Hsla>::new(),
 9856                |mut unique_rows, (highlight_order, anchor_range, hsla)| {
 9857                    let start_row = anchor_range.start().to_display_point(&snapshot).row();
 9858                    let end_row = anchor_range.end().to_display_point(&snapshot).row();
 9859                    for row in start_row.0..=end_row.0 {
 9860                        let used_index =
 9861                            used_highlight_orders.entry(row).or_insert(*highlight_order);
 9862                        if highlight_order >= used_index {
 9863                            *used_index = *highlight_order;
 9864                            match hsla {
 9865                                Some(hsla) => {
 9866                                    unique_rows.insert(DisplayRow(row), *hsla);
 9867                                }
 9868                                None => {
 9869                                    unique_rows.remove(&DisplayRow(row));
 9870                                }
 9871                            }
 9872                        }
 9873                    }
 9874                    unique_rows
 9875                },
 9876            )
 9877    }
 9878
 9879    pub fn set_search_within_ranges(
 9880        &mut self,
 9881        ranges: &[Range<Anchor>],
 9882        cx: &mut ViewContext<Self>,
 9883    ) {
 9884        self.highlight_background::<SearchWithinRange>(
 9885            ranges,
 9886            |colors| colors.editor_document_highlight_read_background,
 9887            cx,
 9888        )
 9889    }
 9890
 9891    pub fn highlight_background<T: 'static>(
 9892        &mut self,
 9893        ranges: &[Range<Anchor>],
 9894        color_fetcher: fn(&ThemeColors) -> Hsla,
 9895        cx: &mut ViewContext<Self>,
 9896    ) {
 9897        let snapshot = self.snapshot(cx);
 9898        // this is to try and catch a panic sooner
 9899        for range in ranges {
 9900            snapshot
 9901                .buffer_snapshot
 9902                .summary_for_anchor::<usize>(&range.start);
 9903            snapshot
 9904                .buffer_snapshot
 9905                .summary_for_anchor::<usize>(&range.end);
 9906        }
 9907
 9908        self.background_highlights
 9909            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
 9910        self.scrollbar_marker_state.dirty = true;
 9911        cx.notify();
 9912    }
 9913
 9914    pub fn clear_background_highlights<T: 'static>(
 9915        &mut self,
 9916        cx: &mut ViewContext<Self>,
 9917    ) -> Option<BackgroundHighlight> {
 9918        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
 9919        if !text_highlights.1.is_empty() {
 9920            self.scrollbar_marker_state.dirty = true;
 9921            cx.notify();
 9922        }
 9923        Some(text_highlights)
 9924    }
 9925
 9926    #[cfg(feature = "test-support")]
 9927    pub fn all_text_background_highlights(
 9928        &mut self,
 9929        cx: &mut ViewContext<Self>,
 9930    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
 9931        let snapshot = self.snapshot(cx);
 9932        let buffer = &snapshot.buffer_snapshot;
 9933        let start = buffer.anchor_before(0);
 9934        let end = buffer.anchor_after(buffer.len());
 9935        let theme = cx.theme().colors();
 9936        self.background_highlights_in_range(start..end, &snapshot, theme)
 9937    }
 9938
 9939    fn document_highlights_for_position<'a>(
 9940        &'a self,
 9941        position: Anchor,
 9942        buffer: &'a MultiBufferSnapshot,
 9943    ) -> impl 'a + Iterator<Item = &Range<Anchor>> {
 9944        let read_highlights = self
 9945            .background_highlights
 9946            .get(&TypeId::of::<DocumentHighlightRead>())
 9947            .map(|h| &h.1);
 9948        let write_highlights = self
 9949            .background_highlights
 9950            .get(&TypeId::of::<DocumentHighlightWrite>())
 9951            .map(|h| &h.1);
 9952        let left_position = position.bias_left(buffer);
 9953        let right_position = position.bias_right(buffer);
 9954        read_highlights
 9955            .into_iter()
 9956            .chain(write_highlights)
 9957            .flat_map(move |ranges| {
 9958                let start_ix = match ranges.binary_search_by(|probe| {
 9959                    let cmp = probe.end.cmp(&left_position, buffer);
 9960                    if cmp.is_ge() {
 9961                        Ordering::Greater
 9962                    } else {
 9963                        Ordering::Less
 9964                    }
 9965                }) {
 9966                    Ok(i) | Err(i) => i,
 9967                };
 9968
 9969                ranges[start_ix..]
 9970                    .iter()
 9971                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
 9972            })
 9973    }
 9974
 9975    pub fn has_background_highlights<T: 'static>(&self) -> bool {
 9976        self.background_highlights
 9977            .get(&TypeId::of::<T>())
 9978            .map_or(false, |(_, highlights)| !highlights.is_empty())
 9979    }
 9980
 9981    pub fn background_highlights_in_range(
 9982        &self,
 9983        search_range: Range<Anchor>,
 9984        display_snapshot: &DisplaySnapshot,
 9985        theme: &ThemeColors,
 9986    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
 9987        let mut results = Vec::new();
 9988        for (color_fetcher, ranges) in self.background_highlights.values() {
 9989            let color = color_fetcher(theme);
 9990            let start_ix = match ranges.binary_search_by(|probe| {
 9991                let cmp = probe
 9992                    .end
 9993                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
 9994                if cmp.is_gt() {
 9995                    Ordering::Greater
 9996                } else {
 9997                    Ordering::Less
 9998                }
 9999            }) {
10000                Ok(i) | Err(i) => i,
10001            };
10002            for range in &ranges[start_ix..] {
10003                if range
10004                    .start
10005                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
10006                    .is_ge()
10007                {
10008                    break;
10009                }
10010
10011                let start = range.start.to_display_point(&display_snapshot);
10012                let end = range.end.to_display_point(&display_snapshot);
10013                results.push((start..end, color))
10014            }
10015        }
10016        results
10017    }
10018
10019    pub fn background_highlight_row_ranges<T: 'static>(
10020        &self,
10021        search_range: Range<Anchor>,
10022        display_snapshot: &DisplaySnapshot,
10023        count: usize,
10024    ) -> Vec<RangeInclusive<DisplayPoint>> {
10025        let mut results = Vec::new();
10026        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
10027            return vec![];
10028        };
10029
10030        let start_ix = match ranges.binary_search_by(|probe| {
10031            let cmp = probe
10032                .end
10033                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
10034            if cmp.is_gt() {
10035                Ordering::Greater
10036            } else {
10037                Ordering::Less
10038            }
10039        }) {
10040            Ok(i) | Err(i) => i,
10041        };
10042        let mut push_region = |start: Option<Point>, end: Option<Point>| {
10043            if let (Some(start_display), Some(end_display)) = (start, end) {
10044                results.push(
10045                    start_display.to_display_point(display_snapshot)
10046                        ..=end_display.to_display_point(display_snapshot),
10047                );
10048            }
10049        };
10050        let mut start_row: Option<Point> = None;
10051        let mut end_row: Option<Point> = None;
10052        if ranges.len() > count {
10053            return Vec::new();
10054        }
10055        for range in &ranges[start_ix..] {
10056            if range
10057                .start
10058                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
10059                .is_ge()
10060            {
10061                break;
10062            }
10063            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
10064            if let Some(current_row) = &end_row {
10065                if end.row == current_row.row {
10066                    continue;
10067                }
10068            }
10069            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
10070            if start_row.is_none() {
10071                assert_eq!(end_row, None);
10072                start_row = Some(start);
10073                end_row = Some(end);
10074                continue;
10075            }
10076            if let Some(current_end) = end_row.as_mut() {
10077                if start.row > current_end.row + 1 {
10078                    push_region(start_row, end_row);
10079                    start_row = Some(start);
10080                    end_row = Some(end);
10081                } else {
10082                    // Merge two hunks.
10083                    *current_end = end;
10084                }
10085            } else {
10086                unreachable!();
10087            }
10088        }
10089        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
10090        push_region(start_row, end_row);
10091        results
10092    }
10093
10094    /// Get the text ranges corresponding to the redaction query
10095    pub fn redacted_ranges(
10096        &self,
10097        search_range: Range<Anchor>,
10098        display_snapshot: &DisplaySnapshot,
10099        cx: &WindowContext,
10100    ) -> Vec<Range<DisplayPoint>> {
10101        display_snapshot
10102            .buffer_snapshot
10103            .redacted_ranges(search_range, |file| {
10104                if let Some(file) = file {
10105                    file.is_private()
10106                        && EditorSettings::get(Some(file.as_ref().into()), cx).redact_private_values
10107                } else {
10108                    false
10109                }
10110            })
10111            .map(|range| {
10112                range.start.to_display_point(display_snapshot)
10113                    ..range.end.to_display_point(display_snapshot)
10114            })
10115            .collect()
10116    }
10117
10118    pub fn highlight_text<T: 'static>(
10119        &mut self,
10120        ranges: Vec<Range<Anchor>>,
10121        style: HighlightStyle,
10122        cx: &mut ViewContext<Self>,
10123    ) {
10124        self.display_map.update(cx, |map, _| {
10125            map.highlight_text(TypeId::of::<T>(), ranges, style)
10126        });
10127        cx.notify();
10128    }
10129
10130    pub(crate) fn highlight_inlays<T: 'static>(
10131        &mut self,
10132        highlights: Vec<InlayHighlight>,
10133        style: HighlightStyle,
10134        cx: &mut ViewContext<Self>,
10135    ) {
10136        self.display_map.update(cx, |map, _| {
10137            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
10138        });
10139        cx.notify();
10140    }
10141
10142    pub fn text_highlights<'a, T: 'static>(
10143        &'a self,
10144        cx: &'a AppContext,
10145    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
10146        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
10147    }
10148
10149    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
10150        let cleared = self
10151            .display_map
10152            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
10153        if cleared {
10154            cx.notify();
10155        }
10156    }
10157
10158    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
10159        (self.read_only(cx) || self.blink_manager.read(cx).visible())
10160            && self.focus_handle.is_focused(cx)
10161    }
10162
10163    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
10164        cx.notify();
10165    }
10166
10167    fn on_buffer_event(
10168        &mut self,
10169        multibuffer: Model<MultiBuffer>,
10170        event: &multi_buffer::Event,
10171        cx: &mut ViewContext<Self>,
10172    ) {
10173        match event {
10174            multi_buffer::Event::Edited {
10175                singleton_buffer_edited,
10176            } => {
10177                self.scrollbar_marker_state.dirty = true;
10178                self.refresh_active_diagnostics(cx);
10179                self.refresh_code_actions(cx);
10180                if self.has_active_inline_completion(cx) {
10181                    self.update_visible_inline_completion(cx);
10182                }
10183                cx.emit(EditorEvent::BufferEdited);
10184                cx.emit(SearchEvent::MatchesInvalidated);
10185
10186                if *singleton_buffer_edited {
10187                    if let Some(project) = &self.project {
10188                        let project = project.read(cx);
10189                        let languages_affected = multibuffer
10190                            .read(cx)
10191                            .all_buffers()
10192                            .into_iter()
10193                            .filter_map(|buffer| {
10194                                let buffer = buffer.read(cx);
10195                                let language = buffer.language()?;
10196                                if project.is_local()
10197                                    && project.language_servers_for_buffer(buffer, cx).count() == 0
10198                                {
10199                                    None
10200                                } else {
10201                                    Some(language)
10202                                }
10203                            })
10204                            .cloned()
10205                            .collect::<HashSet<_>>();
10206                        if !languages_affected.is_empty() {
10207                            self.refresh_inlay_hints(
10208                                InlayHintRefreshReason::BufferEdited(languages_affected),
10209                                cx,
10210                            );
10211                        }
10212                    }
10213                }
10214
10215                let Some(project) = &self.project else { return };
10216                let telemetry = project.read(cx).client().telemetry().clone();
10217                telemetry.log_edit_event("editor");
10218            }
10219            multi_buffer::Event::ExcerptsAdded {
10220                buffer,
10221                predecessor,
10222                excerpts,
10223            } => {
10224                self.tasks_update_task = Some(self.refresh_runnables(cx));
10225                cx.emit(EditorEvent::ExcerptsAdded {
10226                    buffer: buffer.clone(),
10227                    predecessor: *predecessor,
10228                    excerpts: excerpts.clone(),
10229                });
10230                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
10231            }
10232            multi_buffer::Event::ExcerptsRemoved { ids } => {
10233                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
10234                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
10235            }
10236            multi_buffer::Event::Reparsed => {
10237                self.tasks_update_task = Some(self.refresh_runnables(cx));
10238
10239                cx.emit(EditorEvent::Reparsed);
10240            }
10241            multi_buffer::Event::LanguageChanged => {
10242                cx.emit(EditorEvent::Reparsed);
10243                cx.notify();
10244            }
10245            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
10246            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
10247            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
10248                cx.emit(EditorEvent::TitleChanged)
10249            }
10250            multi_buffer::Event::DiffBaseChanged => {
10251                self.scrollbar_marker_state.dirty = true;
10252                cx.emit(EditorEvent::DiffBaseChanged);
10253                cx.notify();
10254            }
10255            multi_buffer::Event::DiffUpdated { buffer } => {
10256                self.sync_expanded_diff_hunks(buffer.clone(), cx);
10257                cx.notify();
10258            }
10259            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
10260            multi_buffer::Event::DiagnosticsUpdated => {
10261                self.refresh_active_diagnostics(cx);
10262                self.scrollbar_marker_state.dirty = true;
10263                cx.notify();
10264            }
10265            _ => {}
10266        };
10267    }
10268
10269    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
10270        cx.notify();
10271    }
10272
10273    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
10274        self.refresh_inline_completion(true, cx);
10275        self.refresh_inlay_hints(
10276            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
10277                self.selections.newest_anchor().head(),
10278                &self.buffer.read(cx).snapshot(cx),
10279                cx,
10280            )),
10281            cx,
10282        );
10283        let editor_settings = EditorSettings::get_global(cx);
10284        self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
10285        self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
10286
10287        if self.mode == EditorMode::Full {
10288            let inline_blame_enabled = ProjectSettings::get_global(cx).git.inline_blame_enabled();
10289            if self.git_blame_inline_enabled != inline_blame_enabled {
10290                self.toggle_git_blame_inline_internal(false, cx);
10291            }
10292        }
10293
10294        cx.notify();
10295    }
10296
10297    pub fn set_searchable(&mut self, searchable: bool) {
10298        self.searchable = searchable;
10299    }
10300
10301    pub fn searchable(&self) -> bool {
10302        self.searchable
10303    }
10304
10305    fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
10306        self.open_excerpts_common(true, cx)
10307    }
10308
10309    fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
10310        self.open_excerpts_common(false, cx)
10311    }
10312
10313    fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
10314        let buffer = self.buffer.read(cx);
10315        if buffer.is_singleton() {
10316            cx.propagate();
10317            return;
10318        }
10319
10320        let Some(workspace) = self.workspace() else {
10321            cx.propagate();
10322            return;
10323        };
10324
10325        let mut new_selections_by_buffer = HashMap::default();
10326        for selection in self.selections.all::<usize>(cx) {
10327            for (buffer, mut range, _) in
10328                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
10329            {
10330                if selection.reversed {
10331                    mem::swap(&mut range.start, &mut range.end);
10332                }
10333                new_selections_by_buffer
10334                    .entry(buffer)
10335                    .or_insert(Vec::new())
10336                    .push(range)
10337            }
10338        }
10339
10340        // We defer the pane interaction because we ourselves are a workspace item
10341        // and activating a new item causes the pane to call a method on us reentrantly,
10342        // which panics if we're on the stack.
10343        cx.window_context().defer(move |cx| {
10344            workspace.update(cx, |workspace, cx| {
10345                let pane = if split {
10346                    workspace.adjacent_pane(cx)
10347                } else {
10348                    workspace.active_pane().clone()
10349                };
10350
10351                for (buffer, ranges) in new_selections_by_buffer {
10352                    let editor = workspace.open_project_item::<Self>(pane.clone(), buffer, cx);
10353                    editor.update(cx, |editor, cx| {
10354                        editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
10355                            s.select_ranges(ranges);
10356                        });
10357                    });
10358                }
10359            })
10360        });
10361    }
10362
10363    fn jump(
10364        &mut self,
10365        path: ProjectPath,
10366        position: Point,
10367        anchor: language::Anchor,
10368        offset_from_top: u32,
10369        cx: &mut ViewContext<Self>,
10370    ) {
10371        let workspace = self.workspace();
10372        cx.spawn(|_, mut cx| async move {
10373            let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
10374            let editor = workspace.update(&mut cx, |workspace, cx| {
10375                // Reset the preview item id before opening the new item
10376                workspace.active_pane().update(cx, |pane, cx| {
10377                    pane.set_preview_item_id(None, cx);
10378                });
10379                workspace.open_path_preview(path, None, true, true, cx)
10380            })?;
10381            let editor = editor
10382                .await?
10383                .downcast::<Editor>()
10384                .ok_or_else(|| anyhow!("opened item was not an editor"))?
10385                .downgrade();
10386            editor.update(&mut cx, |editor, cx| {
10387                let buffer = editor
10388                    .buffer()
10389                    .read(cx)
10390                    .as_singleton()
10391                    .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
10392                let buffer = buffer.read(cx);
10393                let cursor = if buffer.can_resolve(&anchor) {
10394                    language::ToPoint::to_point(&anchor, buffer)
10395                } else {
10396                    buffer.clip_point(position, Bias::Left)
10397                };
10398
10399                let nav_history = editor.nav_history.take();
10400                editor.change_selections(
10401                    Some(Autoscroll::top_relative(offset_from_top as usize)),
10402                    cx,
10403                    |s| {
10404                        s.select_ranges([cursor..cursor]);
10405                    },
10406                );
10407                editor.nav_history = nav_history;
10408
10409                anyhow::Ok(())
10410            })??;
10411
10412            anyhow::Ok(())
10413        })
10414        .detach_and_log_err(cx);
10415    }
10416
10417    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
10418        let snapshot = self.buffer.read(cx).read(cx);
10419        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
10420        Some(
10421            ranges
10422                .iter()
10423                .map(move |range| {
10424                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
10425                })
10426                .collect(),
10427        )
10428    }
10429
10430    fn selection_replacement_ranges(
10431        &self,
10432        range: Range<OffsetUtf16>,
10433        cx: &AppContext,
10434    ) -> Vec<Range<OffsetUtf16>> {
10435        let selections = self.selections.all::<OffsetUtf16>(cx);
10436        let newest_selection = selections
10437            .iter()
10438            .max_by_key(|selection| selection.id)
10439            .unwrap();
10440        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
10441        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
10442        let snapshot = self.buffer.read(cx).read(cx);
10443        selections
10444            .into_iter()
10445            .map(|mut selection| {
10446                selection.start.0 =
10447                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
10448                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
10449                snapshot.clip_offset_utf16(selection.start, Bias::Left)
10450                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
10451            })
10452            .collect()
10453    }
10454
10455    fn report_editor_event(
10456        &self,
10457        operation: &'static str,
10458        file_extension: Option<String>,
10459        cx: &AppContext,
10460    ) {
10461        if cfg!(any(test, feature = "test-support")) {
10462            return;
10463        }
10464
10465        let Some(project) = &self.project else { return };
10466
10467        // If None, we are in a file without an extension
10468        let file = self
10469            .buffer
10470            .read(cx)
10471            .as_singleton()
10472            .and_then(|b| b.read(cx).file());
10473        let file_extension = file_extension.or(file
10474            .as_ref()
10475            .and_then(|file| Path::new(file.file_name(cx)).extension())
10476            .and_then(|e| e.to_str())
10477            .map(|a| a.to_string()));
10478
10479        let vim_mode = cx
10480            .global::<SettingsStore>()
10481            .raw_user_settings()
10482            .get("vim_mode")
10483            == Some(&serde_json::Value::Bool(true));
10484
10485        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
10486            == language::language_settings::InlineCompletionProvider::Copilot;
10487        let copilot_enabled_for_language = self
10488            .buffer
10489            .read(cx)
10490            .settings_at(0, cx)
10491            .show_inline_completions;
10492
10493        let telemetry = project.read(cx).client().telemetry().clone();
10494        telemetry.report_editor_event(
10495            file_extension,
10496            vim_mode,
10497            operation,
10498            copilot_enabled,
10499            copilot_enabled_for_language,
10500        )
10501    }
10502
10503    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
10504    /// with each line being an array of {text, highlight} objects.
10505    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
10506        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
10507            return;
10508        };
10509
10510        #[derive(Serialize)]
10511        struct Chunk<'a> {
10512            text: String,
10513            highlight: Option<&'a str>,
10514        }
10515
10516        let snapshot = buffer.read(cx).snapshot();
10517        let range = self
10518            .selected_text_range(cx)
10519            .and_then(|selected_range| {
10520                if selected_range.is_empty() {
10521                    None
10522                } else {
10523                    Some(selected_range)
10524                }
10525            })
10526            .unwrap_or_else(|| 0..snapshot.len());
10527
10528        let chunks = snapshot.chunks(range, true);
10529        let mut lines = Vec::new();
10530        let mut line: VecDeque<Chunk> = VecDeque::new();
10531
10532        let Some(style) = self.style.as_ref() else {
10533            return;
10534        };
10535
10536        for chunk in chunks {
10537            let highlight = chunk
10538                .syntax_highlight_id
10539                .and_then(|id| id.name(&style.syntax));
10540            let mut chunk_lines = chunk.text.split('\n').peekable();
10541            while let Some(text) = chunk_lines.next() {
10542                let mut merged_with_last_token = false;
10543                if let Some(last_token) = line.back_mut() {
10544                    if last_token.highlight == highlight {
10545                        last_token.text.push_str(text);
10546                        merged_with_last_token = true;
10547                    }
10548                }
10549
10550                if !merged_with_last_token {
10551                    line.push_back(Chunk {
10552                        text: text.into(),
10553                        highlight,
10554                    });
10555                }
10556
10557                if chunk_lines.peek().is_some() {
10558                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
10559                        line.pop_front();
10560                    }
10561                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
10562                        line.pop_back();
10563                    }
10564
10565                    lines.push(mem::take(&mut line));
10566                }
10567            }
10568        }
10569
10570        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
10571            return;
10572        };
10573        cx.write_to_clipboard(ClipboardItem::new(lines));
10574    }
10575
10576    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
10577        &self.inlay_hint_cache
10578    }
10579
10580    pub fn replay_insert_event(
10581        &mut self,
10582        text: &str,
10583        relative_utf16_range: Option<Range<isize>>,
10584        cx: &mut ViewContext<Self>,
10585    ) {
10586        if !self.input_enabled {
10587            cx.emit(EditorEvent::InputIgnored { text: text.into() });
10588            return;
10589        }
10590        if let Some(relative_utf16_range) = relative_utf16_range {
10591            let selections = self.selections.all::<OffsetUtf16>(cx);
10592            self.change_selections(None, cx, |s| {
10593                let new_ranges = selections.into_iter().map(|range| {
10594                    let start = OffsetUtf16(
10595                        range
10596                            .head()
10597                            .0
10598                            .saturating_add_signed(relative_utf16_range.start),
10599                    );
10600                    let end = OffsetUtf16(
10601                        range
10602                            .head()
10603                            .0
10604                            .saturating_add_signed(relative_utf16_range.end),
10605                    );
10606                    start..end
10607                });
10608                s.select_ranges(new_ranges);
10609            });
10610        }
10611
10612        self.handle_input(text, cx);
10613    }
10614
10615    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
10616        let Some(project) = self.project.as_ref() else {
10617            return false;
10618        };
10619        let project = project.read(cx);
10620
10621        let mut supports = false;
10622        self.buffer().read(cx).for_each_buffer(|buffer| {
10623            if !supports {
10624                supports = project
10625                    .language_servers_for_buffer(buffer.read(cx), cx)
10626                    .any(
10627                        |(_, server)| match server.capabilities().inlay_hint_provider {
10628                            Some(lsp::OneOf::Left(enabled)) => enabled,
10629                            Some(lsp::OneOf::Right(_)) => true,
10630                            None => false,
10631                        },
10632                    )
10633            }
10634        });
10635        supports
10636    }
10637
10638    pub fn focus(&self, cx: &mut WindowContext) {
10639        cx.focus(&self.focus_handle)
10640    }
10641
10642    pub fn is_focused(&self, cx: &WindowContext) -> bool {
10643        self.focus_handle.is_focused(cx)
10644    }
10645
10646    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
10647        cx.emit(EditorEvent::Focused);
10648
10649        if let Some(rename) = self.pending_rename.as_ref() {
10650            let rename_editor_focus_handle = rename.editor.read(cx).focus_handle.clone();
10651            cx.focus(&rename_editor_focus_handle);
10652        } else {
10653            if let Some(blame) = self.blame.as_ref() {
10654                blame.update(cx, GitBlame::focus)
10655            }
10656
10657            self.blink_manager.update(cx, BlinkManager::enable);
10658            self.show_cursor_names(cx);
10659            self.buffer.update(cx, |buffer, cx| {
10660                buffer.finalize_last_transaction(cx);
10661                if self.leader_peer_id.is_none() {
10662                    buffer.set_active_selections(
10663                        &self.selections.disjoint_anchors(),
10664                        self.selections.line_mode,
10665                        self.cursor_shape,
10666                        cx,
10667                    );
10668                }
10669            });
10670        }
10671    }
10672
10673    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
10674        self.blink_manager.update(cx, BlinkManager::disable);
10675        self.buffer
10676            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
10677
10678        if let Some(blame) = self.blame.as_ref() {
10679            blame.update(cx, GitBlame::blur)
10680        }
10681        self.hide_context_menu(cx);
10682        hide_hover(self, cx);
10683        cx.emit(EditorEvent::Blurred);
10684        cx.notify();
10685    }
10686
10687    pub fn register_action<A: Action>(
10688        &mut self,
10689        listener: impl Fn(&A, &mut WindowContext) + 'static,
10690    ) -> &mut Self {
10691        let listener = Arc::new(listener);
10692
10693        self.editor_actions.push(Box::new(move |cx| {
10694            let _view = cx.view().clone();
10695            let cx = cx.window_context();
10696            let listener = listener.clone();
10697            cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
10698                let action = action.downcast_ref().unwrap();
10699                if phase == DispatchPhase::Bubble {
10700                    listener(action, cx)
10701                }
10702            })
10703        }));
10704        self
10705    }
10706}
10707
10708fn hunks_for_selections(
10709    multi_buffer_snapshot: &MultiBufferSnapshot,
10710    selections: &[Selection<Anchor>],
10711) -> Vec<DiffHunk<MultiBufferRow>> {
10712    let mut hunks = Vec::with_capacity(selections.len());
10713    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
10714        HashMap::default();
10715    let buffer_rows_for_selections = selections.iter().map(|selection| {
10716        let head = selection.head();
10717        let tail = selection.tail();
10718        let start = MultiBufferRow(tail.to_point(&multi_buffer_snapshot).row);
10719        let end = MultiBufferRow(head.to_point(&multi_buffer_snapshot).row);
10720        if start > end {
10721            end..start
10722        } else {
10723            start..end
10724        }
10725    });
10726
10727    for selected_multi_buffer_rows in buffer_rows_for_selections {
10728        let query_rows =
10729            selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
10730        for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
10731            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
10732            // when the caret is just above or just below the deleted hunk.
10733            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
10734            let related_to_selection = if allow_adjacent {
10735                hunk.associated_range.overlaps(&query_rows)
10736                    || hunk.associated_range.start == query_rows.end
10737                    || hunk.associated_range.end == query_rows.start
10738            } else {
10739                // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
10740                // `hunk.associated_range` is exclusive (e.g. [2..3] means 2nd row is selected)
10741                hunk.associated_range.overlaps(&selected_multi_buffer_rows)
10742                    || selected_multi_buffer_rows.end == hunk.associated_range.start
10743            };
10744            if related_to_selection {
10745                if !processed_buffer_rows
10746                    .entry(hunk.buffer_id)
10747                    .or_default()
10748                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
10749                {
10750                    continue;
10751                }
10752                hunks.push(hunk);
10753            }
10754        }
10755    }
10756
10757    hunks
10758}
10759
10760pub trait CollaborationHub {
10761    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
10762    fn user_participant_indices<'a>(
10763        &self,
10764        cx: &'a AppContext,
10765    ) -> &'a HashMap<u64, ParticipantIndex>;
10766    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
10767}
10768
10769impl CollaborationHub for Model<Project> {
10770    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
10771        self.read(cx).collaborators()
10772    }
10773
10774    fn user_participant_indices<'a>(
10775        &self,
10776        cx: &'a AppContext,
10777    ) -> &'a HashMap<u64, ParticipantIndex> {
10778        self.read(cx).user_store().read(cx).participant_indices()
10779    }
10780
10781    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
10782        let this = self.read(cx);
10783        let user_ids = this.collaborators().values().map(|c| c.user_id);
10784        this.user_store().read_with(cx, |user_store, cx| {
10785            user_store.participant_names(user_ids, cx)
10786        })
10787    }
10788}
10789
10790pub trait CompletionProvider {
10791    fn completions(
10792        &self,
10793        buffer: &Model<Buffer>,
10794        buffer_position: text::Anchor,
10795        cx: &mut ViewContext<Editor>,
10796    ) -> Task<Result<Vec<Completion>>>;
10797
10798    fn resolve_completions(
10799        &self,
10800        buffer: Model<Buffer>,
10801        completion_indices: Vec<usize>,
10802        completions: Arc<RwLock<Box<[Completion]>>>,
10803        cx: &mut ViewContext<Editor>,
10804    ) -> Task<Result<bool>>;
10805
10806    fn apply_additional_edits_for_completion(
10807        &self,
10808        buffer: Model<Buffer>,
10809        completion: Completion,
10810        push_to_history: bool,
10811        cx: &mut ViewContext<Editor>,
10812    ) -> Task<Result<Option<language::Transaction>>>;
10813}
10814
10815impl CompletionProvider for Model<Project> {
10816    fn completions(
10817        &self,
10818        buffer: &Model<Buffer>,
10819        buffer_position: text::Anchor,
10820        cx: &mut ViewContext<Editor>,
10821    ) -> Task<Result<Vec<Completion>>> {
10822        self.update(cx, |project, cx| {
10823            project.completions(&buffer, buffer_position, cx)
10824        })
10825    }
10826
10827    fn resolve_completions(
10828        &self,
10829        buffer: Model<Buffer>,
10830        completion_indices: Vec<usize>,
10831        completions: Arc<RwLock<Box<[Completion]>>>,
10832        cx: &mut ViewContext<Editor>,
10833    ) -> Task<Result<bool>> {
10834        self.update(cx, |project, cx| {
10835            project.resolve_completions(buffer, completion_indices, completions, cx)
10836        })
10837    }
10838
10839    fn apply_additional_edits_for_completion(
10840        &self,
10841        buffer: Model<Buffer>,
10842        completion: Completion,
10843        push_to_history: bool,
10844        cx: &mut ViewContext<Editor>,
10845    ) -> Task<Result<Option<language::Transaction>>> {
10846        self.update(cx, |project, cx| {
10847            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
10848        })
10849    }
10850}
10851
10852fn inlay_hint_settings(
10853    location: Anchor,
10854    snapshot: &MultiBufferSnapshot,
10855    cx: &mut ViewContext<'_, Editor>,
10856) -> InlayHintSettings {
10857    let file = snapshot.file_at(location);
10858    let language = snapshot.language_at(location);
10859    let settings = all_language_settings(file, cx);
10860    settings
10861        .language(language.map(|l| l.name()).as_deref())
10862        .inlay_hints
10863}
10864
10865fn consume_contiguous_rows(
10866    contiguous_row_selections: &mut Vec<Selection<Point>>,
10867    selection: &Selection<Point>,
10868    display_map: &DisplaySnapshot,
10869    selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
10870) -> (MultiBufferRow, MultiBufferRow) {
10871    contiguous_row_selections.push(selection.clone());
10872    let start_row = MultiBufferRow(selection.start.row);
10873    let mut end_row = ending_row(selection, display_map);
10874
10875    while let Some(next_selection) = selections.peek() {
10876        if next_selection.start.row <= end_row.0 {
10877            end_row = ending_row(next_selection, display_map);
10878            contiguous_row_selections.push(selections.next().unwrap().clone());
10879        } else {
10880            break;
10881        }
10882    }
10883    (start_row, end_row)
10884}
10885
10886fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
10887    if next_selection.end.column > 0 || next_selection.is_empty() {
10888        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
10889    } else {
10890        MultiBufferRow(next_selection.end.row)
10891    }
10892}
10893
10894impl EditorSnapshot {
10895    pub fn remote_selections_in_range<'a>(
10896        &'a self,
10897        range: &'a Range<Anchor>,
10898        collaboration_hub: &dyn CollaborationHub,
10899        cx: &'a AppContext,
10900    ) -> impl 'a + Iterator<Item = RemoteSelection> {
10901        let participant_names = collaboration_hub.user_names(cx);
10902        let participant_indices = collaboration_hub.user_participant_indices(cx);
10903        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
10904        let collaborators_by_replica_id = collaborators_by_peer_id
10905            .iter()
10906            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
10907            .collect::<HashMap<_, _>>();
10908        self.buffer_snapshot
10909            .remote_selections_in_range(range)
10910            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
10911                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
10912                let participant_index = participant_indices.get(&collaborator.user_id).copied();
10913                let user_name = participant_names.get(&collaborator.user_id).cloned();
10914                Some(RemoteSelection {
10915                    replica_id,
10916                    selection,
10917                    cursor_shape,
10918                    line_mode,
10919                    participant_index,
10920                    peer_id: collaborator.peer_id,
10921                    user_name,
10922                })
10923            })
10924    }
10925
10926    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
10927        self.display_snapshot.buffer_snapshot.language_at(position)
10928    }
10929
10930    pub fn is_focused(&self) -> bool {
10931        self.is_focused
10932    }
10933
10934    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
10935        self.placeholder_text.as_ref()
10936    }
10937
10938    pub fn scroll_position(&self) -> gpui::Point<f32> {
10939        self.scroll_anchor.scroll_position(&self.display_snapshot)
10940    }
10941
10942    pub fn gutter_dimensions(
10943        &self,
10944        font_id: FontId,
10945        font_size: Pixels,
10946        em_width: Pixels,
10947        max_line_number_width: Pixels,
10948        cx: &AppContext,
10949    ) -> GutterDimensions {
10950        if !self.show_gutter {
10951            return GutterDimensions::default();
10952        }
10953        let descent = cx.text_system().descent(font_id, font_size);
10954
10955        let show_git_gutter = matches!(
10956            ProjectSettings::get_global(cx).git.git_gutter,
10957            Some(GitGutterSetting::TrackedFiles)
10958        );
10959        let gutter_settings = EditorSettings::get_global(cx).gutter;
10960        let gutter_lines_enabled = gutter_settings.line_numbers;
10961        let line_gutter_width = if gutter_lines_enabled {
10962            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
10963            let min_width_for_number_on_gutter = em_width * 4.0;
10964            max_line_number_width.max(min_width_for_number_on_gutter)
10965        } else {
10966            0.0.into()
10967        };
10968
10969        let git_blame_entries_width = self
10970            .render_git_blame_gutter
10971            .then_some(em_width * GIT_BLAME_GUTTER_WIDTH_CHARS);
10972
10973        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
10974        left_padding += if gutter_settings.code_actions {
10975            em_width * 3.0
10976        } else if show_git_gutter && gutter_lines_enabled {
10977            em_width * 2.0
10978        } else if show_git_gutter || gutter_lines_enabled {
10979            em_width
10980        } else {
10981            px(0.)
10982        };
10983
10984        let right_padding = if gutter_settings.folds && gutter_lines_enabled {
10985            em_width * 4.0
10986        } else if gutter_settings.folds {
10987            em_width * 3.0
10988        } else if gutter_lines_enabled {
10989            em_width
10990        } else {
10991            px(0.)
10992        };
10993
10994        GutterDimensions {
10995            left_padding,
10996            right_padding,
10997            width: line_gutter_width + left_padding + right_padding,
10998            margin: -descent,
10999            git_blame_entries_width,
11000        }
11001    }
11002}
11003
11004impl Deref for EditorSnapshot {
11005    type Target = DisplaySnapshot;
11006
11007    fn deref(&self) -> &Self::Target {
11008        &self.display_snapshot
11009    }
11010}
11011
11012#[derive(Clone, Debug, PartialEq, Eq)]
11013pub enum EditorEvent {
11014    InputIgnored {
11015        text: Arc<str>,
11016    },
11017    InputHandled {
11018        utf16_range_to_replace: Option<Range<isize>>,
11019        text: Arc<str>,
11020    },
11021    ExcerptsAdded {
11022        buffer: Model<Buffer>,
11023        predecessor: ExcerptId,
11024        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
11025    },
11026    ExcerptsRemoved {
11027        ids: Vec<ExcerptId>,
11028    },
11029    BufferEdited,
11030    Edited,
11031    Reparsed,
11032    Focused,
11033    Blurred,
11034    DirtyChanged,
11035    Saved,
11036    TitleChanged,
11037    DiffBaseChanged,
11038    SelectionsChanged {
11039        local: bool,
11040    },
11041    ScrollPositionChanged {
11042        local: bool,
11043        autoscroll: bool,
11044    },
11045    Closed,
11046    TransactionUndone {
11047        transaction_id: clock::Lamport,
11048    },
11049    TransactionBegun {
11050        transaction_id: clock::Lamport,
11051    },
11052}
11053
11054impl EventEmitter<EditorEvent> for Editor {}
11055
11056impl FocusableView for Editor {
11057    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
11058        self.focus_handle.clone()
11059    }
11060}
11061
11062impl Render for Editor {
11063    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
11064        let settings = ThemeSettings::get_global(cx);
11065
11066        let text_style = match self.mode {
11067            EditorMode::SingleLine | EditorMode::AutoHeight { .. } => TextStyle {
11068                color: cx.theme().colors().editor_foreground,
11069                font_family: settings.ui_font.family.clone(),
11070                font_features: settings.ui_font.features.clone(),
11071                font_size: rems(0.875).into(),
11072                font_weight: FontWeight::NORMAL,
11073                font_style: FontStyle::Normal,
11074                line_height: relative(settings.buffer_line_height.value()),
11075                background_color: None,
11076                underline: None,
11077                strikethrough: None,
11078                white_space: WhiteSpace::Normal,
11079            },
11080            EditorMode::Full => TextStyle {
11081                color: cx.theme().colors().editor_foreground,
11082                font_family: settings.buffer_font.family.clone(),
11083                font_features: settings.buffer_font.features.clone(),
11084                font_size: settings.buffer_font_size(cx).into(),
11085                font_weight: FontWeight::NORMAL,
11086                font_style: FontStyle::Normal,
11087                line_height: relative(settings.buffer_line_height.value()),
11088                background_color: None,
11089                underline: None,
11090                strikethrough: None,
11091                white_space: WhiteSpace::Normal,
11092            },
11093        };
11094
11095        let background = match self.mode {
11096            EditorMode::SingleLine => cx.theme().system().transparent,
11097            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
11098            EditorMode::Full => cx.theme().colors().editor_background,
11099        };
11100
11101        EditorElement::new(
11102            cx.view(),
11103            EditorStyle {
11104                background,
11105                local_player: cx.theme().players().local(),
11106                text: text_style,
11107                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
11108                syntax: cx.theme().syntax().clone(),
11109                status: cx.theme().status().clone(),
11110                inlay_hints_style: HighlightStyle {
11111                    color: Some(cx.theme().status().hint),
11112                    ..HighlightStyle::default()
11113                },
11114                suggestions_style: HighlightStyle {
11115                    color: Some(cx.theme().status().predictive),
11116                    ..HighlightStyle::default()
11117                },
11118            },
11119        )
11120    }
11121}
11122
11123impl ViewInputHandler for Editor {
11124    fn text_for_range(
11125        &mut self,
11126        range_utf16: Range<usize>,
11127        cx: &mut ViewContext<Self>,
11128    ) -> Option<String> {
11129        Some(
11130            self.buffer
11131                .read(cx)
11132                .read(cx)
11133                .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
11134                .collect(),
11135        )
11136    }
11137
11138    fn selected_text_range(&mut self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
11139        // Prevent the IME menu from appearing when holding down an alphabetic key
11140        // while input is disabled.
11141        if !self.input_enabled {
11142            return None;
11143        }
11144
11145        let range = self.selections.newest::<OffsetUtf16>(cx).range();
11146        Some(range.start.0..range.end.0)
11147    }
11148
11149    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
11150        let snapshot = self.buffer.read(cx).read(cx);
11151        let range = self.text_highlights::<InputComposition>(cx)?.1.get(0)?;
11152        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
11153    }
11154
11155    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
11156        self.clear_highlights::<InputComposition>(cx);
11157        self.ime_transaction.take();
11158    }
11159
11160    fn replace_text_in_range(
11161        &mut self,
11162        range_utf16: Option<Range<usize>>,
11163        text: &str,
11164        cx: &mut ViewContext<Self>,
11165    ) {
11166        if !self.input_enabled {
11167            cx.emit(EditorEvent::InputIgnored { text: text.into() });
11168            return;
11169        }
11170
11171        self.transact(cx, |this, cx| {
11172            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
11173                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
11174                Some(this.selection_replacement_ranges(range_utf16, cx))
11175            } else {
11176                this.marked_text_ranges(cx)
11177            };
11178
11179            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
11180                let newest_selection_id = this.selections.newest_anchor().id;
11181                this.selections
11182                    .all::<OffsetUtf16>(cx)
11183                    .iter()
11184                    .zip(ranges_to_replace.iter())
11185                    .find_map(|(selection, range)| {
11186                        if selection.id == newest_selection_id {
11187                            Some(
11188                                (range.start.0 as isize - selection.head().0 as isize)
11189                                    ..(range.end.0 as isize - selection.head().0 as isize),
11190                            )
11191                        } else {
11192                            None
11193                        }
11194                    })
11195            });
11196
11197            cx.emit(EditorEvent::InputHandled {
11198                utf16_range_to_replace: range_to_replace,
11199                text: text.into(),
11200            });
11201
11202            if let Some(new_selected_ranges) = new_selected_ranges {
11203                this.change_selections(None, cx, |selections| {
11204                    selections.select_ranges(new_selected_ranges)
11205                });
11206                this.backspace(&Default::default(), cx);
11207            }
11208
11209            this.handle_input(text, cx);
11210        });
11211
11212        if let Some(transaction) = self.ime_transaction {
11213            self.buffer.update(cx, |buffer, cx| {
11214                buffer.group_until_transaction(transaction, cx);
11215            });
11216        }
11217
11218        self.unmark_text(cx);
11219    }
11220
11221    fn replace_and_mark_text_in_range(
11222        &mut self,
11223        range_utf16: Option<Range<usize>>,
11224        text: &str,
11225        new_selected_range_utf16: Option<Range<usize>>,
11226        cx: &mut ViewContext<Self>,
11227    ) {
11228        if !self.input_enabled {
11229            cx.emit(EditorEvent::InputIgnored { text: text.into() });
11230            return;
11231        }
11232
11233        let transaction = self.transact(cx, |this, cx| {
11234            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
11235                let snapshot = this.buffer.read(cx).read(cx);
11236                if let Some(relative_range_utf16) = range_utf16.as_ref() {
11237                    for marked_range in &mut marked_ranges {
11238                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
11239                        marked_range.start.0 += relative_range_utf16.start;
11240                        marked_range.start =
11241                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
11242                        marked_range.end =
11243                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
11244                    }
11245                }
11246                Some(marked_ranges)
11247            } else if let Some(range_utf16) = range_utf16 {
11248                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
11249                Some(this.selection_replacement_ranges(range_utf16, cx))
11250            } else {
11251                None
11252            };
11253
11254            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
11255                let newest_selection_id = this.selections.newest_anchor().id;
11256                this.selections
11257                    .all::<OffsetUtf16>(cx)
11258                    .iter()
11259                    .zip(ranges_to_replace.iter())
11260                    .find_map(|(selection, range)| {
11261                        if selection.id == newest_selection_id {
11262                            Some(
11263                                (range.start.0 as isize - selection.head().0 as isize)
11264                                    ..(range.end.0 as isize - selection.head().0 as isize),
11265                            )
11266                        } else {
11267                            None
11268                        }
11269                    })
11270            });
11271
11272            cx.emit(EditorEvent::InputHandled {
11273                utf16_range_to_replace: range_to_replace,
11274                text: text.into(),
11275            });
11276
11277            if let Some(ranges) = ranges_to_replace {
11278                this.change_selections(None, cx, |s| s.select_ranges(ranges));
11279            }
11280
11281            let marked_ranges = {
11282                let snapshot = this.buffer.read(cx).read(cx);
11283                this.selections
11284                    .disjoint_anchors()
11285                    .iter()
11286                    .map(|selection| {
11287                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
11288                    })
11289                    .collect::<Vec<_>>()
11290            };
11291
11292            if text.is_empty() {
11293                this.unmark_text(cx);
11294            } else {
11295                this.highlight_text::<InputComposition>(
11296                    marked_ranges.clone(),
11297                    HighlightStyle {
11298                        underline: Some(UnderlineStyle {
11299                            thickness: px(1.),
11300                            color: None,
11301                            wavy: false,
11302                        }),
11303                        ..Default::default()
11304                    },
11305                    cx,
11306                );
11307            }
11308
11309            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
11310            let use_autoclose = this.use_autoclose;
11311            this.set_use_autoclose(false);
11312            this.handle_input(text, cx);
11313            this.set_use_autoclose(use_autoclose);
11314
11315            if let Some(new_selected_range) = new_selected_range_utf16 {
11316                let snapshot = this.buffer.read(cx).read(cx);
11317                let new_selected_ranges = marked_ranges
11318                    .into_iter()
11319                    .map(|marked_range| {
11320                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
11321                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
11322                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
11323                        snapshot.clip_offset_utf16(new_start, Bias::Left)
11324                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
11325                    })
11326                    .collect::<Vec<_>>();
11327
11328                drop(snapshot);
11329                this.change_selections(None, cx, |selections| {
11330                    selections.select_ranges(new_selected_ranges)
11331                });
11332            }
11333        });
11334
11335        self.ime_transaction = self.ime_transaction.or(transaction);
11336        if let Some(transaction) = self.ime_transaction {
11337            self.buffer.update(cx, |buffer, cx| {
11338                buffer.group_until_transaction(transaction, cx);
11339            });
11340        }
11341
11342        if self.text_highlights::<InputComposition>(cx).is_none() {
11343            self.ime_transaction.take();
11344        }
11345    }
11346
11347    fn bounds_for_range(
11348        &mut self,
11349        range_utf16: Range<usize>,
11350        element_bounds: gpui::Bounds<Pixels>,
11351        cx: &mut ViewContext<Self>,
11352    ) -> Option<gpui::Bounds<Pixels>> {
11353        let text_layout_details = self.text_layout_details(cx);
11354        let style = &text_layout_details.editor_style;
11355        let font_id = cx.text_system().resolve_font(&style.text.font());
11356        let font_size = style.text.font_size.to_pixels(cx.rem_size());
11357        let line_height = style.text.line_height_in_pixels(cx.rem_size());
11358        let em_width = cx
11359            .text_system()
11360            .typographic_bounds(font_id, font_size, 'm')
11361            .unwrap()
11362            .size
11363            .width;
11364
11365        let snapshot = self.snapshot(cx);
11366        let scroll_position = snapshot.scroll_position();
11367        let scroll_left = scroll_position.x * em_width;
11368
11369        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
11370        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
11371            + self.gutter_dimensions.width;
11372        let y = line_height * (start.row().as_f32() - scroll_position.y);
11373
11374        Some(Bounds {
11375            origin: element_bounds.origin + point(x, y),
11376            size: size(em_width, line_height),
11377        })
11378    }
11379}
11380
11381trait SelectionExt {
11382    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
11383    fn spanned_rows(
11384        &self,
11385        include_end_if_at_line_start: bool,
11386        map: &DisplaySnapshot,
11387    ) -> Range<MultiBufferRow>;
11388}
11389
11390impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
11391    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
11392        let start = self
11393            .start
11394            .to_point(&map.buffer_snapshot)
11395            .to_display_point(map);
11396        let end = self
11397            .end
11398            .to_point(&map.buffer_snapshot)
11399            .to_display_point(map);
11400        if self.reversed {
11401            end..start
11402        } else {
11403            start..end
11404        }
11405    }
11406
11407    fn spanned_rows(
11408        &self,
11409        include_end_if_at_line_start: bool,
11410        map: &DisplaySnapshot,
11411    ) -> Range<MultiBufferRow> {
11412        let start = self.start.to_point(&map.buffer_snapshot);
11413        let mut end = self.end.to_point(&map.buffer_snapshot);
11414        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
11415            end.row -= 1;
11416        }
11417
11418        let buffer_start = map.prev_line_boundary(start).0;
11419        let buffer_end = map.next_line_boundary(end).0;
11420        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
11421    }
11422}
11423
11424impl<T: InvalidationRegion> InvalidationStack<T> {
11425    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
11426    where
11427        S: Clone + ToOffset,
11428    {
11429        while let Some(region) = self.last() {
11430            let all_selections_inside_invalidation_ranges =
11431                if selections.len() == region.ranges().len() {
11432                    selections
11433                        .iter()
11434                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
11435                        .all(|(selection, invalidation_range)| {
11436                            let head = selection.head().to_offset(buffer);
11437                            invalidation_range.start <= head && invalidation_range.end >= head
11438                        })
11439                } else {
11440                    false
11441                };
11442
11443            if all_selections_inside_invalidation_ranges {
11444                break;
11445            } else {
11446                self.pop();
11447            }
11448        }
11449    }
11450}
11451
11452impl<T> Default for InvalidationStack<T> {
11453    fn default() -> Self {
11454        Self(Default::default())
11455    }
11456}
11457
11458impl<T> Deref for InvalidationStack<T> {
11459    type Target = Vec<T>;
11460
11461    fn deref(&self) -> &Self::Target {
11462        &self.0
11463    }
11464}
11465
11466impl<T> DerefMut for InvalidationStack<T> {
11467    fn deref_mut(&mut self) -> &mut Self::Target {
11468        &mut self.0
11469    }
11470}
11471
11472impl InvalidationRegion for SnippetState {
11473    fn ranges(&self) -> &[Range<Anchor>] {
11474        &self.ranges[self.active_index]
11475    }
11476}
11477
11478pub fn diagnostic_block_renderer(diagnostic: Diagnostic, _is_valid: bool) -> RenderBlock {
11479    let (text_without_backticks, code_ranges) = highlight_diagnostic_message(&diagnostic);
11480
11481    Box::new(move |cx: &mut BlockContext| {
11482        let group_id: SharedString = cx.block_id.to_string().into();
11483
11484        let mut text_style = cx.text_style().clone();
11485        text_style.color = diagnostic_style(diagnostic.severity, true, cx.theme().status());
11486        let theme_settings = ThemeSettings::get_global(cx);
11487        text_style.font_family = theme_settings.buffer_font.family.clone();
11488        text_style.font_style = theme_settings.buffer_font.style;
11489        text_style.font_features = theme_settings.buffer_font.features.clone();
11490        text_style.font_weight = theme_settings.buffer_font.weight;
11491
11492        let multi_line_diagnostic = diagnostic.message.contains('\n');
11493
11494        let buttons = |diagnostic: &Diagnostic, block_id: usize| {
11495            if multi_line_diagnostic {
11496                v_flex()
11497            } else {
11498                h_flex()
11499            }
11500            .children(diagnostic.is_primary.then(|| {
11501                IconButton::new(("close-block", block_id), IconName::XCircle)
11502                    .icon_color(Color::Muted)
11503                    .size(ButtonSize::Compact)
11504                    .style(ButtonStyle::Transparent)
11505                    .visible_on_hover(group_id.clone())
11506                    .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
11507                    .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
11508            }))
11509            .child(
11510                IconButton::new(("copy-block", block_id), IconName::Copy)
11511                    .icon_color(Color::Muted)
11512                    .size(ButtonSize::Compact)
11513                    .style(ButtonStyle::Transparent)
11514                    .visible_on_hover(group_id.clone())
11515                    .on_click({
11516                        let message = diagnostic.message.clone();
11517                        move |_click, cx| cx.write_to_clipboard(ClipboardItem::new(message.clone()))
11518                    })
11519                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
11520            )
11521        };
11522
11523        let icon_size = buttons(&diagnostic, cx.block_id)
11524            .into_any_element()
11525            .layout_as_root(AvailableSpace::min_size(), cx);
11526
11527        h_flex()
11528            .id(cx.block_id)
11529            .group(group_id.clone())
11530            .relative()
11531            .size_full()
11532            .pl(cx.gutter_dimensions.width)
11533            .w(cx.max_width + cx.gutter_dimensions.width)
11534            .child(
11535                div()
11536                    .flex()
11537                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
11538                    .flex_shrink(),
11539            )
11540            .child(buttons(&diagnostic, cx.block_id))
11541            .child(div().flex().flex_shrink_0().child(
11542                StyledText::new(text_without_backticks.clone()).with_highlights(
11543                    &text_style,
11544                    code_ranges.iter().map(|range| {
11545                        (
11546                            range.clone(),
11547                            HighlightStyle {
11548                                font_weight: Some(FontWeight::BOLD),
11549                                ..Default::default()
11550                            },
11551                        )
11552                    }),
11553                ),
11554            ))
11555            .into_any_element()
11556    })
11557}
11558
11559pub fn highlight_diagnostic_message(diagnostic: &Diagnostic) -> (SharedString, Vec<Range<usize>>) {
11560    let mut text_without_backticks = String::new();
11561    let mut code_ranges = Vec::new();
11562
11563    if let Some(source) = &diagnostic.source {
11564        text_without_backticks.push_str(&source);
11565        code_ranges.push(0..source.len());
11566        text_without_backticks.push_str(": ");
11567    }
11568
11569    let mut prev_offset = 0;
11570    let mut in_code_block = false;
11571    for (ix, _) in diagnostic
11572        .message
11573        .match_indices('`')
11574        .chain([(diagnostic.message.len(), "")])
11575    {
11576        let prev_len = text_without_backticks.len();
11577        text_without_backticks.push_str(&diagnostic.message[prev_offset..ix]);
11578        prev_offset = ix + 1;
11579        if in_code_block {
11580            code_ranges.push(prev_len..text_without_backticks.len());
11581            in_code_block = false;
11582        } else {
11583            in_code_block = true;
11584        }
11585    }
11586
11587    (text_without_backticks.into(), code_ranges)
11588}
11589
11590fn diagnostic_style(severity: DiagnosticSeverity, valid: bool, colors: &StatusColors) -> Hsla {
11591    match (severity, valid) {
11592        (DiagnosticSeverity::ERROR, true) => colors.error,
11593        (DiagnosticSeverity::ERROR, false) => colors.error,
11594        (DiagnosticSeverity::WARNING, true) => colors.warning,
11595        (DiagnosticSeverity::WARNING, false) => colors.warning,
11596        (DiagnosticSeverity::INFORMATION, true) => colors.info,
11597        (DiagnosticSeverity::INFORMATION, false) => colors.info,
11598        (DiagnosticSeverity::HINT, true) => colors.info,
11599        (DiagnosticSeverity::HINT, false) => colors.info,
11600        _ => colors.ignored,
11601    }
11602}
11603
11604pub fn styled_runs_for_code_label<'a>(
11605    label: &'a CodeLabel,
11606    syntax_theme: &'a theme::SyntaxTheme,
11607) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
11608    let fade_out = HighlightStyle {
11609        fade_out: Some(0.35),
11610        ..Default::default()
11611    };
11612
11613    let mut prev_end = label.filter_range.end;
11614    label
11615        .runs
11616        .iter()
11617        .enumerate()
11618        .flat_map(move |(ix, (range, highlight_id))| {
11619            let style = if let Some(style) = highlight_id.style(syntax_theme) {
11620                style
11621            } else {
11622                return Default::default();
11623            };
11624            let mut muted_style = style;
11625            muted_style.highlight(fade_out);
11626
11627            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
11628            if range.start >= label.filter_range.end {
11629                if range.start > prev_end {
11630                    runs.push((prev_end..range.start, fade_out));
11631                }
11632                runs.push((range.clone(), muted_style));
11633            } else if range.end <= label.filter_range.end {
11634                runs.push((range.clone(), style));
11635            } else {
11636                runs.push((range.start..label.filter_range.end, style));
11637                runs.push((label.filter_range.end..range.end, muted_style));
11638            }
11639            prev_end = cmp::max(prev_end, range.end);
11640
11641            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
11642                runs.push((prev_end..label.text.len(), fade_out));
11643            }
11644
11645            runs
11646        })
11647}
11648
11649pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
11650    let mut prev_index = 0;
11651    let mut prev_codepoint: Option<char> = None;
11652    text.char_indices()
11653        .chain([(text.len(), '\0')])
11654        .filter_map(move |(index, codepoint)| {
11655            let prev_codepoint = prev_codepoint.replace(codepoint)?;
11656            let is_boundary = index == text.len()
11657                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
11658                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
11659            if is_boundary {
11660                let chunk = &text[prev_index..index];
11661                prev_index = index;
11662                Some(chunk)
11663            } else {
11664                None
11665            }
11666        })
11667}
11668
11669trait RangeToAnchorExt {
11670    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
11671}
11672
11673impl<T: ToOffset> RangeToAnchorExt for Range<T> {
11674    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
11675        let start_offset = self.start.to_offset(snapshot);
11676        let end_offset = self.end.to_offset(snapshot);
11677        if start_offset == end_offset {
11678            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
11679        } else {
11680            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
11681        }
11682    }
11683}
11684
11685pub trait RowExt {
11686    fn as_f32(&self) -> f32;
11687
11688    fn next_row(&self) -> Self;
11689
11690    fn previous_row(&self) -> Self;
11691
11692    fn minus(&self, other: Self) -> u32;
11693}
11694
11695impl RowExt for DisplayRow {
11696    fn as_f32(&self) -> f32 {
11697        self.0 as f32
11698    }
11699
11700    fn next_row(&self) -> Self {
11701        Self(self.0 + 1)
11702    }
11703
11704    fn previous_row(&self) -> Self {
11705        Self(self.0.saturating_sub(1))
11706    }
11707
11708    fn minus(&self, other: Self) -> u32 {
11709        self.0 - other.0
11710    }
11711}
11712
11713impl RowExt for MultiBufferRow {
11714    fn as_f32(&self) -> f32 {
11715        self.0 as f32
11716    }
11717
11718    fn next_row(&self) -> Self {
11719        Self(self.0 + 1)
11720    }
11721
11722    fn previous_row(&self) -> Self {
11723        Self(self.0.saturating_sub(1))
11724    }
11725
11726    fn minus(&self, other: Self) -> u32 {
11727        self.0 - other.0
11728    }
11729}
11730
11731trait RowRangeExt {
11732    type Row;
11733
11734    fn len(&self) -> usize;
11735
11736    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
11737}
11738
11739impl RowRangeExt for Range<MultiBufferRow> {
11740    type Row = MultiBufferRow;
11741
11742    fn len(&self) -> usize {
11743        (self.end.0 - self.start.0) as usize
11744    }
11745
11746    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
11747        (self.start.0..self.end.0).map(MultiBufferRow)
11748    }
11749}
11750
11751impl RowRangeExt for Range<DisplayRow> {
11752    type Row = DisplayRow;
11753
11754    fn len(&self) -> usize {
11755        (self.end.0 - self.start.0) as usize
11756    }
11757
11758    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
11759        (self.start.0..self.end.0).map(DisplayRow)
11760    }
11761}
11762
11763fn hunk_status(hunk: &DiffHunk<MultiBufferRow>) -> DiffHunkStatus {
11764    if hunk.diff_base_byte_range.is_empty() {
11765        DiffHunkStatus::Added
11766    } else if hunk.associated_range.is_empty() {
11767        DiffHunkStatus::Removed
11768    } else {
11769        DiffHunkStatus::Modified
11770    }
11771}