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