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