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