editor.rs

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