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