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 = snapshot.anchor_before(
 4674                                    (insertion_start + tabstop_range.start) as usize,
 4675                                );
 4676                                let end = snapshot
 4677                                    .anchor_after((insertion_start + tabstop_range.end) as usize);
 4678                                start..end
 4679                            })
 4680                        })
 4681                        .collect::<Vec<_>>();
 4682                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 4683
 4684                    Tabstop {
 4685                        is_end_tabstop,
 4686                        ranges: tabstop_ranges,
 4687                    }
 4688                })
 4689                .collect::<Vec<_>>()
 4690        });
 4691
 4692        if let Some(tabstop) = tabstops.first() {
 4693            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 4694                s.select_ranges(tabstop.ranges.iter().cloned());
 4695            });
 4696
 4697            // If we're already at the last tabstop and it's at the end of the snippet,
 4698            // we're done, we don't need to keep the state around.
 4699            if !tabstop.is_end_tabstop {
 4700                let ranges = tabstops
 4701                    .into_iter()
 4702                    .map(|tabstop| tabstop.ranges)
 4703                    .collect::<Vec<_>>();
 4704                self.snippet_stack.push(SnippetState {
 4705                    active_index: 0,
 4706                    ranges,
 4707                });
 4708            }
 4709
 4710            // Check whether the just-entered snippet ends with an auto-closable bracket.
 4711            if self.autoclose_regions.is_empty() {
 4712                let snapshot = self.buffer.read(cx).snapshot(cx);
 4713                for selection in &mut self.selections.all::<Point>(cx) {
 4714                    let selection_head = selection.head();
 4715                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 4716                        continue;
 4717                    };
 4718
 4719                    let mut bracket_pair = None;
 4720                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 4721                    let prev_chars = snapshot
 4722                        .reversed_chars_at(selection_head)
 4723                        .collect::<String>();
 4724                    for (pair, enabled) in scope.brackets() {
 4725                        if enabled
 4726                            && pair.close
 4727                            && prev_chars.starts_with(pair.start.as_str())
 4728                            && next_chars.starts_with(pair.end.as_str())
 4729                        {
 4730                            bracket_pair = Some(pair.clone());
 4731                            break;
 4732                        }
 4733                    }
 4734                    if let Some(pair) = bracket_pair {
 4735                        let start = snapshot.anchor_after(selection_head);
 4736                        let end = snapshot.anchor_after(selection_head);
 4737                        self.autoclose_regions.push(AutocloseRegion {
 4738                            selection_id: selection.id,
 4739                            range: start..end,
 4740                            pair,
 4741                        });
 4742                    }
 4743                }
 4744            }
 4745        }
 4746        Ok(())
 4747    }
 4748
 4749    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 4750        self.move_to_snippet_tabstop(Bias::Right, cx)
 4751    }
 4752
 4753    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 4754        self.move_to_snippet_tabstop(Bias::Left, cx)
 4755    }
 4756
 4757    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 4758        if let Some(mut snippet) = self.snippet_stack.pop() {
 4759            match bias {
 4760                Bias::Left => {
 4761                    if snippet.active_index > 0 {
 4762                        snippet.active_index -= 1;
 4763                    } else {
 4764                        self.snippet_stack.push(snippet);
 4765                        return false;
 4766                    }
 4767                }
 4768                Bias::Right => {
 4769                    if snippet.active_index + 1 < snippet.ranges.len() {
 4770                        snippet.active_index += 1;
 4771                    } else {
 4772                        self.snippet_stack.push(snippet);
 4773                        return false;
 4774                    }
 4775                }
 4776            }
 4777            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 4778                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 4779                    s.select_anchor_ranges(current_ranges.iter().cloned())
 4780                });
 4781                // If snippet state is not at the last tabstop, push it back on the stack
 4782                if snippet.active_index + 1 < snippet.ranges.len() {
 4783                    self.snippet_stack.push(snippet);
 4784                }
 4785                return true;
 4786            }
 4787        }
 4788
 4789        false
 4790    }
 4791
 4792    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 4793        self.transact(cx, |this, cx| {
 4794            this.select_all(&SelectAll, cx);
 4795            this.insert("", cx);
 4796        });
 4797    }
 4798
 4799    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 4800        self.transact(cx, |this, cx| {
 4801            this.select_autoclose_pair(cx);
 4802            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 4803            if !this.selections.line_mode {
 4804                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 4805                for selection in &mut selections {
 4806                    if selection.is_empty() {
 4807                        let old_head = selection.head();
 4808                        let mut new_head =
 4809                            movement::left(&display_map, old_head.to_display_point(&display_map))
 4810                                .to_point(&display_map);
 4811                        if let Some((buffer, line_buffer_range)) = display_map
 4812                            .buffer_snapshot
 4813                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 4814                        {
 4815                            let indent_size =
 4816                                buffer.indent_size_for_line(line_buffer_range.start.row);
 4817                            let indent_len = match indent_size.kind {
 4818                                IndentKind::Space => {
 4819                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 4820                                }
 4821                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 4822                            };
 4823                            if old_head.column <= indent_size.len && old_head.column > 0 {
 4824                                let indent_len = indent_len.get();
 4825                                new_head = cmp::min(
 4826                                    new_head,
 4827                                    MultiBufferPoint::new(
 4828                                        old_head.row,
 4829                                        ((old_head.column - 1) / indent_len) * indent_len,
 4830                                    ),
 4831                                );
 4832                            }
 4833                        }
 4834
 4835                        selection.set_head(new_head, SelectionGoal::None);
 4836                    }
 4837                }
 4838            }
 4839
 4840            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 4841            this.insert("", cx);
 4842            this.refresh_inline_completion(true, cx);
 4843        });
 4844    }
 4845
 4846    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 4847        self.transact(cx, |this, cx| {
 4848            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 4849                let line_mode = s.line_mode;
 4850                s.move_with(|map, selection| {
 4851                    if selection.is_empty() && !line_mode {
 4852                        let cursor = movement::right(map, selection.head());
 4853                        selection.end = cursor;
 4854                        selection.reversed = true;
 4855                        selection.goal = SelectionGoal::None;
 4856                    }
 4857                })
 4858            });
 4859            this.insert("", cx);
 4860            this.refresh_inline_completion(true, cx);
 4861        });
 4862    }
 4863
 4864    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 4865        if self.move_to_prev_snippet_tabstop(cx) {
 4866            return;
 4867        }
 4868
 4869        self.outdent(&Outdent, cx);
 4870    }
 4871
 4872    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 4873        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 4874            return;
 4875        }
 4876
 4877        let mut selections = self.selections.all_adjusted(cx);
 4878        let buffer = self.buffer.read(cx);
 4879        let snapshot = buffer.snapshot(cx);
 4880        let rows_iter = selections.iter().map(|s| s.head().row);
 4881        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 4882
 4883        let mut edits = Vec::new();
 4884        let mut prev_edited_row = 0;
 4885        let mut row_delta = 0;
 4886        for selection in &mut selections {
 4887            if selection.start.row != prev_edited_row {
 4888                row_delta = 0;
 4889            }
 4890            prev_edited_row = selection.end.row;
 4891
 4892            // If the selection is non-empty, then increase the indentation of the selected lines.
 4893            if !selection.is_empty() {
 4894                row_delta =
 4895                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 4896                continue;
 4897            }
 4898
 4899            // If the selection is empty and the cursor is in the leading whitespace before the
 4900            // suggested indentation, then auto-indent the line.
 4901            let cursor = selection.head();
 4902            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 4903            if let Some(suggested_indent) =
 4904                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 4905            {
 4906                if cursor.column < suggested_indent.len
 4907                    && cursor.column <= current_indent.len
 4908                    && current_indent.len <= suggested_indent.len
 4909                {
 4910                    selection.start = Point::new(cursor.row, suggested_indent.len);
 4911                    selection.end = selection.start;
 4912                    if row_delta == 0 {
 4913                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 4914                            cursor.row,
 4915                            current_indent,
 4916                            suggested_indent,
 4917                        ));
 4918                        row_delta = suggested_indent.len - current_indent.len;
 4919                    }
 4920                    continue;
 4921                }
 4922            }
 4923
 4924            // Accept copilot completion if there is only one selection and the cursor is not
 4925            // in the leading whitespace.
 4926            if self.selections.count() == 1
 4927                && cursor.column >= current_indent.len
 4928                && self.has_active_inline_completion(cx)
 4929            {
 4930                self.accept_inline_completion(cx);
 4931                return;
 4932            }
 4933
 4934            // Otherwise, insert a hard or soft tab.
 4935            let settings = buffer.settings_at(cursor, cx);
 4936            let tab_size = if settings.hard_tabs {
 4937                IndentSize::tab()
 4938            } else {
 4939                let tab_size = settings.tab_size.get();
 4940                let char_column = snapshot
 4941                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 4942                    .flat_map(str::chars)
 4943                    .count()
 4944                    + row_delta as usize;
 4945                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 4946                IndentSize::spaces(chars_to_next_tab_stop)
 4947            };
 4948            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 4949            selection.end = selection.start;
 4950            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 4951            row_delta += tab_size.len;
 4952        }
 4953
 4954        self.transact(cx, |this, cx| {
 4955            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 4956            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 4957            this.refresh_inline_completion(true, cx);
 4958        });
 4959    }
 4960
 4961    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 4962        if self.read_only(cx) {
 4963            return;
 4964        }
 4965        let mut selections = self.selections.all::<Point>(cx);
 4966        let mut prev_edited_row = 0;
 4967        let mut row_delta = 0;
 4968        let mut edits = Vec::new();
 4969        let buffer = self.buffer.read(cx);
 4970        let snapshot = buffer.snapshot(cx);
 4971        for selection in &mut selections {
 4972            if selection.start.row != prev_edited_row {
 4973                row_delta = 0;
 4974            }
 4975            prev_edited_row = selection.end.row;
 4976
 4977            row_delta =
 4978                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 4979        }
 4980
 4981        self.transact(cx, |this, cx| {
 4982            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 4983            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 4984        });
 4985    }
 4986
 4987    fn indent_selection(
 4988        buffer: &MultiBuffer,
 4989        snapshot: &MultiBufferSnapshot,
 4990        selection: &mut Selection<Point>,
 4991        edits: &mut Vec<(Range<Point>, String)>,
 4992        delta_for_start_row: u32,
 4993        cx: &AppContext,
 4994    ) -> u32 {
 4995        let settings = buffer.settings_at(selection.start, cx);
 4996        let tab_size = settings.tab_size.get();
 4997        let indent_kind = if settings.hard_tabs {
 4998            IndentKind::Tab
 4999        } else {
 5000            IndentKind::Space
 5001        };
 5002        let mut start_row = selection.start.row;
 5003        let mut end_row = selection.end.row + 1;
 5004
 5005        // If a selection ends at the beginning of a line, don't indent
 5006        // that last line.
 5007        if selection.end.column == 0 && selection.end.row > selection.start.row {
 5008            end_row -= 1;
 5009        }
 5010
 5011        // Avoid re-indenting a row that has already been indented by a
 5012        // previous selection, but still update this selection's column
 5013        // to reflect that indentation.
 5014        if delta_for_start_row > 0 {
 5015            start_row += 1;
 5016            selection.start.column += delta_for_start_row;
 5017            if selection.end.row == selection.start.row {
 5018                selection.end.column += delta_for_start_row;
 5019            }
 5020        }
 5021
 5022        let mut delta_for_end_row = 0;
 5023        let has_multiple_rows = start_row + 1 != end_row;
 5024        for row in start_row..end_row {
 5025            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 5026            let indent_delta = match (current_indent.kind, indent_kind) {
 5027                (IndentKind::Space, IndentKind::Space) => {
 5028                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 5029                    IndentSize::spaces(columns_to_next_tab_stop)
 5030                }
 5031                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 5032                (_, IndentKind::Tab) => IndentSize::tab(),
 5033            };
 5034
 5035            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 5036                0
 5037            } else {
 5038                selection.start.column
 5039            };
 5040            let row_start = Point::new(row, start);
 5041            edits.push((
 5042                row_start..row_start,
 5043                indent_delta.chars().collect::<String>(),
 5044            ));
 5045
 5046            // Update this selection's endpoints to reflect the indentation.
 5047            if row == selection.start.row {
 5048                selection.start.column += indent_delta.len;
 5049            }
 5050            if row == selection.end.row {
 5051                selection.end.column += indent_delta.len;
 5052                delta_for_end_row = indent_delta.len;
 5053            }
 5054        }
 5055
 5056        if selection.start.row == selection.end.row {
 5057            delta_for_start_row + delta_for_end_row
 5058        } else {
 5059            delta_for_end_row
 5060        }
 5061    }
 5062
 5063    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 5064        if self.read_only(cx) {
 5065            return;
 5066        }
 5067        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5068        let selections = self.selections.all::<Point>(cx);
 5069        let mut deletion_ranges = Vec::new();
 5070        let mut last_outdent = None;
 5071        {
 5072            let buffer = self.buffer.read(cx);
 5073            let snapshot = buffer.snapshot(cx);
 5074            for selection in &selections {
 5075                let settings = buffer.settings_at(selection.start, cx);
 5076                let tab_size = settings.tab_size.get();
 5077                let mut rows = selection.spanned_rows(false, &display_map);
 5078
 5079                // Avoid re-outdenting a row that has already been outdented by a
 5080                // previous selection.
 5081                if let Some(last_row) = last_outdent {
 5082                    if last_row == rows.start {
 5083                        rows.start = rows.start.next_row();
 5084                    }
 5085                }
 5086                let has_multiple_rows = rows.len() > 1;
 5087                for row in rows.iter_rows() {
 5088                    let indent_size = snapshot.indent_size_for_line(row);
 5089                    if indent_size.len > 0 {
 5090                        let deletion_len = match indent_size.kind {
 5091                            IndentKind::Space => {
 5092                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 5093                                if columns_to_prev_tab_stop == 0 {
 5094                                    tab_size
 5095                                } else {
 5096                                    columns_to_prev_tab_stop
 5097                                }
 5098                            }
 5099                            IndentKind::Tab => 1,
 5100                        };
 5101                        let start = if has_multiple_rows
 5102                            || deletion_len > selection.start.column
 5103                            || indent_size.len < selection.start.column
 5104                        {
 5105                            0
 5106                        } else {
 5107                            selection.start.column - deletion_len
 5108                        };
 5109                        deletion_ranges.push(
 5110                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 5111                        );
 5112                        last_outdent = Some(row);
 5113                    }
 5114                }
 5115            }
 5116        }
 5117
 5118        self.transact(cx, |this, cx| {
 5119            this.buffer.update(cx, |buffer, cx| {
 5120                let empty_str: Arc<str> = "".into();
 5121                buffer.edit(
 5122                    deletion_ranges
 5123                        .into_iter()
 5124                        .map(|range| (range, empty_str.clone())),
 5125                    None,
 5126                    cx,
 5127                );
 5128            });
 5129            let selections = this.selections.all::<usize>(cx);
 5130            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5131        });
 5132    }
 5133
 5134    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 5135        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5136        let selections = self.selections.all::<Point>(cx);
 5137
 5138        let mut new_cursors = Vec::new();
 5139        let mut edit_ranges = Vec::new();
 5140        let mut selections = selections.iter().peekable();
 5141        while let Some(selection) = selections.next() {
 5142            let mut rows = selection.spanned_rows(false, &display_map);
 5143            let goal_display_column = selection.head().to_display_point(&display_map).column();
 5144
 5145            // Accumulate contiguous regions of rows that we want to delete.
 5146            while let Some(next_selection) = selections.peek() {
 5147                let next_rows = next_selection.spanned_rows(false, &display_map);
 5148                if next_rows.start <= rows.end {
 5149                    rows.end = next_rows.end;
 5150                    selections.next().unwrap();
 5151                } else {
 5152                    break;
 5153                }
 5154            }
 5155
 5156            let buffer = &display_map.buffer_snapshot;
 5157            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 5158            let edit_end;
 5159            let cursor_buffer_row;
 5160            if buffer.max_point().row >= rows.end.0 {
 5161                // If there's a line after the range, delete the \n from the end of the row range
 5162                // and position the cursor on the next line.
 5163                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 5164                cursor_buffer_row = rows.end;
 5165            } else {
 5166                // If there isn't a line after the range, delete the \n from the line before the
 5167                // start of the row range and position the cursor there.
 5168                edit_start = edit_start.saturating_sub(1);
 5169                edit_end = buffer.len();
 5170                cursor_buffer_row = rows.start.previous_row();
 5171            }
 5172
 5173            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 5174            *cursor.column_mut() =
 5175                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 5176
 5177            new_cursors.push((
 5178                selection.id,
 5179                buffer.anchor_after(cursor.to_point(&display_map)),
 5180            ));
 5181            edit_ranges.push(edit_start..edit_end);
 5182        }
 5183
 5184        self.transact(cx, |this, cx| {
 5185            let buffer = this.buffer.update(cx, |buffer, cx| {
 5186                let empty_str: Arc<str> = "".into();
 5187                buffer.edit(
 5188                    edit_ranges
 5189                        .into_iter()
 5190                        .map(|range| (range, empty_str.clone())),
 5191                    None,
 5192                    cx,
 5193                );
 5194                buffer.snapshot(cx)
 5195            });
 5196            let new_selections = new_cursors
 5197                .into_iter()
 5198                .map(|(id, cursor)| {
 5199                    let cursor = cursor.to_point(&buffer);
 5200                    Selection {
 5201                        id,
 5202                        start: cursor,
 5203                        end: cursor,
 5204                        reversed: false,
 5205                        goal: SelectionGoal::None,
 5206                    }
 5207                })
 5208                .collect();
 5209
 5210            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5211                s.select(new_selections);
 5212            });
 5213        });
 5214    }
 5215
 5216    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 5217        if self.read_only(cx) {
 5218            return;
 5219        }
 5220        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 5221        for selection in self.selections.all::<Point>(cx) {
 5222            let start = MultiBufferRow(selection.start.row);
 5223            let end = if selection.start.row == selection.end.row {
 5224                MultiBufferRow(selection.start.row + 1)
 5225            } else {
 5226                MultiBufferRow(selection.end.row)
 5227            };
 5228
 5229            if let Some(last_row_range) = row_ranges.last_mut() {
 5230                if start <= last_row_range.end {
 5231                    last_row_range.end = end;
 5232                    continue;
 5233                }
 5234            }
 5235            row_ranges.push(start..end);
 5236        }
 5237
 5238        let snapshot = self.buffer.read(cx).snapshot(cx);
 5239        let mut cursor_positions = Vec::new();
 5240        for row_range in &row_ranges {
 5241            let anchor = snapshot.anchor_before(Point::new(
 5242                row_range.end.previous_row().0,
 5243                snapshot.line_len(row_range.end.previous_row()),
 5244            ));
 5245            cursor_positions.push(anchor..anchor);
 5246        }
 5247
 5248        self.transact(cx, |this, cx| {
 5249            for row_range in row_ranges.into_iter().rev() {
 5250                for row in row_range.iter_rows().rev() {
 5251                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 5252                    let next_line_row = row.next_row();
 5253                    let indent = snapshot.indent_size_for_line(next_line_row);
 5254                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 5255
 5256                    let replace = if snapshot.line_len(next_line_row) > indent.len {
 5257                        " "
 5258                    } else {
 5259                        ""
 5260                    };
 5261
 5262                    this.buffer.update(cx, |buffer, cx| {
 5263                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 5264                    });
 5265                }
 5266            }
 5267
 5268            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5269                s.select_anchor_ranges(cursor_positions)
 5270            });
 5271        });
 5272    }
 5273
 5274    pub fn sort_lines_case_sensitive(
 5275        &mut self,
 5276        _: &SortLinesCaseSensitive,
 5277        cx: &mut ViewContext<Self>,
 5278    ) {
 5279        self.manipulate_lines(cx, |lines| lines.sort())
 5280    }
 5281
 5282    pub fn sort_lines_case_insensitive(
 5283        &mut self,
 5284        _: &SortLinesCaseInsensitive,
 5285        cx: &mut ViewContext<Self>,
 5286    ) {
 5287        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 5288    }
 5289
 5290    pub fn unique_lines_case_insensitive(
 5291        &mut self,
 5292        _: &UniqueLinesCaseInsensitive,
 5293        cx: &mut ViewContext<Self>,
 5294    ) {
 5295        self.manipulate_lines(cx, |lines| {
 5296            let mut seen = HashSet::default();
 5297            lines.retain(|line| seen.insert(line.to_lowercase()));
 5298        })
 5299    }
 5300
 5301    pub fn unique_lines_case_sensitive(
 5302        &mut self,
 5303        _: &UniqueLinesCaseSensitive,
 5304        cx: &mut ViewContext<Self>,
 5305    ) {
 5306        self.manipulate_lines(cx, |lines| {
 5307            let mut seen = HashSet::default();
 5308            lines.retain(|line| seen.insert(*line));
 5309        })
 5310    }
 5311
 5312    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 5313        let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
 5314        if !revert_changes.is_empty() {
 5315            self.transact(cx, |editor, cx| {
 5316                editor.buffer().update(cx, |multi_buffer, cx| {
 5317                    for (buffer_id, changes) in revert_changes {
 5318                        if let Some(buffer) = multi_buffer.buffer(buffer_id) {
 5319                            buffer.update(cx, |buffer, cx| {
 5320                                buffer.edit(
 5321                                    changes.into_iter().map(|(range, text)| {
 5322                                        (range, text.to_string().map(Arc::<str>::from))
 5323                                    }),
 5324                                    None,
 5325                                    cx,
 5326                                );
 5327                            });
 5328                        }
 5329                    }
 5330                });
 5331                editor.change_selections(None, cx, |selections| selections.refresh());
 5332            });
 5333        }
 5334    }
 5335
 5336    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 5337        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 5338            let project_path = buffer.read(cx).project_path(cx)?;
 5339            let project = self.project.as_ref()?.read(cx);
 5340            let entry = project.entry_for_path(&project_path, cx)?;
 5341            let abs_path = project.absolute_path(&project_path, cx)?;
 5342            let parent = if entry.is_symlink {
 5343                abs_path.canonicalize().ok()?
 5344            } else {
 5345                abs_path
 5346            }
 5347            .parent()?
 5348            .to_path_buf();
 5349            Some(parent)
 5350        }) {
 5351            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 5352        }
 5353    }
 5354
 5355    fn gather_revert_changes(
 5356        &mut self,
 5357        selections: &[Selection<Anchor>],
 5358        cx: &mut ViewContext<'_, Editor>,
 5359    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 5360        let mut revert_changes = HashMap::default();
 5361        self.buffer.update(cx, |multi_buffer, cx| {
 5362            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 5363            for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
 5364                Self::prepare_revert_change(&mut revert_changes, &multi_buffer, &hunk, cx);
 5365            }
 5366        });
 5367        revert_changes
 5368    }
 5369
 5370    fn prepare_revert_change(
 5371        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 5372        multi_buffer: &MultiBuffer,
 5373        hunk: &DiffHunk<MultiBufferRow>,
 5374        cx: &mut AppContext,
 5375    ) -> Option<()> {
 5376        let buffer = multi_buffer.buffer(hunk.buffer_id)?;
 5377        let buffer = buffer.read(cx);
 5378        let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
 5379        let buffer_snapshot = buffer.snapshot();
 5380        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 5381        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 5382            probe
 5383                .0
 5384                .start
 5385                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 5386                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 5387        }) {
 5388            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 5389            Some(())
 5390        } else {
 5391            None
 5392        }
 5393    }
 5394
 5395    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 5396        self.manipulate_lines(cx, |lines| lines.reverse())
 5397    }
 5398
 5399    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 5400        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 5401    }
 5402
 5403    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 5404    where
 5405        Fn: FnMut(&mut Vec<&str>),
 5406    {
 5407        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5408        let buffer = self.buffer.read(cx).snapshot(cx);
 5409
 5410        let mut edits = Vec::new();
 5411
 5412        let selections = self.selections.all::<Point>(cx);
 5413        let mut selections = selections.iter().peekable();
 5414        let mut contiguous_row_selections = Vec::new();
 5415        let mut new_selections = Vec::new();
 5416        let mut added_lines = 0;
 5417        let mut removed_lines = 0;
 5418
 5419        while let Some(selection) = selections.next() {
 5420            let (start_row, end_row) = consume_contiguous_rows(
 5421                &mut contiguous_row_selections,
 5422                selection,
 5423                &display_map,
 5424                &mut selections,
 5425            );
 5426
 5427            let start_point = Point::new(start_row.0, 0);
 5428            let end_point = Point::new(
 5429                end_row.previous_row().0,
 5430                buffer.line_len(end_row.previous_row()),
 5431            );
 5432            let text = buffer
 5433                .text_for_range(start_point..end_point)
 5434                .collect::<String>();
 5435
 5436            let mut lines = text.split('\n').collect_vec();
 5437
 5438            let lines_before = lines.len();
 5439            callback(&mut lines);
 5440            let lines_after = lines.len();
 5441
 5442            edits.push((start_point..end_point, lines.join("\n")));
 5443
 5444            // Selections must change based on added and removed line count
 5445            let start_row =
 5446                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 5447            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 5448            new_selections.push(Selection {
 5449                id: selection.id,
 5450                start: start_row,
 5451                end: end_row,
 5452                goal: SelectionGoal::None,
 5453                reversed: selection.reversed,
 5454            });
 5455
 5456            if lines_after > lines_before {
 5457                added_lines += lines_after - lines_before;
 5458            } else if lines_before > lines_after {
 5459                removed_lines += lines_before - lines_after;
 5460            }
 5461        }
 5462
 5463        self.transact(cx, |this, cx| {
 5464            let buffer = this.buffer.update(cx, |buffer, cx| {
 5465                buffer.edit(edits, None, cx);
 5466                buffer.snapshot(cx)
 5467            });
 5468
 5469            // Recalculate offsets on newly edited buffer
 5470            let new_selections = new_selections
 5471                .iter()
 5472                .map(|s| {
 5473                    let start_point = Point::new(s.start.0, 0);
 5474                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 5475                    Selection {
 5476                        id: s.id,
 5477                        start: buffer.point_to_offset(start_point),
 5478                        end: buffer.point_to_offset(end_point),
 5479                        goal: s.goal,
 5480                        reversed: s.reversed,
 5481                    }
 5482                })
 5483                .collect();
 5484
 5485            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5486                s.select(new_selections);
 5487            });
 5488
 5489            this.request_autoscroll(Autoscroll::fit(), cx);
 5490        });
 5491    }
 5492
 5493    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 5494        self.manipulate_text(cx, |text| text.to_uppercase())
 5495    }
 5496
 5497    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 5498        self.manipulate_text(cx, |text| text.to_lowercase())
 5499    }
 5500
 5501    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 5502        self.manipulate_text(cx, |text| {
 5503            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 5504            // https://github.com/rutrum/convert-case/issues/16
 5505            text.split('\n')
 5506                .map(|line| line.to_case(Case::Title))
 5507                .join("\n")
 5508        })
 5509    }
 5510
 5511    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 5512        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 5513    }
 5514
 5515    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 5516        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 5517    }
 5518
 5519    pub fn convert_to_upper_camel_case(
 5520        &mut self,
 5521        _: &ConvertToUpperCamelCase,
 5522        cx: &mut ViewContext<Self>,
 5523    ) {
 5524        self.manipulate_text(cx, |text| {
 5525            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 5526            // https://github.com/rutrum/convert-case/issues/16
 5527            text.split('\n')
 5528                .map(|line| line.to_case(Case::UpperCamel))
 5529                .join("\n")
 5530        })
 5531    }
 5532
 5533    pub fn convert_to_lower_camel_case(
 5534        &mut self,
 5535        _: &ConvertToLowerCamelCase,
 5536        cx: &mut ViewContext<Self>,
 5537    ) {
 5538        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 5539    }
 5540
 5541    pub fn convert_to_opposite_case(
 5542        &mut self,
 5543        _: &ConvertToOppositeCase,
 5544        cx: &mut ViewContext<Self>,
 5545    ) {
 5546        self.manipulate_text(cx, |text| {
 5547            text.chars()
 5548                .fold(String::with_capacity(text.len()), |mut t, c| {
 5549                    if c.is_uppercase() {
 5550                        t.extend(c.to_lowercase());
 5551                    } else {
 5552                        t.extend(c.to_uppercase());
 5553                    }
 5554                    t
 5555                })
 5556        })
 5557    }
 5558
 5559    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 5560    where
 5561        Fn: FnMut(&str) -> String,
 5562    {
 5563        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5564        let buffer = self.buffer.read(cx).snapshot(cx);
 5565
 5566        let mut new_selections = Vec::new();
 5567        let mut edits = Vec::new();
 5568        let mut selection_adjustment = 0i32;
 5569
 5570        for selection in self.selections.all::<usize>(cx) {
 5571            let selection_is_empty = selection.is_empty();
 5572
 5573            let (start, end) = if selection_is_empty {
 5574                let word_range = movement::surrounding_word(
 5575                    &display_map,
 5576                    selection.start.to_display_point(&display_map),
 5577                );
 5578                let start = word_range.start.to_offset(&display_map, Bias::Left);
 5579                let end = word_range.end.to_offset(&display_map, Bias::Left);
 5580                (start, end)
 5581            } else {
 5582                (selection.start, selection.end)
 5583            };
 5584
 5585            let text = buffer.text_for_range(start..end).collect::<String>();
 5586            let old_length = text.len() as i32;
 5587            let text = callback(&text);
 5588
 5589            new_selections.push(Selection {
 5590                start: (start as i32 - selection_adjustment) as usize,
 5591                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 5592                goal: SelectionGoal::None,
 5593                ..selection
 5594            });
 5595
 5596            selection_adjustment += old_length - text.len() as i32;
 5597
 5598            edits.push((start..end, text));
 5599        }
 5600
 5601        self.transact(cx, |this, cx| {
 5602            this.buffer.update(cx, |buffer, cx| {
 5603                buffer.edit(edits, None, cx);
 5604            });
 5605
 5606            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5607                s.select(new_selections);
 5608            });
 5609
 5610            this.request_autoscroll(Autoscroll::fit(), cx);
 5611        });
 5612    }
 5613
 5614    pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
 5615        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5616        let buffer = &display_map.buffer_snapshot;
 5617        let selections = self.selections.all::<Point>(cx);
 5618
 5619        let mut edits = Vec::new();
 5620        let mut selections_iter = selections.iter().peekable();
 5621        while let Some(selection) = selections_iter.next() {
 5622            // Avoid duplicating the same lines twice.
 5623            let mut rows = selection.spanned_rows(false, &display_map);
 5624
 5625            while let Some(next_selection) = selections_iter.peek() {
 5626                let next_rows = next_selection.spanned_rows(false, &display_map);
 5627                if next_rows.start < rows.end {
 5628                    rows.end = next_rows.end;
 5629                    selections_iter.next().unwrap();
 5630                } else {
 5631                    break;
 5632                }
 5633            }
 5634
 5635            // Copy the text from the selected row region and splice it either at the start
 5636            // or end of the region.
 5637            let start = Point::new(rows.start.0, 0);
 5638            let end = Point::new(
 5639                rows.end.previous_row().0,
 5640                buffer.line_len(rows.end.previous_row()),
 5641            );
 5642            let text = buffer
 5643                .text_for_range(start..end)
 5644                .chain(Some("\n"))
 5645                .collect::<String>();
 5646            let insert_location = if upwards {
 5647                Point::new(rows.end.0, 0)
 5648            } else {
 5649                start
 5650            };
 5651            edits.push((insert_location..insert_location, text));
 5652        }
 5653
 5654        self.transact(cx, |this, cx| {
 5655            this.buffer.update(cx, |buffer, cx| {
 5656                buffer.edit(edits, None, cx);
 5657            });
 5658
 5659            this.request_autoscroll(Autoscroll::fit(), cx);
 5660        });
 5661    }
 5662
 5663    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 5664        self.duplicate_line(true, cx);
 5665    }
 5666
 5667    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 5668        self.duplicate_line(false, cx);
 5669    }
 5670
 5671    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 5672        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5673        let buffer = self.buffer.read(cx).snapshot(cx);
 5674
 5675        let mut edits = Vec::new();
 5676        let mut unfold_ranges = Vec::new();
 5677        let mut refold_ranges = Vec::new();
 5678
 5679        let selections = self.selections.all::<Point>(cx);
 5680        let mut selections = selections.iter().peekable();
 5681        let mut contiguous_row_selections = Vec::new();
 5682        let mut new_selections = Vec::new();
 5683
 5684        while let Some(selection) = selections.next() {
 5685            // Find all the selections that span a contiguous row range
 5686            let (start_row, end_row) = consume_contiguous_rows(
 5687                &mut contiguous_row_selections,
 5688                selection,
 5689                &display_map,
 5690                &mut selections,
 5691            );
 5692
 5693            // Move the text spanned by the row range to be before the line preceding the row range
 5694            if start_row.0 > 0 {
 5695                let range_to_move = Point::new(
 5696                    start_row.previous_row().0,
 5697                    buffer.line_len(start_row.previous_row()),
 5698                )
 5699                    ..Point::new(
 5700                        end_row.previous_row().0,
 5701                        buffer.line_len(end_row.previous_row()),
 5702                    );
 5703                let insertion_point = display_map
 5704                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 5705                    .0;
 5706
 5707                // Don't move lines across excerpts
 5708                if buffer
 5709                    .excerpt_boundaries_in_range((
 5710                        Bound::Excluded(insertion_point),
 5711                        Bound::Included(range_to_move.end),
 5712                    ))
 5713                    .next()
 5714                    .is_none()
 5715                {
 5716                    let text = buffer
 5717                        .text_for_range(range_to_move.clone())
 5718                        .flat_map(|s| s.chars())
 5719                        .skip(1)
 5720                        .chain(['\n'])
 5721                        .collect::<String>();
 5722
 5723                    edits.push((
 5724                        buffer.anchor_after(range_to_move.start)
 5725                            ..buffer.anchor_before(range_to_move.end),
 5726                        String::new(),
 5727                    ));
 5728                    let insertion_anchor = buffer.anchor_after(insertion_point);
 5729                    edits.push((insertion_anchor..insertion_anchor, text));
 5730
 5731                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 5732
 5733                    // Move selections up
 5734                    new_selections.extend(contiguous_row_selections.drain(..).map(
 5735                        |mut selection| {
 5736                            selection.start.row -= row_delta;
 5737                            selection.end.row -= row_delta;
 5738                            selection
 5739                        },
 5740                    ));
 5741
 5742                    // Move folds up
 5743                    unfold_ranges.push(range_to_move.clone());
 5744                    for fold in display_map.folds_in_range(
 5745                        buffer.anchor_before(range_to_move.start)
 5746                            ..buffer.anchor_after(range_to_move.end),
 5747                    ) {
 5748                        let mut start = fold.range.start.to_point(&buffer);
 5749                        let mut end = fold.range.end.to_point(&buffer);
 5750                        start.row -= row_delta;
 5751                        end.row -= row_delta;
 5752                        refold_ranges.push(start..end);
 5753                    }
 5754                }
 5755            }
 5756
 5757            // If we didn't move line(s), preserve the existing selections
 5758            new_selections.append(&mut contiguous_row_selections);
 5759        }
 5760
 5761        self.transact(cx, |this, cx| {
 5762            this.unfold_ranges(unfold_ranges, true, true, cx);
 5763            this.buffer.update(cx, |buffer, cx| {
 5764                for (range, text) in edits {
 5765                    buffer.edit([(range, text)], None, cx);
 5766                }
 5767            });
 5768            this.fold_ranges(refold_ranges, true, cx);
 5769            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5770                s.select(new_selections);
 5771            })
 5772        });
 5773    }
 5774
 5775    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 5776        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5777        let buffer = self.buffer.read(cx).snapshot(cx);
 5778
 5779        let mut edits = Vec::new();
 5780        let mut unfold_ranges = Vec::new();
 5781        let mut refold_ranges = Vec::new();
 5782
 5783        let selections = self.selections.all::<Point>(cx);
 5784        let mut selections = selections.iter().peekable();
 5785        let mut contiguous_row_selections = Vec::new();
 5786        let mut new_selections = Vec::new();
 5787
 5788        while let Some(selection) = selections.next() {
 5789            // Find all the selections that span a contiguous row range
 5790            let (start_row, end_row) = consume_contiguous_rows(
 5791                &mut contiguous_row_selections,
 5792                selection,
 5793                &display_map,
 5794                &mut selections,
 5795            );
 5796
 5797            // Move the text spanned by the row range to be after the last line of the row range
 5798            if end_row.0 <= buffer.max_point().row {
 5799                let range_to_move =
 5800                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 5801                let insertion_point = display_map
 5802                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 5803                    .0;
 5804
 5805                // Don't move lines across excerpt boundaries
 5806                if buffer
 5807                    .excerpt_boundaries_in_range((
 5808                        Bound::Excluded(range_to_move.start),
 5809                        Bound::Included(insertion_point),
 5810                    ))
 5811                    .next()
 5812                    .is_none()
 5813                {
 5814                    let mut text = String::from("\n");
 5815                    text.extend(buffer.text_for_range(range_to_move.clone()));
 5816                    text.pop(); // Drop trailing newline
 5817                    edits.push((
 5818                        buffer.anchor_after(range_to_move.start)
 5819                            ..buffer.anchor_before(range_to_move.end),
 5820                        String::new(),
 5821                    ));
 5822                    let insertion_anchor = buffer.anchor_after(insertion_point);
 5823                    edits.push((insertion_anchor..insertion_anchor, text));
 5824
 5825                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 5826
 5827                    // Move selections down
 5828                    new_selections.extend(contiguous_row_selections.drain(..).map(
 5829                        |mut selection| {
 5830                            selection.start.row += row_delta;
 5831                            selection.end.row += row_delta;
 5832                            selection
 5833                        },
 5834                    ));
 5835
 5836                    // Move folds down
 5837                    unfold_ranges.push(range_to_move.clone());
 5838                    for fold in display_map.folds_in_range(
 5839                        buffer.anchor_before(range_to_move.start)
 5840                            ..buffer.anchor_after(range_to_move.end),
 5841                    ) {
 5842                        let mut start = fold.range.start.to_point(&buffer);
 5843                        let mut end = fold.range.end.to_point(&buffer);
 5844                        start.row += row_delta;
 5845                        end.row += row_delta;
 5846                        refold_ranges.push(start..end);
 5847                    }
 5848                }
 5849            }
 5850
 5851            // If we didn't move line(s), preserve the existing selections
 5852            new_selections.append(&mut contiguous_row_selections);
 5853        }
 5854
 5855        self.transact(cx, |this, cx| {
 5856            this.unfold_ranges(unfold_ranges, true, true, cx);
 5857            this.buffer.update(cx, |buffer, cx| {
 5858                for (range, text) in edits {
 5859                    buffer.edit([(range, text)], None, cx);
 5860                }
 5861            });
 5862            this.fold_ranges(refold_ranges, true, cx);
 5863            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 5864        });
 5865    }
 5866
 5867    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 5868        let text_layout_details = &self.text_layout_details(cx);
 5869        self.transact(cx, |this, cx| {
 5870            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5871                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 5872                let line_mode = s.line_mode;
 5873                s.move_with(|display_map, selection| {
 5874                    if !selection.is_empty() || line_mode {
 5875                        return;
 5876                    }
 5877
 5878                    let mut head = selection.head();
 5879                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 5880                    if head.column() == display_map.line_len(head.row()) {
 5881                        transpose_offset = display_map
 5882                            .buffer_snapshot
 5883                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 5884                    }
 5885
 5886                    if transpose_offset == 0 {
 5887                        return;
 5888                    }
 5889
 5890                    *head.column_mut() += 1;
 5891                    head = display_map.clip_point(head, Bias::Right);
 5892                    let goal = SelectionGoal::HorizontalPosition(
 5893                        display_map
 5894                            .x_for_display_point(head, &text_layout_details)
 5895                            .into(),
 5896                    );
 5897                    selection.collapse_to(head, goal);
 5898
 5899                    let transpose_start = display_map
 5900                        .buffer_snapshot
 5901                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 5902                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 5903                        let transpose_end = display_map
 5904                            .buffer_snapshot
 5905                            .clip_offset(transpose_offset + 1, Bias::Right);
 5906                        if let Some(ch) =
 5907                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 5908                        {
 5909                            edits.push((transpose_start..transpose_offset, String::new()));
 5910                            edits.push((transpose_end..transpose_end, ch.to_string()));
 5911                        }
 5912                    }
 5913                });
 5914                edits
 5915            });
 5916            this.buffer
 5917                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 5918            let selections = this.selections.all::<usize>(cx);
 5919            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5920                s.select(selections);
 5921            });
 5922        });
 5923    }
 5924
 5925    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 5926        let mut text = String::new();
 5927        let buffer = self.buffer.read(cx).snapshot(cx);
 5928        let mut selections = self.selections.all::<Point>(cx);
 5929        let mut clipboard_selections = Vec::with_capacity(selections.len());
 5930        {
 5931            let max_point = buffer.max_point();
 5932            let mut is_first = true;
 5933            for selection in &mut selections {
 5934                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 5935                if is_entire_line {
 5936                    selection.start = Point::new(selection.start.row, 0);
 5937                    selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 5938                    selection.goal = SelectionGoal::None;
 5939                }
 5940                if is_first {
 5941                    is_first = false;
 5942                } else {
 5943                    text += "\n";
 5944                }
 5945                let mut len = 0;
 5946                for chunk in buffer.text_for_range(selection.start..selection.end) {
 5947                    text.push_str(chunk);
 5948                    len += chunk.len();
 5949                }
 5950                clipboard_selections.push(ClipboardSelection {
 5951                    len,
 5952                    is_entire_line,
 5953                    first_line_indent: buffer
 5954                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 5955                        .len,
 5956                });
 5957            }
 5958        }
 5959
 5960        self.transact(cx, |this, cx| {
 5961            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5962                s.select(selections);
 5963            });
 5964            this.insert("", cx);
 5965            cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
 5966        });
 5967    }
 5968
 5969    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 5970        let selections = self.selections.all::<Point>(cx);
 5971        let buffer = self.buffer.read(cx).read(cx);
 5972        let mut text = String::new();
 5973
 5974        let mut clipboard_selections = Vec::with_capacity(selections.len());
 5975        {
 5976            let max_point = buffer.max_point();
 5977            let mut is_first = true;
 5978            for selection in selections.iter() {
 5979                let mut start = selection.start;
 5980                let mut end = selection.end;
 5981                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 5982                if is_entire_line {
 5983                    start = Point::new(start.row, 0);
 5984                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 5985                }
 5986                if is_first {
 5987                    is_first = false;
 5988                } else {
 5989                    text += "\n";
 5990                }
 5991                let mut len = 0;
 5992                for chunk in buffer.text_for_range(start..end) {
 5993                    text.push_str(chunk);
 5994                    len += chunk.len();
 5995                }
 5996                clipboard_selections.push(ClipboardSelection {
 5997                    len,
 5998                    is_entire_line,
 5999                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 6000                });
 6001            }
 6002        }
 6003
 6004        cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
 6005    }
 6006
 6007    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 6008        if self.read_only(cx) {
 6009            return;
 6010        }
 6011
 6012        self.transact(cx, |this, cx| {
 6013            if let Some(item) = cx.read_from_clipboard() {
 6014                let clipboard_text = Cow::Borrowed(item.text());
 6015                if let Some(mut clipboard_selections) = item.metadata::<Vec<ClipboardSelection>>() {
 6016                    let old_selections = this.selections.all::<usize>(cx);
 6017                    let all_selections_were_entire_line =
 6018                        clipboard_selections.iter().all(|s| s.is_entire_line);
 6019                    let first_selection_indent_column =
 6020                        clipboard_selections.first().map(|s| s.first_line_indent);
 6021                    if clipboard_selections.len() != old_selections.len() {
 6022                        clipboard_selections.drain(..);
 6023                    }
 6024
 6025                    this.buffer.update(cx, |buffer, cx| {
 6026                        let snapshot = buffer.read(cx);
 6027                        let mut start_offset = 0;
 6028                        let mut edits = Vec::new();
 6029                        let mut original_indent_columns = Vec::new();
 6030                        let line_mode = this.selections.line_mode;
 6031                        for (ix, selection) in old_selections.iter().enumerate() {
 6032                            let to_insert;
 6033                            let entire_line;
 6034                            let original_indent_column;
 6035                            if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 6036                                let end_offset = start_offset + clipboard_selection.len;
 6037                                to_insert = &clipboard_text[start_offset..end_offset];
 6038                                entire_line = clipboard_selection.is_entire_line;
 6039                                start_offset = end_offset + 1;
 6040                                original_indent_column =
 6041                                    Some(clipboard_selection.first_line_indent);
 6042                            } else {
 6043                                to_insert = clipboard_text.as_str();
 6044                                entire_line = all_selections_were_entire_line;
 6045                                original_indent_column = first_selection_indent_column
 6046                            }
 6047
 6048                            // If the corresponding selection was empty when this slice of the
 6049                            // clipboard text was written, then the entire line containing the
 6050                            // selection was copied. If this selection is also currently empty,
 6051                            // then paste the line before the current line of the buffer.
 6052                            let range = if selection.is_empty() && !line_mode && entire_line {
 6053                                let column = selection.start.to_point(&snapshot).column as usize;
 6054                                let line_start = selection.start - column;
 6055                                line_start..line_start
 6056                            } else {
 6057                                selection.range()
 6058                            };
 6059
 6060                            edits.push((range, to_insert));
 6061                            original_indent_columns.extend(original_indent_column);
 6062                        }
 6063                        drop(snapshot);
 6064
 6065                        buffer.edit(
 6066                            edits,
 6067                            Some(AutoindentMode::Block {
 6068                                original_indent_columns,
 6069                            }),
 6070                            cx,
 6071                        );
 6072                    });
 6073
 6074                    let selections = this.selections.all::<usize>(cx);
 6075                    this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6076                } else {
 6077                    this.insert(&clipboard_text, cx);
 6078                }
 6079            }
 6080        });
 6081    }
 6082
 6083    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 6084        if self.read_only(cx) {
 6085            return;
 6086        }
 6087
 6088        if let Some(tx_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 6089            if let Some((selections, _)) = self.selection_history.transaction(tx_id).cloned() {
 6090                self.change_selections(None, cx, |s| {
 6091                    s.select_anchors(selections.to_vec());
 6092                });
 6093            }
 6094            self.request_autoscroll(Autoscroll::fit(), cx);
 6095            self.unmark_text(cx);
 6096            self.refresh_inline_completion(true, cx);
 6097            cx.emit(EditorEvent::Edited);
 6098            cx.emit(EditorEvent::TransactionUndone {
 6099                transaction_id: tx_id,
 6100            });
 6101        }
 6102    }
 6103
 6104    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 6105        if self.read_only(cx) {
 6106            return;
 6107        }
 6108
 6109        if let Some(tx_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 6110            if let Some((_, Some(selections))) = self.selection_history.transaction(tx_id).cloned()
 6111            {
 6112                self.change_selections(None, cx, |s| {
 6113                    s.select_anchors(selections.to_vec());
 6114                });
 6115            }
 6116            self.request_autoscroll(Autoscroll::fit(), cx);
 6117            self.unmark_text(cx);
 6118            self.refresh_inline_completion(true, cx);
 6119            cx.emit(EditorEvent::Edited);
 6120        }
 6121    }
 6122
 6123    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 6124        self.buffer
 6125            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 6126    }
 6127
 6128    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 6129        self.buffer
 6130            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 6131    }
 6132
 6133    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 6134        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6135            let line_mode = s.line_mode;
 6136            s.move_with(|map, selection| {
 6137                let cursor = if selection.is_empty() && !line_mode {
 6138                    movement::left(map, selection.start)
 6139                } else {
 6140                    selection.start
 6141                };
 6142                selection.collapse_to(cursor, SelectionGoal::None);
 6143            });
 6144        })
 6145    }
 6146
 6147    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 6148        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6149            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 6150        })
 6151    }
 6152
 6153    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 6154        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6155            let line_mode = s.line_mode;
 6156            s.move_with(|map, selection| {
 6157                let cursor = if selection.is_empty() && !line_mode {
 6158                    movement::right(map, selection.end)
 6159                } else {
 6160                    selection.end
 6161                };
 6162                selection.collapse_to(cursor, SelectionGoal::None)
 6163            });
 6164        })
 6165    }
 6166
 6167    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 6168        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6169            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 6170        })
 6171    }
 6172
 6173    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 6174        if self.take_rename(true, cx).is_some() {
 6175            return;
 6176        }
 6177
 6178        if matches!(self.mode, EditorMode::SingleLine) {
 6179            cx.propagate();
 6180            return;
 6181        }
 6182
 6183        let text_layout_details = &self.text_layout_details(cx);
 6184
 6185        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6186            let line_mode = s.line_mode;
 6187            s.move_with(|map, selection| {
 6188                if !selection.is_empty() && !line_mode {
 6189                    selection.goal = SelectionGoal::None;
 6190                }
 6191                let (cursor, goal) = movement::up(
 6192                    map,
 6193                    selection.start,
 6194                    selection.goal,
 6195                    false,
 6196                    &text_layout_details,
 6197                );
 6198                selection.collapse_to(cursor, goal);
 6199            });
 6200        })
 6201    }
 6202
 6203    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 6204        if self.take_rename(true, cx).is_some() {
 6205            return;
 6206        }
 6207
 6208        if matches!(self.mode, EditorMode::SingleLine) {
 6209            cx.propagate();
 6210            return;
 6211        }
 6212
 6213        let text_layout_details = &self.text_layout_details(cx);
 6214
 6215        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6216            let line_mode = s.line_mode;
 6217            s.move_with(|map, selection| {
 6218                if !selection.is_empty() && !line_mode {
 6219                    selection.goal = SelectionGoal::None;
 6220                }
 6221                let (cursor, goal) = movement::up_by_rows(
 6222                    map,
 6223                    selection.start,
 6224                    action.lines,
 6225                    selection.goal,
 6226                    false,
 6227                    &text_layout_details,
 6228                );
 6229                selection.collapse_to(cursor, goal);
 6230            });
 6231        })
 6232    }
 6233
 6234    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 6235        if self.take_rename(true, cx).is_some() {
 6236            return;
 6237        }
 6238
 6239        if matches!(self.mode, EditorMode::SingleLine) {
 6240            cx.propagate();
 6241            return;
 6242        }
 6243
 6244        let text_layout_details = &self.text_layout_details(cx);
 6245
 6246        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6247            let line_mode = s.line_mode;
 6248            s.move_with(|map, selection| {
 6249                if !selection.is_empty() && !line_mode {
 6250                    selection.goal = SelectionGoal::None;
 6251                }
 6252                let (cursor, goal) = movement::down_by_rows(
 6253                    map,
 6254                    selection.start,
 6255                    action.lines,
 6256                    selection.goal,
 6257                    false,
 6258                    &text_layout_details,
 6259                );
 6260                selection.collapse_to(cursor, goal);
 6261            });
 6262        })
 6263    }
 6264
 6265    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 6266        let text_layout_details = &self.text_layout_details(cx);
 6267        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6268            s.move_heads_with(|map, head, goal| {
 6269                movement::down_by_rows(map, head, action.lines, goal, false, &text_layout_details)
 6270            })
 6271        })
 6272    }
 6273
 6274    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 6275        let text_layout_details = &self.text_layout_details(cx);
 6276        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6277            s.move_heads_with(|map, head, goal| {
 6278                movement::up_by_rows(map, head, action.lines, goal, false, &text_layout_details)
 6279            })
 6280        })
 6281    }
 6282
 6283    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 6284        if self.take_rename(true, cx).is_some() {
 6285            return;
 6286        }
 6287
 6288        if matches!(self.mode, EditorMode::SingleLine) {
 6289            cx.propagate();
 6290            return;
 6291        }
 6292
 6293        let row_count = if let Some(row_count) = self.visible_line_count() {
 6294            row_count as u32 - 1
 6295        } else {
 6296            return;
 6297        };
 6298
 6299        let autoscroll = if action.center_cursor {
 6300            Autoscroll::center()
 6301        } else {
 6302            Autoscroll::fit()
 6303        };
 6304
 6305        let text_layout_details = &self.text_layout_details(cx);
 6306
 6307        self.change_selections(Some(autoscroll), cx, |s| {
 6308            let line_mode = s.line_mode;
 6309            s.move_with(|map, selection| {
 6310                if !selection.is_empty() && !line_mode {
 6311                    selection.goal = SelectionGoal::None;
 6312                }
 6313                let (cursor, goal) = movement::up_by_rows(
 6314                    map,
 6315                    selection.end,
 6316                    row_count,
 6317                    selection.goal,
 6318                    false,
 6319                    &text_layout_details,
 6320                );
 6321                selection.collapse_to(cursor, goal);
 6322            });
 6323        });
 6324    }
 6325
 6326    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 6327        let text_layout_details = &self.text_layout_details(cx);
 6328        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6329            s.move_heads_with(|map, head, goal| {
 6330                movement::up(map, head, goal, false, &text_layout_details)
 6331            })
 6332        })
 6333    }
 6334
 6335    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 6336        self.take_rename(true, cx);
 6337
 6338        if self.mode == EditorMode::SingleLine {
 6339            cx.propagate();
 6340            return;
 6341        }
 6342
 6343        let text_layout_details = &self.text_layout_details(cx);
 6344        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6345            let line_mode = s.line_mode;
 6346            s.move_with(|map, selection| {
 6347                if !selection.is_empty() && !line_mode {
 6348                    selection.goal = SelectionGoal::None;
 6349                }
 6350                let (cursor, goal) = movement::down(
 6351                    map,
 6352                    selection.end,
 6353                    selection.goal,
 6354                    false,
 6355                    &text_layout_details,
 6356                );
 6357                selection.collapse_to(cursor, goal);
 6358            });
 6359        });
 6360    }
 6361
 6362    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 6363        if self.take_rename(true, cx).is_some() {
 6364            return;
 6365        }
 6366
 6367        if self
 6368            .context_menu
 6369            .write()
 6370            .as_mut()
 6371            .map(|menu| menu.select_last(self.project.as_ref(), cx))
 6372            .unwrap_or(false)
 6373        {
 6374            return;
 6375        }
 6376
 6377        if matches!(self.mode, EditorMode::SingleLine) {
 6378            cx.propagate();
 6379            return;
 6380        }
 6381
 6382        let row_count = if let Some(row_count) = self.visible_line_count() {
 6383            row_count as u32 - 1
 6384        } else {
 6385            return;
 6386        };
 6387
 6388        let autoscroll = if action.center_cursor {
 6389            Autoscroll::center()
 6390        } else {
 6391            Autoscroll::fit()
 6392        };
 6393
 6394        let text_layout_details = &self.text_layout_details(cx);
 6395        self.change_selections(Some(autoscroll), cx, |s| {
 6396            let line_mode = s.line_mode;
 6397            s.move_with(|map, selection| {
 6398                if !selection.is_empty() && !line_mode {
 6399                    selection.goal = SelectionGoal::None;
 6400                }
 6401                let (cursor, goal) = movement::down_by_rows(
 6402                    map,
 6403                    selection.end,
 6404                    row_count,
 6405                    selection.goal,
 6406                    false,
 6407                    &text_layout_details,
 6408                );
 6409                selection.collapse_to(cursor, goal);
 6410            });
 6411        });
 6412    }
 6413
 6414    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 6415        let text_layout_details = &self.text_layout_details(cx);
 6416        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6417            s.move_heads_with(|map, head, goal| {
 6418                movement::down(map, head, goal, false, &text_layout_details)
 6419            })
 6420        });
 6421    }
 6422
 6423    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 6424        if let Some(context_menu) = self.context_menu.write().as_mut() {
 6425            context_menu.select_first(self.project.as_ref(), cx);
 6426        }
 6427    }
 6428
 6429    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 6430        if let Some(context_menu) = self.context_menu.write().as_mut() {
 6431            context_menu.select_prev(self.project.as_ref(), cx);
 6432        }
 6433    }
 6434
 6435    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 6436        if let Some(context_menu) = self.context_menu.write().as_mut() {
 6437            context_menu.select_next(self.project.as_ref(), cx);
 6438        }
 6439    }
 6440
 6441    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 6442        if let Some(context_menu) = self.context_menu.write().as_mut() {
 6443            context_menu.select_last(self.project.as_ref(), cx);
 6444        }
 6445    }
 6446
 6447    pub fn move_to_previous_word_start(
 6448        &mut self,
 6449        _: &MoveToPreviousWordStart,
 6450        cx: &mut ViewContext<Self>,
 6451    ) {
 6452        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6453            s.move_cursors_with(|map, head, _| {
 6454                (
 6455                    movement::previous_word_start(map, head),
 6456                    SelectionGoal::None,
 6457                )
 6458            });
 6459        })
 6460    }
 6461
 6462    pub fn move_to_previous_subword_start(
 6463        &mut self,
 6464        _: &MoveToPreviousSubwordStart,
 6465        cx: &mut ViewContext<Self>,
 6466    ) {
 6467        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6468            s.move_cursors_with(|map, head, _| {
 6469                (
 6470                    movement::previous_subword_start(map, head),
 6471                    SelectionGoal::None,
 6472                )
 6473            });
 6474        })
 6475    }
 6476
 6477    pub fn select_to_previous_word_start(
 6478        &mut self,
 6479        _: &SelectToPreviousWordStart,
 6480        cx: &mut ViewContext<Self>,
 6481    ) {
 6482        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6483            s.move_heads_with(|map, head, _| {
 6484                (
 6485                    movement::previous_word_start(map, head),
 6486                    SelectionGoal::None,
 6487                )
 6488            });
 6489        })
 6490    }
 6491
 6492    pub fn select_to_previous_subword_start(
 6493        &mut self,
 6494        _: &SelectToPreviousSubwordStart,
 6495        cx: &mut ViewContext<Self>,
 6496    ) {
 6497        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6498            s.move_heads_with(|map, head, _| {
 6499                (
 6500                    movement::previous_subword_start(map, head),
 6501                    SelectionGoal::None,
 6502                )
 6503            });
 6504        })
 6505    }
 6506
 6507    pub fn delete_to_previous_word_start(
 6508        &mut self,
 6509        _: &DeleteToPreviousWordStart,
 6510        cx: &mut ViewContext<Self>,
 6511    ) {
 6512        self.transact(cx, |this, cx| {
 6513            this.select_autoclose_pair(cx);
 6514            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6515                let line_mode = s.line_mode;
 6516                s.move_with(|map, selection| {
 6517                    if selection.is_empty() && !line_mode {
 6518                        let cursor = movement::previous_word_start(map, selection.head());
 6519                        selection.set_head(cursor, SelectionGoal::None);
 6520                    }
 6521                });
 6522            });
 6523            this.insert("", cx);
 6524        });
 6525    }
 6526
 6527    pub fn delete_to_previous_subword_start(
 6528        &mut self,
 6529        _: &DeleteToPreviousSubwordStart,
 6530        cx: &mut ViewContext<Self>,
 6531    ) {
 6532        self.transact(cx, |this, cx| {
 6533            this.select_autoclose_pair(cx);
 6534            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6535                let line_mode = s.line_mode;
 6536                s.move_with(|map, selection| {
 6537                    if selection.is_empty() && !line_mode {
 6538                        let cursor = movement::previous_subword_start(map, selection.head());
 6539                        selection.set_head(cursor, SelectionGoal::None);
 6540                    }
 6541                });
 6542            });
 6543            this.insert("", cx);
 6544        });
 6545    }
 6546
 6547    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 6548        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6549            s.move_cursors_with(|map, head, _| {
 6550                (movement::next_word_end(map, head), SelectionGoal::None)
 6551            });
 6552        })
 6553    }
 6554
 6555    pub fn move_to_next_subword_end(
 6556        &mut self,
 6557        _: &MoveToNextSubwordEnd,
 6558        cx: &mut ViewContext<Self>,
 6559    ) {
 6560        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6561            s.move_cursors_with(|map, head, _| {
 6562                (movement::next_subword_end(map, head), SelectionGoal::None)
 6563            });
 6564        })
 6565    }
 6566
 6567    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 6568        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6569            s.move_heads_with(|map, head, _| {
 6570                (movement::next_word_end(map, head), SelectionGoal::None)
 6571            });
 6572        })
 6573    }
 6574
 6575    pub fn select_to_next_subword_end(
 6576        &mut self,
 6577        _: &SelectToNextSubwordEnd,
 6578        cx: &mut ViewContext<Self>,
 6579    ) {
 6580        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6581            s.move_heads_with(|map, head, _| {
 6582                (movement::next_subword_end(map, head), SelectionGoal::None)
 6583            });
 6584        })
 6585    }
 6586
 6587    pub fn delete_to_next_word_end(&mut self, _: &DeleteToNextWordEnd, cx: &mut ViewContext<Self>) {
 6588        self.transact(cx, |this, cx| {
 6589            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6590                let line_mode = s.line_mode;
 6591                s.move_with(|map, selection| {
 6592                    if selection.is_empty() && !line_mode {
 6593                        let cursor = movement::next_word_end(map, selection.head());
 6594                        selection.set_head(cursor, SelectionGoal::None);
 6595                    }
 6596                });
 6597            });
 6598            this.insert("", cx);
 6599        });
 6600    }
 6601
 6602    pub fn delete_to_next_subword_end(
 6603        &mut self,
 6604        _: &DeleteToNextSubwordEnd,
 6605        cx: &mut ViewContext<Self>,
 6606    ) {
 6607        self.transact(cx, |this, cx| {
 6608            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6609                s.move_with(|map, selection| {
 6610                    if selection.is_empty() {
 6611                        let cursor = movement::next_subword_end(map, selection.head());
 6612                        selection.set_head(cursor, SelectionGoal::None);
 6613                    }
 6614                });
 6615            });
 6616            this.insert("", cx);
 6617        });
 6618    }
 6619
 6620    pub fn move_to_beginning_of_line(
 6621        &mut self,
 6622        action: &MoveToBeginningOfLine,
 6623        cx: &mut ViewContext<Self>,
 6624    ) {
 6625        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6626            s.move_cursors_with(|map, head, _| {
 6627                (
 6628                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 6629                    SelectionGoal::None,
 6630                )
 6631            });
 6632        })
 6633    }
 6634
 6635    pub fn select_to_beginning_of_line(
 6636        &mut self,
 6637        action: &SelectToBeginningOfLine,
 6638        cx: &mut ViewContext<Self>,
 6639    ) {
 6640        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6641            s.move_heads_with(|map, head, _| {
 6642                (
 6643                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 6644                    SelectionGoal::None,
 6645                )
 6646            });
 6647        });
 6648    }
 6649
 6650    pub fn delete_to_beginning_of_line(
 6651        &mut self,
 6652        _: &DeleteToBeginningOfLine,
 6653        cx: &mut ViewContext<Self>,
 6654    ) {
 6655        self.transact(cx, |this, cx| {
 6656            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6657                s.move_with(|_, selection| {
 6658                    selection.reversed = true;
 6659                });
 6660            });
 6661
 6662            this.select_to_beginning_of_line(
 6663                &SelectToBeginningOfLine {
 6664                    stop_at_soft_wraps: false,
 6665                },
 6666                cx,
 6667            );
 6668            this.backspace(&Backspace, cx);
 6669        });
 6670    }
 6671
 6672    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 6673        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6674            s.move_cursors_with(|map, head, _| {
 6675                (
 6676                    movement::line_end(map, head, action.stop_at_soft_wraps),
 6677                    SelectionGoal::None,
 6678                )
 6679            });
 6680        })
 6681    }
 6682
 6683    pub fn select_to_end_of_line(
 6684        &mut self,
 6685        action: &SelectToEndOfLine,
 6686        cx: &mut ViewContext<Self>,
 6687    ) {
 6688        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6689            s.move_heads_with(|map, head, _| {
 6690                (
 6691                    movement::line_end(map, head, action.stop_at_soft_wraps),
 6692                    SelectionGoal::None,
 6693                )
 6694            });
 6695        })
 6696    }
 6697
 6698    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 6699        self.transact(cx, |this, cx| {
 6700            this.select_to_end_of_line(
 6701                &SelectToEndOfLine {
 6702                    stop_at_soft_wraps: false,
 6703                },
 6704                cx,
 6705            );
 6706            this.delete(&Delete, cx);
 6707        });
 6708    }
 6709
 6710    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 6711        self.transact(cx, |this, cx| {
 6712            this.select_to_end_of_line(
 6713                &SelectToEndOfLine {
 6714                    stop_at_soft_wraps: false,
 6715                },
 6716                cx,
 6717            );
 6718            this.cut(&Cut, cx);
 6719        });
 6720    }
 6721
 6722    pub fn move_to_start_of_paragraph(
 6723        &mut self,
 6724        _: &MoveToStartOfParagraph,
 6725        cx: &mut ViewContext<Self>,
 6726    ) {
 6727        if matches!(self.mode, EditorMode::SingleLine) {
 6728            cx.propagate();
 6729            return;
 6730        }
 6731
 6732        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6733            s.move_with(|map, selection| {
 6734                selection.collapse_to(
 6735                    movement::start_of_paragraph(map, selection.head(), 1),
 6736                    SelectionGoal::None,
 6737                )
 6738            });
 6739        })
 6740    }
 6741
 6742    pub fn move_to_end_of_paragraph(
 6743        &mut self,
 6744        _: &MoveToEndOfParagraph,
 6745        cx: &mut ViewContext<Self>,
 6746    ) {
 6747        if matches!(self.mode, EditorMode::SingleLine) {
 6748            cx.propagate();
 6749            return;
 6750        }
 6751
 6752        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6753            s.move_with(|map, selection| {
 6754                selection.collapse_to(
 6755                    movement::end_of_paragraph(map, selection.head(), 1),
 6756                    SelectionGoal::None,
 6757                )
 6758            });
 6759        })
 6760    }
 6761
 6762    pub fn select_to_start_of_paragraph(
 6763        &mut self,
 6764        _: &SelectToStartOfParagraph,
 6765        cx: &mut ViewContext<Self>,
 6766    ) {
 6767        if matches!(self.mode, EditorMode::SingleLine) {
 6768            cx.propagate();
 6769            return;
 6770        }
 6771
 6772        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6773            s.move_heads_with(|map, head, _| {
 6774                (
 6775                    movement::start_of_paragraph(map, head, 1),
 6776                    SelectionGoal::None,
 6777                )
 6778            });
 6779        })
 6780    }
 6781
 6782    pub fn select_to_end_of_paragraph(
 6783        &mut self,
 6784        _: &SelectToEndOfParagraph,
 6785        cx: &mut ViewContext<Self>,
 6786    ) {
 6787        if matches!(self.mode, EditorMode::SingleLine) {
 6788            cx.propagate();
 6789            return;
 6790        }
 6791
 6792        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6793            s.move_heads_with(|map, head, _| {
 6794                (
 6795                    movement::end_of_paragraph(map, head, 1),
 6796                    SelectionGoal::None,
 6797                )
 6798            });
 6799        })
 6800    }
 6801
 6802    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 6803        if matches!(self.mode, EditorMode::SingleLine) {
 6804            cx.propagate();
 6805            return;
 6806        }
 6807
 6808        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6809            s.select_ranges(vec![0..0]);
 6810        });
 6811    }
 6812
 6813    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 6814        let mut selection = self.selections.last::<Point>(cx);
 6815        selection.set_head(Point::zero(), SelectionGoal::None);
 6816
 6817        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6818            s.select(vec![selection]);
 6819        });
 6820    }
 6821
 6822    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 6823        if matches!(self.mode, EditorMode::SingleLine) {
 6824            cx.propagate();
 6825            return;
 6826        }
 6827
 6828        let cursor = self.buffer.read(cx).read(cx).len();
 6829        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6830            s.select_ranges(vec![cursor..cursor])
 6831        });
 6832    }
 6833
 6834    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 6835        self.nav_history = nav_history;
 6836    }
 6837
 6838    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 6839        self.nav_history.as_ref()
 6840    }
 6841
 6842    fn push_to_nav_history(
 6843        &mut self,
 6844        cursor_anchor: Anchor,
 6845        new_position: Option<Point>,
 6846        cx: &mut ViewContext<Self>,
 6847    ) {
 6848        if let Some(nav_history) = self.nav_history.as_mut() {
 6849            let buffer = self.buffer.read(cx).read(cx);
 6850            let cursor_position = cursor_anchor.to_point(&buffer);
 6851            let scroll_state = self.scroll_manager.anchor();
 6852            let scroll_top_row = scroll_state.top_row(&buffer);
 6853            drop(buffer);
 6854
 6855            if let Some(new_position) = new_position {
 6856                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 6857                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 6858                    return;
 6859                }
 6860            }
 6861
 6862            nav_history.push(
 6863                Some(NavigationData {
 6864                    cursor_anchor,
 6865                    cursor_position,
 6866                    scroll_anchor: scroll_state,
 6867                    scroll_top_row,
 6868                }),
 6869                cx,
 6870            );
 6871        }
 6872    }
 6873
 6874    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 6875        let buffer = self.buffer.read(cx).snapshot(cx);
 6876        let mut selection = self.selections.first::<usize>(cx);
 6877        selection.set_head(buffer.len(), SelectionGoal::None);
 6878        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6879            s.select(vec![selection]);
 6880        });
 6881    }
 6882
 6883    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 6884        let end = self.buffer.read(cx).read(cx).len();
 6885        self.change_selections(None, cx, |s| {
 6886            s.select_ranges(vec![0..end]);
 6887        });
 6888    }
 6889
 6890    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 6891        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6892        let mut selections = self.selections.all::<Point>(cx);
 6893        let max_point = display_map.buffer_snapshot.max_point();
 6894        for selection in &mut selections {
 6895            let rows = selection.spanned_rows(true, &display_map);
 6896            selection.start = Point::new(rows.start.0, 0);
 6897            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 6898            selection.reversed = false;
 6899        }
 6900        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6901            s.select(selections);
 6902        });
 6903    }
 6904
 6905    pub fn split_selection_into_lines(
 6906        &mut self,
 6907        _: &SplitSelectionIntoLines,
 6908        cx: &mut ViewContext<Self>,
 6909    ) {
 6910        let mut to_unfold = Vec::new();
 6911        let mut new_selection_ranges = Vec::new();
 6912        {
 6913            let selections = self.selections.all::<Point>(cx);
 6914            let buffer = self.buffer.read(cx).read(cx);
 6915            for selection in selections {
 6916                for row in selection.start.row..selection.end.row {
 6917                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 6918                    new_selection_ranges.push(cursor..cursor);
 6919                }
 6920                new_selection_ranges.push(selection.end..selection.end);
 6921                to_unfold.push(selection.start..selection.end);
 6922            }
 6923        }
 6924        self.unfold_ranges(to_unfold, true, true, cx);
 6925        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6926            s.select_ranges(new_selection_ranges);
 6927        });
 6928    }
 6929
 6930    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 6931        self.add_selection(true, cx);
 6932    }
 6933
 6934    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 6935        self.add_selection(false, cx);
 6936    }
 6937
 6938    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 6939        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6940        let mut selections = self.selections.all::<Point>(cx);
 6941        let text_layout_details = self.text_layout_details(cx);
 6942        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 6943            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 6944            let range = oldest_selection.display_range(&display_map).sorted();
 6945
 6946            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 6947            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 6948            let positions = start_x.min(end_x)..start_x.max(end_x);
 6949
 6950            selections.clear();
 6951            let mut stack = Vec::new();
 6952            for row in range.start.row().0..=range.end.row().0 {
 6953                if let Some(selection) = self.selections.build_columnar_selection(
 6954                    &display_map,
 6955                    DisplayRow(row),
 6956                    &positions,
 6957                    oldest_selection.reversed,
 6958                    &text_layout_details,
 6959                ) {
 6960                    stack.push(selection.id);
 6961                    selections.push(selection);
 6962                }
 6963            }
 6964
 6965            if above {
 6966                stack.reverse();
 6967            }
 6968
 6969            AddSelectionsState { above, stack }
 6970        });
 6971
 6972        let last_added_selection = *state.stack.last().unwrap();
 6973        let mut new_selections = Vec::new();
 6974        if above == state.above {
 6975            let end_row = if above {
 6976                DisplayRow(0)
 6977            } else {
 6978                display_map.max_point().row()
 6979            };
 6980
 6981            'outer: for selection in selections {
 6982                if selection.id == last_added_selection {
 6983                    let range = selection.display_range(&display_map).sorted();
 6984                    debug_assert_eq!(range.start.row(), range.end.row());
 6985                    let mut row = range.start.row();
 6986                    let positions =
 6987                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 6988                            px(start)..px(end)
 6989                        } else {
 6990                            let start_x =
 6991                                display_map.x_for_display_point(range.start, &text_layout_details);
 6992                            let end_x =
 6993                                display_map.x_for_display_point(range.end, &text_layout_details);
 6994                            start_x.min(end_x)..start_x.max(end_x)
 6995                        };
 6996
 6997                    while row != end_row {
 6998                        if above {
 6999                            row.0 -= 1;
 7000                        } else {
 7001                            row.0 += 1;
 7002                        }
 7003
 7004                        if let Some(new_selection) = self.selections.build_columnar_selection(
 7005                            &display_map,
 7006                            row,
 7007                            &positions,
 7008                            selection.reversed,
 7009                            &text_layout_details,
 7010                        ) {
 7011                            state.stack.push(new_selection.id);
 7012                            if above {
 7013                                new_selections.push(new_selection);
 7014                                new_selections.push(selection);
 7015                            } else {
 7016                                new_selections.push(selection);
 7017                                new_selections.push(new_selection);
 7018                            }
 7019
 7020                            continue 'outer;
 7021                        }
 7022                    }
 7023                }
 7024
 7025                new_selections.push(selection);
 7026            }
 7027        } else {
 7028            new_selections = selections;
 7029            new_selections.retain(|s| s.id != last_added_selection);
 7030            state.stack.pop();
 7031        }
 7032
 7033        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7034            s.select(new_selections);
 7035        });
 7036        if state.stack.len() > 1 {
 7037            self.add_selections_state = Some(state);
 7038        }
 7039    }
 7040
 7041    pub fn select_next_match_internal(
 7042        &mut self,
 7043        display_map: &DisplaySnapshot,
 7044        replace_newest: bool,
 7045        autoscroll: Option<Autoscroll>,
 7046        cx: &mut ViewContext<Self>,
 7047    ) -> Result<()> {
 7048        fn select_next_match_ranges(
 7049            this: &mut Editor,
 7050            range: Range<usize>,
 7051            replace_newest: bool,
 7052            auto_scroll: Option<Autoscroll>,
 7053            cx: &mut ViewContext<Editor>,
 7054        ) {
 7055            this.unfold_ranges([range.clone()], false, true, cx);
 7056            this.change_selections(auto_scroll, cx, |s| {
 7057                if replace_newest {
 7058                    s.delete(s.newest_anchor().id);
 7059                }
 7060                s.insert_range(range.clone());
 7061            });
 7062        }
 7063
 7064        let buffer = &display_map.buffer_snapshot;
 7065        let mut selections = self.selections.all::<usize>(cx);
 7066        if let Some(mut select_next_state) = self.select_next_state.take() {
 7067            let query = &select_next_state.query;
 7068            if !select_next_state.done {
 7069                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 7070                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 7071                let mut next_selected_range = None;
 7072
 7073                let bytes_after_last_selection =
 7074                    buffer.bytes_in_range(last_selection.end..buffer.len());
 7075                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 7076                let query_matches = query
 7077                    .stream_find_iter(bytes_after_last_selection)
 7078                    .map(|result| (last_selection.end, result))
 7079                    .chain(
 7080                        query
 7081                            .stream_find_iter(bytes_before_first_selection)
 7082                            .map(|result| (0, result)),
 7083                    );
 7084
 7085                for (start_offset, query_match) in query_matches {
 7086                    let query_match = query_match.unwrap(); // can only fail due to I/O
 7087                    let offset_range =
 7088                        start_offset + query_match.start()..start_offset + query_match.end();
 7089                    let display_range = offset_range.start.to_display_point(&display_map)
 7090                        ..offset_range.end.to_display_point(&display_map);
 7091
 7092                    if !select_next_state.wordwise
 7093                        || (!movement::is_inside_word(&display_map, display_range.start)
 7094                            && !movement::is_inside_word(&display_map, display_range.end))
 7095                    {
 7096                        // TODO: This is n^2, because we might check all the selections
 7097                        if !selections
 7098                            .iter()
 7099                            .any(|selection| selection.range().overlaps(&offset_range))
 7100                        {
 7101                            next_selected_range = Some(offset_range);
 7102                            break;
 7103                        }
 7104                    }
 7105                }
 7106
 7107                if let Some(next_selected_range) = next_selected_range {
 7108                    select_next_match_ranges(
 7109                        self,
 7110                        next_selected_range,
 7111                        replace_newest,
 7112                        autoscroll,
 7113                        cx,
 7114                    );
 7115                } else {
 7116                    select_next_state.done = true;
 7117                }
 7118            }
 7119
 7120            self.select_next_state = Some(select_next_state);
 7121        } else {
 7122            let mut only_carets = true;
 7123            let mut same_text_selected = true;
 7124            let mut selected_text = None;
 7125
 7126            let mut selections_iter = selections.iter().peekable();
 7127            while let Some(selection) = selections_iter.next() {
 7128                if selection.start != selection.end {
 7129                    only_carets = false;
 7130                }
 7131
 7132                if same_text_selected {
 7133                    if selected_text.is_none() {
 7134                        selected_text =
 7135                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 7136                    }
 7137
 7138                    if let Some(next_selection) = selections_iter.peek() {
 7139                        if next_selection.range().len() == selection.range().len() {
 7140                            let next_selected_text = buffer
 7141                                .text_for_range(next_selection.range())
 7142                                .collect::<String>();
 7143                            if Some(next_selected_text) != selected_text {
 7144                                same_text_selected = false;
 7145                                selected_text = None;
 7146                            }
 7147                        } else {
 7148                            same_text_selected = false;
 7149                            selected_text = None;
 7150                        }
 7151                    }
 7152                }
 7153            }
 7154
 7155            if only_carets {
 7156                for selection in &mut selections {
 7157                    let word_range = movement::surrounding_word(
 7158                        &display_map,
 7159                        selection.start.to_display_point(&display_map),
 7160                    );
 7161                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 7162                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 7163                    selection.goal = SelectionGoal::None;
 7164                    selection.reversed = false;
 7165                    select_next_match_ranges(
 7166                        self,
 7167                        selection.start..selection.end,
 7168                        replace_newest,
 7169                        autoscroll,
 7170                        cx,
 7171                    );
 7172                }
 7173
 7174                if selections.len() == 1 {
 7175                    let selection = selections
 7176                        .last()
 7177                        .expect("ensured that there's only one selection");
 7178                    let query = buffer
 7179                        .text_for_range(selection.start..selection.end)
 7180                        .collect::<String>();
 7181                    let is_empty = query.is_empty();
 7182                    let select_state = SelectNextState {
 7183                        query: AhoCorasick::new(&[query])?,
 7184                        wordwise: true,
 7185                        done: is_empty,
 7186                    };
 7187                    self.select_next_state = Some(select_state);
 7188                } else {
 7189                    self.select_next_state = None;
 7190                }
 7191            } else if let Some(selected_text) = selected_text {
 7192                self.select_next_state = Some(SelectNextState {
 7193                    query: AhoCorasick::new(&[selected_text])?,
 7194                    wordwise: false,
 7195                    done: false,
 7196                });
 7197                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 7198            }
 7199        }
 7200        Ok(())
 7201    }
 7202
 7203    pub fn select_all_matches(
 7204        &mut self,
 7205        _action: &SelectAllMatches,
 7206        cx: &mut ViewContext<Self>,
 7207    ) -> Result<()> {
 7208        self.push_to_selection_history();
 7209        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7210
 7211        self.select_next_match_internal(&display_map, false, None, cx)?;
 7212        let Some(select_next_state) = self.select_next_state.as_mut() else {
 7213            return Ok(());
 7214        };
 7215        if select_next_state.done {
 7216            return Ok(());
 7217        }
 7218
 7219        let mut new_selections = self.selections.all::<usize>(cx);
 7220
 7221        let buffer = &display_map.buffer_snapshot;
 7222        let query_matches = select_next_state
 7223            .query
 7224            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 7225
 7226        for query_match in query_matches {
 7227            let query_match = query_match.unwrap(); // can only fail due to I/O
 7228            let offset_range = query_match.start()..query_match.end();
 7229            let display_range = offset_range.start.to_display_point(&display_map)
 7230                ..offset_range.end.to_display_point(&display_map);
 7231
 7232            if !select_next_state.wordwise
 7233                || (!movement::is_inside_word(&display_map, display_range.start)
 7234                    && !movement::is_inside_word(&display_map, display_range.end))
 7235            {
 7236                self.selections.change_with(cx, |selections| {
 7237                    new_selections.push(Selection {
 7238                        id: selections.new_selection_id(),
 7239                        start: offset_range.start,
 7240                        end: offset_range.end,
 7241                        reversed: false,
 7242                        goal: SelectionGoal::None,
 7243                    });
 7244                });
 7245            }
 7246        }
 7247
 7248        new_selections.sort_by_key(|selection| selection.start);
 7249        let mut ix = 0;
 7250        while ix + 1 < new_selections.len() {
 7251            let current_selection = &new_selections[ix];
 7252            let next_selection = &new_selections[ix + 1];
 7253            if current_selection.range().overlaps(&next_selection.range()) {
 7254                if current_selection.id < next_selection.id {
 7255                    new_selections.remove(ix + 1);
 7256                } else {
 7257                    new_selections.remove(ix);
 7258                }
 7259            } else {
 7260                ix += 1;
 7261            }
 7262        }
 7263
 7264        select_next_state.done = true;
 7265        self.unfold_ranges(
 7266            new_selections.iter().map(|selection| selection.range()),
 7267            false,
 7268            false,
 7269            cx,
 7270        );
 7271        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 7272            selections.select(new_selections)
 7273        });
 7274
 7275        Ok(())
 7276    }
 7277
 7278    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 7279        self.push_to_selection_history();
 7280        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7281        self.select_next_match_internal(
 7282            &display_map,
 7283            action.replace_newest,
 7284            Some(Autoscroll::newest()),
 7285            cx,
 7286        )?;
 7287        Ok(())
 7288    }
 7289
 7290    pub fn select_previous(
 7291        &mut self,
 7292        action: &SelectPrevious,
 7293        cx: &mut ViewContext<Self>,
 7294    ) -> Result<()> {
 7295        self.push_to_selection_history();
 7296        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7297        let buffer = &display_map.buffer_snapshot;
 7298        let mut selections = self.selections.all::<usize>(cx);
 7299        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 7300            let query = &select_prev_state.query;
 7301            if !select_prev_state.done {
 7302                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 7303                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 7304                let mut next_selected_range = None;
 7305                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 7306                let bytes_before_last_selection =
 7307                    buffer.reversed_bytes_in_range(0..last_selection.start);
 7308                let bytes_after_first_selection =
 7309                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 7310                let query_matches = query
 7311                    .stream_find_iter(bytes_before_last_selection)
 7312                    .map(|result| (last_selection.start, result))
 7313                    .chain(
 7314                        query
 7315                            .stream_find_iter(bytes_after_first_selection)
 7316                            .map(|result| (buffer.len(), result)),
 7317                    );
 7318                for (end_offset, query_match) in query_matches {
 7319                    let query_match = query_match.unwrap(); // can only fail due to I/O
 7320                    let offset_range =
 7321                        end_offset - query_match.end()..end_offset - query_match.start();
 7322                    let display_range = offset_range.start.to_display_point(&display_map)
 7323                        ..offset_range.end.to_display_point(&display_map);
 7324
 7325                    if !select_prev_state.wordwise
 7326                        || (!movement::is_inside_word(&display_map, display_range.start)
 7327                            && !movement::is_inside_word(&display_map, display_range.end))
 7328                    {
 7329                        next_selected_range = Some(offset_range);
 7330                        break;
 7331                    }
 7332                }
 7333
 7334                if let Some(next_selected_range) = next_selected_range {
 7335                    self.unfold_ranges([next_selected_range.clone()], false, true, cx);
 7336                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 7337                        if action.replace_newest {
 7338                            s.delete(s.newest_anchor().id);
 7339                        }
 7340                        s.insert_range(next_selected_range);
 7341                    });
 7342                } else {
 7343                    select_prev_state.done = true;
 7344                }
 7345            }
 7346
 7347            self.select_prev_state = Some(select_prev_state);
 7348        } else {
 7349            let mut only_carets = true;
 7350            let mut same_text_selected = true;
 7351            let mut selected_text = None;
 7352
 7353            let mut selections_iter = selections.iter().peekable();
 7354            while let Some(selection) = selections_iter.next() {
 7355                if selection.start != selection.end {
 7356                    only_carets = false;
 7357                }
 7358
 7359                if same_text_selected {
 7360                    if selected_text.is_none() {
 7361                        selected_text =
 7362                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 7363                    }
 7364
 7365                    if let Some(next_selection) = selections_iter.peek() {
 7366                        if next_selection.range().len() == selection.range().len() {
 7367                            let next_selected_text = buffer
 7368                                .text_for_range(next_selection.range())
 7369                                .collect::<String>();
 7370                            if Some(next_selected_text) != selected_text {
 7371                                same_text_selected = false;
 7372                                selected_text = None;
 7373                            }
 7374                        } else {
 7375                            same_text_selected = false;
 7376                            selected_text = None;
 7377                        }
 7378                    }
 7379                }
 7380            }
 7381
 7382            if only_carets {
 7383                for selection in &mut selections {
 7384                    let word_range = movement::surrounding_word(
 7385                        &display_map,
 7386                        selection.start.to_display_point(&display_map),
 7387                    );
 7388                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 7389                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 7390                    selection.goal = SelectionGoal::None;
 7391                    selection.reversed = false;
 7392                }
 7393                if selections.len() == 1 {
 7394                    let selection = selections
 7395                        .last()
 7396                        .expect("ensured that there's only one selection");
 7397                    let query = buffer
 7398                        .text_for_range(selection.start..selection.end)
 7399                        .collect::<String>();
 7400                    let is_empty = query.is_empty();
 7401                    let select_state = SelectNextState {
 7402                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 7403                        wordwise: true,
 7404                        done: is_empty,
 7405                    };
 7406                    self.select_prev_state = Some(select_state);
 7407                } else {
 7408                    self.select_prev_state = None;
 7409                }
 7410
 7411                self.unfold_ranges(
 7412                    selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 7413                    false,
 7414                    true,
 7415                    cx,
 7416                );
 7417                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 7418                    s.select(selections);
 7419                });
 7420            } else if let Some(selected_text) = selected_text {
 7421                self.select_prev_state = Some(SelectNextState {
 7422                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 7423                    wordwise: false,
 7424                    done: false,
 7425                });
 7426                self.select_previous(action, cx)?;
 7427            }
 7428        }
 7429        Ok(())
 7430    }
 7431
 7432    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 7433        let text_layout_details = &self.text_layout_details(cx);
 7434        self.transact(cx, |this, cx| {
 7435            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 7436            let mut edits = Vec::new();
 7437            let mut selection_edit_ranges = Vec::new();
 7438            let mut last_toggled_row = None;
 7439            let snapshot = this.buffer.read(cx).read(cx);
 7440            let empty_str: Arc<str> = "".into();
 7441            let mut suffixes_inserted = Vec::new();
 7442
 7443            fn comment_prefix_range(
 7444                snapshot: &MultiBufferSnapshot,
 7445                row: MultiBufferRow,
 7446                comment_prefix: &str,
 7447                comment_prefix_whitespace: &str,
 7448            ) -> Range<Point> {
 7449                let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
 7450
 7451                let mut line_bytes = snapshot
 7452                    .bytes_in_range(start..snapshot.max_point())
 7453                    .flatten()
 7454                    .copied();
 7455
 7456                // If this line currently begins with the line comment prefix, then record
 7457                // the range containing the prefix.
 7458                if line_bytes
 7459                    .by_ref()
 7460                    .take(comment_prefix.len())
 7461                    .eq(comment_prefix.bytes())
 7462                {
 7463                    // Include any whitespace that matches the comment prefix.
 7464                    let matching_whitespace_len = line_bytes
 7465                        .zip(comment_prefix_whitespace.bytes())
 7466                        .take_while(|(a, b)| a == b)
 7467                        .count() as u32;
 7468                    let end = Point::new(
 7469                        start.row,
 7470                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 7471                    );
 7472                    start..end
 7473                } else {
 7474                    start..start
 7475                }
 7476            }
 7477
 7478            fn comment_suffix_range(
 7479                snapshot: &MultiBufferSnapshot,
 7480                row: MultiBufferRow,
 7481                comment_suffix: &str,
 7482                comment_suffix_has_leading_space: bool,
 7483            ) -> Range<Point> {
 7484                let end = Point::new(row.0, snapshot.line_len(row));
 7485                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 7486
 7487                let mut line_end_bytes = snapshot
 7488                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 7489                    .flatten()
 7490                    .copied();
 7491
 7492                let leading_space_len = if suffix_start_column > 0
 7493                    && line_end_bytes.next() == Some(b' ')
 7494                    && comment_suffix_has_leading_space
 7495                {
 7496                    1
 7497                } else {
 7498                    0
 7499                };
 7500
 7501                // If this line currently begins with the line comment prefix, then record
 7502                // the range containing the prefix.
 7503                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 7504                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 7505                    start..end
 7506                } else {
 7507                    end..end
 7508                }
 7509            }
 7510
 7511            // TODO: Handle selections that cross excerpts
 7512            for selection in &mut selections {
 7513                let start_column = snapshot
 7514                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 7515                    .len;
 7516                let language = if let Some(language) =
 7517                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 7518                {
 7519                    language
 7520                } else {
 7521                    continue;
 7522                };
 7523
 7524                selection_edit_ranges.clear();
 7525
 7526                // If multiple selections contain a given row, avoid processing that
 7527                // row more than once.
 7528                let mut start_row = MultiBufferRow(selection.start.row);
 7529                if last_toggled_row == Some(start_row) {
 7530                    start_row = start_row.next_row();
 7531                }
 7532                let end_row =
 7533                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 7534                        MultiBufferRow(selection.end.row - 1)
 7535                    } else {
 7536                        MultiBufferRow(selection.end.row)
 7537                    };
 7538                last_toggled_row = Some(end_row);
 7539
 7540                if start_row > end_row {
 7541                    continue;
 7542                }
 7543
 7544                // If the language has line comments, toggle those.
 7545                let full_comment_prefixes = language.line_comment_prefixes();
 7546                if !full_comment_prefixes.is_empty() {
 7547                    let first_prefix = full_comment_prefixes
 7548                        .first()
 7549                        .expect("prefixes is non-empty");
 7550                    let prefix_trimmed_lengths = full_comment_prefixes
 7551                        .iter()
 7552                        .map(|p| p.trim_end_matches(' ').len())
 7553                        .collect::<SmallVec<[usize; 4]>>();
 7554
 7555                    let mut all_selection_lines_are_comments = true;
 7556
 7557                    for row in start_row.0..=end_row.0 {
 7558                        let row = MultiBufferRow(row);
 7559                        if start_row < end_row && snapshot.is_line_blank(row) {
 7560                            continue;
 7561                        }
 7562
 7563                        let prefix_range = full_comment_prefixes
 7564                            .iter()
 7565                            .zip(prefix_trimmed_lengths.iter().copied())
 7566                            .map(|(prefix, trimmed_prefix_len)| {
 7567                                comment_prefix_range(
 7568                                    snapshot.deref(),
 7569                                    row,
 7570                                    &prefix[..trimmed_prefix_len],
 7571                                    &prefix[trimmed_prefix_len..],
 7572                                )
 7573                            })
 7574                            .max_by_key(|range| range.end.column - range.start.column)
 7575                            .expect("prefixes is non-empty");
 7576
 7577                        if prefix_range.is_empty() {
 7578                            all_selection_lines_are_comments = false;
 7579                        }
 7580
 7581                        selection_edit_ranges.push(prefix_range);
 7582                    }
 7583
 7584                    if all_selection_lines_are_comments {
 7585                        edits.extend(
 7586                            selection_edit_ranges
 7587                                .iter()
 7588                                .cloned()
 7589                                .map(|range| (range, empty_str.clone())),
 7590                        );
 7591                    } else {
 7592                        let min_column = selection_edit_ranges
 7593                            .iter()
 7594                            .map(|range| range.start.column)
 7595                            .min()
 7596                            .unwrap_or(0);
 7597                        edits.extend(selection_edit_ranges.iter().map(|range| {
 7598                            let position = Point::new(range.start.row, min_column);
 7599                            (position..position, first_prefix.clone())
 7600                        }));
 7601                    }
 7602                } else if let Some((full_comment_prefix, comment_suffix)) =
 7603                    language.block_comment_delimiters()
 7604                {
 7605                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 7606                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 7607                    let prefix_range = comment_prefix_range(
 7608                        snapshot.deref(),
 7609                        start_row,
 7610                        comment_prefix,
 7611                        comment_prefix_whitespace,
 7612                    );
 7613                    let suffix_range = comment_suffix_range(
 7614                        snapshot.deref(),
 7615                        end_row,
 7616                        comment_suffix.trim_start_matches(' '),
 7617                        comment_suffix.starts_with(' '),
 7618                    );
 7619
 7620                    if prefix_range.is_empty() || suffix_range.is_empty() {
 7621                        edits.push((
 7622                            prefix_range.start..prefix_range.start,
 7623                            full_comment_prefix.clone(),
 7624                        ));
 7625                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 7626                        suffixes_inserted.push((end_row, comment_suffix.len()));
 7627                    } else {
 7628                        edits.push((prefix_range, empty_str.clone()));
 7629                        edits.push((suffix_range, empty_str.clone()));
 7630                    }
 7631                } else {
 7632                    continue;
 7633                }
 7634            }
 7635
 7636            drop(snapshot);
 7637            this.buffer.update(cx, |buffer, cx| {
 7638                buffer.edit(edits, None, cx);
 7639            });
 7640
 7641            // Adjust selections so that they end before any comment suffixes that
 7642            // were inserted.
 7643            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 7644            let mut selections = this.selections.all::<Point>(cx);
 7645            let snapshot = this.buffer.read(cx).read(cx);
 7646            for selection in &mut selections {
 7647                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 7648                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 7649                        Ordering::Less => {
 7650                            suffixes_inserted.next();
 7651                            continue;
 7652                        }
 7653                        Ordering::Greater => break,
 7654                        Ordering::Equal => {
 7655                            if selection.end.column == snapshot.line_len(row) {
 7656                                if selection.is_empty() {
 7657                                    selection.start.column -= suffix_len as u32;
 7658                                }
 7659                                selection.end.column -= suffix_len as u32;
 7660                            }
 7661                            break;
 7662                        }
 7663                    }
 7664                }
 7665            }
 7666
 7667            drop(snapshot);
 7668            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 7669
 7670            let selections = this.selections.all::<Point>(cx);
 7671            let selections_on_single_row = selections.windows(2).all(|selections| {
 7672                selections[0].start.row == selections[1].start.row
 7673                    && selections[0].end.row == selections[1].end.row
 7674                    && selections[0].start.row == selections[0].end.row
 7675            });
 7676            let selections_selecting = selections
 7677                .iter()
 7678                .any(|selection| selection.start != selection.end);
 7679            let advance_downwards = action.advance_downwards
 7680                && selections_on_single_row
 7681                && !selections_selecting
 7682                && this.mode != EditorMode::SingleLine;
 7683
 7684            if advance_downwards {
 7685                let snapshot = this.buffer.read(cx).snapshot(cx);
 7686
 7687                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7688                    s.move_cursors_with(|display_snapshot, display_point, _| {
 7689                        let mut point = display_point.to_point(display_snapshot);
 7690                        point.row += 1;
 7691                        point = snapshot.clip_point(point, Bias::Left);
 7692                        let display_point = point.to_display_point(display_snapshot);
 7693                        let goal = SelectionGoal::HorizontalPosition(
 7694                            display_snapshot
 7695                                .x_for_display_point(display_point, &text_layout_details)
 7696                                .into(),
 7697                        );
 7698                        (display_point, goal)
 7699                    })
 7700                });
 7701            }
 7702        });
 7703    }
 7704
 7705    pub fn select_larger_syntax_node(
 7706        &mut self,
 7707        _: &SelectLargerSyntaxNode,
 7708        cx: &mut ViewContext<Self>,
 7709    ) {
 7710        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7711        let buffer = self.buffer.read(cx).snapshot(cx);
 7712        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 7713
 7714        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 7715        let mut selected_larger_node = false;
 7716        let new_selections = old_selections
 7717            .iter()
 7718            .map(|selection| {
 7719                let old_range = selection.start..selection.end;
 7720                let mut new_range = old_range.clone();
 7721                while let Some(containing_range) =
 7722                    buffer.range_for_syntax_ancestor(new_range.clone())
 7723                {
 7724                    new_range = containing_range;
 7725                    if !display_map.intersects_fold(new_range.start)
 7726                        && !display_map.intersects_fold(new_range.end)
 7727                    {
 7728                        break;
 7729                    }
 7730                }
 7731
 7732                selected_larger_node |= new_range != old_range;
 7733                Selection {
 7734                    id: selection.id,
 7735                    start: new_range.start,
 7736                    end: new_range.end,
 7737                    goal: SelectionGoal::None,
 7738                    reversed: selection.reversed,
 7739                }
 7740            })
 7741            .collect::<Vec<_>>();
 7742
 7743        if selected_larger_node {
 7744            stack.push(old_selections);
 7745            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7746                s.select(new_selections);
 7747            });
 7748        }
 7749        self.select_larger_syntax_node_stack = stack;
 7750    }
 7751
 7752    pub fn select_smaller_syntax_node(
 7753        &mut self,
 7754        _: &SelectSmallerSyntaxNode,
 7755        cx: &mut ViewContext<Self>,
 7756    ) {
 7757        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 7758        if let Some(selections) = stack.pop() {
 7759            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7760                s.select(selections.to_vec());
 7761            });
 7762        }
 7763        self.select_larger_syntax_node_stack = stack;
 7764    }
 7765
 7766    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 7767        let project = self.project.clone();
 7768        cx.spawn(|this, mut cx| async move {
 7769            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 7770                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 7771            }) else {
 7772                return;
 7773            };
 7774
 7775            let Some(project) = project else {
 7776                return;
 7777            };
 7778            if project
 7779                .update(&mut cx, |this, _| this.is_remote())
 7780                .unwrap_or(true)
 7781            {
 7782                // Do not display any test indicators in remote projects.
 7783                return;
 7784            }
 7785            let new_rows =
 7786                cx.background_executor()
 7787                    .spawn({
 7788                        let snapshot = display_snapshot.clone();
 7789                        async move {
 7790                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 7791                        }
 7792                    })
 7793                    .await;
 7794            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 7795
 7796            this.update(&mut cx, |this, _| {
 7797                this.clear_tasks();
 7798                for (key, value) in rows {
 7799                    this.insert_tasks(key, value);
 7800                }
 7801            })
 7802            .ok();
 7803        })
 7804    }
 7805    fn fetch_runnable_ranges(
 7806        snapshot: &DisplaySnapshot,
 7807        range: Range<Anchor>,
 7808    ) -> Vec<language::RunnableRange> {
 7809        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 7810    }
 7811
 7812    fn runnable_rows(
 7813        project: Model<Project>,
 7814        snapshot: DisplaySnapshot,
 7815        runnable_ranges: Vec<RunnableRange>,
 7816        mut cx: AsyncWindowContext,
 7817    ) -> Vec<((BufferId, u32), (usize, RunnableTasks))> {
 7818        runnable_ranges
 7819            .into_iter()
 7820            .filter_map(|mut runnable| {
 7821                let (tasks, _) = cx
 7822                    .update(|cx| {
 7823                        Self::resolve_runnable(project.clone(), &mut runnable.runnable, cx)
 7824                    })
 7825                    .ok()?;
 7826                if tasks.is_empty() {
 7827                    return None;
 7828                }
 7829
 7830                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 7831
 7832                let row = snapshot
 7833                    .buffer_snapshot
 7834                    .buffer_line_for_row(MultiBufferRow(point.row))?
 7835                    .1
 7836                    .start
 7837                    .row;
 7838
 7839                Some((
 7840                    (runnable.buffer_id, row),
 7841                    (
 7842                        runnable.run_range.start,
 7843                        RunnableTasks {
 7844                            templates: tasks,
 7845                            column: point.column,
 7846                            extra_variables: runnable.extra_captures,
 7847                        },
 7848                    ),
 7849                ))
 7850            })
 7851            .collect()
 7852    }
 7853
 7854    fn resolve_runnable(
 7855        project: Model<Project>,
 7856        runnable: &mut Runnable,
 7857        cx: &WindowContext<'_>,
 7858    ) -> (Vec<(TaskSourceKind, TaskTemplate)>, Option<WorktreeId>) {
 7859        let (inventory, worktree_id) = project.read_with(cx, |project, cx| {
 7860            let worktree_id = project
 7861                .buffer_for_id(runnable.buffer)
 7862                .and_then(|buffer| buffer.read(cx).file())
 7863                .map(|file| WorktreeId::from_usize(file.worktree_id()));
 7864
 7865            (project.task_inventory().clone(), worktree_id)
 7866        });
 7867
 7868        let inventory = inventory.read(cx);
 7869        let tags = mem::take(&mut runnable.tags);
 7870        let mut tags: Vec<_> = tags
 7871            .into_iter()
 7872            .flat_map(|tag| {
 7873                let tag = tag.0.clone();
 7874                inventory
 7875                    .list_tasks(Some(runnable.language.clone()), worktree_id)
 7876                    .into_iter()
 7877                    .filter(move |(_, template)| {
 7878                        template.tags.iter().any(|source_tag| source_tag == &tag)
 7879                    })
 7880            })
 7881            .sorted_by_key(|(kind, _)| kind.to_owned())
 7882            .collect();
 7883        if let Some((leading_tag_source, _)) = tags.first() {
 7884            // Strongest source wins; if we have worktree tag binding, prefer that to
 7885            // global and language bindings;
 7886            // if we have a global binding, prefer that to language binding.
 7887            let first_mismatch = tags
 7888                .iter()
 7889                .position(|(tag_source, _)| tag_source != leading_tag_source);
 7890            if let Some(index) = first_mismatch {
 7891                tags.truncate(index);
 7892            }
 7893        }
 7894
 7895        (tags, worktree_id)
 7896    }
 7897
 7898    pub fn move_to_enclosing_bracket(
 7899        &mut self,
 7900        _: &MoveToEnclosingBracket,
 7901        cx: &mut ViewContext<Self>,
 7902    ) {
 7903        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7904            s.move_offsets_with(|snapshot, selection| {
 7905                let Some(enclosing_bracket_ranges) =
 7906                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 7907                else {
 7908                    return;
 7909                };
 7910
 7911                let mut best_length = usize::MAX;
 7912                let mut best_inside = false;
 7913                let mut best_in_bracket_range = false;
 7914                let mut best_destination = None;
 7915                for (open, close) in enclosing_bracket_ranges {
 7916                    let close = close.to_inclusive();
 7917                    let length = close.end() - open.start;
 7918                    let inside = selection.start >= open.end && selection.end <= *close.start();
 7919                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 7920                        || close.contains(&selection.head());
 7921
 7922                    // If best is next to a bracket and current isn't, skip
 7923                    if !in_bracket_range && best_in_bracket_range {
 7924                        continue;
 7925                    }
 7926
 7927                    // Prefer smaller lengths unless best is inside and current isn't
 7928                    if length > best_length && (best_inside || !inside) {
 7929                        continue;
 7930                    }
 7931
 7932                    best_length = length;
 7933                    best_inside = inside;
 7934                    best_in_bracket_range = in_bracket_range;
 7935                    best_destination = Some(
 7936                        if close.contains(&selection.start) && close.contains(&selection.end) {
 7937                            if inside {
 7938                                open.end
 7939                            } else {
 7940                                open.start
 7941                            }
 7942                        } else {
 7943                            if inside {
 7944                                *close.start()
 7945                            } else {
 7946                                *close.end()
 7947                            }
 7948                        },
 7949                    );
 7950                }
 7951
 7952                if let Some(destination) = best_destination {
 7953                    selection.collapse_to(destination, SelectionGoal::None);
 7954                }
 7955            })
 7956        });
 7957    }
 7958
 7959    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 7960        self.end_selection(cx);
 7961        self.selection_history.mode = SelectionHistoryMode::Undoing;
 7962        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 7963            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 7964            self.select_next_state = entry.select_next_state;
 7965            self.select_prev_state = entry.select_prev_state;
 7966            self.add_selections_state = entry.add_selections_state;
 7967            self.request_autoscroll(Autoscroll::newest(), cx);
 7968        }
 7969        self.selection_history.mode = SelectionHistoryMode::Normal;
 7970    }
 7971
 7972    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 7973        self.end_selection(cx);
 7974        self.selection_history.mode = SelectionHistoryMode::Redoing;
 7975        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 7976            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 7977            self.select_next_state = entry.select_next_state;
 7978            self.select_prev_state = entry.select_prev_state;
 7979            self.add_selections_state = entry.add_selections_state;
 7980            self.request_autoscroll(Autoscroll::newest(), cx);
 7981        }
 7982        self.selection_history.mode = SelectionHistoryMode::Normal;
 7983    }
 7984
 7985    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 7986        let selections = self.selections.disjoint_anchors();
 7987
 7988        let lines = if action.lines == 0 { 3 } else { action.lines };
 7989
 7990        self.buffer.update(cx, |buffer, cx| {
 7991            buffer.expand_excerpts(
 7992                selections
 7993                    .into_iter()
 7994                    .map(|selection| selection.head().excerpt_id)
 7995                    .dedup(),
 7996                lines,
 7997                cx,
 7998            )
 7999        })
 8000    }
 8001
 8002    pub fn expand_excerpt(&mut self, excerpt: ExcerptId, cx: &mut ViewContext<Self>) {
 8003        self.buffer
 8004            .update(cx, |buffer, cx| buffer.expand_excerpts([excerpt], 3, cx))
 8005    }
 8006
 8007    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 8008        self.go_to_diagnostic_impl(Direction::Next, cx)
 8009    }
 8010
 8011    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 8012        self.go_to_diagnostic_impl(Direction::Prev, cx)
 8013    }
 8014
 8015    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 8016        let buffer = self.buffer.read(cx).snapshot(cx);
 8017        let selection = self.selections.newest::<usize>(cx);
 8018
 8019        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 8020        if direction == Direction::Next {
 8021            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 8022                let (group_id, jump_to) = popover.activation_info();
 8023                if self.activate_diagnostics(group_id, cx) {
 8024                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8025                        let mut new_selection = s.newest_anchor().clone();
 8026                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 8027                        s.select_anchors(vec![new_selection.clone()]);
 8028                    });
 8029                }
 8030                return;
 8031            }
 8032        }
 8033
 8034        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 8035            active_diagnostics
 8036                .primary_range
 8037                .to_offset(&buffer)
 8038                .to_inclusive()
 8039        });
 8040        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 8041            if active_primary_range.contains(&selection.head()) {
 8042                *active_primary_range.start()
 8043            } else {
 8044                selection.head()
 8045            }
 8046        } else {
 8047            selection.head()
 8048        };
 8049        let snapshot = self.snapshot(cx);
 8050        loop {
 8051            let diagnostics = if direction == Direction::Prev {
 8052                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 8053            } else {
 8054                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 8055            }
 8056            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 8057            let group = diagnostics
 8058                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 8059                // be sorted in a stable way
 8060                // skip until we are at current active diagnostic, if it exists
 8061                .skip_while(|entry| {
 8062                    (match direction {
 8063                        Direction::Prev => entry.range.start >= search_start,
 8064                        Direction::Next => entry.range.start <= search_start,
 8065                    }) && self
 8066                        .active_diagnostics
 8067                        .as_ref()
 8068                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 8069                })
 8070                .find_map(|entry| {
 8071                    if entry.diagnostic.is_primary
 8072                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 8073                        && !entry.range.is_empty()
 8074                        // if we match with the active diagnostic, skip it
 8075                        && Some(entry.diagnostic.group_id)
 8076                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 8077                    {
 8078                        Some((entry.range, entry.diagnostic.group_id))
 8079                    } else {
 8080                        None
 8081                    }
 8082                });
 8083
 8084            if let Some((primary_range, group_id)) = group {
 8085                if self.activate_diagnostics(group_id, cx) {
 8086                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8087                        s.select(vec![Selection {
 8088                            id: selection.id,
 8089                            start: primary_range.start,
 8090                            end: primary_range.start,
 8091                            reversed: false,
 8092                            goal: SelectionGoal::None,
 8093                        }]);
 8094                    });
 8095                }
 8096                break;
 8097            } else {
 8098                // Cycle around to the start of the buffer, potentially moving back to the start of
 8099                // the currently active diagnostic.
 8100                active_primary_range.take();
 8101                if direction == Direction::Prev {
 8102                    if search_start == buffer.len() {
 8103                        break;
 8104                    } else {
 8105                        search_start = buffer.len();
 8106                    }
 8107                } else if search_start == 0 {
 8108                    break;
 8109                } else {
 8110                    search_start = 0;
 8111                }
 8112            }
 8113        }
 8114    }
 8115
 8116    fn go_to_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 8117        let snapshot = self
 8118            .display_map
 8119            .update(cx, |display_map, cx| display_map.snapshot(cx));
 8120        let selection = self.selections.newest::<Point>(cx);
 8121
 8122        if !self.seek_in_direction(
 8123            &snapshot,
 8124            selection.head(),
 8125            false,
 8126            snapshot.buffer_snapshot.git_diff_hunks_in_range(
 8127                MultiBufferRow(selection.head().row + 1)..MultiBufferRow::MAX,
 8128            ),
 8129            cx,
 8130        ) {
 8131            let wrapped_point = Point::zero();
 8132            self.seek_in_direction(
 8133                &snapshot,
 8134                wrapped_point,
 8135                true,
 8136                snapshot.buffer_snapshot.git_diff_hunks_in_range(
 8137                    MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
 8138                ),
 8139                cx,
 8140            );
 8141        }
 8142    }
 8143
 8144    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 8145        let snapshot = self
 8146            .display_map
 8147            .update(cx, |display_map, cx| display_map.snapshot(cx));
 8148        let selection = self.selections.newest::<Point>(cx);
 8149
 8150        if !self.seek_in_direction(
 8151            &snapshot,
 8152            selection.head(),
 8153            false,
 8154            snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
 8155                MultiBufferRow(0)..MultiBufferRow(selection.head().row),
 8156            ),
 8157            cx,
 8158        ) {
 8159            let wrapped_point = snapshot.buffer_snapshot.max_point();
 8160            self.seek_in_direction(
 8161                &snapshot,
 8162                wrapped_point,
 8163                true,
 8164                snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
 8165                    MultiBufferRow(0)..MultiBufferRow(wrapped_point.row),
 8166                ),
 8167                cx,
 8168            );
 8169        }
 8170    }
 8171
 8172    fn seek_in_direction(
 8173        &mut self,
 8174        snapshot: &DisplaySnapshot,
 8175        initial_point: Point,
 8176        is_wrapped: bool,
 8177        hunks: impl Iterator<Item = DiffHunk<MultiBufferRow>>,
 8178        cx: &mut ViewContext<Editor>,
 8179    ) -> bool {
 8180        let display_point = initial_point.to_display_point(snapshot);
 8181        let mut hunks = hunks
 8182            .map(|hunk| diff_hunk_to_display(&hunk, &snapshot))
 8183            .filter(|hunk| {
 8184                if is_wrapped {
 8185                    true
 8186                } else {
 8187                    !hunk.contains_display_row(display_point.row())
 8188                }
 8189            })
 8190            .dedup();
 8191
 8192        if let Some(hunk) = hunks.next() {
 8193            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8194                let row = hunk.start_display_row();
 8195                let point = DisplayPoint::new(row, 0);
 8196                s.select_display_ranges([point..point]);
 8197            });
 8198
 8199            true
 8200        } else {
 8201            false
 8202        }
 8203    }
 8204
 8205    pub fn go_to_definition(
 8206        &mut self,
 8207        _: &GoToDefinition,
 8208        cx: &mut ViewContext<Self>,
 8209    ) -> Task<Result<bool>> {
 8210        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx)
 8211    }
 8212
 8213    pub fn go_to_implementation(
 8214        &mut self,
 8215        _: &GoToImplementation,
 8216        cx: &mut ViewContext<Self>,
 8217    ) -> Task<Result<bool>> {
 8218        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 8219    }
 8220
 8221    pub fn go_to_implementation_split(
 8222        &mut self,
 8223        _: &GoToImplementationSplit,
 8224        cx: &mut ViewContext<Self>,
 8225    ) -> Task<Result<bool>> {
 8226        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 8227    }
 8228
 8229    pub fn go_to_type_definition(
 8230        &mut self,
 8231        _: &GoToTypeDefinition,
 8232        cx: &mut ViewContext<Self>,
 8233    ) -> Task<Result<bool>> {
 8234        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 8235    }
 8236
 8237    pub fn go_to_definition_split(
 8238        &mut self,
 8239        _: &GoToDefinitionSplit,
 8240        cx: &mut ViewContext<Self>,
 8241    ) -> Task<Result<bool>> {
 8242        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 8243    }
 8244
 8245    pub fn go_to_type_definition_split(
 8246        &mut self,
 8247        _: &GoToTypeDefinitionSplit,
 8248        cx: &mut ViewContext<Self>,
 8249    ) -> Task<Result<bool>> {
 8250        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 8251    }
 8252
 8253    fn go_to_definition_of_kind(
 8254        &mut self,
 8255        kind: GotoDefinitionKind,
 8256        split: bool,
 8257        cx: &mut ViewContext<Self>,
 8258    ) -> Task<Result<bool>> {
 8259        let Some(workspace) = self.workspace() else {
 8260            return Task::ready(Ok(false));
 8261        };
 8262        let buffer = self.buffer.read(cx);
 8263        let head = self.selections.newest::<usize>(cx).head();
 8264        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 8265            text_anchor
 8266        } else {
 8267            return Task::ready(Ok(false));
 8268        };
 8269
 8270        let project = workspace.read(cx).project().clone();
 8271        let definitions = project.update(cx, |project, cx| match kind {
 8272            GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
 8273            GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
 8274            GotoDefinitionKind::Implementation => project.implementation(&buffer, head, cx),
 8275        });
 8276
 8277        cx.spawn(|editor, mut cx| async move {
 8278            let definitions = definitions.await?;
 8279            let navigated = editor
 8280                .update(&mut cx, |editor, cx| {
 8281                    editor.navigate_to_hover_links(
 8282                        Some(kind),
 8283                        definitions
 8284                            .into_iter()
 8285                            .filter(|location| {
 8286                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 8287                            })
 8288                            .map(HoverLink::Text)
 8289                            .collect::<Vec<_>>(),
 8290                        split,
 8291                        cx,
 8292                    )
 8293                })?
 8294                .await?;
 8295            anyhow::Ok(navigated)
 8296        })
 8297    }
 8298
 8299    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 8300        let position = self.selections.newest_anchor().head();
 8301        let Some((buffer, buffer_position)) =
 8302            self.buffer.read(cx).text_anchor_for_position(position, cx)
 8303        else {
 8304            return;
 8305        };
 8306
 8307        cx.spawn(|editor, mut cx| async move {
 8308            if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
 8309                editor.update(&mut cx, |_, cx| {
 8310                    cx.open_url(&url);
 8311                })
 8312            } else {
 8313                Ok(())
 8314            }
 8315        })
 8316        .detach();
 8317    }
 8318
 8319    pub(crate) fn navigate_to_hover_links(
 8320        &mut self,
 8321        kind: Option<GotoDefinitionKind>,
 8322        mut definitions: Vec<HoverLink>,
 8323        split: bool,
 8324        cx: &mut ViewContext<Editor>,
 8325    ) -> Task<Result<bool>> {
 8326        // If there is one definition, just open it directly
 8327        if definitions.len() == 1 {
 8328            let definition = definitions.pop().unwrap();
 8329            let target_task = match definition {
 8330                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 8331                HoverLink::InlayHint(lsp_location, server_id) => {
 8332                    self.compute_target_location(lsp_location, server_id, cx)
 8333                }
 8334                HoverLink::Url(url) => {
 8335                    cx.open_url(&url);
 8336                    Task::ready(Ok(None))
 8337                }
 8338            };
 8339            cx.spawn(|editor, mut cx| async move {
 8340                let target = target_task.await.context("target resolution task")?;
 8341                if let Some(target) = target {
 8342                    editor.update(&mut cx, |editor, cx| {
 8343                        let Some(workspace) = editor.workspace() else {
 8344                            return false;
 8345                        };
 8346                        let pane = workspace.read(cx).active_pane().clone();
 8347
 8348                        let range = target.range.to_offset(target.buffer.read(cx));
 8349                        let range = editor.range_for_match(&range);
 8350                        if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 8351                            editor.change_selections(Some(Autoscroll::focused()), cx, |s| {
 8352                                s.select_ranges([range]);
 8353                            });
 8354                        } else {
 8355                            cx.window_context().defer(move |cx| {
 8356                                let target_editor: View<Self> =
 8357                                    workspace.update(cx, |workspace, cx| {
 8358                                        let pane = if split {
 8359                                            workspace.adjacent_pane(cx)
 8360                                        } else {
 8361                                            workspace.active_pane().clone()
 8362                                        };
 8363
 8364                                        workspace.open_project_item(pane, target.buffer.clone(), cx)
 8365                                    });
 8366                                target_editor.update(cx, |target_editor, cx| {
 8367                                    // When selecting a definition in a different buffer, disable the nav history
 8368                                    // to avoid creating a history entry at the previous cursor location.
 8369                                    pane.update(cx, |pane, _| pane.disable_history());
 8370                                    target_editor.change_selections(
 8371                                        Some(Autoscroll::focused()),
 8372                                        cx,
 8373                                        |s| {
 8374                                            s.select_ranges([range]);
 8375                                        },
 8376                                    );
 8377                                    pane.update(cx, |pane, _| pane.enable_history());
 8378                                });
 8379                            });
 8380                        }
 8381                        true
 8382                    })
 8383                } else {
 8384                    Ok(false)
 8385                }
 8386            })
 8387        } else if !definitions.is_empty() {
 8388            let replica_id = self.replica_id(cx);
 8389            cx.spawn(|editor, mut cx| async move {
 8390                let (title, location_tasks, workspace) = editor
 8391                    .update(&mut cx, |editor, cx| {
 8392                        let tab_kind = match kind {
 8393                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 8394                            _ => "Definitions",
 8395                        };
 8396                        let title = definitions
 8397                            .iter()
 8398                            .find_map(|definition| match definition {
 8399                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 8400                                    let buffer = origin.buffer.read(cx);
 8401                                    format!(
 8402                                        "{} for {}",
 8403                                        tab_kind,
 8404                                        buffer
 8405                                            .text_for_range(origin.range.clone())
 8406                                            .collect::<String>()
 8407                                    )
 8408                                }),
 8409                                HoverLink::InlayHint(_, _) => None,
 8410                                HoverLink::Url(_) => None,
 8411                            })
 8412                            .unwrap_or(tab_kind.to_string());
 8413                        let location_tasks = definitions
 8414                            .into_iter()
 8415                            .map(|definition| match definition {
 8416                                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 8417                                HoverLink::InlayHint(lsp_location, server_id) => {
 8418                                    editor.compute_target_location(lsp_location, server_id, cx)
 8419                                }
 8420                                HoverLink::Url(_) => Task::ready(Ok(None)),
 8421                            })
 8422                            .collect::<Vec<_>>();
 8423                        (title, location_tasks, editor.workspace().clone())
 8424                    })
 8425                    .context("location tasks preparation")?;
 8426
 8427                let locations = futures::future::join_all(location_tasks)
 8428                    .await
 8429                    .into_iter()
 8430                    .filter_map(|location| location.transpose())
 8431                    .collect::<Result<_>>()
 8432                    .context("location tasks")?;
 8433
 8434                let Some(workspace) = workspace else {
 8435                    return Ok(false);
 8436                };
 8437                let opened = workspace
 8438                    .update(&mut cx, |workspace, cx| {
 8439                        Self::open_locations_in_multibuffer(
 8440                            workspace, locations, replica_id, title, split, cx,
 8441                        )
 8442                    })
 8443                    .ok();
 8444
 8445                anyhow::Ok(opened.is_some())
 8446            })
 8447        } else {
 8448            Task::ready(Ok(false))
 8449        }
 8450    }
 8451
 8452    fn compute_target_location(
 8453        &self,
 8454        lsp_location: lsp::Location,
 8455        server_id: LanguageServerId,
 8456        cx: &mut ViewContext<Editor>,
 8457    ) -> Task<anyhow::Result<Option<Location>>> {
 8458        let Some(project) = self.project.clone() else {
 8459            return Task::Ready(Some(Ok(None)));
 8460        };
 8461
 8462        cx.spawn(move |editor, mut cx| async move {
 8463            let location_task = editor.update(&mut cx, |editor, cx| {
 8464                project.update(cx, |project, cx| {
 8465                    let language_server_name =
 8466                        editor.buffer.read(cx).as_singleton().and_then(|buffer| {
 8467                            project
 8468                                .language_server_for_buffer(buffer.read(cx), server_id, cx)
 8469                                .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
 8470                        });
 8471                    language_server_name.map(|language_server_name| {
 8472                        project.open_local_buffer_via_lsp(
 8473                            lsp_location.uri.clone(),
 8474                            server_id,
 8475                            language_server_name,
 8476                            cx,
 8477                        )
 8478                    })
 8479                })
 8480            })?;
 8481            let location = match location_task {
 8482                Some(task) => Some({
 8483                    let target_buffer_handle = task.await.context("open local buffer")?;
 8484                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
 8485                        let target_start = target_buffer
 8486                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
 8487                        let target_end = target_buffer
 8488                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
 8489                        target_buffer.anchor_after(target_start)
 8490                            ..target_buffer.anchor_before(target_end)
 8491                    })?;
 8492                    Location {
 8493                        buffer: target_buffer_handle,
 8494                        range,
 8495                    }
 8496                }),
 8497                None => None,
 8498            };
 8499            Ok(location)
 8500        })
 8501    }
 8502
 8503    pub fn find_all_references(
 8504        &mut self,
 8505        _: &FindAllReferences,
 8506        cx: &mut ViewContext<Self>,
 8507    ) -> Option<Task<Result<()>>> {
 8508        let multi_buffer = self.buffer.read(cx);
 8509        let selection = self.selections.newest::<usize>(cx);
 8510        let head = selection.head();
 8511
 8512        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 8513        let head_anchor = multi_buffer_snapshot.anchor_at(
 8514            head,
 8515            if head < selection.tail() {
 8516                Bias::Right
 8517            } else {
 8518                Bias::Left
 8519            },
 8520        );
 8521
 8522        match self
 8523            .find_all_references_task_sources
 8524            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
 8525        {
 8526            Ok(_) => {
 8527                log::info!(
 8528                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
 8529                );
 8530                return None;
 8531            }
 8532            Err(i) => {
 8533                self.find_all_references_task_sources.insert(i, head_anchor);
 8534            }
 8535        }
 8536
 8537        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
 8538        let replica_id = self.replica_id(cx);
 8539        let workspace = self.workspace()?;
 8540        let project = workspace.read(cx).project().clone();
 8541        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
 8542        Some(cx.spawn(|editor, mut cx| async move {
 8543            let _cleanup = defer({
 8544                let mut cx = cx.clone();
 8545                move || {
 8546                    let _ = editor.update(&mut cx, |editor, _| {
 8547                        if let Ok(i) =
 8548                            editor
 8549                                .find_all_references_task_sources
 8550                                .binary_search_by(|anchor| {
 8551                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
 8552                                })
 8553                        {
 8554                            editor.find_all_references_task_sources.remove(i);
 8555                        }
 8556                    });
 8557                }
 8558            });
 8559
 8560            let locations = references.await?;
 8561            if locations.is_empty() {
 8562                return anyhow::Ok(());
 8563            }
 8564
 8565            workspace.update(&mut cx, |workspace, cx| {
 8566                let title = locations
 8567                    .first()
 8568                    .as_ref()
 8569                    .map(|location| {
 8570                        let buffer = location.buffer.read(cx);
 8571                        format!(
 8572                            "References to `{}`",
 8573                            buffer
 8574                                .text_for_range(location.range.clone())
 8575                                .collect::<String>()
 8576                        )
 8577                    })
 8578                    .unwrap();
 8579                Self::open_locations_in_multibuffer(
 8580                    workspace, locations, replica_id, title, false, cx,
 8581                );
 8582            })
 8583        }))
 8584    }
 8585
 8586    /// Opens a multibuffer with the given project locations in it
 8587    pub fn open_locations_in_multibuffer(
 8588        workspace: &mut Workspace,
 8589        mut locations: Vec<Location>,
 8590        replica_id: ReplicaId,
 8591        title: String,
 8592        split: bool,
 8593        cx: &mut ViewContext<Workspace>,
 8594    ) {
 8595        // If there are multiple definitions, open them in a multibuffer
 8596        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
 8597        let mut locations = locations.into_iter().peekable();
 8598        let mut ranges_to_highlight = Vec::new();
 8599        let capability = workspace.project().read(cx).capability();
 8600
 8601        let excerpt_buffer = cx.new_model(|cx| {
 8602            let mut multibuffer = MultiBuffer::new(replica_id, capability);
 8603            while let Some(location) = locations.next() {
 8604                let buffer = location.buffer.read(cx);
 8605                let mut ranges_for_buffer = Vec::new();
 8606                let range = location.range.to_offset(buffer);
 8607                ranges_for_buffer.push(range.clone());
 8608
 8609                while let Some(next_location) = locations.peek() {
 8610                    if next_location.buffer == location.buffer {
 8611                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
 8612                        locations.next();
 8613                    } else {
 8614                        break;
 8615                    }
 8616                }
 8617
 8618                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
 8619                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
 8620                    location.buffer.clone(),
 8621                    ranges_for_buffer,
 8622                    DEFAULT_MULTIBUFFER_CONTEXT,
 8623                    cx,
 8624                ))
 8625            }
 8626
 8627            multibuffer.with_title(title)
 8628        });
 8629
 8630        let editor = cx.new_view(|cx| {
 8631            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), cx)
 8632        });
 8633        editor.update(cx, |editor, cx| {
 8634            editor.highlight_background::<Self>(
 8635                &ranges_to_highlight,
 8636                |theme| theme.editor_highlighted_line_background,
 8637                cx,
 8638            );
 8639        });
 8640
 8641        let item = Box::new(editor);
 8642        let item_id = item.item_id();
 8643
 8644        if split {
 8645            workspace.split_item(SplitDirection::Right, item.clone(), cx);
 8646        } else {
 8647            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
 8648                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
 8649                    pane.close_current_preview_item(cx)
 8650                } else {
 8651                    None
 8652                }
 8653            });
 8654            workspace.add_item_to_active_pane(item.clone(), destination_index, cx);
 8655        }
 8656        workspace.active_pane().update(cx, |pane, cx| {
 8657            pane.set_preview_item_id(Some(item_id), cx);
 8658        });
 8659    }
 8660
 8661    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 8662        use language::ToOffset as _;
 8663
 8664        let project = self.project.clone()?;
 8665        let selection = self.selections.newest_anchor().clone();
 8666        let (cursor_buffer, cursor_buffer_position) = self
 8667            .buffer
 8668            .read(cx)
 8669            .text_anchor_for_position(selection.head(), cx)?;
 8670        let (tail_buffer, cursor_buffer_position_end) = self
 8671            .buffer
 8672            .read(cx)
 8673            .text_anchor_for_position(selection.tail(), cx)?;
 8674        if tail_buffer != cursor_buffer {
 8675            return None;
 8676        }
 8677
 8678        let snapshot = cursor_buffer.read(cx).snapshot();
 8679        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
 8680        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
 8681        let prepare_rename = project.update(cx, |project, cx| {
 8682            project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
 8683        });
 8684        drop(snapshot);
 8685
 8686        Some(cx.spawn(|this, mut cx| async move {
 8687            let rename_range = if let Some(range) = prepare_rename.await? {
 8688                Some(range)
 8689            } else {
 8690                this.update(&mut cx, |this, cx| {
 8691                    let buffer = this.buffer.read(cx).snapshot(cx);
 8692                    let mut buffer_highlights = this
 8693                        .document_highlights_for_position(selection.head(), &buffer)
 8694                        .filter(|highlight| {
 8695                            highlight.start.excerpt_id == selection.head().excerpt_id
 8696                                && highlight.end.excerpt_id == selection.head().excerpt_id
 8697                        });
 8698                    buffer_highlights
 8699                        .next()
 8700                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
 8701                })?
 8702            };
 8703            if let Some(rename_range) = rename_range {
 8704                this.update(&mut cx, |this, cx| {
 8705                    let snapshot = cursor_buffer.read(cx).snapshot();
 8706                    let rename_buffer_range = rename_range.to_offset(&snapshot);
 8707                    let cursor_offset_in_rename_range =
 8708                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
 8709                    let cursor_offset_in_rename_range_end =
 8710                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
 8711
 8712                    this.take_rename(false, cx);
 8713                    let buffer = this.buffer.read(cx).read(cx);
 8714                    let cursor_offset = selection.head().to_offset(&buffer);
 8715                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
 8716                    let rename_end = rename_start + rename_buffer_range.len();
 8717                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
 8718                    let mut old_highlight_id = None;
 8719                    let old_name: Arc<str> = buffer
 8720                        .chunks(rename_start..rename_end, true)
 8721                        .map(|chunk| {
 8722                            if old_highlight_id.is_none() {
 8723                                old_highlight_id = chunk.syntax_highlight_id;
 8724                            }
 8725                            chunk.text
 8726                        })
 8727                        .collect::<String>()
 8728                        .into();
 8729
 8730                    drop(buffer);
 8731
 8732                    // Position the selection in the rename editor so that it matches the current selection.
 8733                    this.show_local_selections = false;
 8734                    let rename_editor = cx.new_view(|cx| {
 8735                        let mut editor = Editor::single_line(cx);
 8736                        editor.buffer.update(cx, |buffer, cx| {
 8737                            buffer.edit([(0..0, old_name.clone())], None, cx)
 8738                        });
 8739                        let rename_selection_range = match cursor_offset_in_rename_range
 8740                            .cmp(&cursor_offset_in_rename_range_end)
 8741                        {
 8742                            Ordering::Equal => {
 8743                                editor.select_all(&SelectAll, cx);
 8744                                return editor;
 8745                            }
 8746                            Ordering::Less => {
 8747                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
 8748                            }
 8749                            Ordering::Greater => {
 8750                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
 8751                            }
 8752                        };
 8753                        if rename_selection_range.end > old_name.len() {
 8754                            editor.select_all(&SelectAll, cx);
 8755                        } else {
 8756                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8757                                s.select_ranges([rename_selection_range]);
 8758                            });
 8759                        }
 8760                        editor
 8761                    });
 8762
 8763                    let write_highlights =
 8764                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
 8765                    let read_highlights =
 8766                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
 8767                    let ranges = write_highlights
 8768                        .iter()
 8769                        .flat_map(|(_, ranges)| ranges.iter())
 8770                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
 8771                        .cloned()
 8772                        .collect();
 8773
 8774                    this.highlight_text::<Rename>(
 8775                        ranges,
 8776                        HighlightStyle {
 8777                            fade_out: Some(0.6),
 8778                            ..Default::default()
 8779                        },
 8780                        cx,
 8781                    );
 8782                    let rename_focus_handle = rename_editor.focus_handle(cx);
 8783                    cx.focus(&rename_focus_handle);
 8784                    let block_id = this.insert_blocks(
 8785                        [BlockProperties {
 8786                            style: BlockStyle::Flex,
 8787                            position: range.start,
 8788                            height: 1,
 8789                            render: Box::new({
 8790                                let rename_editor = rename_editor.clone();
 8791                                move |cx: &mut BlockContext| {
 8792                                    let mut text_style = cx.editor_style.text.clone();
 8793                                    if let Some(highlight_style) = old_highlight_id
 8794                                        .and_then(|h| h.style(&cx.editor_style.syntax))
 8795                                    {
 8796                                        text_style = text_style.highlight(highlight_style);
 8797                                    }
 8798                                    div()
 8799                                        .pl(cx.anchor_x)
 8800                                        .child(EditorElement::new(
 8801                                            &rename_editor,
 8802                                            EditorStyle {
 8803                                                background: cx.theme().system().transparent,
 8804                                                local_player: cx.editor_style.local_player,
 8805                                                text: text_style,
 8806                                                scrollbar_width: cx.editor_style.scrollbar_width,
 8807                                                syntax: cx.editor_style.syntax.clone(),
 8808                                                status: cx.editor_style.status.clone(),
 8809                                                inlay_hints_style: HighlightStyle {
 8810                                                    color: Some(cx.theme().status().hint),
 8811                                                    font_weight: Some(FontWeight::BOLD),
 8812                                                    ..HighlightStyle::default()
 8813                                                },
 8814                                                suggestions_style: HighlightStyle {
 8815                                                    color: Some(cx.theme().status().predictive),
 8816                                                    ..HighlightStyle::default()
 8817                                                },
 8818                                            },
 8819                                        ))
 8820                                        .into_any_element()
 8821                                }
 8822                            }),
 8823                            disposition: BlockDisposition::Below,
 8824                        }],
 8825                        Some(Autoscroll::fit()),
 8826                        cx,
 8827                    )[0];
 8828                    this.pending_rename = Some(RenameState {
 8829                        range,
 8830                        old_name,
 8831                        editor: rename_editor,
 8832                        block_id,
 8833                    });
 8834                })?;
 8835            }
 8836
 8837            Ok(())
 8838        }))
 8839    }
 8840
 8841    pub fn confirm_rename(
 8842        &mut self,
 8843        _: &ConfirmRename,
 8844        cx: &mut ViewContext<Self>,
 8845    ) -> Option<Task<Result<()>>> {
 8846        let rename = self.take_rename(false, cx)?;
 8847        let workspace = self.workspace()?;
 8848        let (start_buffer, start) = self
 8849            .buffer
 8850            .read(cx)
 8851            .text_anchor_for_position(rename.range.start, cx)?;
 8852        let (end_buffer, end) = self
 8853            .buffer
 8854            .read(cx)
 8855            .text_anchor_for_position(rename.range.end, cx)?;
 8856        if start_buffer != end_buffer {
 8857            return None;
 8858        }
 8859
 8860        let buffer = start_buffer;
 8861        let range = start..end;
 8862        let old_name = rename.old_name;
 8863        let new_name = rename.editor.read(cx).text(cx);
 8864
 8865        let rename = workspace
 8866            .read(cx)
 8867            .project()
 8868            .clone()
 8869            .update(cx, |project, cx| {
 8870                project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
 8871            });
 8872        let workspace = workspace.downgrade();
 8873
 8874        Some(cx.spawn(|editor, mut cx| async move {
 8875            let project_transaction = rename.await?;
 8876            Self::open_project_transaction(
 8877                &editor,
 8878                workspace,
 8879                project_transaction,
 8880                format!("Rename: {}{}", old_name, new_name),
 8881                cx.clone(),
 8882            )
 8883            .await?;
 8884
 8885            editor.update(&mut cx, |editor, cx| {
 8886                editor.refresh_document_highlights(cx);
 8887            })?;
 8888            Ok(())
 8889        }))
 8890    }
 8891
 8892    fn take_rename(
 8893        &mut self,
 8894        moving_cursor: bool,
 8895        cx: &mut ViewContext<Self>,
 8896    ) -> Option<RenameState> {
 8897        let rename = self.pending_rename.take()?;
 8898        if rename.editor.focus_handle(cx).is_focused(cx) {
 8899            cx.focus(&self.focus_handle);
 8900        }
 8901
 8902        self.remove_blocks(
 8903            [rename.block_id].into_iter().collect(),
 8904            Some(Autoscroll::fit()),
 8905            cx,
 8906        );
 8907        self.clear_highlights::<Rename>(cx);
 8908        self.show_local_selections = true;
 8909
 8910        if moving_cursor {
 8911            let rename_editor = rename.editor.read(cx);
 8912            let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
 8913
 8914            // Update the selection to match the position of the selection inside
 8915            // the rename editor.
 8916            let snapshot = self.buffer.read(cx).read(cx);
 8917            let rename_range = rename.range.to_offset(&snapshot);
 8918            let cursor_in_editor = snapshot
 8919                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
 8920                .min(rename_range.end);
 8921            drop(snapshot);
 8922
 8923            self.change_selections(None, cx, |s| {
 8924                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
 8925            });
 8926        } else {
 8927            self.refresh_document_highlights(cx);
 8928        }
 8929
 8930        Some(rename)
 8931    }
 8932
 8933    pub fn pending_rename(&self) -> Option<&RenameState> {
 8934        self.pending_rename.as_ref()
 8935    }
 8936
 8937    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 8938        let project = match &self.project {
 8939            Some(project) => project.clone(),
 8940            None => return None,
 8941        };
 8942
 8943        Some(self.perform_format(project, FormatTrigger::Manual, cx))
 8944    }
 8945
 8946    fn perform_format(
 8947        &mut self,
 8948        project: Model<Project>,
 8949        trigger: FormatTrigger,
 8950        cx: &mut ViewContext<Self>,
 8951    ) -> Task<Result<()>> {
 8952        let buffer = self.buffer().clone();
 8953        let mut buffers = buffer.read(cx).all_buffers();
 8954        if trigger == FormatTrigger::Save {
 8955            buffers.retain(|buffer| buffer.read(cx).is_dirty());
 8956        }
 8957
 8958        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
 8959        let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
 8960
 8961        cx.spawn(|_, mut cx| async move {
 8962            let transaction = futures::select_biased! {
 8963                () = timeout => {
 8964                    log::warn!("timed out waiting for formatting");
 8965                    None
 8966                }
 8967                transaction = format.log_err().fuse() => transaction,
 8968            };
 8969
 8970            buffer
 8971                .update(&mut cx, |buffer, cx| {
 8972                    if let Some(transaction) = transaction {
 8973                        if !buffer.is_singleton() {
 8974                            buffer.push_transaction(&transaction.0, cx);
 8975                        }
 8976                    }
 8977
 8978                    cx.notify();
 8979                })
 8980                .ok();
 8981
 8982            Ok(())
 8983        })
 8984    }
 8985
 8986    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
 8987        if let Some(project) = self.project.clone() {
 8988            self.buffer.update(cx, |multi_buffer, cx| {
 8989                project.update(cx, |project, cx| {
 8990                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
 8991                });
 8992            })
 8993        }
 8994    }
 8995
 8996    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
 8997        cx.show_character_palette();
 8998    }
 8999
 9000    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
 9001        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
 9002            let buffer = self.buffer.read(cx).snapshot(cx);
 9003            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
 9004            let is_valid = buffer
 9005                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
 9006                .any(|entry| {
 9007                    entry.diagnostic.is_primary
 9008                        && !entry.range.is_empty()
 9009                        && entry.range.start == primary_range_start
 9010                        && entry.diagnostic.message == active_diagnostics.primary_message
 9011                });
 9012
 9013            if is_valid != active_diagnostics.is_valid {
 9014                active_diagnostics.is_valid = is_valid;
 9015                let mut new_styles = HashMap::default();
 9016                for (block_id, diagnostic) in &active_diagnostics.blocks {
 9017                    new_styles.insert(
 9018                        *block_id,
 9019                        diagnostic_block_renderer(diagnostic.clone(), is_valid),
 9020                    );
 9021                }
 9022                self.display_map
 9023                    .update(cx, |display_map, _| display_map.replace_blocks(new_styles));
 9024            }
 9025        }
 9026    }
 9027
 9028    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
 9029        self.dismiss_diagnostics(cx);
 9030        let snapshot = self.snapshot(cx);
 9031        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
 9032            let buffer = self.buffer.read(cx).snapshot(cx);
 9033
 9034            let mut primary_range = None;
 9035            let mut primary_message = None;
 9036            let mut group_end = Point::zero();
 9037            let diagnostic_group = buffer
 9038                .diagnostic_group::<MultiBufferPoint>(group_id)
 9039                .filter_map(|entry| {
 9040                    if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
 9041                        && (entry.range.start.row == entry.range.end.row
 9042                            || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
 9043                    {
 9044                        return None;
 9045                    }
 9046                    if entry.range.end > group_end {
 9047                        group_end = entry.range.end;
 9048                    }
 9049                    if entry.diagnostic.is_primary {
 9050                        primary_range = Some(entry.range.clone());
 9051                        primary_message = Some(entry.diagnostic.message.clone());
 9052                    }
 9053                    Some(entry)
 9054                })
 9055                .collect::<Vec<_>>();
 9056            let primary_range = primary_range?;
 9057            let primary_message = primary_message?;
 9058            let primary_range =
 9059                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
 9060
 9061            let blocks = display_map
 9062                .insert_blocks(
 9063                    diagnostic_group.iter().map(|entry| {
 9064                        let diagnostic = entry.diagnostic.clone();
 9065                        let message_height = diagnostic.message.matches('\n').count() as u8 + 1;
 9066                        BlockProperties {
 9067                            style: BlockStyle::Fixed,
 9068                            position: buffer.anchor_after(entry.range.start),
 9069                            height: message_height,
 9070                            render: diagnostic_block_renderer(diagnostic, true),
 9071                            disposition: BlockDisposition::Below,
 9072                        }
 9073                    }),
 9074                    cx,
 9075                )
 9076                .into_iter()
 9077                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
 9078                .collect();
 9079
 9080            Some(ActiveDiagnosticGroup {
 9081                primary_range,
 9082                primary_message,
 9083                group_id,
 9084                blocks,
 9085                is_valid: true,
 9086            })
 9087        });
 9088        self.active_diagnostics.is_some()
 9089    }
 9090
 9091    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
 9092        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
 9093            self.display_map.update(cx, |display_map, cx| {
 9094                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
 9095            });
 9096            cx.notify();
 9097        }
 9098    }
 9099
 9100    pub fn set_selections_from_remote(
 9101        &mut self,
 9102        selections: Vec<Selection<Anchor>>,
 9103        pending_selection: Option<Selection<Anchor>>,
 9104        cx: &mut ViewContext<Self>,
 9105    ) {
 9106        let old_cursor_position = self.selections.newest_anchor().head();
 9107        self.selections.change_with(cx, |s| {
 9108            s.select_anchors(selections);
 9109            if let Some(pending_selection) = pending_selection {
 9110                s.set_pending(pending_selection, SelectMode::Character);
 9111            } else {
 9112                s.clear_pending();
 9113            }
 9114        });
 9115        self.selections_did_change(false, &old_cursor_position, cx);
 9116    }
 9117
 9118    fn push_to_selection_history(&mut self) {
 9119        self.selection_history.push(SelectionHistoryEntry {
 9120            selections: self.selections.disjoint_anchors(),
 9121            select_next_state: self.select_next_state.clone(),
 9122            select_prev_state: self.select_prev_state.clone(),
 9123            add_selections_state: self.add_selections_state.clone(),
 9124        });
 9125    }
 9126
 9127    pub fn transact(
 9128        &mut self,
 9129        cx: &mut ViewContext<Self>,
 9130        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
 9131    ) -> Option<TransactionId> {
 9132        self.start_transaction_at(Instant::now(), cx);
 9133        update(self, cx);
 9134        self.end_transaction_at(Instant::now(), cx)
 9135    }
 9136
 9137    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
 9138        self.end_selection(cx);
 9139        if let Some(tx_id) = self
 9140            .buffer
 9141            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
 9142        {
 9143            self.selection_history
 9144                .insert_transaction(tx_id, self.selections.disjoint_anchors());
 9145            cx.emit(EditorEvent::TransactionBegun {
 9146                transaction_id: tx_id,
 9147            })
 9148        }
 9149    }
 9150
 9151    fn end_transaction_at(
 9152        &mut self,
 9153        now: Instant,
 9154        cx: &mut ViewContext<Self>,
 9155    ) -> Option<TransactionId> {
 9156        if let Some(tx_id) = self
 9157            .buffer
 9158            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
 9159        {
 9160            if let Some((_, end_selections)) = self.selection_history.transaction_mut(tx_id) {
 9161                *end_selections = Some(self.selections.disjoint_anchors());
 9162            } else {
 9163                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
 9164            }
 9165
 9166            cx.emit(EditorEvent::Edited);
 9167            Some(tx_id)
 9168        } else {
 9169            None
 9170        }
 9171    }
 9172
 9173    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
 9174        let mut fold_ranges = Vec::new();
 9175
 9176        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9177
 9178        let selections = self.selections.all_adjusted(cx);
 9179        for selection in selections {
 9180            let range = selection.range().sorted();
 9181            let buffer_start_row = range.start.row;
 9182
 9183            for row in (0..=range.end.row).rev() {
 9184                let fold_range = display_map.foldable_range(MultiBufferRow(row));
 9185
 9186                if let Some(fold_range) = fold_range {
 9187                    if fold_range.end.row >= buffer_start_row {
 9188                        fold_ranges.push(fold_range);
 9189                        if row <= range.start.row {
 9190                            break;
 9191                        }
 9192                    }
 9193                }
 9194            }
 9195        }
 9196
 9197        self.fold_ranges(fold_ranges, true, cx);
 9198    }
 9199
 9200    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
 9201        let buffer_row = fold_at.buffer_row;
 9202        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9203
 9204        if let Some(fold_range) = display_map.foldable_range(buffer_row) {
 9205            let autoscroll = self
 9206                .selections
 9207                .all::<Point>(cx)
 9208                .iter()
 9209                .any(|selection| fold_range.overlaps(&selection.range()));
 9210
 9211            self.fold_ranges(std::iter::once(fold_range), autoscroll, cx);
 9212        }
 9213    }
 9214
 9215    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
 9216        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9217        let buffer = &display_map.buffer_snapshot;
 9218        let selections = self.selections.all::<Point>(cx);
 9219        let ranges = selections
 9220            .iter()
 9221            .map(|s| {
 9222                let range = s.display_range(&display_map).sorted();
 9223                let mut start = range.start.to_point(&display_map);
 9224                let mut end = range.end.to_point(&display_map);
 9225                start.column = 0;
 9226                end.column = buffer.line_len(MultiBufferRow(end.row));
 9227                start..end
 9228            })
 9229            .collect::<Vec<_>>();
 9230
 9231        self.unfold_ranges(ranges, true, true, cx);
 9232    }
 9233
 9234    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
 9235        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9236
 9237        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
 9238            ..Point::new(
 9239                unfold_at.buffer_row.0,
 9240                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
 9241            );
 9242
 9243        let autoscroll = self
 9244            .selections
 9245            .all::<Point>(cx)
 9246            .iter()
 9247            .any(|selection| selection.range().overlaps(&intersection_range));
 9248
 9249        self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
 9250    }
 9251
 9252    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
 9253        let selections = self.selections.all::<Point>(cx);
 9254        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9255        let line_mode = self.selections.line_mode;
 9256        let ranges = selections.into_iter().map(|s| {
 9257            if line_mode {
 9258                let start = Point::new(s.start.row, 0);
 9259                let end = Point::new(
 9260                    s.end.row,
 9261                    display_map
 9262                        .buffer_snapshot
 9263                        .line_len(MultiBufferRow(s.end.row)),
 9264                );
 9265                start..end
 9266            } else {
 9267                s.start..s.end
 9268            }
 9269        });
 9270        self.fold_ranges(ranges, true, cx);
 9271    }
 9272
 9273    pub fn fold_ranges<T: ToOffset + Clone>(
 9274        &mut self,
 9275        ranges: impl IntoIterator<Item = Range<T>>,
 9276        auto_scroll: bool,
 9277        cx: &mut ViewContext<Self>,
 9278    ) {
 9279        let mut fold_ranges = Vec::new();
 9280        let mut buffers_affected = HashMap::default();
 9281        let multi_buffer = self.buffer().read(cx);
 9282        for range in ranges {
 9283            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
 9284                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
 9285            };
 9286            fold_ranges.push(range);
 9287        }
 9288
 9289        let mut ranges = fold_ranges.into_iter().peekable();
 9290        if ranges.peek().is_some() {
 9291            self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
 9292
 9293            if auto_scroll {
 9294                self.request_autoscroll(Autoscroll::fit(), cx);
 9295            }
 9296
 9297            for buffer in buffers_affected.into_values() {
 9298                self.sync_expanded_diff_hunks(buffer, cx);
 9299            }
 9300
 9301            cx.notify();
 9302
 9303            if let Some(active_diagnostics) = self.active_diagnostics.take() {
 9304                // Clear diagnostics block when folding a range that contains it.
 9305                let snapshot = self.snapshot(cx);
 9306                if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
 9307                    drop(snapshot);
 9308                    self.active_diagnostics = Some(active_diagnostics);
 9309                    self.dismiss_diagnostics(cx);
 9310                } else {
 9311                    self.active_diagnostics = Some(active_diagnostics);
 9312                }
 9313            }
 9314
 9315            self.scrollbar_marker_state.dirty = true;
 9316        }
 9317    }
 9318
 9319    pub fn unfold_ranges<T: ToOffset + Clone>(
 9320        &mut self,
 9321        ranges: impl IntoIterator<Item = Range<T>>,
 9322        inclusive: bool,
 9323        auto_scroll: bool,
 9324        cx: &mut ViewContext<Self>,
 9325    ) {
 9326        let mut unfold_ranges = Vec::new();
 9327        let mut buffers_affected = HashMap::default();
 9328        let multi_buffer = self.buffer().read(cx);
 9329        for range in ranges {
 9330            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
 9331                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
 9332            };
 9333            unfold_ranges.push(range);
 9334        }
 9335
 9336        let mut ranges = unfold_ranges.into_iter().peekable();
 9337        if ranges.peek().is_some() {
 9338            self.display_map
 9339                .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
 9340            if auto_scroll {
 9341                self.request_autoscroll(Autoscroll::fit(), cx);
 9342            }
 9343
 9344            for buffer in buffers_affected.into_values() {
 9345                self.sync_expanded_diff_hunks(buffer, cx);
 9346            }
 9347
 9348            cx.notify();
 9349            self.scrollbar_marker_state.dirty = true;
 9350        }
 9351    }
 9352
 9353    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
 9354        if hovered != self.gutter_hovered {
 9355            self.gutter_hovered = hovered;
 9356            cx.notify();
 9357        }
 9358    }
 9359
 9360    pub fn insert_blocks(
 9361        &mut self,
 9362        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
 9363        autoscroll: Option<Autoscroll>,
 9364        cx: &mut ViewContext<Self>,
 9365    ) -> Vec<BlockId> {
 9366        let blocks = self
 9367            .display_map
 9368            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
 9369        if let Some(autoscroll) = autoscroll {
 9370            self.request_autoscroll(autoscroll, cx);
 9371        }
 9372        blocks
 9373    }
 9374
 9375    pub fn replace_blocks(
 9376        &mut self,
 9377        blocks: HashMap<BlockId, RenderBlock>,
 9378        autoscroll: Option<Autoscroll>,
 9379        cx: &mut ViewContext<Self>,
 9380    ) {
 9381        self.display_map
 9382            .update(cx, |display_map, _| display_map.replace_blocks(blocks));
 9383        if let Some(autoscroll) = autoscroll {
 9384            self.request_autoscroll(autoscroll, cx);
 9385        }
 9386    }
 9387
 9388    pub fn remove_blocks(
 9389        &mut self,
 9390        block_ids: HashSet<BlockId>,
 9391        autoscroll: Option<Autoscroll>,
 9392        cx: &mut ViewContext<Self>,
 9393    ) {
 9394        self.display_map.update(cx, |display_map, cx| {
 9395            display_map.remove_blocks(block_ids, cx)
 9396        });
 9397        if let Some(autoscroll) = autoscroll {
 9398            self.request_autoscroll(autoscroll, cx);
 9399        }
 9400    }
 9401
 9402    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
 9403        self.display_map
 9404            .update(cx, |map, cx| map.snapshot(cx))
 9405            .longest_row()
 9406    }
 9407
 9408    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
 9409        self.display_map
 9410            .update(cx, |map, cx| map.snapshot(cx))
 9411            .max_point()
 9412    }
 9413
 9414    pub fn text(&self, cx: &AppContext) -> String {
 9415        self.buffer.read(cx).read(cx).text()
 9416    }
 9417
 9418    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
 9419        let text = self.text(cx);
 9420        let text = text.trim();
 9421
 9422        if text.is_empty() {
 9423            return None;
 9424        }
 9425
 9426        Some(text.to_string())
 9427    }
 9428
 9429    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
 9430        self.transact(cx, |this, cx| {
 9431            this.buffer
 9432                .read(cx)
 9433                .as_singleton()
 9434                .expect("you can only call set_text on editors for singleton buffers")
 9435                .update(cx, |buffer, cx| buffer.set_text(text, cx));
 9436        });
 9437    }
 9438
 9439    pub fn display_text(&self, cx: &mut AppContext) -> String {
 9440        self.display_map
 9441            .update(cx, |map, cx| map.snapshot(cx))
 9442            .text()
 9443    }
 9444
 9445    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
 9446        let mut wrap_guides = smallvec::smallvec![];
 9447
 9448        if self.show_wrap_guides == Some(false) {
 9449            return wrap_guides;
 9450        }
 9451
 9452        let settings = self.buffer.read(cx).settings_at(0, cx);
 9453        if settings.show_wrap_guides {
 9454            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
 9455                wrap_guides.push((soft_wrap as usize, true));
 9456            }
 9457            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
 9458        }
 9459
 9460        wrap_guides
 9461    }
 9462
 9463    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
 9464        let settings = self.buffer.read(cx).settings_at(0, cx);
 9465        let mode = self
 9466            .soft_wrap_mode_override
 9467            .unwrap_or_else(|| settings.soft_wrap);
 9468        match mode {
 9469            language_settings::SoftWrap::None => SoftWrap::None,
 9470            language_settings::SoftWrap::PreferLine => SoftWrap::PreferLine,
 9471            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
 9472            language_settings::SoftWrap::PreferredLineLength => {
 9473                SoftWrap::Column(settings.preferred_line_length)
 9474            }
 9475        }
 9476    }
 9477
 9478    pub fn set_soft_wrap_mode(
 9479        &mut self,
 9480        mode: language_settings::SoftWrap,
 9481        cx: &mut ViewContext<Self>,
 9482    ) {
 9483        self.soft_wrap_mode_override = Some(mode);
 9484        cx.notify();
 9485    }
 9486
 9487    pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
 9488        let rem_size = cx.rem_size();
 9489        self.display_map.update(cx, |map, cx| {
 9490            map.set_font(
 9491                style.text.font(),
 9492                style.text.font_size.to_pixels(rem_size),
 9493                cx,
 9494            )
 9495        });
 9496        self.style = Some(style);
 9497    }
 9498
 9499    pub fn style(&self) -> Option<&EditorStyle> {
 9500        self.style.as_ref()
 9501    }
 9502
 9503    // Called by the element. This method is not designed to be called outside of the editor
 9504    // element's layout code because it does not notify when rewrapping is computed synchronously.
 9505    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
 9506        self.display_map
 9507            .update(cx, |map, cx| map.set_wrap_width(width, cx))
 9508    }
 9509
 9510    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
 9511        if self.soft_wrap_mode_override.is_some() {
 9512            self.soft_wrap_mode_override.take();
 9513        } else {
 9514            let soft_wrap = match self.soft_wrap_mode(cx) {
 9515                SoftWrap::None | SoftWrap::PreferLine => language_settings::SoftWrap::EditorWidth,
 9516                SoftWrap::EditorWidth | SoftWrap::Column(_) => {
 9517                    language_settings::SoftWrap::PreferLine
 9518                }
 9519            };
 9520            self.soft_wrap_mode_override = Some(soft_wrap);
 9521        }
 9522        cx.notify();
 9523    }
 9524
 9525    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
 9526        let mut editor_settings = EditorSettings::get_global(cx).clone();
 9527        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
 9528        EditorSettings::override_global(editor_settings, cx);
 9529    }
 9530
 9531    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
 9532        self.show_gutter = show_gutter;
 9533        cx.notify();
 9534    }
 9535
 9536    pub fn set_show_wrap_guides(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
 9537        self.show_wrap_guides = Some(show_gutter);
 9538        cx.notify();
 9539    }
 9540
 9541    pub fn reveal_in_finder(&mut self, _: &RevealInFinder, cx: &mut ViewContext<Self>) {
 9542        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
 9543            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
 9544                cx.reveal_path(&file.abs_path(cx));
 9545            }
 9546        }
 9547    }
 9548
 9549    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
 9550        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
 9551            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
 9552                if let Some(path) = file.abs_path(cx).to_str() {
 9553                    cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
 9554                }
 9555            }
 9556        }
 9557    }
 9558
 9559    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
 9560        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
 9561            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
 9562                if let Some(path) = file.path().to_str() {
 9563                    cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
 9564                }
 9565            }
 9566        }
 9567    }
 9568
 9569    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
 9570        self.show_git_blame_gutter = !self.show_git_blame_gutter;
 9571
 9572        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
 9573            self.start_git_blame(true, cx);
 9574        }
 9575
 9576        cx.notify();
 9577    }
 9578
 9579    pub fn toggle_git_blame_inline(
 9580        &mut self,
 9581        _: &ToggleGitBlameInline,
 9582        cx: &mut ViewContext<Self>,
 9583    ) {
 9584        self.toggle_git_blame_inline_internal(true, cx);
 9585        cx.notify();
 9586    }
 9587
 9588    pub fn git_blame_inline_enabled(&self) -> bool {
 9589        self.git_blame_inline_enabled
 9590    }
 9591
 9592    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
 9593        if let Some(project) = self.project.as_ref() {
 9594            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
 9595                return;
 9596            };
 9597
 9598            if buffer.read(cx).file().is_none() {
 9599                return;
 9600            }
 9601
 9602            let focused = self.focus_handle(cx).contains_focused(cx);
 9603
 9604            let project = project.clone();
 9605            let blame =
 9606                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
 9607            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
 9608            self.blame = Some(blame);
 9609        }
 9610    }
 9611
 9612    fn toggle_git_blame_inline_internal(
 9613        &mut self,
 9614        user_triggered: bool,
 9615        cx: &mut ViewContext<Self>,
 9616    ) {
 9617        if self.git_blame_inline_enabled {
 9618            self.git_blame_inline_enabled = false;
 9619            self.show_git_blame_inline = false;
 9620            self.show_git_blame_inline_delay_task.take();
 9621        } else {
 9622            self.git_blame_inline_enabled = true;
 9623            self.start_git_blame_inline(user_triggered, cx);
 9624        }
 9625
 9626        cx.notify();
 9627    }
 9628
 9629    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
 9630        self.start_git_blame(user_triggered, cx);
 9631
 9632        if ProjectSettings::get_global(cx)
 9633            .git
 9634            .inline_blame_delay()
 9635            .is_some()
 9636        {
 9637            self.start_inline_blame_timer(cx);
 9638        } else {
 9639            self.show_git_blame_inline = true
 9640        }
 9641    }
 9642
 9643    pub fn blame(&self) -> Option<&Model<GitBlame>> {
 9644        self.blame.as_ref()
 9645    }
 9646
 9647    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
 9648        self.show_git_blame_gutter && self.has_blame_entries(cx)
 9649    }
 9650
 9651    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
 9652        self.show_git_blame_inline
 9653            && self.focus_handle.is_focused(cx)
 9654            && !self.newest_selection_head_on_empty_line(cx)
 9655            && self.has_blame_entries(cx)
 9656    }
 9657
 9658    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
 9659        self.blame()
 9660            .map_or(false, |blame| blame.read(cx).has_generated_entries())
 9661    }
 9662
 9663    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
 9664        let cursor_anchor = self.selections.newest_anchor().head();
 9665
 9666        let snapshot = self.buffer.read(cx).snapshot(cx);
 9667        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
 9668
 9669        snapshot.line_len(buffer_row) == 0
 9670    }
 9671
 9672    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
 9673        let (path, repo) = maybe!({
 9674            let project_handle = self.project.as_ref()?.clone();
 9675            let project = project_handle.read(cx);
 9676            let buffer = self.buffer().read(cx).as_singleton()?;
 9677            let path = buffer
 9678                .read(cx)
 9679                .file()?
 9680                .as_local()?
 9681                .path()
 9682                .to_str()?
 9683                .to_string();
 9684            let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
 9685            Some((path, repo))
 9686        })
 9687        .ok_or_else(|| anyhow!("unable to open git repository"))?;
 9688
 9689        const REMOTE_NAME: &str = "origin";
 9690        let origin_url = repo
 9691            .lock()
 9692            .remote_url(REMOTE_NAME)
 9693            .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
 9694        let sha = repo
 9695            .lock()
 9696            .head_sha()
 9697            .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
 9698        let selections = self.selections.all::<Point>(cx);
 9699        let selection = selections.iter().peekable().next();
 9700
 9701        let (provider, remote) =
 9702            parse_git_remote_url(GitHostingProviderRegistry::default_global(cx), &origin_url)
 9703                .ok_or_else(|| anyhow!("failed to parse Git remote URL"))?;
 9704
 9705        Ok(provider.build_permalink(
 9706            remote,
 9707            BuildPermalinkParams {
 9708                sha: &sha,
 9709                path: &path,
 9710                selection: selection.map(|selection| {
 9711                    let range = selection.range();
 9712                    let start = range.start.row;
 9713                    let end = range.end.row;
 9714                    start..end
 9715                }),
 9716            },
 9717        ))
 9718    }
 9719
 9720    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
 9721        let permalink = self.get_permalink_to_line(cx);
 9722
 9723        match permalink {
 9724            Ok(permalink) => {
 9725                cx.write_to_clipboard(ClipboardItem::new(permalink.to_string()));
 9726            }
 9727            Err(err) => {
 9728                let message = format!("Failed to copy permalink: {err}");
 9729
 9730                Err::<(), anyhow::Error>(err).log_err();
 9731
 9732                if let Some(workspace) = self.workspace() {
 9733                    workspace.update(cx, |workspace, cx| {
 9734                        struct CopyPermalinkToLine;
 9735
 9736                        workspace.show_toast(
 9737                            Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
 9738                            cx,
 9739                        )
 9740                    })
 9741                }
 9742            }
 9743        }
 9744    }
 9745
 9746    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
 9747        let permalink = self.get_permalink_to_line(cx);
 9748
 9749        match permalink {
 9750            Ok(permalink) => {
 9751                cx.open_url(permalink.as_ref());
 9752            }
 9753            Err(err) => {
 9754                let message = format!("Failed to open permalink: {err}");
 9755
 9756                Err::<(), anyhow::Error>(err).log_err();
 9757
 9758                if let Some(workspace) = self.workspace() {
 9759                    workspace.update(cx, |workspace, cx| {
 9760                        struct OpenPermalinkToLine;
 9761
 9762                        workspace.show_toast(
 9763                            Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
 9764                            cx,
 9765                        )
 9766                    })
 9767                }
 9768            }
 9769        }
 9770    }
 9771
 9772    /// Adds or removes (on `None` color) a highlight for the rows corresponding to the anchor range given.
 9773    /// On matching anchor range, replaces the old highlight; does not clear the other existing highlights.
 9774    /// If multiple anchor ranges will produce highlights for the same row, the last range added will be used.
 9775    pub fn highlight_rows<T: 'static>(
 9776        &mut self,
 9777        rows: RangeInclusive<Anchor>,
 9778        color: Option<Hsla>,
 9779        cx: &mut ViewContext<Self>,
 9780    ) {
 9781        let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
 9782        match self.highlighted_rows.entry(TypeId::of::<T>()) {
 9783            hash_map::Entry::Occupied(o) => {
 9784                let row_highlights = o.into_mut();
 9785                let existing_highlight_index =
 9786                    row_highlights.binary_search_by(|(_, highlight_range, _)| {
 9787                        highlight_range
 9788                            .start()
 9789                            .cmp(&rows.start(), &multi_buffer_snapshot)
 9790                            .then(
 9791                                highlight_range
 9792                                    .end()
 9793                                    .cmp(&rows.end(), &multi_buffer_snapshot),
 9794                            )
 9795                    });
 9796                match color {
 9797                    Some(color) => {
 9798                        let insert_index = match existing_highlight_index {
 9799                            Ok(i) => i,
 9800                            Err(i) => i,
 9801                        };
 9802                        row_highlights.insert(
 9803                            insert_index,
 9804                            (post_inc(&mut self.highlight_order), rows, Some(color)),
 9805                        );
 9806                    }
 9807                    None => match existing_highlight_index {
 9808                        Ok(i) => {
 9809                            row_highlights.remove(i);
 9810                        }
 9811                        Err(i) => {
 9812                            row_highlights
 9813                                .insert(i, (post_inc(&mut self.highlight_order), rows, None));
 9814                        }
 9815                    },
 9816                }
 9817            }
 9818            hash_map::Entry::Vacant(v) => {
 9819                v.insert(vec![(post_inc(&mut self.highlight_order), rows, color)]);
 9820            }
 9821        }
 9822    }
 9823
 9824    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
 9825    pub fn clear_row_highlights<T: 'static>(&mut self) {
 9826        self.highlighted_rows.remove(&TypeId::of::<T>());
 9827    }
 9828
 9829    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
 9830    pub fn highlighted_rows<T: 'static>(
 9831        &self,
 9832    ) -> Option<impl Iterator<Item = (&RangeInclusive<Anchor>, Option<&Hsla>)>> {
 9833        Some(
 9834            self.highlighted_rows
 9835                .get(&TypeId::of::<T>())?
 9836                .iter()
 9837                .map(|(_, range, color)| (range, color.as_ref())),
 9838        )
 9839    }
 9840
 9841    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
 9842    /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
 9843    /// Allows to ignore certain kinds of highlights.
 9844    pub fn highlighted_display_rows(
 9845        &mut self,
 9846        exclude_highlights: HashSet<TypeId>,
 9847        cx: &mut WindowContext,
 9848    ) -> BTreeMap<DisplayRow, Hsla> {
 9849        let snapshot = self.snapshot(cx);
 9850        let mut used_highlight_orders = HashMap::default();
 9851        self.highlighted_rows
 9852            .iter()
 9853            .filter(|(type_id, _)| !exclude_highlights.contains(type_id))
 9854            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
 9855            .fold(
 9856                BTreeMap::<DisplayRow, Hsla>::new(),
 9857                |mut unique_rows, (highlight_order, anchor_range, hsla)| {
 9858                    let start_row = anchor_range.start().to_display_point(&snapshot).row();
 9859                    let end_row = anchor_range.end().to_display_point(&snapshot).row();
 9860                    for row in start_row.0..=end_row.0 {
 9861                        let used_index =
 9862                            used_highlight_orders.entry(row).or_insert(*highlight_order);
 9863                        if highlight_order >= used_index {
 9864                            *used_index = *highlight_order;
 9865                            match hsla {
 9866                                Some(hsla) => {
 9867                                    unique_rows.insert(DisplayRow(row), *hsla);
 9868                                }
 9869                                None => {
 9870                                    unique_rows.remove(&DisplayRow(row));
 9871                                }
 9872                            }
 9873                        }
 9874                    }
 9875                    unique_rows
 9876                },
 9877            )
 9878    }
 9879
 9880    pub fn set_search_within_ranges(
 9881        &mut self,
 9882        ranges: &[Range<Anchor>],
 9883        cx: &mut ViewContext<Self>,
 9884    ) {
 9885        self.highlight_background::<SearchWithinRange>(
 9886            ranges,
 9887            |colors| colors.editor_document_highlight_read_background,
 9888            cx,
 9889        )
 9890    }
 9891
 9892    pub fn highlight_background<T: 'static>(
 9893        &mut self,
 9894        ranges: &[Range<Anchor>],
 9895        color_fetcher: fn(&ThemeColors) -> Hsla,
 9896        cx: &mut ViewContext<Self>,
 9897    ) {
 9898        let snapshot = self.snapshot(cx);
 9899        // this is to try and catch a panic sooner
 9900        for range in ranges {
 9901            snapshot
 9902                .buffer_snapshot
 9903                .summary_for_anchor::<usize>(&range.start);
 9904            snapshot
 9905                .buffer_snapshot
 9906                .summary_for_anchor::<usize>(&range.end);
 9907        }
 9908
 9909        self.background_highlights
 9910            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
 9911        self.scrollbar_marker_state.dirty = true;
 9912        cx.notify();
 9913    }
 9914
 9915    pub fn clear_background_highlights<T: 'static>(
 9916        &mut self,
 9917        cx: &mut ViewContext<Self>,
 9918    ) -> Option<BackgroundHighlight> {
 9919        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
 9920        if !text_highlights.1.is_empty() {
 9921            self.scrollbar_marker_state.dirty = true;
 9922            cx.notify();
 9923        }
 9924        Some(text_highlights)
 9925    }
 9926
 9927    #[cfg(feature = "test-support")]
 9928    pub fn all_text_background_highlights(
 9929        &mut self,
 9930        cx: &mut ViewContext<Self>,
 9931    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
 9932        let snapshot = self.snapshot(cx);
 9933        let buffer = &snapshot.buffer_snapshot;
 9934        let start = buffer.anchor_before(0);
 9935        let end = buffer.anchor_after(buffer.len());
 9936        let theme = cx.theme().colors();
 9937        self.background_highlights_in_range(start..end, &snapshot, theme)
 9938    }
 9939
 9940    fn document_highlights_for_position<'a>(
 9941        &'a self,
 9942        position: Anchor,
 9943        buffer: &'a MultiBufferSnapshot,
 9944    ) -> impl 'a + Iterator<Item = &Range<Anchor>> {
 9945        let read_highlights = self
 9946            .background_highlights
 9947            .get(&TypeId::of::<DocumentHighlightRead>())
 9948            .map(|h| &h.1);
 9949        let write_highlights = self
 9950            .background_highlights
 9951            .get(&TypeId::of::<DocumentHighlightWrite>())
 9952            .map(|h| &h.1);
 9953        let left_position = position.bias_left(buffer);
 9954        let right_position = position.bias_right(buffer);
 9955        read_highlights
 9956            .into_iter()
 9957            .chain(write_highlights)
 9958            .flat_map(move |ranges| {
 9959                let start_ix = match ranges.binary_search_by(|probe| {
 9960                    let cmp = probe.end.cmp(&left_position, buffer);
 9961                    if cmp.is_ge() {
 9962                        Ordering::Greater
 9963                    } else {
 9964                        Ordering::Less
 9965                    }
 9966                }) {
 9967                    Ok(i) | Err(i) => i,
 9968                };
 9969
 9970                ranges[start_ix..]
 9971                    .iter()
 9972                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
 9973            })
 9974    }
 9975
 9976    pub fn has_background_highlights<T: 'static>(&self) -> bool {
 9977        self.background_highlights
 9978            .get(&TypeId::of::<T>())
 9979            .map_or(false, |(_, highlights)| !highlights.is_empty())
 9980    }
 9981
 9982    pub fn background_highlights_in_range(
 9983        &self,
 9984        search_range: Range<Anchor>,
 9985        display_snapshot: &DisplaySnapshot,
 9986        theme: &ThemeColors,
 9987    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
 9988        let mut results = Vec::new();
 9989        for (color_fetcher, ranges) in self.background_highlights.values() {
 9990            let color = color_fetcher(theme);
 9991            let start_ix = match ranges.binary_search_by(|probe| {
 9992                let cmp = probe
 9993                    .end
 9994                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
 9995                if cmp.is_gt() {
 9996                    Ordering::Greater
 9997                } else {
 9998                    Ordering::Less
 9999                }
10000            }) {
10001                Ok(i) | Err(i) => i,
10002            };
10003            for range in &ranges[start_ix..] {
10004                if range
10005                    .start
10006                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
10007                    .is_ge()
10008                {
10009                    break;
10010                }
10011
10012                let start = range.start.to_display_point(&display_snapshot);
10013                let end = range.end.to_display_point(&display_snapshot);
10014                results.push((start..end, color))
10015            }
10016        }
10017        results
10018    }
10019
10020    pub fn background_highlight_row_ranges<T: 'static>(
10021        &self,
10022        search_range: Range<Anchor>,
10023        display_snapshot: &DisplaySnapshot,
10024        count: usize,
10025    ) -> Vec<RangeInclusive<DisplayPoint>> {
10026        let mut results = Vec::new();
10027        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
10028            return vec![];
10029        };
10030
10031        let start_ix = match ranges.binary_search_by(|probe| {
10032            let cmp = probe
10033                .end
10034                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
10035            if cmp.is_gt() {
10036                Ordering::Greater
10037            } else {
10038                Ordering::Less
10039            }
10040        }) {
10041            Ok(i) | Err(i) => i,
10042        };
10043        let mut push_region = |start: Option<Point>, end: Option<Point>| {
10044            if let (Some(start_display), Some(end_display)) = (start, end) {
10045                results.push(
10046                    start_display.to_display_point(display_snapshot)
10047                        ..=end_display.to_display_point(display_snapshot),
10048                );
10049            }
10050        };
10051        let mut start_row: Option<Point> = None;
10052        let mut end_row: Option<Point> = None;
10053        if ranges.len() > count {
10054            return Vec::new();
10055        }
10056        for range in &ranges[start_ix..] {
10057            if range
10058                .start
10059                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
10060                .is_ge()
10061            {
10062                break;
10063            }
10064            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
10065            if let Some(current_row) = &end_row {
10066                if end.row == current_row.row {
10067                    continue;
10068                }
10069            }
10070            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
10071            if start_row.is_none() {
10072                assert_eq!(end_row, None);
10073                start_row = Some(start);
10074                end_row = Some(end);
10075                continue;
10076            }
10077            if let Some(current_end) = end_row.as_mut() {
10078                if start.row > current_end.row + 1 {
10079                    push_region(start_row, end_row);
10080                    start_row = Some(start);
10081                    end_row = Some(end);
10082                } else {
10083                    // Merge two hunks.
10084                    *current_end = end;
10085                }
10086            } else {
10087                unreachable!();
10088            }
10089        }
10090        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
10091        push_region(start_row, end_row);
10092        results
10093    }
10094
10095    /// Get the text ranges corresponding to the redaction query
10096    pub fn redacted_ranges(
10097        &self,
10098        search_range: Range<Anchor>,
10099        display_snapshot: &DisplaySnapshot,
10100        cx: &WindowContext,
10101    ) -> Vec<Range<DisplayPoint>> {
10102        display_snapshot
10103            .buffer_snapshot
10104            .redacted_ranges(search_range, |file| {
10105                if let Some(file) = file {
10106                    file.is_private()
10107                        && EditorSettings::get(Some(file.as_ref().into()), cx).redact_private_values
10108                } else {
10109                    false
10110                }
10111            })
10112            .map(|range| {
10113                range.start.to_display_point(display_snapshot)
10114                    ..range.end.to_display_point(display_snapshot)
10115            })
10116            .collect()
10117    }
10118
10119    pub fn highlight_text<T: 'static>(
10120        &mut self,
10121        ranges: Vec<Range<Anchor>>,
10122        style: HighlightStyle,
10123        cx: &mut ViewContext<Self>,
10124    ) {
10125        self.display_map.update(cx, |map, _| {
10126            map.highlight_text(TypeId::of::<T>(), ranges, style)
10127        });
10128        cx.notify();
10129    }
10130
10131    pub(crate) fn highlight_inlays<T: 'static>(
10132        &mut self,
10133        highlights: Vec<InlayHighlight>,
10134        style: HighlightStyle,
10135        cx: &mut ViewContext<Self>,
10136    ) {
10137        self.display_map.update(cx, |map, _| {
10138            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
10139        });
10140        cx.notify();
10141    }
10142
10143    pub fn text_highlights<'a, T: 'static>(
10144        &'a self,
10145        cx: &'a AppContext,
10146    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
10147        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
10148    }
10149
10150    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
10151        let cleared = self
10152            .display_map
10153            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
10154        if cleared {
10155            cx.notify();
10156        }
10157    }
10158
10159    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
10160        (self.read_only(cx) || self.blink_manager.read(cx).visible())
10161            && self.focus_handle.is_focused(cx)
10162    }
10163
10164    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
10165        cx.notify();
10166    }
10167
10168    fn on_buffer_event(
10169        &mut self,
10170        multibuffer: Model<MultiBuffer>,
10171        event: &multi_buffer::Event,
10172        cx: &mut ViewContext<Self>,
10173    ) {
10174        match event {
10175            multi_buffer::Event::Edited {
10176                singleton_buffer_edited,
10177            } => {
10178                self.scrollbar_marker_state.dirty = true;
10179                self.refresh_active_diagnostics(cx);
10180                self.refresh_code_actions(cx);
10181                if self.has_active_inline_completion(cx) {
10182                    self.update_visible_inline_completion(cx);
10183                }
10184                cx.emit(EditorEvent::BufferEdited);
10185                cx.emit(SearchEvent::MatchesInvalidated);
10186
10187                if *singleton_buffer_edited {
10188                    if let Some(project) = &self.project {
10189                        let project = project.read(cx);
10190                        let languages_affected = multibuffer
10191                            .read(cx)
10192                            .all_buffers()
10193                            .into_iter()
10194                            .filter_map(|buffer| {
10195                                let buffer = buffer.read(cx);
10196                                let language = buffer.language()?;
10197                                if project.is_local()
10198                                    && project.language_servers_for_buffer(buffer, cx).count() == 0
10199                                {
10200                                    None
10201                                } else {
10202                                    Some(language)
10203                                }
10204                            })
10205                            .cloned()
10206                            .collect::<HashSet<_>>();
10207                        if !languages_affected.is_empty() {
10208                            self.refresh_inlay_hints(
10209                                InlayHintRefreshReason::BufferEdited(languages_affected),
10210                                cx,
10211                            );
10212                        }
10213                    }
10214                }
10215
10216                let Some(project) = &self.project else { return };
10217                let telemetry = project.read(cx).client().telemetry().clone();
10218                telemetry.log_edit_event("editor");
10219            }
10220            multi_buffer::Event::ExcerptsAdded {
10221                buffer,
10222                predecessor,
10223                excerpts,
10224            } => {
10225                self.tasks_update_task = Some(self.refresh_runnables(cx));
10226                cx.emit(EditorEvent::ExcerptsAdded {
10227                    buffer: buffer.clone(),
10228                    predecessor: *predecessor,
10229                    excerpts: excerpts.clone(),
10230                });
10231                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
10232            }
10233            multi_buffer::Event::ExcerptsRemoved { ids } => {
10234                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
10235                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
10236            }
10237            multi_buffer::Event::Reparsed => {
10238                self.tasks_update_task = Some(self.refresh_runnables(cx));
10239
10240                cx.emit(EditorEvent::Reparsed);
10241            }
10242            multi_buffer::Event::LanguageChanged => {
10243                cx.emit(EditorEvent::Reparsed);
10244                cx.notify();
10245            }
10246            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
10247            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
10248            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
10249                cx.emit(EditorEvent::TitleChanged)
10250            }
10251            multi_buffer::Event::DiffBaseChanged => {
10252                self.scrollbar_marker_state.dirty = true;
10253                cx.emit(EditorEvent::DiffBaseChanged);
10254                cx.notify();
10255            }
10256            multi_buffer::Event::DiffUpdated { buffer } => {
10257                self.sync_expanded_diff_hunks(buffer.clone(), cx);
10258                cx.notify();
10259            }
10260            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
10261            multi_buffer::Event::DiagnosticsUpdated => {
10262                self.refresh_active_diagnostics(cx);
10263                self.scrollbar_marker_state.dirty = true;
10264                cx.notify();
10265            }
10266            _ => {}
10267        };
10268    }
10269
10270    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
10271        cx.notify();
10272    }
10273
10274    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
10275        self.refresh_inline_completion(true, cx);
10276        self.refresh_inlay_hints(
10277            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
10278                self.selections.newest_anchor().head(),
10279                &self.buffer.read(cx).snapshot(cx),
10280                cx,
10281            )),
10282            cx,
10283        );
10284        let editor_settings = EditorSettings::get_global(cx);
10285        self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
10286        self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
10287
10288        if self.mode == EditorMode::Full {
10289            let inline_blame_enabled = ProjectSettings::get_global(cx).git.inline_blame_enabled();
10290            if self.git_blame_inline_enabled != inline_blame_enabled {
10291                self.toggle_git_blame_inline_internal(false, cx);
10292            }
10293        }
10294
10295        cx.notify();
10296    }
10297
10298    pub fn set_searchable(&mut self, searchable: bool) {
10299        self.searchable = searchable;
10300    }
10301
10302    pub fn searchable(&self) -> bool {
10303        self.searchable
10304    }
10305
10306    fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
10307        self.open_excerpts_common(true, cx)
10308    }
10309
10310    fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
10311        self.open_excerpts_common(false, cx)
10312    }
10313
10314    fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
10315        let buffer = self.buffer.read(cx);
10316        if buffer.is_singleton() {
10317            cx.propagate();
10318            return;
10319        }
10320
10321        let Some(workspace) = self.workspace() else {
10322            cx.propagate();
10323            return;
10324        };
10325
10326        let mut new_selections_by_buffer = HashMap::default();
10327        for selection in self.selections.all::<usize>(cx) {
10328            for (buffer, mut range, _) in
10329                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
10330            {
10331                if selection.reversed {
10332                    mem::swap(&mut range.start, &mut range.end);
10333                }
10334                new_selections_by_buffer
10335                    .entry(buffer)
10336                    .or_insert(Vec::new())
10337                    .push(range)
10338            }
10339        }
10340
10341        // We defer the pane interaction because we ourselves are a workspace item
10342        // and activating a new item causes the pane to call a method on us reentrantly,
10343        // which panics if we're on the stack.
10344        cx.window_context().defer(move |cx| {
10345            workspace.update(cx, |workspace, cx| {
10346                let pane = if split {
10347                    workspace.adjacent_pane(cx)
10348                } else {
10349                    workspace.active_pane().clone()
10350                };
10351
10352                for (buffer, ranges) in new_selections_by_buffer {
10353                    let editor = workspace.open_project_item::<Self>(pane.clone(), buffer, cx);
10354                    editor.update(cx, |editor, cx| {
10355                        editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
10356                            s.select_ranges(ranges);
10357                        });
10358                    });
10359                }
10360            })
10361        });
10362    }
10363
10364    fn jump(
10365        &mut self,
10366        path: ProjectPath,
10367        position: Point,
10368        anchor: language::Anchor,
10369        offset_from_top: u32,
10370        cx: &mut ViewContext<Self>,
10371    ) {
10372        let workspace = self.workspace();
10373        cx.spawn(|_, mut cx| async move {
10374            let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
10375            let editor = workspace.update(&mut cx, |workspace, cx| {
10376                // Reset the preview item id before opening the new item
10377                workspace.active_pane().update(cx, |pane, cx| {
10378                    pane.set_preview_item_id(None, cx);
10379                });
10380                workspace.open_path_preview(path, None, true, true, cx)
10381            })?;
10382            let editor = editor
10383                .await?
10384                .downcast::<Editor>()
10385                .ok_or_else(|| anyhow!("opened item was not an editor"))?
10386                .downgrade();
10387            editor.update(&mut cx, |editor, cx| {
10388                let buffer = editor
10389                    .buffer()
10390                    .read(cx)
10391                    .as_singleton()
10392                    .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
10393                let buffer = buffer.read(cx);
10394                let cursor = if buffer.can_resolve(&anchor) {
10395                    language::ToPoint::to_point(&anchor, buffer)
10396                } else {
10397                    buffer.clip_point(position, Bias::Left)
10398                };
10399
10400                let nav_history = editor.nav_history.take();
10401                editor.change_selections(
10402                    Some(Autoscroll::top_relative(offset_from_top as usize)),
10403                    cx,
10404                    |s| {
10405                        s.select_ranges([cursor..cursor]);
10406                    },
10407                );
10408                editor.nav_history = nav_history;
10409
10410                anyhow::Ok(())
10411            })??;
10412
10413            anyhow::Ok(())
10414        })
10415        .detach_and_log_err(cx);
10416    }
10417
10418    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
10419        let snapshot = self.buffer.read(cx).read(cx);
10420        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
10421        Some(
10422            ranges
10423                .iter()
10424                .map(move |range| {
10425                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
10426                })
10427                .collect(),
10428        )
10429    }
10430
10431    fn selection_replacement_ranges(
10432        &self,
10433        range: Range<OffsetUtf16>,
10434        cx: &AppContext,
10435    ) -> Vec<Range<OffsetUtf16>> {
10436        let selections = self.selections.all::<OffsetUtf16>(cx);
10437        let newest_selection = selections
10438            .iter()
10439            .max_by_key(|selection| selection.id)
10440            .unwrap();
10441        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
10442        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
10443        let snapshot = self.buffer.read(cx).read(cx);
10444        selections
10445            .into_iter()
10446            .map(|mut selection| {
10447                selection.start.0 =
10448                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
10449                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
10450                snapshot.clip_offset_utf16(selection.start, Bias::Left)
10451                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
10452            })
10453            .collect()
10454    }
10455
10456    fn report_editor_event(
10457        &self,
10458        operation: &'static str,
10459        file_extension: Option<String>,
10460        cx: &AppContext,
10461    ) {
10462        if cfg!(any(test, feature = "test-support")) {
10463            return;
10464        }
10465
10466        let Some(project) = &self.project else { return };
10467
10468        // If None, we are in a file without an extension
10469        let file = self
10470            .buffer
10471            .read(cx)
10472            .as_singleton()
10473            .and_then(|b| b.read(cx).file());
10474        let file_extension = file_extension.or(file
10475            .as_ref()
10476            .and_then(|file| Path::new(file.file_name(cx)).extension())
10477            .and_then(|e| e.to_str())
10478            .map(|a| a.to_string()));
10479
10480        let vim_mode = cx
10481            .global::<SettingsStore>()
10482            .raw_user_settings()
10483            .get("vim_mode")
10484            == Some(&serde_json::Value::Bool(true));
10485
10486        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
10487            == language::language_settings::InlineCompletionProvider::Copilot;
10488        let copilot_enabled_for_language = self
10489            .buffer
10490            .read(cx)
10491            .settings_at(0, cx)
10492            .show_inline_completions;
10493
10494        let telemetry = project.read(cx).client().telemetry().clone();
10495        telemetry.report_editor_event(
10496            file_extension,
10497            vim_mode,
10498            operation,
10499            copilot_enabled,
10500            copilot_enabled_for_language,
10501        )
10502    }
10503
10504    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
10505    /// with each line being an array of {text, highlight} objects.
10506    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
10507        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
10508            return;
10509        };
10510
10511        #[derive(Serialize)]
10512        struct Chunk<'a> {
10513            text: String,
10514            highlight: Option<&'a str>,
10515        }
10516
10517        let snapshot = buffer.read(cx).snapshot();
10518        let range = self
10519            .selected_text_range(cx)
10520            .and_then(|selected_range| {
10521                if selected_range.is_empty() {
10522                    None
10523                } else {
10524                    Some(selected_range)
10525                }
10526            })
10527            .unwrap_or_else(|| 0..snapshot.len());
10528
10529        let chunks = snapshot.chunks(range, true);
10530        let mut lines = Vec::new();
10531        let mut line: VecDeque<Chunk> = VecDeque::new();
10532
10533        let Some(style) = self.style.as_ref() else {
10534            return;
10535        };
10536
10537        for chunk in chunks {
10538            let highlight = chunk
10539                .syntax_highlight_id
10540                .and_then(|id| id.name(&style.syntax));
10541            let mut chunk_lines = chunk.text.split('\n').peekable();
10542            while let Some(text) = chunk_lines.next() {
10543                let mut merged_with_last_token = false;
10544                if let Some(last_token) = line.back_mut() {
10545                    if last_token.highlight == highlight {
10546                        last_token.text.push_str(text);
10547                        merged_with_last_token = true;
10548                    }
10549                }
10550
10551                if !merged_with_last_token {
10552                    line.push_back(Chunk {
10553                        text: text.into(),
10554                        highlight,
10555                    });
10556                }
10557
10558                if chunk_lines.peek().is_some() {
10559                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
10560                        line.pop_front();
10561                    }
10562                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
10563                        line.pop_back();
10564                    }
10565
10566                    lines.push(mem::take(&mut line));
10567                }
10568            }
10569        }
10570
10571        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
10572            return;
10573        };
10574        cx.write_to_clipboard(ClipboardItem::new(lines));
10575    }
10576
10577    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
10578        &self.inlay_hint_cache
10579    }
10580
10581    pub fn replay_insert_event(
10582        &mut self,
10583        text: &str,
10584        relative_utf16_range: Option<Range<isize>>,
10585        cx: &mut ViewContext<Self>,
10586    ) {
10587        if !self.input_enabled {
10588            cx.emit(EditorEvent::InputIgnored { text: text.into() });
10589            return;
10590        }
10591        if let Some(relative_utf16_range) = relative_utf16_range {
10592            let selections = self.selections.all::<OffsetUtf16>(cx);
10593            self.change_selections(None, cx, |s| {
10594                let new_ranges = selections.into_iter().map(|range| {
10595                    let start = OffsetUtf16(
10596                        range
10597                            .head()
10598                            .0
10599                            .saturating_add_signed(relative_utf16_range.start),
10600                    );
10601                    let end = OffsetUtf16(
10602                        range
10603                            .head()
10604                            .0
10605                            .saturating_add_signed(relative_utf16_range.end),
10606                    );
10607                    start..end
10608                });
10609                s.select_ranges(new_ranges);
10610            });
10611        }
10612
10613        self.handle_input(text, cx);
10614    }
10615
10616    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
10617        let Some(project) = self.project.as_ref() else {
10618            return false;
10619        };
10620        let project = project.read(cx);
10621
10622        let mut supports = false;
10623        self.buffer().read(cx).for_each_buffer(|buffer| {
10624            if !supports {
10625                supports = project
10626                    .language_servers_for_buffer(buffer.read(cx), cx)
10627                    .any(
10628                        |(_, server)| match server.capabilities().inlay_hint_provider {
10629                            Some(lsp::OneOf::Left(enabled)) => enabled,
10630                            Some(lsp::OneOf::Right(_)) => true,
10631                            None => false,
10632                        },
10633                    )
10634            }
10635        });
10636        supports
10637    }
10638
10639    pub fn focus(&self, cx: &mut WindowContext) {
10640        cx.focus(&self.focus_handle)
10641    }
10642
10643    pub fn is_focused(&self, cx: &WindowContext) -> bool {
10644        self.focus_handle.is_focused(cx)
10645    }
10646
10647    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
10648        cx.emit(EditorEvent::Focused);
10649
10650        if let Some(rename) = self.pending_rename.as_ref() {
10651            let rename_editor_focus_handle = rename.editor.read(cx).focus_handle.clone();
10652            cx.focus(&rename_editor_focus_handle);
10653        } else {
10654            if let Some(blame) = self.blame.as_ref() {
10655                blame.update(cx, GitBlame::focus)
10656            }
10657
10658            self.blink_manager.update(cx, BlinkManager::enable);
10659            self.show_cursor_names(cx);
10660            self.buffer.update(cx, |buffer, cx| {
10661                buffer.finalize_last_transaction(cx);
10662                if self.leader_peer_id.is_none() {
10663                    buffer.set_active_selections(
10664                        &self.selections.disjoint_anchors(),
10665                        self.selections.line_mode,
10666                        self.cursor_shape,
10667                        cx,
10668                    );
10669                }
10670            });
10671        }
10672    }
10673
10674    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
10675        self.blink_manager.update(cx, BlinkManager::disable);
10676        self.buffer
10677            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
10678
10679        if let Some(blame) = self.blame.as_ref() {
10680            blame.update(cx, GitBlame::blur)
10681        }
10682        self.hide_context_menu(cx);
10683        hide_hover(self, cx);
10684        cx.emit(EditorEvent::Blurred);
10685        cx.notify();
10686    }
10687
10688    pub fn register_action<A: Action>(
10689        &mut self,
10690        listener: impl Fn(&A, &mut WindowContext) + 'static,
10691    ) -> &mut Self {
10692        let listener = Arc::new(listener);
10693
10694        self.editor_actions.push(Box::new(move |cx| {
10695            let _view = cx.view().clone();
10696            let cx = cx.window_context();
10697            let listener = listener.clone();
10698            cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
10699                let action = action.downcast_ref().unwrap();
10700                if phase == DispatchPhase::Bubble {
10701                    listener(action, cx)
10702                }
10703            })
10704        }));
10705        self
10706    }
10707}
10708
10709fn hunks_for_selections(
10710    multi_buffer_snapshot: &MultiBufferSnapshot,
10711    selections: &[Selection<Anchor>],
10712) -> Vec<DiffHunk<MultiBufferRow>> {
10713    let mut hunks = Vec::with_capacity(selections.len());
10714    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
10715        HashMap::default();
10716    let buffer_rows_for_selections = selections.iter().map(|selection| {
10717        let head = selection.head();
10718        let tail = selection.tail();
10719        let start = MultiBufferRow(tail.to_point(&multi_buffer_snapshot).row);
10720        let end = MultiBufferRow(head.to_point(&multi_buffer_snapshot).row);
10721        if start > end {
10722            end..start
10723        } else {
10724            start..end
10725        }
10726    });
10727
10728    for selected_multi_buffer_rows in buffer_rows_for_selections {
10729        let query_rows =
10730            selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
10731        for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
10732            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
10733            // when the caret is just above or just below the deleted hunk.
10734            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
10735            let related_to_selection = if allow_adjacent {
10736                hunk.associated_range.overlaps(&query_rows)
10737                    || hunk.associated_range.start == query_rows.end
10738                    || hunk.associated_range.end == query_rows.start
10739            } else {
10740                // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
10741                // `hunk.associated_range` is exclusive (e.g. [2..3] means 2nd row is selected)
10742                hunk.associated_range.overlaps(&selected_multi_buffer_rows)
10743                    || selected_multi_buffer_rows.end == hunk.associated_range.start
10744            };
10745            if related_to_selection {
10746                if !processed_buffer_rows
10747                    .entry(hunk.buffer_id)
10748                    .or_default()
10749                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
10750                {
10751                    continue;
10752                }
10753                hunks.push(hunk);
10754            }
10755        }
10756    }
10757
10758    hunks
10759}
10760
10761pub trait CollaborationHub {
10762    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
10763    fn user_participant_indices<'a>(
10764        &self,
10765        cx: &'a AppContext,
10766    ) -> &'a HashMap<u64, ParticipantIndex>;
10767    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
10768}
10769
10770impl CollaborationHub for Model<Project> {
10771    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
10772        self.read(cx).collaborators()
10773    }
10774
10775    fn user_participant_indices<'a>(
10776        &self,
10777        cx: &'a AppContext,
10778    ) -> &'a HashMap<u64, ParticipantIndex> {
10779        self.read(cx).user_store().read(cx).participant_indices()
10780    }
10781
10782    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
10783        let this = self.read(cx);
10784        let user_ids = this.collaborators().values().map(|c| c.user_id);
10785        this.user_store().read_with(cx, |user_store, cx| {
10786            user_store.participant_names(user_ids, cx)
10787        })
10788    }
10789}
10790
10791pub trait CompletionProvider {
10792    fn completions(
10793        &self,
10794        buffer: &Model<Buffer>,
10795        buffer_position: text::Anchor,
10796        cx: &mut ViewContext<Editor>,
10797    ) -> Task<Result<Vec<Completion>>>;
10798
10799    fn resolve_completions(
10800        &self,
10801        buffer: Model<Buffer>,
10802        completion_indices: Vec<usize>,
10803        completions: Arc<RwLock<Box<[Completion]>>>,
10804        cx: &mut ViewContext<Editor>,
10805    ) -> Task<Result<bool>>;
10806
10807    fn apply_additional_edits_for_completion(
10808        &self,
10809        buffer: Model<Buffer>,
10810        completion: Completion,
10811        push_to_history: bool,
10812        cx: &mut ViewContext<Editor>,
10813    ) -> Task<Result<Option<language::Transaction>>>;
10814}
10815
10816impl CompletionProvider for Model<Project> {
10817    fn completions(
10818        &self,
10819        buffer: &Model<Buffer>,
10820        buffer_position: text::Anchor,
10821        cx: &mut ViewContext<Editor>,
10822    ) -> Task<Result<Vec<Completion>>> {
10823        self.update(cx, |project, cx| {
10824            project.completions(&buffer, buffer_position, cx)
10825        })
10826    }
10827
10828    fn resolve_completions(
10829        &self,
10830        buffer: Model<Buffer>,
10831        completion_indices: Vec<usize>,
10832        completions: Arc<RwLock<Box<[Completion]>>>,
10833        cx: &mut ViewContext<Editor>,
10834    ) -> Task<Result<bool>> {
10835        self.update(cx, |project, cx| {
10836            project.resolve_completions(buffer, completion_indices, completions, cx)
10837        })
10838    }
10839
10840    fn apply_additional_edits_for_completion(
10841        &self,
10842        buffer: Model<Buffer>,
10843        completion: Completion,
10844        push_to_history: bool,
10845        cx: &mut ViewContext<Editor>,
10846    ) -> Task<Result<Option<language::Transaction>>> {
10847        self.update(cx, |project, cx| {
10848            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
10849        })
10850    }
10851}
10852
10853fn inlay_hint_settings(
10854    location: Anchor,
10855    snapshot: &MultiBufferSnapshot,
10856    cx: &mut ViewContext<'_, Editor>,
10857) -> InlayHintSettings {
10858    let file = snapshot.file_at(location);
10859    let language = snapshot.language_at(location);
10860    let settings = all_language_settings(file, cx);
10861    settings
10862        .language(language.map(|l| l.name()).as_deref())
10863        .inlay_hints
10864}
10865
10866fn consume_contiguous_rows(
10867    contiguous_row_selections: &mut Vec<Selection<Point>>,
10868    selection: &Selection<Point>,
10869    display_map: &DisplaySnapshot,
10870    selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
10871) -> (MultiBufferRow, MultiBufferRow) {
10872    contiguous_row_selections.push(selection.clone());
10873    let start_row = MultiBufferRow(selection.start.row);
10874    let mut end_row = ending_row(selection, display_map);
10875
10876    while let Some(next_selection) = selections.peek() {
10877        if next_selection.start.row <= end_row.0 {
10878            end_row = ending_row(next_selection, display_map);
10879            contiguous_row_selections.push(selections.next().unwrap().clone());
10880        } else {
10881            break;
10882        }
10883    }
10884    (start_row, end_row)
10885}
10886
10887fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
10888    if next_selection.end.column > 0 || next_selection.is_empty() {
10889        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
10890    } else {
10891        MultiBufferRow(next_selection.end.row)
10892    }
10893}
10894
10895impl EditorSnapshot {
10896    pub fn remote_selections_in_range<'a>(
10897        &'a self,
10898        range: &'a Range<Anchor>,
10899        collaboration_hub: &dyn CollaborationHub,
10900        cx: &'a AppContext,
10901    ) -> impl 'a + Iterator<Item = RemoteSelection> {
10902        let participant_names = collaboration_hub.user_names(cx);
10903        let participant_indices = collaboration_hub.user_participant_indices(cx);
10904        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
10905        let collaborators_by_replica_id = collaborators_by_peer_id
10906            .iter()
10907            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
10908            .collect::<HashMap<_, _>>();
10909        self.buffer_snapshot
10910            .remote_selections_in_range(range)
10911            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
10912                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
10913                let participant_index = participant_indices.get(&collaborator.user_id).copied();
10914                let user_name = participant_names.get(&collaborator.user_id).cloned();
10915                Some(RemoteSelection {
10916                    replica_id,
10917                    selection,
10918                    cursor_shape,
10919                    line_mode,
10920                    participant_index,
10921                    peer_id: collaborator.peer_id,
10922                    user_name,
10923                })
10924            })
10925    }
10926
10927    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
10928        self.display_snapshot.buffer_snapshot.language_at(position)
10929    }
10930
10931    pub fn is_focused(&self) -> bool {
10932        self.is_focused
10933    }
10934
10935    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
10936        self.placeholder_text.as_ref()
10937    }
10938
10939    pub fn scroll_position(&self) -> gpui::Point<f32> {
10940        self.scroll_anchor.scroll_position(&self.display_snapshot)
10941    }
10942
10943    pub fn gutter_dimensions(
10944        &self,
10945        font_id: FontId,
10946        font_size: Pixels,
10947        em_width: Pixels,
10948        max_line_number_width: Pixels,
10949        cx: &AppContext,
10950    ) -> GutterDimensions {
10951        if !self.show_gutter {
10952            return GutterDimensions::default();
10953        }
10954        let descent = cx.text_system().descent(font_id, font_size);
10955
10956        let show_git_gutter = matches!(
10957            ProjectSettings::get_global(cx).git.git_gutter,
10958            Some(GitGutterSetting::TrackedFiles)
10959        );
10960        let gutter_settings = EditorSettings::get_global(cx).gutter;
10961        let gutter_lines_enabled = gutter_settings.line_numbers;
10962        let line_gutter_width = if gutter_lines_enabled {
10963            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
10964            let min_width_for_number_on_gutter = em_width * 4.0;
10965            max_line_number_width.max(min_width_for_number_on_gutter)
10966        } else {
10967            0.0.into()
10968        };
10969
10970        let git_blame_entries_width = self
10971            .render_git_blame_gutter
10972            .then_some(em_width * GIT_BLAME_GUTTER_WIDTH_CHARS);
10973
10974        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
10975        left_padding += if gutter_settings.code_actions {
10976            em_width * 3.0
10977        } else if show_git_gutter && gutter_lines_enabled {
10978            em_width * 2.0
10979        } else if show_git_gutter || gutter_lines_enabled {
10980            em_width
10981        } else {
10982            px(0.)
10983        };
10984
10985        let right_padding = if gutter_settings.folds && gutter_lines_enabled {
10986            em_width * 4.0
10987        } else if gutter_settings.folds {
10988            em_width * 3.0
10989        } else if gutter_lines_enabled {
10990            em_width
10991        } else {
10992            px(0.)
10993        };
10994
10995        GutterDimensions {
10996            left_padding,
10997            right_padding,
10998            width: line_gutter_width + left_padding + right_padding,
10999            margin: -descent,
11000            git_blame_entries_width,
11001        }
11002    }
11003}
11004
11005impl Deref for EditorSnapshot {
11006    type Target = DisplaySnapshot;
11007
11008    fn deref(&self) -> &Self::Target {
11009        &self.display_snapshot
11010    }
11011}
11012
11013#[derive(Clone, Debug, PartialEq, Eq)]
11014pub enum EditorEvent {
11015    InputIgnored {
11016        text: Arc<str>,
11017    },
11018    InputHandled {
11019        utf16_range_to_replace: Option<Range<isize>>,
11020        text: Arc<str>,
11021    },
11022    ExcerptsAdded {
11023        buffer: Model<Buffer>,
11024        predecessor: ExcerptId,
11025        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
11026    },
11027    ExcerptsRemoved {
11028        ids: Vec<ExcerptId>,
11029    },
11030    BufferEdited,
11031    Edited,
11032    Reparsed,
11033    Focused,
11034    Blurred,
11035    DirtyChanged,
11036    Saved,
11037    TitleChanged,
11038    DiffBaseChanged,
11039    SelectionsChanged {
11040        local: bool,
11041    },
11042    ScrollPositionChanged {
11043        local: bool,
11044        autoscroll: bool,
11045    },
11046    Closed,
11047    TransactionUndone {
11048        transaction_id: clock::Lamport,
11049    },
11050    TransactionBegun {
11051        transaction_id: clock::Lamport,
11052    },
11053}
11054
11055impl EventEmitter<EditorEvent> for Editor {}
11056
11057impl FocusableView for Editor {
11058    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
11059        self.focus_handle.clone()
11060    }
11061}
11062
11063impl Render for Editor {
11064    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
11065        let settings = ThemeSettings::get_global(cx);
11066
11067        let text_style = match self.mode {
11068            EditorMode::SingleLine | EditorMode::AutoHeight { .. } => TextStyle {
11069                color: cx.theme().colors().editor_foreground,
11070                font_family: settings.ui_font.family.clone(),
11071                font_features: settings.ui_font.features.clone(),
11072                font_size: rems(0.875).into(),
11073                font_weight: FontWeight::NORMAL,
11074                font_style: FontStyle::Normal,
11075                line_height: relative(settings.buffer_line_height.value()),
11076                background_color: None,
11077                underline: None,
11078                strikethrough: None,
11079                white_space: WhiteSpace::Normal,
11080            },
11081            EditorMode::Full => TextStyle {
11082                color: cx.theme().colors().editor_foreground,
11083                font_family: settings.buffer_font.family.clone(),
11084                font_features: settings.buffer_font.features.clone(),
11085                font_size: settings.buffer_font_size(cx).into(),
11086                font_weight: FontWeight::NORMAL,
11087                font_style: FontStyle::Normal,
11088                line_height: relative(settings.buffer_line_height.value()),
11089                background_color: None,
11090                underline: None,
11091                strikethrough: None,
11092                white_space: WhiteSpace::Normal,
11093            },
11094        };
11095
11096        let background = match self.mode {
11097            EditorMode::SingleLine => cx.theme().system().transparent,
11098            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
11099            EditorMode::Full => cx.theme().colors().editor_background,
11100        };
11101
11102        EditorElement::new(
11103            cx.view(),
11104            EditorStyle {
11105                background,
11106                local_player: cx.theme().players().local(),
11107                text: text_style,
11108                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
11109                syntax: cx.theme().syntax().clone(),
11110                status: cx.theme().status().clone(),
11111                inlay_hints_style: HighlightStyle {
11112                    color: Some(cx.theme().status().hint),
11113                    ..HighlightStyle::default()
11114                },
11115                suggestions_style: HighlightStyle {
11116                    color: Some(cx.theme().status().predictive),
11117                    ..HighlightStyle::default()
11118                },
11119            },
11120        )
11121    }
11122}
11123
11124impl ViewInputHandler for Editor {
11125    fn text_for_range(
11126        &mut self,
11127        range_utf16: Range<usize>,
11128        cx: &mut ViewContext<Self>,
11129    ) -> Option<String> {
11130        Some(
11131            self.buffer
11132                .read(cx)
11133                .read(cx)
11134                .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
11135                .collect(),
11136        )
11137    }
11138
11139    fn selected_text_range(&mut self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
11140        // Prevent the IME menu from appearing when holding down an alphabetic key
11141        // while input is disabled.
11142        if !self.input_enabled {
11143            return None;
11144        }
11145
11146        let range = self.selections.newest::<OffsetUtf16>(cx).range();
11147        Some(range.start.0..range.end.0)
11148    }
11149
11150    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
11151        let snapshot = self.buffer.read(cx).read(cx);
11152        let range = self.text_highlights::<InputComposition>(cx)?.1.get(0)?;
11153        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
11154    }
11155
11156    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
11157        self.clear_highlights::<InputComposition>(cx);
11158        self.ime_transaction.take();
11159    }
11160
11161    fn replace_text_in_range(
11162        &mut self,
11163        range_utf16: Option<Range<usize>>,
11164        text: &str,
11165        cx: &mut ViewContext<Self>,
11166    ) {
11167        if !self.input_enabled {
11168            cx.emit(EditorEvent::InputIgnored { text: text.into() });
11169            return;
11170        }
11171
11172        self.transact(cx, |this, cx| {
11173            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
11174                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
11175                Some(this.selection_replacement_ranges(range_utf16, cx))
11176            } else {
11177                this.marked_text_ranges(cx)
11178            };
11179
11180            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
11181                let newest_selection_id = this.selections.newest_anchor().id;
11182                this.selections
11183                    .all::<OffsetUtf16>(cx)
11184                    .iter()
11185                    .zip(ranges_to_replace.iter())
11186                    .find_map(|(selection, range)| {
11187                        if selection.id == newest_selection_id {
11188                            Some(
11189                                (range.start.0 as isize - selection.head().0 as isize)
11190                                    ..(range.end.0 as isize - selection.head().0 as isize),
11191                            )
11192                        } else {
11193                            None
11194                        }
11195                    })
11196            });
11197
11198            cx.emit(EditorEvent::InputHandled {
11199                utf16_range_to_replace: range_to_replace,
11200                text: text.into(),
11201            });
11202
11203            if let Some(new_selected_ranges) = new_selected_ranges {
11204                this.change_selections(None, cx, |selections| {
11205                    selections.select_ranges(new_selected_ranges)
11206                });
11207                this.backspace(&Default::default(), cx);
11208            }
11209
11210            this.handle_input(text, cx);
11211        });
11212
11213        if let Some(transaction) = self.ime_transaction {
11214            self.buffer.update(cx, |buffer, cx| {
11215                buffer.group_until_transaction(transaction, cx);
11216            });
11217        }
11218
11219        self.unmark_text(cx);
11220    }
11221
11222    fn replace_and_mark_text_in_range(
11223        &mut self,
11224        range_utf16: Option<Range<usize>>,
11225        text: &str,
11226        new_selected_range_utf16: Option<Range<usize>>,
11227        cx: &mut ViewContext<Self>,
11228    ) {
11229        if !self.input_enabled {
11230            cx.emit(EditorEvent::InputIgnored { text: text.into() });
11231            return;
11232        }
11233
11234        let transaction = self.transact(cx, |this, cx| {
11235            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
11236                let snapshot = this.buffer.read(cx).read(cx);
11237                if let Some(relative_range_utf16) = range_utf16.as_ref() {
11238                    for marked_range in &mut marked_ranges {
11239                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
11240                        marked_range.start.0 += relative_range_utf16.start;
11241                        marked_range.start =
11242                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
11243                        marked_range.end =
11244                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
11245                    }
11246                }
11247                Some(marked_ranges)
11248            } else if let Some(range_utf16) = range_utf16 {
11249                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
11250                Some(this.selection_replacement_ranges(range_utf16, cx))
11251            } else {
11252                None
11253            };
11254
11255            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
11256                let newest_selection_id = this.selections.newest_anchor().id;
11257                this.selections
11258                    .all::<OffsetUtf16>(cx)
11259                    .iter()
11260                    .zip(ranges_to_replace.iter())
11261                    .find_map(|(selection, range)| {
11262                        if selection.id == newest_selection_id {
11263                            Some(
11264                                (range.start.0 as isize - selection.head().0 as isize)
11265                                    ..(range.end.0 as isize - selection.head().0 as isize),
11266                            )
11267                        } else {
11268                            None
11269                        }
11270                    })
11271            });
11272
11273            cx.emit(EditorEvent::InputHandled {
11274                utf16_range_to_replace: range_to_replace,
11275                text: text.into(),
11276            });
11277
11278            if let Some(ranges) = ranges_to_replace {
11279                this.change_selections(None, cx, |s| s.select_ranges(ranges));
11280            }
11281
11282            let marked_ranges = {
11283                let snapshot = this.buffer.read(cx).read(cx);
11284                this.selections
11285                    .disjoint_anchors()
11286                    .iter()
11287                    .map(|selection| {
11288                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
11289                    })
11290                    .collect::<Vec<_>>()
11291            };
11292
11293            if text.is_empty() {
11294                this.unmark_text(cx);
11295            } else {
11296                this.highlight_text::<InputComposition>(
11297                    marked_ranges.clone(),
11298                    HighlightStyle {
11299                        underline: Some(UnderlineStyle {
11300                            thickness: px(1.),
11301                            color: None,
11302                            wavy: false,
11303                        }),
11304                        ..Default::default()
11305                    },
11306                    cx,
11307                );
11308            }
11309
11310            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
11311            let use_autoclose = this.use_autoclose;
11312            this.set_use_autoclose(false);
11313            this.handle_input(text, cx);
11314            this.set_use_autoclose(use_autoclose);
11315
11316            if let Some(new_selected_range) = new_selected_range_utf16 {
11317                let snapshot = this.buffer.read(cx).read(cx);
11318                let new_selected_ranges = marked_ranges
11319                    .into_iter()
11320                    .map(|marked_range| {
11321                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
11322                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
11323                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
11324                        snapshot.clip_offset_utf16(new_start, Bias::Left)
11325                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
11326                    })
11327                    .collect::<Vec<_>>();
11328
11329                drop(snapshot);
11330                this.change_selections(None, cx, |selections| {
11331                    selections.select_ranges(new_selected_ranges)
11332                });
11333            }
11334        });
11335
11336        self.ime_transaction = self.ime_transaction.or(transaction);
11337        if let Some(transaction) = self.ime_transaction {
11338            self.buffer.update(cx, |buffer, cx| {
11339                buffer.group_until_transaction(transaction, cx);
11340            });
11341        }
11342
11343        if self.text_highlights::<InputComposition>(cx).is_none() {
11344            self.ime_transaction.take();
11345        }
11346    }
11347
11348    fn bounds_for_range(
11349        &mut self,
11350        range_utf16: Range<usize>,
11351        element_bounds: gpui::Bounds<Pixels>,
11352        cx: &mut ViewContext<Self>,
11353    ) -> Option<gpui::Bounds<Pixels>> {
11354        let text_layout_details = self.text_layout_details(cx);
11355        let style = &text_layout_details.editor_style;
11356        let font_id = cx.text_system().resolve_font(&style.text.font());
11357        let font_size = style.text.font_size.to_pixels(cx.rem_size());
11358        let line_height = style.text.line_height_in_pixels(cx.rem_size());
11359        let em_width = cx
11360            .text_system()
11361            .typographic_bounds(font_id, font_size, 'm')
11362            .unwrap()
11363            .size
11364            .width;
11365
11366        let snapshot = self.snapshot(cx);
11367        let scroll_position = snapshot.scroll_position();
11368        let scroll_left = scroll_position.x * em_width;
11369
11370        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
11371        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
11372            + self.gutter_dimensions.width;
11373        let y = line_height * (start.row().as_f32() - scroll_position.y);
11374
11375        Some(Bounds {
11376            origin: element_bounds.origin + point(x, y),
11377            size: size(em_width, line_height),
11378        })
11379    }
11380}
11381
11382trait SelectionExt {
11383    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
11384    fn spanned_rows(
11385        &self,
11386        include_end_if_at_line_start: bool,
11387        map: &DisplaySnapshot,
11388    ) -> Range<MultiBufferRow>;
11389}
11390
11391impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
11392    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
11393        let start = self
11394            .start
11395            .to_point(&map.buffer_snapshot)
11396            .to_display_point(map);
11397        let end = self
11398            .end
11399            .to_point(&map.buffer_snapshot)
11400            .to_display_point(map);
11401        if self.reversed {
11402            end..start
11403        } else {
11404            start..end
11405        }
11406    }
11407
11408    fn spanned_rows(
11409        &self,
11410        include_end_if_at_line_start: bool,
11411        map: &DisplaySnapshot,
11412    ) -> Range<MultiBufferRow> {
11413        let start = self.start.to_point(&map.buffer_snapshot);
11414        let mut end = self.end.to_point(&map.buffer_snapshot);
11415        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
11416            end.row -= 1;
11417        }
11418
11419        let buffer_start = map.prev_line_boundary(start).0;
11420        let buffer_end = map.next_line_boundary(end).0;
11421        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
11422    }
11423}
11424
11425impl<T: InvalidationRegion> InvalidationStack<T> {
11426    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
11427    where
11428        S: Clone + ToOffset,
11429    {
11430        while let Some(region) = self.last() {
11431            let all_selections_inside_invalidation_ranges =
11432                if selections.len() == region.ranges().len() {
11433                    selections
11434                        .iter()
11435                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
11436                        .all(|(selection, invalidation_range)| {
11437                            let head = selection.head().to_offset(buffer);
11438                            invalidation_range.start <= head && invalidation_range.end >= head
11439                        })
11440                } else {
11441                    false
11442                };
11443
11444            if all_selections_inside_invalidation_ranges {
11445                break;
11446            } else {
11447                self.pop();
11448            }
11449        }
11450    }
11451}
11452
11453impl<T> Default for InvalidationStack<T> {
11454    fn default() -> Self {
11455        Self(Default::default())
11456    }
11457}
11458
11459impl<T> Deref for InvalidationStack<T> {
11460    type Target = Vec<T>;
11461
11462    fn deref(&self) -> &Self::Target {
11463        &self.0
11464    }
11465}
11466
11467impl<T> DerefMut for InvalidationStack<T> {
11468    fn deref_mut(&mut self) -> &mut Self::Target {
11469        &mut self.0
11470    }
11471}
11472
11473impl InvalidationRegion for SnippetState {
11474    fn ranges(&self) -> &[Range<Anchor>] {
11475        &self.ranges[self.active_index]
11476    }
11477}
11478
11479pub fn diagnostic_block_renderer(diagnostic: Diagnostic, _is_valid: bool) -> RenderBlock {
11480    let (text_without_backticks, code_ranges) = highlight_diagnostic_message(&diagnostic);
11481
11482    Box::new(move |cx: &mut BlockContext| {
11483        let group_id: SharedString = cx.block_id.to_string().into();
11484
11485        let mut text_style = cx.text_style().clone();
11486        text_style.color = diagnostic_style(diagnostic.severity, true, cx.theme().status());
11487        let theme_settings = ThemeSettings::get_global(cx);
11488        text_style.font_family = theme_settings.buffer_font.family.clone();
11489        text_style.font_style = theme_settings.buffer_font.style;
11490        text_style.font_features = theme_settings.buffer_font.features.clone();
11491        text_style.font_weight = theme_settings.buffer_font.weight;
11492
11493        let multi_line_diagnostic = diagnostic.message.contains('\n');
11494
11495        let buttons = |diagnostic: &Diagnostic, block_id: usize| {
11496            if multi_line_diagnostic {
11497                v_flex()
11498            } else {
11499                h_flex()
11500            }
11501            .children(diagnostic.is_primary.then(|| {
11502                IconButton::new(("close-block", block_id), IconName::XCircle)
11503                    .icon_color(Color::Muted)
11504                    .size(ButtonSize::Compact)
11505                    .style(ButtonStyle::Transparent)
11506                    .visible_on_hover(group_id.clone())
11507                    .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
11508                    .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
11509            }))
11510            .child(
11511                IconButton::new(("copy-block", block_id), IconName::Copy)
11512                    .icon_color(Color::Muted)
11513                    .size(ButtonSize::Compact)
11514                    .style(ButtonStyle::Transparent)
11515                    .visible_on_hover(group_id.clone())
11516                    .on_click({
11517                        let message = diagnostic.message.clone();
11518                        move |_click, cx| cx.write_to_clipboard(ClipboardItem::new(message.clone()))
11519                    })
11520                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
11521            )
11522        };
11523
11524        let icon_size = buttons(&diagnostic, cx.block_id)
11525            .into_any_element()
11526            .layout_as_root(AvailableSpace::min_size(), cx);
11527
11528        h_flex()
11529            .id(cx.block_id)
11530            .group(group_id.clone())
11531            .relative()
11532            .size_full()
11533            .pl(cx.gutter_dimensions.width)
11534            .w(cx.max_width + cx.gutter_dimensions.width)
11535            .child(
11536                div()
11537                    .flex()
11538                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
11539                    .flex_shrink(),
11540            )
11541            .child(buttons(&diagnostic, cx.block_id))
11542            .child(div().flex().flex_shrink_0().child(
11543                StyledText::new(text_without_backticks.clone()).with_highlights(
11544                    &text_style,
11545                    code_ranges.iter().map(|range| {
11546                        (
11547                            range.clone(),
11548                            HighlightStyle {
11549                                font_weight: Some(FontWeight::BOLD),
11550                                ..Default::default()
11551                            },
11552                        )
11553                    }),
11554                ),
11555            ))
11556            .into_any_element()
11557    })
11558}
11559
11560pub fn highlight_diagnostic_message(diagnostic: &Diagnostic) -> (SharedString, Vec<Range<usize>>) {
11561    let mut text_without_backticks = String::new();
11562    let mut code_ranges = Vec::new();
11563
11564    if let Some(source) = &diagnostic.source {
11565        text_without_backticks.push_str(&source);
11566        code_ranges.push(0..source.len());
11567        text_without_backticks.push_str(": ");
11568    }
11569
11570    let mut prev_offset = 0;
11571    let mut in_code_block = false;
11572    for (ix, _) in diagnostic
11573        .message
11574        .match_indices('`')
11575        .chain([(diagnostic.message.len(), "")])
11576    {
11577        let prev_len = text_without_backticks.len();
11578        text_without_backticks.push_str(&diagnostic.message[prev_offset..ix]);
11579        prev_offset = ix + 1;
11580        if in_code_block {
11581            code_ranges.push(prev_len..text_without_backticks.len());
11582            in_code_block = false;
11583        } else {
11584            in_code_block = true;
11585        }
11586    }
11587
11588    (text_without_backticks.into(), code_ranges)
11589}
11590
11591fn diagnostic_style(severity: DiagnosticSeverity, valid: bool, colors: &StatusColors) -> Hsla {
11592    match (severity, valid) {
11593        (DiagnosticSeverity::ERROR, true) => colors.error,
11594        (DiagnosticSeverity::ERROR, false) => colors.error,
11595        (DiagnosticSeverity::WARNING, true) => colors.warning,
11596        (DiagnosticSeverity::WARNING, false) => colors.warning,
11597        (DiagnosticSeverity::INFORMATION, true) => colors.info,
11598        (DiagnosticSeverity::INFORMATION, false) => colors.info,
11599        (DiagnosticSeverity::HINT, true) => colors.info,
11600        (DiagnosticSeverity::HINT, false) => colors.info,
11601        _ => colors.ignored,
11602    }
11603}
11604
11605pub fn styled_runs_for_code_label<'a>(
11606    label: &'a CodeLabel,
11607    syntax_theme: &'a theme::SyntaxTheme,
11608) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
11609    let fade_out = HighlightStyle {
11610        fade_out: Some(0.35),
11611        ..Default::default()
11612    };
11613
11614    let mut prev_end = label.filter_range.end;
11615    label
11616        .runs
11617        .iter()
11618        .enumerate()
11619        .flat_map(move |(ix, (range, highlight_id))| {
11620            let style = if let Some(style) = highlight_id.style(syntax_theme) {
11621                style
11622            } else {
11623                return Default::default();
11624            };
11625            let mut muted_style = style;
11626            muted_style.highlight(fade_out);
11627
11628            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
11629            if range.start >= label.filter_range.end {
11630                if range.start > prev_end {
11631                    runs.push((prev_end..range.start, fade_out));
11632                }
11633                runs.push((range.clone(), muted_style));
11634            } else if range.end <= label.filter_range.end {
11635                runs.push((range.clone(), style));
11636            } else {
11637                runs.push((range.start..label.filter_range.end, style));
11638                runs.push((label.filter_range.end..range.end, muted_style));
11639            }
11640            prev_end = cmp::max(prev_end, range.end);
11641
11642            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
11643                runs.push((prev_end..label.text.len(), fade_out));
11644            }
11645
11646            runs
11647        })
11648}
11649
11650pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
11651    let mut prev_index = 0;
11652    let mut prev_codepoint: Option<char> = None;
11653    text.char_indices()
11654        .chain([(text.len(), '\0')])
11655        .filter_map(move |(index, codepoint)| {
11656            let prev_codepoint = prev_codepoint.replace(codepoint)?;
11657            let is_boundary = index == text.len()
11658                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
11659                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
11660            if is_boundary {
11661                let chunk = &text[prev_index..index];
11662                prev_index = index;
11663                Some(chunk)
11664            } else {
11665                None
11666            }
11667        })
11668}
11669
11670trait RangeToAnchorExt {
11671    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
11672}
11673
11674impl<T: ToOffset> RangeToAnchorExt for Range<T> {
11675    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
11676        let start_offset = self.start.to_offset(snapshot);
11677        let end_offset = self.end.to_offset(snapshot);
11678        if start_offset == end_offset {
11679            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
11680        } else {
11681            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
11682        }
11683    }
11684}
11685
11686pub trait RowExt {
11687    fn as_f32(&self) -> f32;
11688
11689    fn next_row(&self) -> Self;
11690
11691    fn previous_row(&self) -> Self;
11692
11693    fn minus(&self, other: Self) -> u32;
11694}
11695
11696impl RowExt for DisplayRow {
11697    fn as_f32(&self) -> f32 {
11698        self.0 as f32
11699    }
11700
11701    fn next_row(&self) -> Self {
11702        Self(self.0 + 1)
11703    }
11704
11705    fn previous_row(&self) -> Self {
11706        Self(self.0.saturating_sub(1))
11707    }
11708
11709    fn minus(&self, other: Self) -> u32 {
11710        self.0 - other.0
11711    }
11712}
11713
11714impl RowExt for MultiBufferRow {
11715    fn as_f32(&self) -> f32 {
11716        self.0 as f32
11717    }
11718
11719    fn next_row(&self) -> Self {
11720        Self(self.0 + 1)
11721    }
11722
11723    fn previous_row(&self) -> Self {
11724        Self(self.0.saturating_sub(1))
11725    }
11726
11727    fn minus(&self, other: Self) -> u32 {
11728        self.0 - other.0
11729    }
11730}
11731
11732trait RowRangeExt {
11733    type Row;
11734
11735    fn len(&self) -> usize;
11736
11737    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
11738}
11739
11740impl RowRangeExt for Range<MultiBufferRow> {
11741    type Row = MultiBufferRow;
11742
11743    fn len(&self) -> usize {
11744        (self.end.0 - self.start.0) as usize
11745    }
11746
11747    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
11748        (self.start.0..self.end.0).map(MultiBufferRow)
11749    }
11750}
11751
11752impl RowRangeExt for Range<DisplayRow> {
11753    type Row = DisplayRow;
11754
11755    fn len(&self) -> usize {
11756        (self.end.0 - self.start.0) as usize
11757    }
11758
11759    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
11760        (self.start.0..self.end.0).map(DisplayRow)
11761    }
11762}
11763
11764fn hunk_status(hunk: &DiffHunk<MultiBufferRow>) -> DiffHunkStatus {
11765    if hunk.diff_base_byte_range.is_empty() {
11766        DiffHunkStatus::Added
11767    } else if hunk.associated_range.is_empty() {
11768        DiffHunkStatus::Removed
11769    } else {
11770        DiffHunkStatus::Modified
11771    }
11772}