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