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