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