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