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 behavior.
   15pub mod actions;
   16mod blame_entry_tooltip;
   17mod blink_manager;
   18mod clangd_ext;
   19mod debounced_delay;
   20pub mod display_map;
   21mod editor_settings;
   22mod editor_settings_controls;
   23mod element;
   24mod git;
   25mod highlight_matching_bracket;
   26mod hover_links;
   27mod hover_popover;
   28mod hunk_diff;
   29mod indent_guides;
   30mod inlay_hint_cache;
   31mod inline_completion_provider;
   32pub mod items;
   33mod linked_editing_ranges;
   34mod lsp_ext;
   35mod mouse_context_menu;
   36pub mod movement;
   37mod persistence;
   38mod proposed_changes_editor;
   39mod rust_analyzer_ext;
   40pub mod scroll;
   41mod selections_collection;
   42pub mod tasks;
   43
   44#[cfg(test)]
   45mod editor_tests;
   46mod signature_help;
   47#[cfg(any(test, feature = "test-support"))]
   48pub mod test;
   49
   50use ::git::diff::DiffHunkStatus;
   51pub(crate) use actions::*;
   52use aho_corasick::AhoCorasick;
   53use anyhow::{anyhow, Context as _, Result};
   54use blink_manager::BlinkManager;
   55use client::{Collaborator, ParticipantIndex};
   56use clock::ReplicaId;
   57use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
   58use convert_case::{Case, Casing};
   59use debounced_delay::DebouncedDelay;
   60use display_map::*;
   61pub use display_map::{DisplayPoint, FoldPlaceholder};
   62pub use editor_settings::{
   63    CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
   64};
   65pub use editor_settings_controls::*;
   66use element::LineWithInvisibles;
   67pub use element::{
   68    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   69};
   70use futures::{future, FutureExt};
   71use fuzzy::{StringMatch, StringMatchCandidate};
   72use git::blame::GitBlame;
   73use gpui::{
   74    div, impl_actions, point, prelude::*, px, relative, size, uniform_list, Action, AnyElement,
   75    AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds, ClipboardEntry,
   76    ClipboardItem, Context, DispatchPhase, ElementId, EventEmitter, FocusHandle, FocusOutEvent,
   77    FocusableView, FontId, FontWeight, HighlightStyle, Hsla, InteractiveText, KeyContext,
   78    ListSizingBehavior, Model, MouseButton, PaintQuad, ParentElement, Pixels, Render, SharedString,
   79    Size, StrikethroughStyle, Styled, StyledText, Subscription, Task, TextStyle,
   80    TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle, View,
   81    ViewContext, ViewInputHandler, VisualContext, WeakFocusHandle, WeakView, WindowContext,
   82};
   83use highlight_matching_bracket::refresh_matching_bracket_highlights;
   84use hover_popover::{hide_hover, HoverState};
   85pub(crate) use hunk_diff::HoveredHunk;
   86use hunk_diff::{diff_hunk_to_display, ExpandedHunks};
   87use indent_guides::ActiveIndentGuidesState;
   88use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   89pub use inline_completion_provider::*;
   90pub use items::MAX_TAB_TITLE_LEN;
   91use itertools::Itertools;
   92use language::{
   93    language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
   94    markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
   95    CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
   96    Point, Selection, SelectionGoal, TransactionId,
   97};
   98use language::{
   99    point_to_lsp, BufferRow, CharClassifier, LanguageServerName, Runnable, RunnableRange,
  100};
  101use linked_editing_ranges::refresh_linked_ranges;
  102pub use proposed_changes_editor::{
  103    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  104};
  105use similar::{ChangeTag, TextDiff};
  106use task::{ResolvedTask, TaskTemplate, TaskVariables};
  107
  108use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  109pub use lsp::CompletionContext;
  110use lsp::{
  111    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  112    LanguageServerId,
  113};
  114use mouse_context_menu::MouseContextMenu;
  115use movement::TextLayoutDetails;
  116pub use multi_buffer::{
  117    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
  118    ToPoint,
  119};
  120use multi_buffer::{
  121    ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
  122};
  123use ordered_float::OrderedFloat;
  124use parking_lot::{Mutex, RwLock};
  125use project::{
  126    lsp_store::{FormatTarget, FormatTrigger},
  127    project_settings::{GitGutterSetting, ProjectSettings},
  128    CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Item, Location,
  129    LocationLink, Project, ProjectPath, ProjectTransaction, TaskSourceKind,
  130};
  131use rand::prelude::*;
  132use rpc::{proto::*, ErrorExt};
  133use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  134use selections_collection::{resolve_multiple, MutableSelectionsCollection, SelectionsCollection};
  135use serde::{Deserialize, Serialize};
  136use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  137use smallvec::SmallVec;
  138use snippet::Snippet;
  139use std::{
  140    any::TypeId,
  141    borrow::Cow,
  142    cell::RefCell,
  143    cmp::{self, Ordering, Reverse},
  144    mem,
  145    num::NonZeroU32,
  146    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  147    path::{Path, PathBuf},
  148    rc::Rc,
  149    sync::Arc,
  150    time::{Duration, Instant},
  151};
  152pub use sum_tree::Bias;
  153use sum_tree::TreeMap;
  154use text::{BufferId, OffsetUtf16, Rope};
  155use theme::{
  156    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  157    ThemeColors, ThemeSettings,
  158};
  159use ui::{
  160    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
  161    ListItem, Popover, PopoverMenuHandle, Tooltip,
  162};
  163use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  164use workspace::item::{ItemHandle, PreviewTabsSettings};
  165use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
  166use workspace::{
  167    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  168};
  169use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  170
  171use crate::hover_links::find_url;
  172use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  173
  174pub const FILE_HEADER_HEIGHT: u32 = 2;
  175pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  176pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  177pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  178const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  179const MAX_LINE_LEN: usize = 1024;
  180const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  181const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  182pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  183#[doc(hidden)]
  184pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  185#[doc(hidden)]
  186pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
  187
  188pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  189pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  190
  191pub fn render_parsed_markdown(
  192    element_id: impl Into<ElementId>,
  193    parsed: &language::ParsedMarkdown,
  194    editor_style: &EditorStyle,
  195    workspace: Option<WeakView<Workspace>>,
  196    cx: &mut WindowContext,
  197) -> InteractiveText {
  198    let code_span_background_color = cx
  199        .theme()
  200        .colors()
  201        .editor_document_highlight_read_background;
  202
  203    let highlights = gpui::combine_highlights(
  204        parsed.highlights.iter().filter_map(|(range, highlight)| {
  205            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  206            Some((range.clone(), highlight))
  207        }),
  208        parsed
  209            .regions
  210            .iter()
  211            .zip(&parsed.region_ranges)
  212            .filter_map(|(region, range)| {
  213                if region.code {
  214                    Some((
  215                        range.clone(),
  216                        HighlightStyle {
  217                            background_color: Some(code_span_background_color),
  218                            ..Default::default()
  219                        },
  220                    ))
  221                } else {
  222                    None
  223                }
  224            }),
  225    );
  226    // hello
  227
  228    let mut links = Vec::new();
  229    let mut link_ranges = Vec::new();
  230    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  231        if let Some(link) = region.link.clone() {
  232            links.push(link);
  233            link_ranges.push(range.clone());
  234        }
  235    }
  236
  237    InteractiveText::new(
  238        element_id,
  239        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  240    )
  241    .on_click(link_ranges, move |clicked_range_ix, cx| {
  242        match &links[clicked_range_ix] {
  243            markdown::Link::Web { url } => cx.open_url(url),
  244            markdown::Link::Path { path } => {
  245                if let Some(workspace) = &workspace {
  246                    _ = workspace.update(cx, |workspace, cx| {
  247                        workspace.open_abs_path(path.clone(), false, cx).detach();
  248                    });
  249                }
  250            }
  251        }
  252    })
  253}
  254
  255#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  256pub(crate) enum InlayId {
  257    Suggestion(usize),
  258    Hint(usize),
  259}
  260
  261impl InlayId {
  262    fn id(&self) -> usize {
  263        match self {
  264            Self::Suggestion(id) => *id,
  265            Self::Hint(id) => *id,
  266        }
  267    }
  268}
  269
  270enum DiffRowHighlight {}
  271enum DocumentHighlightRead {}
  272enum DocumentHighlightWrite {}
  273enum InputComposition {}
  274
  275#[derive(Copy, Clone, PartialEq, Eq)]
  276pub enum Direction {
  277    Prev,
  278    Next,
  279}
  280
  281#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  282pub enum Navigated {
  283    Yes,
  284    No,
  285}
  286
  287impl Navigated {
  288    pub fn from_bool(yes: bool) -> Navigated {
  289        if yes {
  290            Navigated::Yes
  291        } else {
  292            Navigated::No
  293        }
  294    }
  295}
  296
  297pub fn init_settings(cx: &mut AppContext) {
  298    EditorSettings::register(cx);
  299}
  300
  301pub fn init(cx: &mut AppContext) {
  302    init_settings(cx);
  303
  304    workspace::register_project_item::<Editor>(cx);
  305    workspace::FollowableViewRegistry::register::<Editor>(cx);
  306    workspace::register_serializable_item::<Editor>(cx);
  307
  308    cx.observe_new_views(
  309        |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
  310            workspace.register_action(Editor::new_file);
  311            workspace.register_action(Editor::new_file_vertical);
  312            workspace.register_action(Editor::new_file_horizontal);
  313        },
  314    )
  315    .detach();
  316
  317    cx.on_action(move |_: &workspace::NewFile, cx| {
  318        let app_state = workspace::AppState::global(cx);
  319        if let Some(app_state) = app_state.upgrade() {
  320            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  321                Editor::new_file(workspace, &Default::default(), cx)
  322            })
  323            .detach();
  324        }
  325    });
  326    cx.on_action(move |_: &workspace::NewWindow, cx| {
  327        let app_state = workspace::AppState::global(cx);
  328        if let Some(app_state) = app_state.upgrade() {
  329            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  330                Editor::new_file(workspace, &Default::default(), cx)
  331            })
  332            .detach();
  333        }
  334    });
  335}
  336
  337pub struct SearchWithinRange;
  338
  339trait InvalidationRegion {
  340    fn ranges(&self) -> &[Range<Anchor>];
  341}
  342
  343#[derive(Clone, Debug, PartialEq)]
  344pub enum SelectPhase {
  345    Begin {
  346        position: DisplayPoint,
  347        add: bool,
  348        click_count: usize,
  349    },
  350    BeginColumnar {
  351        position: DisplayPoint,
  352        reset: bool,
  353        goal_column: u32,
  354    },
  355    Extend {
  356        position: DisplayPoint,
  357        click_count: usize,
  358    },
  359    Update {
  360        position: DisplayPoint,
  361        goal_column: u32,
  362        scroll_delta: gpui::Point<f32>,
  363    },
  364    End,
  365}
  366
  367#[derive(Clone, Debug)]
  368pub enum SelectMode {
  369    Character,
  370    Word(Range<Anchor>),
  371    Line(Range<Anchor>),
  372    All,
  373}
  374
  375#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  376pub enum EditorMode {
  377    SingleLine { auto_width: bool },
  378    AutoHeight { max_lines: usize },
  379    Full,
  380}
  381
  382#[derive(Copy, Clone, Debug)]
  383pub enum SoftWrap {
  384    /// Prefer not to wrap at all.
  385    ///
  386    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  387    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  388    GitDiff,
  389    /// Prefer a single line generally, unless an overly long line is encountered.
  390    None,
  391    /// Soft wrap lines that exceed the editor width.
  392    EditorWidth,
  393    /// Soft wrap lines at the preferred line length.
  394    Column(u32),
  395    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  396    Bounded(u32),
  397}
  398
  399#[derive(Clone)]
  400pub struct EditorStyle {
  401    pub background: Hsla,
  402    pub local_player: PlayerColor,
  403    pub text: TextStyle,
  404    pub scrollbar_width: Pixels,
  405    pub syntax: Arc<SyntaxTheme>,
  406    pub status: StatusColors,
  407    pub inlay_hints_style: HighlightStyle,
  408    pub suggestions_style: HighlightStyle,
  409    pub unnecessary_code_fade: f32,
  410}
  411
  412impl Default for EditorStyle {
  413    fn default() -> Self {
  414        Self {
  415            background: Hsla::default(),
  416            local_player: PlayerColor::default(),
  417            text: TextStyle::default(),
  418            scrollbar_width: Pixels::default(),
  419            syntax: Default::default(),
  420            // HACK: Status colors don't have a real default.
  421            // We should look into removing the status colors from the editor
  422            // style and retrieve them directly from the theme.
  423            status: StatusColors::dark(),
  424            inlay_hints_style: HighlightStyle::default(),
  425            suggestions_style: HighlightStyle::default(),
  426            unnecessary_code_fade: Default::default(),
  427        }
  428    }
  429}
  430
  431pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
  432    let show_background = language_settings::language_settings(None, None, cx)
  433        .inlay_hints
  434        .show_background;
  435
  436    HighlightStyle {
  437        color: Some(cx.theme().status().hint),
  438        background_color: show_background.then(|| cx.theme().status().hint_background),
  439        ..HighlightStyle::default()
  440    }
  441}
  442
  443type CompletionId = usize;
  444
  445#[derive(Clone, Debug)]
  446struct CompletionState {
  447    // render_inlay_ids represents the inlay hints that are inserted
  448    // for rendering the inline completions. They may be discontinuous
  449    // in the event that the completion provider returns some intersection
  450    // with the existing content.
  451    render_inlay_ids: Vec<InlayId>,
  452    // text is the resulting rope that is inserted when the user accepts a completion.
  453    text: Rope,
  454    // position is the position of the cursor when the completion was triggered.
  455    position: multi_buffer::Anchor,
  456    // delete_range is the range of text that this completion state covers.
  457    // if the completion is accepted, this range should be deleted.
  458    delete_range: Option<Range<multi_buffer::Anchor>>,
  459}
  460
  461#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  462struct EditorActionId(usize);
  463
  464impl EditorActionId {
  465    pub fn post_inc(&mut self) -> Self {
  466        let answer = self.0;
  467
  468        *self = Self(answer + 1);
  469
  470        Self(answer)
  471    }
  472}
  473
  474// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  475// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  476
  477type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  478type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
  479
  480#[derive(Default)]
  481struct ScrollbarMarkerState {
  482    scrollbar_size: Size<Pixels>,
  483    dirty: bool,
  484    markers: Arc<[PaintQuad]>,
  485    pending_refresh: Option<Task<Result<()>>>,
  486}
  487
  488impl ScrollbarMarkerState {
  489    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  490        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  491    }
  492}
  493
  494#[derive(Clone, Debug)]
  495struct RunnableTasks {
  496    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  497    offset: MultiBufferOffset,
  498    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  499    column: u32,
  500    // Values of all named captures, including those starting with '_'
  501    extra_variables: HashMap<String, String>,
  502    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  503    context_range: Range<BufferOffset>,
  504}
  505
  506#[derive(Clone)]
  507struct ResolvedTasks {
  508    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  509    position: Anchor,
  510}
  511#[derive(Copy, Clone, Debug)]
  512struct MultiBufferOffset(usize);
  513#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  514struct BufferOffset(usize);
  515
  516// Addons allow storing per-editor state in other crates (e.g. Vim)
  517pub trait Addon: 'static {
  518    fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
  519
  520    fn to_any(&self) -> &dyn std::any::Any;
  521}
  522
  523/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
  524///
  525/// See the [module level documentation](self) for more information.
  526pub struct Editor {
  527    focus_handle: FocusHandle,
  528    last_focused_descendant: Option<WeakFocusHandle>,
  529    /// The text buffer being edited
  530    buffer: Model<MultiBuffer>,
  531    /// Map of how text in the buffer should be displayed.
  532    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  533    pub display_map: Model<DisplayMap>,
  534    pub selections: SelectionsCollection,
  535    pub scroll_manager: ScrollManager,
  536    /// When inline assist editors are linked, they all render cursors because
  537    /// typing enters text into each of them, even the ones that aren't focused.
  538    pub(crate) show_cursor_when_unfocused: bool,
  539    columnar_selection_tail: Option<Anchor>,
  540    add_selections_state: Option<AddSelectionsState>,
  541    select_next_state: Option<SelectNextState>,
  542    select_prev_state: Option<SelectNextState>,
  543    selection_history: SelectionHistory,
  544    autoclose_regions: Vec<AutocloseRegion>,
  545    snippet_stack: InvalidationStack<SnippetState>,
  546    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  547    ime_transaction: Option<TransactionId>,
  548    active_diagnostics: Option<ActiveDiagnosticGroup>,
  549    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  550
  551    project: Option<Model<Project>>,
  552    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  553    completion_provider: Option<Box<dyn CompletionProvider>>,
  554    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  555    blink_manager: Model<BlinkManager>,
  556    show_cursor_names: bool,
  557    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  558    pub show_local_selections: bool,
  559    mode: EditorMode,
  560    show_breadcrumbs: bool,
  561    show_gutter: bool,
  562    show_line_numbers: Option<bool>,
  563    use_relative_line_numbers: Option<bool>,
  564    show_git_diff_gutter: Option<bool>,
  565    show_code_actions: Option<bool>,
  566    show_runnables: Option<bool>,
  567    show_wrap_guides: Option<bool>,
  568    show_indent_guides: Option<bool>,
  569    placeholder_text: Option<Arc<str>>,
  570    highlight_order: usize,
  571    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  572    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  573    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  574    scrollbar_marker_state: ScrollbarMarkerState,
  575    active_indent_guides_state: ActiveIndentGuidesState,
  576    nav_history: Option<ItemNavHistory>,
  577    context_menu: RwLock<Option<ContextMenu>>,
  578    mouse_context_menu: Option<MouseContextMenu>,
  579    hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
  580    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  581    signature_help_state: SignatureHelpState,
  582    auto_signature_help: Option<bool>,
  583    find_all_references_task_sources: Vec<Anchor>,
  584    next_completion_id: CompletionId,
  585    completion_documentation_pre_resolve_debounce: DebouncedDelay,
  586    available_code_actions: Option<(Location, Arc<[AvailableCodeAction]>)>,
  587    code_actions_task: Option<Task<Result<()>>>,
  588    document_highlights_task: Option<Task<()>>,
  589    linked_editing_range_task: Option<Task<Option<()>>>,
  590    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  591    pending_rename: Option<RenameState>,
  592    searchable: bool,
  593    cursor_shape: CursorShape,
  594    current_line_highlight: Option<CurrentLineHighlight>,
  595    collapse_matches: bool,
  596    autoindent_mode: Option<AutoindentMode>,
  597    workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
  598    input_enabled: bool,
  599    use_modal_editing: bool,
  600    read_only: bool,
  601    leader_peer_id: Option<PeerId>,
  602    remote_id: Option<ViewId>,
  603    hover_state: HoverState,
  604    gutter_hovered: bool,
  605    hovered_link_state: Option<HoveredLinkState>,
  606    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  607    code_action_providers: Vec<Arc<dyn CodeActionProvider>>,
  608    active_inline_completion: Option<CompletionState>,
  609    // enable_inline_completions is a switch that Vim can use to disable
  610    // inline completions based on its mode.
  611    enable_inline_completions: bool,
  612    show_inline_completions_override: Option<bool>,
  613    inlay_hint_cache: InlayHintCache,
  614    expanded_hunks: ExpandedHunks,
  615    next_inlay_id: usize,
  616    _subscriptions: Vec<Subscription>,
  617    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  618    gutter_dimensions: GutterDimensions,
  619    style: Option<EditorStyle>,
  620    text_style_refinement: Option<TextStyleRefinement>,
  621    next_editor_action_id: EditorActionId,
  622    editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
  623    use_autoclose: bool,
  624    use_auto_surround: bool,
  625    auto_replace_emoji_shortcode: bool,
  626    show_git_blame_gutter: bool,
  627    show_git_blame_inline: bool,
  628    show_git_blame_inline_delay_task: Option<Task<()>>,
  629    git_blame_inline_enabled: bool,
  630    serialize_dirty_buffers: bool,
  631    show_selection_menu: Option<bool>,
  632    blame: Option<Model<GitBlame>>,
  633    blame_subscription: Option<Subscription>,
  634    custom_context_menu: Option<
  635        Box<
  636            dyn 'static
  637                + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
  638        >,
  639    >,
  640    last_bounds: Option<Bounds<Pixels>>,
  641    expect_bounds_change: Option<Bounds<Pixels>>,
  642    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  643    tasks_update_task: Option<Task<()>>,
  644    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  645    breadcrumb_header: Option<String>,
  646    focused_block: Option<FocusedBlock>,
  647    next_scroll_position: NextScrollCursorCenterTopBottom,
  648    addons: HashMap<TypeId, Box<dyn Addon>>,
  649    _scroll_cursor_center_top_bottom_task: Task<()>,
  650}
  651
  652#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  653enum NextScrollCursorCenterTopBottom {
  654    #[default]
  655    Center,
  656    Top,
  657    Bottom,
  658}
  659
  660impl NextScrollCursorCenterTopBottom {
  661    fn next(&self) -> Self {
  662        match self {
  663            Self::Center => Self::Top,
  664            Self::Top => Self::Bottom,
  665            Self::Bottom => Self::Center,
  666        }
  667    }
  668}
  669
  670#[derive(Clone)]
  671pub struct EditorSnapshot {
  672    pub mode: EditorMode,
  673    show_gutter: bool,
  674    show_line_numbers: Option<bool>,
  675    show_git_diff_gutter: Option<bool>,
  676    show_code_actions: Option<bool>,
  677    show_runnables: Option<bool>,
  678    git_blame_gutter_max_author_length: Option<usize>,
  679    pub display_snapshot: DisplaySnapshot,
  680    pub placeholder_text: Option<Arc<str>>,
  681    is_focused: bool,
  682    scroll_anchor: ScrollAnchor,
  683    ongoing_scroll: OngoingScroll,
  684    current_line_highlight: CurrentLineHighlight,
  685    gutter_hovered: bool,
  686}
  687
  688const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  689
  690#[derive(Default, Debug, Clone, Copy)]
  691pub struct GutterDimensions {
  692    pub left_padding: Pixels,
  693    pub right_padding: Pixels,
  694    pub width: Pixels,
  695    pub margin: Pixels,
  696    pub git_blame_entries_width: Option<Pixels>,
  697}
  698
  699impl GutterDimensions {
  700    /// The full width of the space taken up by the gutter.
  701    pub fn full_width(&self) -> Pixels {
  702        self.margin + self.width
  703    }
  704
  705    /// The width of the space reserved for the fold indicators,
  706    /// use alongside 'justify_end' and `gutter_width` to
  707    /// right align content with the line numbers
  708    pub fn fold_area_width(&self) -> Pixels {
  709        self.margin + self.right_padding
  710    }
  711}
  712
  713#[derive(Debug)]
  714pub struct RemoteSelection {
  715    pub replica_id: ReplicaId,
  716    pub selection: Selection<Anchor>,
  717    pub cursor_shape: CursorShape,
  718    pub peer_id: PeerId,
  719    pub line_mode: bool,
  720    pub participant_index: Option<ParticipantIndex>,
  721    pub user_name: Option<SharedString>,
  722}
  723
  724#[derive(Clone, Debug)]
  725struct SelectionHistoryEntry {
  726    selections: Arc<[Selection<Anchor>]>,
  727    select_next_state: Option<SelectNextState>,
  728    select_prev_state: Option<SelectNextState>,
  729    add_selections_state: Option<AddSelectionsState>,
  730}
  731
  732enum SelectionHistoryMode {
  733    Normal,
  734    Undoing,
  735    Redoing,
  736}
  737
  738#[derive(Clone, PartialEq, Eq, Hash)]
  739struct HoveredCursor {
  740    replica_id: u16,
  741    selection_id: usize,
  742}
  743
  744impl Default for SelectionHistoryMode {
  745    fn default() -> Self {
  746        Self::Normal
  747    }
  748}
  749
  750#[derive(Default)]
  751struct SelectionHistory {
  752    #[allow(clippy::type_complexity)]
  753    selections_by_transaction:
  754        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  755    mode: SelectionHistoryMode,
  756    undo_stack: VecDeque<SelectionHistoryEntry>,
  757    redo_stack: VecDeque<SelectionHistoryEntry>,
  758}
  759
  760impl SelectionHistory {
  761    fn insert_transaction(
  762        &mut self,
  763        transaction_id: TransactionId,
  764        selections: Arc<[Selection<Anchor>]>,
  765    ) {
  766        self.selections_by_transaction
  767            .insert(transaction_id, (selections, None));
  768    }
  769
  770    #[allow(clippy::type_complexity)]
  771    fn transaction(
  772        &self,
  773        transaction_id: TransactionId,
  774    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  775        self.selections_by_transaction.get(&transaction_id)
  776    }
  777
  778    #[allow(clippy::type_complexity)]
  779    fn transaction_mut(
  780        &mut self,
  781        transaction_id: TransactionId,
  782    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  783        self.selections_by_transaction.get_mut(&transaction_id)
  784    }
  785
  786    fn push(&mut self, entry: SelectionHistoryEntry) {
  787        if !entry.selections.is_empty() {
  788            match self.mode {
  789                SelectionHistoryMode::Normal => {
  790                    self.push_undo(entry);
  791                    self.redo_stack.clear();
  792                }
  793                SelectionHistoryMode::Undoing => self.push_redo(entry),
  794                SelectionHistoryMode::Redoing => self.push_undo(entry),
  795            }
  796        }
  797    }
  798
  799    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  800        if self
  801            .undo_stack
  802            .back()
  803            .map_or(true, |e| e.selections != entry.selections)
  804        {
  805            self.undo_stack.push_back(entry);
  806            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  807                self.undo_stack.pop_front();
  808            }
  809        }
  810    }
  811
  812    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  813        if self
  814            .redo_stack
  815            .back()
  816            .map_or(true, |e| e.selections != entry.selections)
  817        {
  818            self.redo_stack.push_back(entry);
  819            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  820                self.redo_stack.pop_front();
  821            }
  822        }
  823    }
  824}
  825
  826struct RowHighlight {
  827    index: usize,
  828    range: Range<Anchor>,
  829    color: Hsla,
  830    should_autoscroll: bool,
  831}
  832
  833#[derive(Clone, Debug)]
  834struct AddSelectionsState {
  835    above: bool,
  836    stack: Vec<usize>,
  837}
  838
  839#[derive(Clone)]
  840struct SelectNextState {
  841    query: AhoCorasick,
  842    wordwise: bool,
  843    done: bool,
  844}
  845
  846impl std::fmt::Debug for SelectNextState {
  847    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  848        f.debug_struct(std::any::type_name::<Self>())
  849            .field("wordwise", &self.wordwise)
  850            .field("done", &self.done)
  851            .finish()
  852    }
  853}
  854
  855#[derive(Debug)]
  856struct AutocloseRegion {
  857    selection_id: usize,
  858    range: Range<Anchor>,
  859    pair: BracketPair,
  860}
  861
  862#[derive(Debug)]
  863struct SnippetState {
  864    ranges: Vec<Vec<Range<Anchor>>>,
  865    active_index: usize,
  866}
  867
  868#[doc(hidden)]
  869pub struct RenameState {
  870    pub range: Range<Anchor>,
  871    pub old_name: Arc<str>,
  872    pub editor: View<Editor>,
  873    block_id: CustomBlockId,
  874}
  875
  876struct InvalidationStack<T>(Vec<T>);
  877
  878struct RegisteredInlineCompletionProvider {
  879    provider: Arc<dyn InlineCompletionProviderHandle>,
  880    _subscription: Subscription,
  881}
  882
  883enum ContextMenu {
  884    Completions(CompletionsMenu),
  885    CodeActions(CodeActionsMenu),
  886}
  887
  888impl ContextMenu {
  889    fn select_first(
  890        &mut self,
  891        provider: Option<&dyn CompletionProvider>,
  892        cx: &mut ViewContext<Editor>,
  893    ) -> bool {
  894        if self.visible() {
  895            match self {
  896                ContextMenu::Completions(menu) => menu.select_first(provider, cx),
  897                ContextMenu::CodeActions(menu) => menu.select_first(cx),
  898            }
  899            true
  900        } else {
  901            false
  902        }
  903    }
  904
  905    fn select_prev(
  906        &mut self,
  907        provider: Option<&dyn CompletionProvider>,
  908        cx: &mut ViewContext<Editor>,
  909    ) -> bool {
  910        if self.visible() {
  911            match self {
  912                ContextMenu::Completions(menu) => menu.select_prev(provider, cx),
  913                ContextMenu::CodeActions(menu) => menu.select_prev(cx),
  914            }
  915            true
  916        } else {
  917            false
  918        }
  919    }
  920
  921    fn select_next(
  922        &mut self,
  923        provider: Option<&dyn CompletionProvider>,
  924        cx: &mut ViewContext<Editor>,
  925    ) -> bool {
  926        if self.visible() {
  927            match self {
  928                ContextMenu::Completions(menu) => menu.select_next(provider, cx),
  929                ContextMenu::CodeActions(menu) => menu.select_next(cx),
  930            }
  931            true
  932        } else {
  933            false
  934        }
  935    }
  936
  937    fn select_last(
  938        &mut self,
  939        provider: Option<&dyn CompletionProvider>,
  940        cx: &mut ViewContext<Editor>,
  941    ) -> bool {
  942        if self.visible() {
  943            match self {
  944                ContextMenu::Completions(menu) => menu.select_last(provider, cx),
  945                ContextMenu::CodeActions(menu) => menu.select_last(cx),
  946            }
  947            true
  948        } else {
  949            false
  950        }
  951    }
  952
  953    fn visible(&self) -> bool {
  954        match self {
  955            ContextMenu::Completions(menu) => menu.visible(),
  956            ContextMenu::CodeActions(menu) => menu.visible(),
  957        }
  958    }
  959
  960    fn render(
  961        &self,
  962        cursor_position: DisplayPoint,
  963        style: &EditorStyle,
  964        max_height: Pixels,
  965        workspace: Option<WeakView<Workspace>>,
  966        cx: &mut ViewContext<Editor>,
  967    ) -> (ContextMenuOrigin, AnyElement) {
  968        match self {
  969            ContextMenu::Completions(menu) => (
  970                ContextMenuOrigin::EditorPoint(cursor_position),
  971                menu.render(style, max_height, workspace, cx),
  972            ),
  973            ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
  974        }
  975    }
  976}
  977
  978enum ContextMenuOrigin {
  979    EditorPoint(DisplayPoint),
  980    GutterIndicator(DisplayRow),
  981}
  982
  983#[derive(Clone)]
  984struct CompletionsMenu {
  985    id: CompletionId,
  986    sort_completions: bool,
  987    initial_position: Anchor,
  988    buffer: Model<Buffer>,
  989    completions: Arc<RwLock<Box<[Completion]>>>,
  990    match_candidates: Arc<[StringMatchCandidate]>,
  991    matches: Arc<[StringMatch]>,
  992    selected_item: usize,
  993    scroll_handle: UniformListScrollHandle,
  994    selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
  995}
  996
  997impl CompletionsMenu {
  998    fn select_first(
  999        &mut self,
 1000        provider: Option<&dyn CompletionProvider>,
 1001        cx: &mut ViewContext<Editor>,
 1002    ) {
 1003        self.selected_item = 0;
 1004        self.scroll_handle.scroll_to_item(self.selected_item);
 1005        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1006        cx.notify();
 1007    }
 1008
 1009    fn select_prev(
 1010        &mut self,
 1011        provider: Option<&dyn CompletionProvider>,
 1012        cx: &mut ViewContext<Editor>,
 1013    ) {
 1014        if self.selected_item > 0 {
 1015            self.selected_item -= 1;
 1016        } else {
 1017            self.selected_item = self.matches.len() - 1;
 1018        }
 1019        self.scroll_handle.scroll_to_item(self.selected_item);
 1020        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1021        cx.notify();
 1022    }
 1023
 1024    fn select_next(
 1025        &mut self,
 1026        provider: Option<&dyn CompletionProvider>,
 1027        cx: &mut ViewContext<Editor>,
 1028    ) {
 1029        if self.selected_item + 1 < self.matches.len() {
 1030            self.selected_item += 1;
 1031        } else {
 1032            self.selected_item = 0;
 1033        }
 1034        self.scroll_handle.scroll_to_item(self.selected_item);
 1035        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1036        cx.notify();
 1037    }
 1038
 1039    fn select_last(
 1040        &mut self,
 1041        provider: Option<&dyn CompletionProvider>,
 1042        cx: &mut ViewContext<Editor>,
 1043    ) {
 1044        self.selected_item = self.matches.len() - 1;
 1045        self.scroll_handle.scroll_to_item(self.selected_item);
 1046        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1047        cx.notify();
 1048    }
 1049
 1050    fn pre_resolve_completion_documentation(
 1051        buffer: Model<Buffer>,
 1052        completions: Arc<RwLock<Box<[Completion]>>>,
 1053        matches: Arc<[StringMatch]>,
 1054        editor: &Editor,
 1055        cx: &mut ViewContext<Editor>,
 1056    ) -> Task<()> {
 1057        let settings = EditorSettings::get_global(cx);
 1058        if !settings.show_completion_documentation {
 1059            return Task::ready(());
 1060        }
 1061
 1062        let Some(provider) = editor.completion_provider.as_ref() else {
 1063            return Task::ready(());
 1064        };
 1065
 1066        let resolve_task = provider.resolve_completions(
 1067            buffer,
 1068            matches.iter().map(|m| m.candidate_id).collect(),
 1069            completions.clone(),
 1070            cx,
 1071        );
 1072
 1073        cx.spawn(move |this, mut cx| async move {
 1074            if let Some(true) = resolve_task.await.log_err() {
 1075                this.update(&mut cx, |_, cx| cx.notify()).ok();
 1076            }
 1077        })
 1078    }
 1079
 1080    fn attempt_resolve_selected_completion_documentation(
 1081        &mut self,
 1082        provider: Option<&dyn CompletionProvider>,
 1083        cx: &mut ViewContext<Editor>,
 1084    ) {
 1085        let settings = EditorSettings::get_global(cx);
 1086        if !settings.show_completion_documentation {
 1087            return;
 1088        }
 1089
 1090        let completion_index = self.matches[self.selected_item].candidate_id;
 1091        let Some(provider) = provider else {
 1092            return;
 1093        };
 1094
 1095        let resolve_task = provider.resolve_completions(
 1096            self.buffer.clone(),
 1097            vec![completion_index],
 1098            self.completions.clone(),
 1099            cx,
 1100        );
 1101
 1102        let delay_ms =
 1103            EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
 1104        let delay = Duration::from_millis(delay_ms);
 1105
 1106        self.selected_completion_documentation_resolve_debounce
 1107            .lock()
 1108            .fire_new(delay, cx, |_, cx| {
 1109                cx.spawn(move |this, mut cx| async move {
 1110                    if let Some(true) = resolve_task.await.log_err() {
 1111                        this.update(&mut cx, |_, cx| cx.notify()).ok();
 1112                    }
 1113                })
 1114            });
 1115    }
 1116
 1117    fn visible(&self) -> bool {
 1118        !self.matches.is_empty()
 1119    }
 1120
 1121    fn render(
 1122        &self,
 1123        style: &EditorStyle,
 1124        max_height: Pixels,
 1125        workspace: Option<WeakView<Workspace>>,
 1126        cx: &mut ViewContext<Editor>,
 1127    ) -> AnyElement {
 1128        let settings = EditorSettings::get_global(cx);
 1129        let show_completion_documentation = settings.show_completion_documentation;
 1130
 1131        let widest_completion_ix = self
 1132            .matches
 1133            .iter()
 1134            .enumerate()
 1135            .max_by_key(|(_, mat)| {
 1136                let completions = self.completions.read();
 1137                let completion = &completions[mat.candidate_id];
 1138                let documentation = &completion.documentation;
 1139
 1140                let mut len = completion.label.text.chars().count();
 1141                if let Some(Documentation::SingleLine(text)) = documentation {
 1142                    if show_completion_documentation {
 1143                        len += text.chars().count();
 1144                    }
 1145                }
 1146
 1147                len
 1148            })
 1149            .map(|(ix, _)| ix);
 1150
 1151        let completions = self.completions.clone();
 1152        let matches = self.matches.clone();
 1153        let selected_item = self.selected_item;
 1154        let style = style.clone();
 1155
 1156        let multiline_docs = if show_completion_documentation {
 1157            let mat = &self.matches[selected_item];
 1158            let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
 1159                Some(Documentation::MultiLinePlainText(text)) => {
 1160                    Some(div().child(SharedString::from(text.clone())))
 1161                }
 1162                Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
 1163                    Some(div().child(render_parsed_markdown(
 1164                        "completions_markdown",
 1165                        parsed,
 1166                        &style,
 1167                        workspace,
 1168                        cx,
 1169                    )))
 1170                }
 1171                _ => None,
 1172            };
 1173            multiline_docs.map(|div| {
 1174                div.id("multiline_docs")
 1175                    .max_h(max_height)
 1176                    .flex_1()
 1177                    .px_1p5()
 1178                    .py_1()
 1179                    .min_w(px(260.))
 1180                    .max_w(px(640.))
 1181                    .w(px(500.))
 1182                    .overflow_y_scroll()
 1183                    .occlude()
 1184            })
 1185        } else {
 1186            None
 1187        };
 1188
 1189        let list = uniform_list(
 1190            cx.view().clone(),
 1191            "completions",
 1192            matches.len(),
 1193            move |_editor, range, cx| {
 1194                let start_ix = range.start;
 1195                let completions_guard = completions.read();
 1196
 1197                matches[range]
 1198                    .iter()
 1199                    .enumerate()
 1200                    .map(|(ix, mat)| {
 1201                        let item_ix = start_ix + ix;
 1202                        let candidate_id = mat.candidate_id;
 1203                        let completion = &completions_guard[candidate_id];
 1204
 1205                        let documentation = if show_completion_documentation {
 1206                            &completion.documentation
 1207                        } else {
 1208                            &None
 1209                        };
 1210
 1211                        let highlights = gpui::combine_highlights(
 1212                            mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
 1213                            styled_runs_for_code_label(&completion.label, &style.syntax).map(
 1214                                |(range, mut highlight)| {
 1215                                    // Ignore font weight for syntax highlighting, as we'll use it
 1216                                    // for fuzzy matches.
 1217                                    highlight.font_weight = None;
 1218
 1219                                    if completion.lsp_completion.deprecated.unwrap_or(false) {
 1220                                        highlight.strikethrough = Some(StrikethroughStyle {
 1221                                            thickness: 1.0.into(),
 1222                                            ..Default::default()
 1223                                        });
 1224                                        highlight.color = Some(cx.theme().colors().text_muted);
 1225                                    }
 1226
 1227                                    (range, highlight)
 1228                                },
 1229                            ),
 1230                        );
 1231                        let completion_label = StyledText::new(completion.label.text.clone())
 1232                            .with_highlights(&style.text, highlights);
 1233                        let documentation_label =
 1234                            if let Some(Documentation::SingleLine(text)) = documentation {
 1235                                if text.trim().is_empty() {
 1236                                    None
 1237                                } else {
 1238                                    Some(
 1239                                        Label::new(text.clone())
 1240                                            .ml_4()
 1241                                            .size(LabelSize::Small)
 1242                                            .color(Color::Muted),
 1243                                    )
 1244                                }
 1245                            } else {
 1246                                None
 1247                            };
 1248
 1249                        let color_swatch = completion
 1250                            .color()
 1251                            .map(|color| div().size_4().bg(color).rounded_sm());
 1252
 1253                        div().min_w(px(220.)).max_w(px(540.)).child(
 1254                            ListItem::new(mat.candidate_id)
 1255                                .inset(true)
 1256                                .selected(item_ix == selected_item)
 1257                                .on_click(cx.listener(move |editor, _event, cx| {
 1258                                    cx.stop_propagation();
 1259                                    if let Some(task) = editor.confirm_completion(
 1260                                        &ConfirmCompletion {
 1261                                            item_ix: Some(item_ix),
 1262                                        },
 1263                                        cx,
 1264                                    ) {
 1265                                        task.detach_and_log_err(cx)
 1266                                    }
 1267                                }))
 1268                                .start_slot::<Div>(color_swatch)
 1269                                .child(h_flex().overflow_hidden().child(completion_label))
 1270                                .end_slot::<Label>(documentation_label),
 1271                        )
 1272                    })
 1273                    .collect()
 1274            },
 1275        )
 1276        .occlude()
 1277        .max_h(max_height)
 1278        .track_scroll(self.scroll_handle.clone())
 1279        .with_width_from_item(widest_completion_ix)
 1280        .with_sizing_behavior(ListSizingBehavior::Infer);
 1281
 1282        Popover::new()
 1283            .child(list)
 1284            .when_some(multiline_docs, |popover, multiline_docs| {
 1285                popover.aside(multiline_docs)
 1286            })
 1287            .into_any_element()
 1288    }
 1289
 1290    pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
 1291        let mut matches = if let Some(query) = query {
 1292            fuzzy::match_strings(
 1293                &self.match_candidates,
 1294                query,
 1295                query.chars().any(|c| c.is_uppercase()),
 1296                100,
 1297                &Default::default(),
 1298                executor,
 1299            )
 1300            .await
 1301        } else {
 1302            self.match_candidates
 1303                .iter()
 1304                .enumerate()
 1305                .map(|(candidate_id, candidate)| StringMatch {
 1306                    candidate_id,
 1307                    score: Default::default(),
 1308                    positions: Default::default(),
 1309                    string: candidate.string.clone(),
 1310                })
 1311                .collect()
 1312        };
 1313
 1314        // Remove all candidates where the query's start does not match the start of any word in the candidate
 1315        if let Some(query) = query {
 1316            if let Some(query_start) = query.chars().next() {
 1317                matches.retain(|string_match| {
 1318                    split_words(&string_match.string).any(|word| {
 1319                        // Check that the first codepoint of the word as lowercase matches the first
 1320                        // codepoint of the query as lowercase
 1321                        word.chars()
 1322                            .flat_map(|codepoint| codepoint.to_lowercase())
 1323                            .zip(query_start.to_lowercase())
 1324                            .all(|(word_cp, query_cp)| word_cp == query_cp)
 1325                    })
 1326                });
 1327            }
 1328        }
 1329
 1330        let completions = self.completions.read();
 1331        if self.sort_completions {
 1332            matches.sort_unstable_by_key(|mat| {
 1333                // We do want to strike a balance here between what the language server tells us
 1334                // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
 1335                // `Creat` and there is a local variable called `CreateComponent`).
 1336                // So what we do is: we bucket all matches into two buckets
 1337                // - Strong matches
 1338                // - Weak matches
 1339                // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
 1340                // and the Weak matches are the rest.
 1341                //
 1342                // For the strong matches, we sort by the language-servers score first and for the weak
 1343                // matches, we prefer our fuzzy finder first.
 1344                //
 1345                // The thinking behind that: it's useless to take the sort_text the language-server gives
 1346                // us into account when it's obviously a bad match.
 1347
 1348                #[derive(PartialEq, Eq, PartialOrd, Ord)]
 1349                enum MatchScore<'a> {
 1350                    Strong {
 1351                        sort_text: Option<&'a str>,
 1352                        score: Reverse<OrderedFloat<f64>>,
 1353                        sort_key: (usize, &'a str),
 1354                    },
 1355                    Weak {
 1356                        score: Reverse<OrderedFloat<f64>>,
 1357                        sort_text: Option<&'a str>,
 1358                        sort_key: (usize, &'a str),
 1359                    },
 1360                }
 1361
 1362                let completion = &completions[mat.candidate_id];
 1363                let sort_key = completion.sort_key();
 1364                let sort_text = completion.lsp_completion.sort_text.as_deref();
 1365                let score = Reverse(OrderedFloat(mat.score));
 1366
 1367                if mat.score >= 0.2 {
 1368                    MatchScore::Strong {
 1369                        sort_text,
 1370                        score,
 1371                        sort_key,
 1372                    }
 1373                } else {
 1374                    MatchScore::Weak {
 1375                        score,
 1376                        sort_text,
 1377                        sort_key,
 1378                    }
 1379                }
 1380            });
 1381        }
 1382
 1383        for mat in &mut matches {
 1384            let completion = &completions[mat.candidate_id];
 1385            mat.string.clone_from(&completion.label.text);
 1386            for position in &mut mat.positions {
 1387                *position += completion.label.filter_range.start;
 1388            }
 1389        }
 1390        drop(completions);
 1391
 1392        self.matches = matches.into();
 1393        self.selected_item = 0;
 1394    }
 1395}
 1396
 1397struct AvailableCodeAction {
 1398    excerpt_id: ExcerptId,
 1399    action: CodeAction,
 1400    provider: Arc<dyn CodeActionProvider>,
 1401}
 1402
 1403#[derive(Clone)]
 1404struct CodeActionContents {
 1405    tasks: Option<Arc<ResolvedTasks>>,
 1406    actions: Option<Arc<[AvailableCodeAction]>>,
 1407}
 1408
 1409impl CodeActionContents {
 1410    fn len(&self) -> usize {
 1411        match (&self.tasks, &self.actions) {
 1412            (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
 1413            (Some(tasks), None) => tasks.templates.len(),
 1414            (None, Some(actions)) => actions.len(),
 1415            (None, None) => 0,
 1416        }
 1417    }
 1418
 1419    fn is_empty(&self) -> bool {
 1420        match (&self.tasks, &self.actions) {
 1421            (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
 1422            (Some(tasks), None) => tasks.templates.is_empty(),
 1423            (None, Some(actions)) => actions.is_empty(),
 1424            (None, None) => true,
 1425        }
 1426    }
 1427
 1428    fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
 1429        self.tasks
 1430            .iter()
 1431            .flat_map(|tasks| {
 1432                tasks
 1433                    .templates
 1434                    .iter()
 1435                    .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
 1436            })
 1437            .chain(self.actions.iter().flat_map(|actions| {
 1438                actions.iter().map(|available| CodeActionsItem::CodeAction {
 1439                    excerpt_id: available.excerpt_id,
 1440                    action: available.action.clone(),
 1441                    provider: available.provider.clone(),
 1442                })
 1443            }))
 1444    }
 1445    fn get(&self, index: usize) -> Option<CodeActionsItem> {
 1446        match (&self.tasks, &self.actions) {
 1447            (Some(tasks), Some(actions)) => {
 1448                if index < tasks.templates.len() {
 1449                    tasks
 1450                        .templates
 1451                        .get(index)
 1452                        .cloned()
 1453                        .map(|(kind, task)| CodeActionsItem::Task(kind, task))
 1454                } else {
 1455                    actions.get(index - tasks.templates.len()).map(|available| {
 1456                        CodeActionsItem::CodeAction {
 1457                            excerpt_id: available.excerpt_id,
 1458                            action: available.action.clone(),
 1459                            provider: available.provider.clone(),
 1460                        }
 1461                    })
 1462                }
 1463            }
 1464            (Some(tasks), None) => tasks
 1465                .templates
 1466                .get(index)
 1467                .cloned()
 1468                .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
 1469            (None, Some(actions)) => {
 1470                actions
 1471                    .get(index)
 1472                    .map(|available| CodeActionsItem::CodeAction {
 1473                        excerpt_id: available.excerpt_id,
 1474                        action: available.action.clone(),
 1475                        provider: available.provider.clone(),
 1476                    })
 1477            }
 1478            (None, None) => None,
 1479        }
 1480    }
 1481}
 1482
 1483#[allow(clippy::large_enum_variant)]
 1484#[derive(Clone)]
 1485enum CodeActionsItem {
 1486    Task(TaskSourceKind, ResolvedTask),
 1487    CodeAction {
 1488        excerpt_id: ExcerptId,
 1489        action: CodeAction,
 1490        provider: Arc<dyn CodeActionProvider>,
 1491    },
 1492}
 1493
 1494impl CodeActionsItem {
 1495    fn as_task(&self) -> Option<&ResolvedTask> {
 1496        let Self::Task(_, task) = self else {
 1497            return None;
 1498        };
 1499        Some(task)
 1500    }
 1501    fn as_code_action(&self) -> Option<&CodeAction> {
 1502        let Self::CodeAction { action, .. } = self else {
 1503            return None;
 1504        };
 1505        Some(action)
 1506    }
 1507    fn label(&self) -> String {
 1508        match self {
 1509            Self::CodeAction { action, .. } => action.lsp_action.title.clone(),
 1510            Self::Task(_, task) => task.resolved_label.clone(),
 1511        }
 1512    }
 1513}
 1514
 1515struct CodeActionsMenu {
 1516    actions: CodeActionContents,
 1517    buffer: Model<Buffer>,
 1518    selected_item: usize,
 1519    scroll_handle: UniformListScrollHandle,
 1520    deployed_from_indicator: Option<DisplayRow>,
 1521}
 1522
 1523impl CodeActionsMenu {
 1524    fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
 1525        self.selected_item = 0;
 1526        self.scroll_handle.scroll_to_item(self.selected_item);
 1527        cx.notify()
 1528    }
 1529
 1530    fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
 1531        if self.selected_item > 0 {
 1532            self.selected_item -= 1;
 1533        } else {
 1534            self.selected_item = self.actions.len() - 1;
 1535        }
 1536        self.scroll_handle.scroll_to_item(self.selected_item);
 1537        cx.notify();
 1538    }
 1539
 1540    fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
 1541        if self.selected_item + 1 < self.actions.len() {
 1542            self.selected_item += 1;
 1543        } else {
 1544            self.selected_item = 0;
 1545        }
 1546        self.scroll_handle.scroll_to_item(self.selected_item);
 1547        cx.notify();
 1548    }
 1549
 1550    fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
 1551        self.selected_item = self.actions.len() - 1;
 1552        self.scroll_handle.scroll_to_item(self.selected_item);
 1553        cx.notify()
 1554    }
 1555
 1556    fn visible(&self) -> bool {
 1557        !self.actions.is_empty()
 1558    }
 1559
 1560    fn render(
 1561        &self,
 1562        cursor_position: DisplayPoint,
 1563        _style: &EditorStyle,
 1564        max_height: Pixels,
 1565        cx: &mut ViewContext<Editor>,
 1566    ) -> (ContextMenuOrigin, AnyElement) {
 1567        let actions = self.actions.clone();
 1568        let selected_item = self.selected_item;
 1569        let element = uniform_list(
 1570            cx.view().clone(),
 1571            "code_actions_menu",
 1572            self.actions.len(),
 1573            move |_this, range, cx| {
 1574                actions
 1575                    .iter()
 1576                    .skip(range.start)
 1577                    .take(range.end - range.start)
 1578                    .enumerate()
 1579                    .map(|(ix, action)| {
 1580                        let item_ix = range.start + ix;
 1581                        let selected = selected_item == item_ix;
 1582                        let colors = cx.theme().colors();
 1583                        div()
 1584                            .px_1()
 1585                            .rounded_md()
 1586                            .text_color(colors.text)
 1587                            .when(selected, |style| {
 1588                                style
 1589                                    .bg(colors.element_active)
 1590                                    .text_color(colors.text_accent)
 1591                            })
 1592                            .hover(|style| {
 1593                                style
 1594                                    .bg(colors.element_hover)
 1595                                    .text_color(colors.text_accent)
 1596                            })
 1597                            .whitespace_nowrap()
 1598                            .when_some(action.as_code_action(), |this, action| {
 1599                                this.on_mouse_down(
 1600                                    MouseButton::Left,
 1601                                    cx.listener(move |editor, _, cx| {
 1602                                        cx.stop_propagation();
 1603                                        if let Some(task) = editor.confirm_code_action(
 1604                                            &ConfirmCodeAction {
 1605                                                item_ix: Some(item_ix),
 1606                                            },
 1607                                            cx,
 1608                                        ) {
 1609                                            task.detach_and_log_err(cx)
 1610                                        }
 1611                                    }),
 1612                                )
 1613                                // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
 1614                                .child(SharedString::from(action.lsp_action.title.clone()))
 1615                            })
 1616                            .when_some(action.as_task(), |this, task| {
 1617                                this.on_mouse_down(
 1618                                    MouseButton::Left,
 1619                                    cx.listener(move |editor, _, cx| {
 1620                                        cx.stop_propagation();
 1621                                        if let Some(task) = editor.confirm_code_action(
 1622                                            &ConfirmCodeAction {
 1623                                                item_ix: Some(item_ix),
 1624                                            },
 1625                                            cx,
 1626                                        ) {
 1627                                            task.detach_and_log_err(cx)
 1628                                        }
 1629                                    }),
 1630                                )
 1631                                .child(SharedString::from(task.resolved_label.clone()))
 1632                            })
 1633                    })
 1634                    .collect()
 1635            },
 1636        )
 1637        .elevation_1(cx)
 1638        .p_1()
 1639        .max_h(max_height)
 1640        .occlude()
 1641        .track_scroll(self.scroll_handle.clone())
 1642        .with_width_from_item(
 1643            self.actions
 1644                .iter()
 1645                .enumerate()
 1646                .max_by_key(|(_, action)| match action {
 1647                    CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
 1648                    CodeActionsItem::CodeAction { action, .. } => {
 1649                        action.lsp_action.title.chars().count()
 1650                    }
 1651                })
 1652                .map(|(ix, _)| ix),
 1653        )
 1654        .with_sizing_behavior(ListSizingBehavior::Infer)
 1655        .into_any_element();
 1656
 1657        let cursor_position = if let Some(row) = self.deployed_from_indicator {
 1658            ContextMenuOrigin::GutterIndicator(row)
 1659        } else {
 1660            ContextMenuOrigin::EditorPoint(cursor_position)
 1661        };
 1662
 1663        (cursor_position, element)
 1664    }
 1665}
 1666
 1667#[derive(Debug)]
 1668struct ActiveDiagnosticGroup {
 1669    primary_range: Range<Anchor>,
 1670    primary_message: String,
 1671    group_id: usize,
 1672    blocks: HashMap<CustomBlockId, Diagnostic>,
 1673    is_valid: bool,
 1674}
 1675
 1676#[derive(Serialize, Deserialize, Clone, Debug)]
 1677pub struct ClipboardSelection {
 1678    pub len: usize,
 1679    pub is_entire_line: bool,
 1680    pub first_line_indent: u32,
 1681}
 1682
 1683#[derive(Debug)]
 1684pub(crate) struct NavigationData {
 1685    cursor_anchor: Anchor,
 1686    cursor_position: Point,
 1687    scroll_anchor: ScrollAnchor,
 1688    scroll_top_row: u32,
 1689}
 1690
 1691#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1692pub enum GotoDefinitionKind {
 1693    Symbol,
 1694    Declaration,
 1695    Type,
 1696    Implementation,
 1697}
 1698
 1699#[derive(Debug, Clone)]
 1700enum InlayHintRefreshReason {
 1701    Toggle(bool),
 1702    SettingsChange(InlayHintSettings),
 1703    NewLinesShown,
 1704    BufferEdited(HashSet<Arc<Language>>),
 1705    RefreshRequested,
 1706    ExcerptsRemoved(Vec<ExcerptId>),
 1707}
 1708
 1709impl InlayHintRefreshReason {
 1710    fn description(&self) -> &'static str {
 1711        match self {
 1712            Self::Toggle(_) => "toggle",
 1713            Self::SettingsChange(_) => "settings change",
 1714            Self::NewLinesShown => "new lines shown",
 1715            Self::BufferEdited(_) => "buffer edited",
 1716            Self::RefreshRequested => "refresh requested",
 1717            Self::ExcerptsRemoved(_) => "excerpts removed",
 1718        }
 1719    }
 1720}
 1721
 1722pub(crate) struct FocusedBlock {
 1723    id: BlockId,
 1724    focus_handle: WeakFocusHandle,
 1725}
 1726
 1727impl Editor {
 1728    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
 1729        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1730        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1731        Self::new(
 1732            EditorMode::SingleLine { auto_width: false },
 1733            buffer,
 1734            None,
 1735            false,
 1736            cx,
 1737        )
 1738    }
 1739
 1740    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
 1741        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1742        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1743        Self::new(EditorMode::Full, buffer, None, false, cx)
 1744    }
 1745
 1746    pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
 1747        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1748        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1749        Self::new(
 1750            EditorMode::SingleLine { auto_width: true },
 1751            buffer,
 1752            None,
 1753            false,
 1754            cx,
 1755        )
 1756    }
 1757
 1758    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
 1759        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1760        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1761        Self::new(
 1762            EditorMode::AutoHeight { max_lines },
 1763            buffer,
 1764            None,
 1765            false,
 1766            cx,
 1767        )
 1768    }
 1769
 1770    pub fn for_buffer(
 1771        buffer: Model<Buffer>,
 1772        project: Option<Model<Project>>,
 1773        cx: &mut ViewContext<Self>,
 1774    ) -> Self {
 1775        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1776        Self::new(EditorMode::Full, buffer, project, false, cx)
 1777    }
 1778
 1779    pub fn for_multibuffer(
 1780        buffer: Model<MultiBuffer>,
 1781        project: Option<Model<Project>>,
 1782        show_excerpt_controls: bool,
 1783        cx: &mut ViewContext<Self>,
 1784    ) -> Self {
 1785        Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
 1786    }
 1787
 1788    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 1789        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1790        let mut clone = Self::new(
 1791            self.mode,
 1792            self.buffer.clone(),
 1793            self.project.clone(),
 1794            show_excerpt_controls,
 1795            cx,
 1796        );
 1797        self.display_map.update(cx, |display_map, cx| {
 1798            let snapshot = display_map.snapshot(cx);
 1799            clone.display_map.update(cx, |display_map, cx| {
 1800                display_map.set_state(&snapshot, cx);
 1801            });
 1802        });
 1803        clone.selections.clone_state(&self.selections);
 1804        clone.scroll_manager.clone_state(&self.scroll_manager);
 1805        clone.searchable = self.searchable;
 1806        clone
 1807    }
 1808
 1809    pub fn new(
 1810        mode: EditorMode,
 1811        buffer: Model<MultiBuffer>,
 1812        project: Option<Model<Project>>,
 1813        show_excerpt_controls: bool,
 1814        cx: &mut ViewContext<Self>,
 1815    ) -> Self {
 1816        let style = cx.text_style();
 1817        let font_size = style.font_size.to_pixels(cx.rem_size());
 1818        let editor = cx.view().downgrade();
 1819        let fold_placeholder = FoldPlaceholder {
 1820            constrain_width: true,
 1821            render: Arc::new(move |fold_id, fold_range, cx| {
 1822                let editor = editor.clone();
 1823                div()
 1824                    .id(fold_id)
 1825                    .bg(cx.theme().colors().ghost_element_background)
 1826                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1827                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1828                    .rounded_sm()
 1829                    .size_full()
 1830                    .cursor_pointer()
 1831                    .child("")
 1832                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 1833                    .on_click(move |_, cx| {
 1834                        editor
 1835                            .update(cx, |editor, cx| {
 1836                                editor.unfold_ranges(
 1837                                    [fold_range.start..fold_range.end],
 1838                                    true,
 1839                                    false,
 1840                                    cx,
 1841                                );
 1842                                cx.stop_propagation();
 1843                            })
 1844                            .ok();
 1845                    })
 1846                    .into_any()
 1847            }),
 1848            merge_adjacent: true,
 1849        };
 1850        let display_map = cx.new_model(|cx| {
 1851            DisplayMap::new(
 1852                buffer.clone(),
 1853                style.font(),
 1854                font_size,
 1855                None,
 1856                show_excerpt_controls,
 1857                FILE_HEADER_HEIGHT,
 1858                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1859                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1860                fold_placeholder,
 1861                cx,
 1862            )
 1863        });
 1864
 1865        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1866
 1867        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1868
 1869        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1870            .then(|| language_settings::SoftWrap::None);
 1871
 1872        let mut project_subscriptions = Vec::new();
 1873        if mode == EditorMode::Full {
 1874            if let Some(project) = project.as_ref() {
 1875                if buffer.read(cx).is_singleton() {
 1876                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
 1877                        cx.emit(EditorEvent::TitleChanged);
 1878                    }));
 1879                }
 1880                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
 1881                    if let project::Event::RefreshInlayHints = event {
 1882                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1883                    } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1884                        if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1885                            let focus_handle = editor.focus_handle(cx);
 1886                            if focus_handle.is_focused(cx) {
 1887                                let snapshot = buffer.read(cx).snapshot();
 1888                                for (range, snippet) in snippet_edits {
 1889                                    let editor_range =
 1890                                        language::range_from_lsp(*range).to_offset(&snapshot);
 1891                                    editor
 1892                                        .insert_snippet(&[editor_range], snippet.clone(), cx)
 1893                                        .ok();
 1894                                }
 1895                            }
 1896                        }
 1897                    }
 1898                }));
 1899                if let Some(task_inventory) = project
 1900                    .read(cx)
 1901                    .task_store()
 1902                    .read(cx)
 1903                    .task_inventory()
 1904                    .cloned()
 1905                {
 1906                    project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
 1907                        editor.tasks_update_task = Some(editor.refresh_runnables(cx));
 1908                    }));
 1909                }
 1910            }
 1911        }
 1912
 1913        let inlay_hint_settings = inlay_hint_settings(
 1914            selections.newest_anchor().head(),
 1915            &buffer.read(cx).snapshot(cx),
 1916            cx,
 1917        );
 1918        let focus_handle = cx.focus_handle();
 1919        cx.on_focus(&focus_handle, Self::handle_focus).detach();
 1920        cx.on_focus_in(&focus_handle, Self::handle_focus_in)
 1921            .detach();
 1922        cx.on_focus_out(&focus_handle, Self::handle_focus_out)
 1923            .detach();
 1924        cx.on_blur(&focus_handle, Self::handle_blur).detach();
 1925
 1926        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1927            Some(false)
 1928        } else {
 1929            None
 1930        };
 1931
 1932        let mut code_action_providers = Vec::new();
 1933        if let Some(project) = project.clone() {
 1934            code_action_providers.push(Arc::new(project) as Arc<_>);
 1935        }
 1936
 1937        let mut this = Self {
 1938            focus_handle,
 1939            show_cursor_when_unfocused: false,
 1940            last_focused_descendant: None,
 1941            buffer: buffer.clone(),
 1942            display_map: display_map.clone(),
 1943            selections,
 1944            scroll_manager: ScrollManager::new(cx),
 1945            columnar_selection_tail: None,
 1946            add_selections_state: None,
 1947            select_next_state: None,
 1948            select_prev_state: None,
 1949            selection_history: Default::default(),
 1950            autoclose_regions: Default::default(),
 1951            snippet_stack: Default::default(),
 1952            select_larger_syntax_node_stack: Vec::new(),
 1953            ime_transaction: Default::default(),
 1954            active_diagnostics: None,
 1955            soft_wrap_mode_override,
 1956            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1957            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1958            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1959            project,
 1960            blink_manager: blink_manager.clone(),
 1961            show_local_selections: true,
 1962            mode,
 1963            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1964            show_gutter: mode == EditorMode::Full,
 1965            show_line_numbers: None,
 1966            use_relative_line_numbers: None,
 1967            show_git_diff_gutter: None,
 1968            show_code_actions: None,
 1969            show_runnables: None,
 1970            show_wrap_guides: None,
 1971            show_indent_guides,
 1972            placeholder_text: None,
 1973            highlight_order: 0,
 1974            highlighted_rows: HashMap::default(),
 1975            background_highlights: Default::default(),
 1976            gutter_highlights: TreeMap::default(),
 1977            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1978            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1979            nav_history: None,
 1980            context_menu: RwLock::new(None),
 1981            mouse_context_menu: None,
 1982            hunk_controls_menu_handle: PopoverMenuHandle::default(),
 1983            completion_tasks: Default::default(),
 1984            signature_help_state: SignatureHelpState::default(),
 1985            auto_signature_help: None,
 1986            find_all_references_task_sources: Vec::new(),
 1987            next_completion_id: 0,
 1988            completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
 1989            next_inlay_id: 0,
 1990            code_action_providers,
 1991            available_code_actions: Default::default(),
 1992            code_actions_task: Default::default(),
 1993            document_highlights_task: Default::default(),
 1994            linked_editing_range_task: Default::default(),
 1995            pending_rename: Default::default(),
 1996            searchable: true,
 1997            cursor_shape: EditorSettings::get_global(cx)
 1998                .cursor_shape
 1999                .unwrap_or_default(),
 2000            current_line_highlight: None,
 2001            autoindent_mode: Some(AutoindentMode::EachLine),
 2002            collapse_matches: false,
 2003            workspace: None,
 2004            input_enabled: true,
 2005            use_modal_editing: mode == EditorMode::Full,
 2006            read_only: false,
 2007            use_autoclose: true,
 2008            use_auto_surround: true,
 2009            auto_replace_emoji_shortcode: false,
 2010            leader_peer_id: None,
 2011            remote_id: None,
 2012            hover_state: Default::default(),
 2013            hovered_link_state: Default::default(),
 2014            inline_completion_provider: None,
 2015            active_inline_completion: None,
 2016            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 2017            expanded_hunks: ExpandedHunks::default(),
 2018            gutter_hovered: false,
 2019            pixel_position_of_newest_cursor: None,
 2020            last_bounds: None,
 2021            expect_bounds_change: None,
 2022            gutter_dimensions: GutterDimensions::default(),
 2023            style: None,
 2024            show_cursor_names: false,
 2025            hovered_cursors: Default::default(),
 2026            next_editor_action_id: EditorActionId::default(),
 2027            editor_actions: Rc::default(),
 2028            show_inline_completions_override: None,
 2029            enable_inline_completions: true,
 2030            custom_context_menu: None,
 2031            show_git_blame_gutter: false,
 2032            show_git_blame_inline: false,
 2033            show_selection_menu: None,
 2034            show_git_blame_inline_delay_task: None,
 2035            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 2036            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 2037                .session
 2038                .restore_unsaved_buffers,
 2039            blame: None,
 2040            blame_subscription: None,
 2041            tasks: Default::default(),
 2042            _subscriptions: vec![
 2043                cx.observe(&buffer, Self::on_buffer_changed),
 2044                cx.subscribe(&buffer, Self::on_buffer_event),
 2045                cx.observe(&display_map, Self::on_display_map_changed),
 2046                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 2047                cx.observe_global::<SettingsStore>(Self::settings_changed),
 2048                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 2049                cx.observe_window_activation(|editor, cx| {
 2050                    let active = cx.is_window_active();
 2051                    editor.blink_manager.update(cx, |blink_manager, cx| {
 2052                        if active {
 2053                            blink_manager.enable(cx);
 2054                        } else {
 2055                            blink_manager.disable(cx);
 2056                        }
 2057                    });
 2058                }),
 2059            ],
 2060            tasks_update_task: None,
 2061            linked_edit_ranges: Default::default(),
 2062            previous_search_ranges: None,
 2063            breadcrumb_header: None,
 2064            focused_block: None,
 2065            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 2066            addons: HashMap::default(),
 2067            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 2068            text_style_refinement: None,
 2069        };
 2070        this.tasks_update_task = Some(this.refresh_runnables(cx));
 2071        this._subscriptions.extend(project_subscriptions);
 2072
 2073        this.end_selection(cx);
 2074        this.scroll_manager.show_scrollbar(cx);
 2075
 2076        if mode == EditorMode::Full {
 2077            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 2078            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 2079
 2080            if this.git_blame_inline_enabled {
 2081                this.git_blame_inline_enabled = true;
 2082                this.start_git_blame_inline(false, cx);
 2083            }
 2084        }
 2085
 2086        this.report_editor_event("open", None, cx);
 2087        this
 2088    }
 2089
 2090    pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
 2091        self.mouse_context_menu
 2092            .as_ref()
 2093            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
 2094    }
 2095
 2096    fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
 2097        let mut key_context = KeyContext::new_with_defaults();
 2098        key_context.add("Editor");
 2099        let mode = match self.mode {
 2100            EditorMode::SingleLine { .. } => "single_line",
 2101            EditorMode::AutoHeight { .. } => "auto_height",
 2102            EditorMode::Full => "full",
 2103        };
 2104
 2105        if EditorSettings::jupyter_enabled(cx) {
 2106            key_context.add("jupyter");
 2107        }
 2108
 2109        key_context.set("mode", mode);
 2110        if self.pending_rename.is_some() {
 2111            key_context.add("renaming");
 2112        }
 2113        if self.context_menu_visible() {
 2114            match self.context_menu.read().as_ref() {
 2115                Some(ContextMenu::Completions(_)) => {
 2116                    key_context.add("menu");
 2117                    key_context.add("showing_completions")
 2118                }
 2119                Some(ContextMenu::CodeActions(_)) => {
 2120                    key_context.add("menu");
 2121                    key_context.add("showing_code_actions")
 2122                }
 2123                None => {}
 2124            }
 2125        }
 2126
 2127        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 2128        if !self.focus_handle(cx).contains_focused(cx)
 2129            || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
 2130        {
 2131            for addon in self.addons.values() {
 2132                addon.extend_key_context(&mut key_context, cx)
 2133            }
 2134        }
 2135
 2136        if let Some(extension) = self
 2137            .buffer
 2138            .read(cx)
 2139            .as_singleton()
 2140            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 2141        {
 2142            key_context.set("extension", extension.to_string());
 2143        }
 2144
 2145        if self.has_active_inline_completion(cx) {
 2146            key_context.add("copilot_suggestion");
 2147            key_context.add("inline_completion");
 2148        }
 2149
 2150        key_context
 2151    }
 2152
 2153    pub fn new_file(
 2154        workspace: &mut Workspace,
 2155        _: &workspace::NewFile,
 2156        cx: &mut ViewContext<Workspace>,
 2157    ) {
 2158        Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
 2159            "Failed to create buffer",
 2160            cx,
 2161            |e, _| match e.error_code() {
 2162                ErrorCode::RemoteUpgradeRequired => Some(format!(
 2163                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2164                e.error_tag("required").unwrap_or("the latest version")
 2165            )),
 2166                _ => None,
 2167            },
 2168        );
 2169    }
 2170
 2171    pub fn new_in_workspace(
 2172        workspace: &mut Workspace,
 2173        cx: &mut ViewContext<Workspace>,
 2174    ) -> Task<Result<View<Editor>>> {
 2175        let project = workspace.project().clone();
 2176        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2177
 2178        cx.spawn(|workspace, mut cx| async move {
 2179            let buffer = create.await?;
 2180            workspace.update(&mut cx, |workspace, cx| {
 2181                let editor =
 2182                    cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
 2183                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 2184                editor
 2185            })
 2186        })
 2187    }
 2188
 2189    fn new_file_vertical(
 2190        workspace: &mut Workspace,
 2191        _: &workspace::NewFileSplitVertical,
 2192        cx: &mut ViewContext<Workspace>,
 2193    ) {
 2194        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
 2195    }
 2196
 2197    fn new_file_horizontal(
 2198        workspace: &mut Workspace,
 2199        _: &workspace::NewFileSplitHorizontal,
 2200        cx: &mut ViewContext<Workspace>,
 2201    ) {
 2202        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
 2203    }
 2204
 2205    fn new_file_in_direction(
 2206        workspace: &mut Workspace,
 2207        direction: SplitDirection,
 2208        cx: &mut ViewContext<Workspace>,
 2209    ) {
 2210        let project = workspace.project().clone();
 2211        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2212
 2213        cx.spawn(|workspace, mut cx| async move {
 2214            let buffer = create.await?;
 2215            workspace.update(&mut cx, move |workspace, cx| {
 2216                workspace.split_item(
 2217                    direction,
 2218                    Box::new(
 2219                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 2220                    ),
 2221                    cx,
 2222                )
 2223            })?;
 2224            anyhow::Ok(())
 2225        })
 2226        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 2227            ErrorCode::RemoteUpgradeRequired => Some(format!(
 2228                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2229                e.error_tag("required").unwrap_or("the latest version")
 2230            )),
 2231            _ => None,
 2232        });
 2233    }
 2234
 2235    pub fn leader_peer_id(&self) -> Option<PeerId> {
 2236        self.leader_peer_id
 2237    }
 2238
 2239    pub fn buffer(&self) -> &Model<MultiBuffer> {
 2240        &self.buffer
 2241    }
 2242
 2243    pub fn workspace(&self) -> Option<View<Workspace>> {
 2244        self.workspace.as_ref()?.0.upgrade()
 2245    }
 2246
 2247    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
 2248        self.buffer().read(cx).title(cx)
 2249    }
 2250
 2251    pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
 2252        let git_blame_gutter_max_author_length = self
 2253            .render_git_blame_gutter(cx)
 2254            .then(|| {
 2255                if let Some(blame) = self.blame.as_ref() {
 2256                    let max_author_length =
 2257                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 2258                    Some(max_author_length)
 2259                } else {
 2260                    None
 2261                }
 2262            })
 2263            .flatten();
 2264
 2265        EditorSnapshot {
 2266            mode: self.mode,
 2267            show_gutter: self.show_gutter,
 2268            show_line_numbers: self.show_line_numbers,
 2269            show_git_diff_gutter: self.show_git_diff_gutter,
 2270            show_code_actions: self.show_code_actions,
 2271            show_runnables: self.show_runnables,
 2272            git_blame_gutter_max_author_length,
 2273            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 2274            scroll_anchor: self.scroll_manager.anchor(),
 2275            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 2276            placeholder_text: self.placeholder_text.clone(),
 2277            is_focused: self.focus_handle.is_focused(cx),
 2278            current_line_highlight: self
 2279                .current_line_highlight
 2280                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 2281            gutter_hovered: self.gutter_hovered,
 2282        }
 2283    }
 2284
 2285    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
 2286        self.buffer.read(cx).language_at(point, cx)
 2287    }
 2288
 2289    pub fn file_at<T: ToOffset>(
 2290        &self,
 2291        point: T,
 2292        cx: &AppContext,
 2293    ) -> Option<Arc<dyn language::File>> {
 2294        self.buffer.read(cx).read(cx).file_at(point).cloned()
 2295    }
 2296
 2297    pub fn active_excerpt(
 2298        &self,
 2299        cx: &AppContext,
 2300    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
 2301        self.buffer
 2302            .read(cx)
 2303            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 2304    }
 2305
 2306    pub fn mode(&self) -> EditorMode {
 2307        self.mode
 2308    }
 2309
 2310    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 2311        self.collaboration_hub.as_deref()
 2312    }
 2313
 2314    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 2315        self.collaboration_hub = Some(hub);
 2316    }
 2317
 2318    pub fn set_custom_context_menu(
 2319        &mut self,
 2320        f: impl 'static
 2321            + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
 2322    ) {
 2323        self.custom_context_menu = Some(Box::new(f))
 2324    }
 2325
 2326    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 2327        self.completion_provider = provider;
 2328    }
 2329
 2330    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 2331        self.semantics_provider.clone()
 2332    }
 2333
 2334    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 2335        self.semantics_provider = provider;
 2336    }
 2337
 2338    pub fn set_inline_completion_provider<T>(
 2339        &mut self,
 2340        provider: Option<Model<T>>,
 2341        cx: &mut ViewContext<Self>,
 2342    ) where
 2343        T: InlineCompletionProvider,
 2344    {
 2345        self.inline_completion_provider =
 2346            provider.map(|provider| RegisteredInlineCompletionProvider {
 2347                _subscription: cx.observe(&provider, |this, _, cx| {
 2348                    if this.focus_handle.is_focused(cx) {
 2349                        this.update_visible_inline_completion(cx);
 2350                    }
 2351                }),
 2352                provider: Arc::new(provider),
 2353            });
 2354        self.refresh_inline_completion(false, false, cx);
 2355    }
 2356
 2357    pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
 2358        self.placeholder_text.as_deref()
 2359    }
 2360
 2361    pub fn set_placeholder_text(
 2362        &mut self,
 2363        placeholder_text: impl Into<Arc<str>>,
 2364        cx: &mut ViewContext<Self>,
 2365    ) {
 2366        let placeholder_text = Some(placeholder_text.into());
 2367        if self.placeholder_text != placeholder_text {
 2368            self.placeholder_text = placeholder_text;
 2369            cx.notify();
 2370        }
 2371    }
 2372
 2373    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
 2374        self.cursor_shape = cursor_shape;
 2375
 2376        // Disrupt blink for immediate user feedback that the cursor shape has changed
 2377        self.blink_manager.update(cx, BlinkManager::show_cursor);
 2378
 2379        cx.notify();
 2380    }
 2381
 2382    pub fn set_current_line_highlight(
 2383        &mut self,
 2384        current_line_highlight: Option<CurrentLineHighlight>,
 2385    ) {
 2386        self.current_line_highlight = current_line_highlight;
 2387    }
 2388
 2389    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 2390        self.collapse_matches = collapse_matches;
 2391    }
 2392
 2393    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 2394        if self.collapse_matches {
 2395            return range.start..range.start;
 2396        }
 2397        range.clone()
 2398    }
 2399
 2400    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
 2401        if self.display_map.read(cx).clip_at_line_ends != clip {
 2402            self.display_map
 2403                .update(cx, |map, _| map.clip_at_line_ends = clip);
 2404        }
 2405    }
 2406
 2407    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 2408        self.input_enabled = input_enabled;
 2409    }
 2410
 2411    pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
 2412        self.enable_inline_completions = enabled;
 2413    }
 2414
 2415    pub fn set_autoindent(&mut self, autoindent: bool) {
 2416        if autoindent {
 2417            self.autoindent_mode = Some(AutoindentMode::EachLine);
 2418        } else {
 2419            self.autoindent_mode = None;
 2420        }
 2421    }
 2422
 2423    pub fn read_only(&self, cx: &AppContext) -> bool {
 2424        self.read_only || self.buffer.read(cx).read_only()
 2425    }
 2426
 2427    pub fn set_read_only(&mut self, read_only: bool) {
 2428        self.read_only = read_only;
 2429    }
 2430
 2431    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 2432        self.use_autoclose = autoclose;
 2433    }
 2434
 2435    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 2436        self.use_auto_surround = auto_surround;
 2437    }
 2438
 2439    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 2440        self.auto_replace_emoji_shortcode = auto_replace;
 2441    }
 2442
 2443    pub fn toggle_inline_completions(
 2444        &mut self,
 2445        _: &ToggleInlineCompletions,
 2446        cx: &mut ViewContext<Self>,
 2447    ) {
 2448        if self.show_inline_completions_override.is_some() {
 2449            self.set_show_inline_completions(None, cx);
 2450        } else {
 2451            let cursor = self.selections.newest_anchor().head();
 2452            if let Some((buffer, cursor_buffer_position)) =
 2453                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 2454            {
 2455                let show_inline_completions =
 2456                    !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
 2457                self.set_show_inline_completions(Some(show_inline_completions), cx);
 2458            }
 2459        }
 2460    }
 2461
 2462    pub fn set_show_inline_completions(
 2463        &mut self,
 2464        show_inline_completions: Option<bool>,
 2465        cx: &mut ViewContext<Self>,
 2466    ) {
 2467        self.show_inline_completions_override = show_inline_completions;
 2468        self.refresh_inline_completion(false, true, cx);
 2469    }
 2470
 2471    fn should_show_inline_completions(
 2472        &self,
 2473        buffer: &Model<Buffer>,
 2474        buffer_position: language::Anchor,
 2475        cx: &AppContext,
 2476    ) -> bool {
 2477        if let Some(provider) = self.inline_completion_provider() {
 2478            if let Some(show_inline_completions) = self.show_inline_completions_override {
 2479                show_inline_completions
 2480            } else {
 2481                self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
 2482            }
 2483        } else {
 2484            false
 2485        }
 2486    }
 2487
 2488    pub fn set_use_modal_editing(&mut self, to: bool) {
 2489        self.use_modal_editing = to;
 2490    }
 2491
 2492    pub fn use_modal_editing(&self) -> bool {
 2493        self.use_modal_editing
 2494    }
 2495
 2496    fn selections_did_change(
 2497        &mut self,
 2498        local: bool,
 2499        old_cursor_position: &Anchor,
 2500        show_completions: bool,
 2501        cx: &mut ViewContext<Self>,
 2502    ) {
 2503        cx.invalidate_character_coordinates();
 2504
 2505        // Copy selections to primary selection buffer
 2506        #[cfg(target_os = "linux")]
 2507        if local {
 2508            let selections = self.selections.all::<usize>(cx);
 2509            let buffer_handle = self.buffer.read(cx).read(cx);
 2510
 2511            let mut text = String::new();
 2512            for (index, selection) in selections.iter().enumerate() {
 2513                let text_for_selection = buffer_handle
 2514                    .text_for_range(selection.start..selection.end)
 2515                    .collect::<String>();
 2516
 2517                text.push_str(&text_for_selection);
 2518                if index != selections.len() - 1 {
 2519                    text.push('\n');
 2520                }
 2521            }
 2522
 2523            if !text.is_empty() {
 2524                cx.write_to_primary(ClipboardItem::new_string(text));
 2525            }
 2526        }
 2527
 2528        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
 2529            self.buffer.update(cx, |buffer, cx| {
 2530                buffer.set_active_selections(
 2531                    &self.selections.disjoint_anchors(),
 2532                    self.selections.line_mode,
 2533                    self.cursor_shape,
 2534                    cx,
 2535                )
 2536            });
 2537        }
 2538        let display_map = self
 2539            .display_map
 2540            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2541        let buffer = &display_map.buffer_snapshot;
 2542        self.add_selections_state = None;
 2543        self.select_next_state = None;
 2544        self.select_prev_state = None;
 2545        self.select_larger_syntax_node_stack.clear();
 2546        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2547        self.snippet_stack
 2548            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2549        self.take_rename(false, cx);
 2550
 2551        let new_cursor_position = self.selections.newest_anchor().head();
 2552
 2553        self.push_to_nav_history(
 2554            *old_cursor_position,
 2555            Some(new_cursor_position.to_point(buffer)),
 2556            cx,
 2557        );
 2558
 2559        if local {
 2560            let new_cursor_position = self.selections.newest_anchor().head();
 2561            let mut context_menu = self.context_menu.write();
 2562            let completion_menu = match context_menu.as_ref() {
 2563                Some(ContextMenu::Completions(menu)) => Some(menu),
 2564
 2565                _ => {
 2566                    *context_menu = None;
 2567                    None
 2568                }
 2569            };
 2570
 2571            if let Some(completion_menu) = completion_menu {
 2572                let cursor_position = new_cursor_position.to_offset(buffer);
 2573                let (word_range, kind) =
 2574                    buffer.surrounding_word(completion_menu.initial_position, true);
 2575                if kind == Some(CharKind::Word)
 2576                    && word_range.to_inclusive().contains(&cursor_position)
 2577                {
 2578                    let mut completion_menu = completion_menu.clone();
 2579                    drop(context_menu);
 2580
 2581                    let query = Self::completion_query(buffer, cursor_position);
 2582                    cx.spawn(move |this, mut cx| async move {
 2583                        completion_menu
 2584                            .filter(query.as_deref(), cx.background_executor().clone())
 2585                            .await;
 2586
 2587                        this.update(&mut cx, |this, cx| {
 2588                            let mut context_menu = this.context_menu.write();
 2589                            let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
 2590                                return;
 2591                            };
 2592
 2593                            if menu.id > completion_menu.id {
 2594                                return;
 2595                            }
 2596
 2597                            *context_menu = Some(ContextMenu::Completions(completion_menu));
 2598                            drop(context_menu);
 2599                            cx.notify();
 2600                        })
 2601                    })
 2602                    .detach();
 2603
 2604                    if show_completions {
 2605                        self.show_completions(&ShowCompletions { trigger: None }, cx);
 2606                    }
 2607                } else {
 2608                    drop(context_menu);
 2609                    self.hide_context_menu(cx);
 2610                }
 2611            } else {
 2612                drop(context_menu);
 2613            }
 2614
 2615            hide_hover(self, cx);
 2616
 2617            if old_cursor_position.to_display_point(&display_map).row()
 2618                != new_cursor_position.to_display_point(&display_map).row()
 2619            {
 2620                self.available_code_actions.take();
 2621            }
 2622            self.refresh_code_actions(cx);
 2623            self.refresh_document_highlights(cx);
 2624            refresh_matching_bracket_highlights(self, cx);
 2625            self.discard_inline_completion(false, cx);
 2626            linked_editing_ranges::refresh_linked_ranges(self, cx);
 2627            if self.git_blame_inline_enabled {
 2628                self.start_inline_blame_timer(cx);
 2629            }
 2630        }
 2631
 2632        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2633        cx.emit(EditorEvent::SelectionsChanged { local });
 2634
 2635        if self.selections.disjoint_anchors().len() == 1 {
 2636            cx.emit(SearchEvent::ActiveMatchChanged)
 2637        }
 2638        cx.notify();
 2639    }
 2640
 2641    pub fn change_selections<R>(
 2642        &mut self,
 2643        autoscroll: Option<Autoscroll>,
 2644        cx: &mut ViewContext<Self>,
 2645        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2646    ) -> R {
 2647        self.change_selections_inner(autoscroll, true, cx, change)
 2648    }
 2649
 2650    pub fn change_selections_inner<R>(
 2651        &mut self,
 2652        autoscroll: Option<Autoscroll>,
 2653        request_completions: bool,
 2654        cx: &mut ViewContext<Self>,
 2655        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2656    ) -> R {
 2657        let old_cursor_position = self.selections.newest_anchor().head();
 2658        self.push_to_selection_history();
 2659
 2660        let (changed, result) = self.selections.change_with(cx, change);
 2661
 2662        if changed {
 2663            if let Some(autoscroll) = autoscroll {
 2664                self.request_autoscroll(autoscroll, cx);
 2665            }
 2666            self.selections_did_change(true, &old_cursor_position, request_completions, cx);
 2667
 2668            if self.should_open_signature_help_automatically(
 2669                &old_cursor_position,
 2670                self.signature_help_state.backspace_pressed(),
 2671                cx,
 2672            ) {
 2673                self.show_signature_help(&ShowSignatureHelp, cx);
 2674            }
 2675            self.signature_help_state.set_backspace_pressed(false);
 2676        }
 2677
 2678        result
 2679    }
 2680
 2681    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2682    where
 2683        I: IntoIterator<Item = (Range<S>, T)>,
 2684        S: ToOffset,
 2685        T: Into<Arc<str>>,
 2686    {
 2687        if self.read_only(cx) {
 2688            return;
 2689        }
 2690
 2691        self.buffer
 2692            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2693    }
 2694
 2695    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2696    where
 2697        I: IntoIterator<Item = (Range<S>, T)>,
 2698        S: ToOffset,
 2699        T: Into<Arc<str>>,
 2700    {
 2701        if self.read_only(cx) {
 2702            return;
 2703        }
 2704
 2705        self.buffer.update(cx, |buffer, cx| {
 2706            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2707        });
 2708    }
 2709
 2710    pub fn edit_with_block_indent<I, S, T>(
 2711        &mut self,
 2712        edits: I,
 2713        original_indent_columns: Vec<u32>,
 2714        cx: &mut ViewContext<Self>,
 2715    ) where
 2716        I: IntoIterator<Item = (Range<S>, T)>,
 2717        S: ToOffset,
 2718        T: Into<Arc<str>>,
 2719    {
 2720        if self.read_only(cx) {
 2721            return;
 2722        }
 2723
 2724        self.buffer.update(cx, |buffer, cx| {
 2725            buffer.edit(
 2726                edits,
 2727                Some(AutoindentMode::Block {
 2728                    original_indent_columns,
 2729                }),
 2730                cx,
 2731            )
 2732        });
 2733    }
 2734
 2735    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
 2736        self.hide_context_menu(cx);
 2737
 2738        match phase {
 2739            SelectPhase::Begin {
 2740                position,
 2741                add,
 2742                click_count,
 2743            } => self.begin_selection(position, add, click_count, cx),
 2744            SelectPhase::BeginColumnar {
 2745                position,
 2746                goal_column,
 2747                reset,
 2748            } => self.begin_columnar_selection(position, goal_column, reset, cx),
 2749            SelectPhase::Extend {
 2750                position,
 2751                click_count,
 2752            } => self.extend_selection(position, click_count, cx),
 2753            SelectPhase::Update {
 2754                position,
 2755                goal_column,
 2756                scroll_delta,
 2757            } => self.update_selection(position, goal_column, scroll_delta, cx),
 2758            SelectPhase::End => self.end_selection(cx),
 2759        }
 2760    }
 2761
 2762    fn extend_selection(
 2763        &mut self,
 2764        position: DisplayPoint,
 2765        click_count: usize,
 2766        cx: &mut ViewContext<Self>,
 2767    ) {
 2768        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2769        let tail = self.selections.newest::<usize>(cx).tail();
 2770        self.begin_selection(position, false, click_count, cx);
 2771
 2772        let position = position.to_offset(&display_map, Bias::Left);
 2773        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2774
 2775        let mut pending_selection = self
 2776            .selections
 2777            .pending_anchor()
 2778            .expect("extend_selection not called with pending selection");
 2779        if position >= tail {
 2780            pending_selection.start = tail_anchor;
 2781        } else {
 2782            pending_selection.end = tail_anchor;
 2783            pending_selection.reversed = true;
 2784        }
 2785
 2786        let mut pending_mode = self.selections.pending_mode().unwrap();
 2787        match &mut pending_mode {
 2788            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2789            _ => {}
 2790        }
 2791
 2792        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 2793            s.set_pending(pending_selection, pending_mode)
 2794        });
 2795    }
 2796
 2797    fn begin_selection(
 2798        &mut self,
 2799        position: DisplayPoint,
 2800        add: bool,
 2801        click_count: usize,
 2802        cx: &mut ViewContext<Self>,
 2803    ) {
 2804        if !self.focus_handle.is_focused(cx) {
 2805            self.last_focused_descendant = None;
 2806            cx.focus(&self.focus_handle);
 2807        }
 2808
 2809        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2810        let buffer = &display_map.buffer_snapshot;
 2811        let newest_selection = self.selections.newest_anchor().clone();
 2812        let position = display_map.clip_point(position, Bias::Left);
 2813
 2814        let start;
 2815        let end;
 2816        let mode;
 2817        let auto_scroll;
 2818        match click_count {
 2819            1 => {
 2820                start = buffer.anchor_before(position.to_point(&display_map));
 2821                end = start;
 2822                mode = SelectMode::Character;
 2823                auto_scroll = true;
 2824            }
 2825            2 => {
 2826                let range = movement::surrounding_word(&display_map, position);
 2827                start = buffer.anchor_before(range.start.to_point(&display_map));
 2828                end = buffer.anchor_before(range.end.to_point(&display_map));
 2829                mode = SelectMode::Word(start..end);
 2830                auto_scroll = true;
 2831            }
 2832            3 => {
 2833                let position = display_map
 2834                    .clip_point(position, Bias::Left)
 2835                    .to_point(&display_map);
 2836                let line_start = display_map.prev_line_boundary(position).0;
 2837                let next_line_start = buffer.clip_point(
 2838                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2839                    Bias::Left,
 2840                );
 2841                start = buffer.anchor_before(line_start);
 2842                end = buffer.anchor_before(next_line_start);
 2843                mode = SelectMode::Line(start..end);
 2844                auto_scroll = true;
 2845            }
 2846            _ => {
 2847                start = buffer.anchor_before(0);
 2848                end = buffer.anchor_before(buffer.len());
 2849                mode = SelectMode::All;
 2850                auto_scroll = false;
 2851            }
 2852        }
 2853
 2854        let point_to_delete: Option<usize> = {
 2855            let selected_points: Vec<Selection<Point>> =
 2856                self.selections.disjoint_in_range(start..end, cx);
 2857
 2858            if !add || click_count > 1 {
 2859                None
 2860            } else if !selected_points.is_empty() {
 2861                Some(selected_points[0].id)
 2862            } else {
 2863                let clicked_point_already_selected =
 2864                    self.selections.disjoint.iter().find(|selection| {
 2865                        selection.start.to_point(buffer) == start.to_point(buffer)
 2866                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2867                    });
 2868
 2869                clicked_point_already_selected.map(|selection| selection.id)
 2870            }
 2871        };
 2872
 2873        let selections_count = self.selections.count();
 2874
 2875        self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
 2876            if let Some(point_to_delete) = point_to_delete {
 2877                s.delete(point_to_delete);
 2878
 2879                if selections_count == 1 {
 2880                    s.set_pending_anchor_range(start..end, mode);
 2881                }
 2882            } else {
 2883                if !add {
 2884                    s.clear_disjoint();
 2885                } else if click_count > 1 {
 2886                    s.delete(newest_selection.id)
 2887                }
 2888
 2889                s.set_pending_anchor_range(start..end, mode);
 2890            }
 2891        });
 2892    }
 2893
 2894    fn begin_columnar_selection(
 2895        &mut self,
 2896        position: DisplayPoint,
 2897        goal_column: u32,
 2898        reset: bool,
 2899        cx: &mut ViewContext<Self>,
 2900    ) {
 2901        if !self.focus_handle.is_focused(cx) {
 2902            self.last_focused_descendant = None;
 2903            cx.focus(&self.focus_handle);
 2904        }
 2905
 2906        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2907
 2908        if reset {
 2909            let pointer_position = display_map
 2910                .buffer_snapshot
 2911                .anchor_before(position.to_point(&display_map));
 2912
 2913            self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 2914                s.clear_disjoint();
 2915                s.set_pending_anchor_range(
 2916                    pointer_position..pointer_position,
 2917                    SelectMode::Character,
 2918                );
 2919            });
 2920        }
 2921
 2922        let tail = self.selections.newest::<Point>(cx).tail();
 2923        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2924
 2925        if !reset {
 2926            self.select_columns(
 2927                tail.to_display_point(&display_map),
 2928                position,
 2929                goal_column,
 2930                &display_map,
 2931                cx,
 2932            );
 2933        }
 2934    }
 2935
 2936    fn update_selection(
 2937        &mut self,
 2938        position: DisplayPoint,
 2939        goal_column: u32,
 2940        scroll_delta: gpui::Point<f32>,
 2941        cx: &mut ViewContext<Self>,
 2942    ) {
 2943        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2944
 2945        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2946            let tail = tail.to_display_point(&display_map);
 2947            self.select_columns(tail, position, goal_column, &display_map, cx);
 2948        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2949            let buffer = self.buffer.read(cx).snapshot(cx);
 2950            let head;
 2951            let tail;
 2952            let mode = self.selections.pending_mode().unwrap();
 2953            match &mode {
 2954                SelectMode::Character => {
 2955                    head = position.to_point(&display_map);
 2956                    tail = pending.tail().to_point(&buffer);
 2957                }
 2958                SelectMode::Word(original_range) => {
 2959                    let original_display_range = original_range.start.to_display_point(&display_map)
 2960                        ..original_range.end.to_display_point(&display_map);
 2961                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2962                        ..original_display_range.end.to_point(&display_map);
 2963                    if movement::is_inside_word(&display_map, position)
 2964                        || original_display_range.contains(&position)
 2965                    {
 2966                        let word_range = movement::surrounding_word(&display_map, position);
 2967                        if word_range.start < original_display_range.start {
 2968                            head = word_range.start.to_point(&display_map);
 2969                        } else {
 2970                            head = word_range.end.to_point(&display_map);
 2971                        }
 2972                    } else {
 2973                        head = position.to_point(&display_map);
 2974                    }
 2975
 2976                    if head <= original_buffer_range.start {
 2977                        tail = original_buffer_range.end;
 2978                    } else {
 2979                        tail = original_buffer_range.start;
 2980                    }
 2981                }
 2982                SelectMode::Line(original_range) => {
 2983                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2984
 2985                    let position = display_map
 2986                        .clip_point(position, Bias::Left)
 2987                        .to_point(&display_map);
 2988                    let line_start = display_map.prev_line_boundary(position).0;
 2989                    let next_line_start = buffer.clip_point(
 2990                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2991                        Bias::Left,
 2992                    );
 2993
 2994                    if line_start < original_range.start {
 2995                        head = line_start
 2996                    } else {
 2997                        head = next_line_start
 2998                    }
 2999
 3000                    if head <= original_range.start {
 3001                        tail = original_range.end;
 3002                    } else {
 3003                        tail = original_range.start;
 3004                    }
 3005                }
 3006                SelectMode::All => {
 3007                    return;
 3008                }
 3009            };
 3010
 3011            if head < tail {
 3012                pending.start = buffer.anchor_before(head);
 3013                pending.end = buffer.anchor_before(tail);
 3014                pending.reversed = true;
 3015            } else {
 3016                pending.start = buffer.anchor_before(tail);
 3017                pending.end = buffer.anchor_before(head);
 3018                pending.reversed = false;
 3019            }
 3020
 3021            self.change_selections(None, cx, |s| {
 3022                s.set_pending(pending, mode);
 3023            });
 3024        } else {
 3025            log::error!("update_selection dispatched with no pending selection");
 3026            return;
 3027        }
 3028
 3029        self.apply_scroll_delta(scroll_delta, cx);
 3030        cx.notify();
 3031    }
 3032
 3033    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 3034        self.columnar_selection_tail.take();
 3035        if self.selections.pending_anchor().is_some() {
 3036            let selections = self.selections.all::<usize>(cx);
 3037            self.change_selections(None, cx, |s| {
 3038                s.select(selections);
 3039                s.clear_pending();
 3040            });
 3041        }
 3042    }
 3043
 3044    fn select_columns(
 3045        &mut self,
 3046        tail: DisplayPoint,
 3047        head: DisplayPoint,
 3048        goal_column: u32,
 3049        display_map: &DisplaySnapshot,
 3050        cx: &mut ViewContext<Self>,
 3051    ) {
 3052        let start_row = cmp::min(tail.row(), head.row());
 3053        let end_row = cmp::max(tail.row(), head.row());
 3054        let start_column = cmp::min(tail.column(), goal_column);
 3055        let end_column = cmp::max(tail.column(), goal_column);
 3056        let reversed = start_column < tail.column();
 3057
 3058        let selection_ranges = (start_row.0..=end_row.0)
 3059            .map(DisplayRow)
 3060            .filter_map(|row| {
 3061                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 3062                    let start = display_map
 3063                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 3064                        .to_point(display_map);
 3065                    let end = display_map
 3066                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 3067                        .to_point(display_map);
 3068                    if reversed {
 3069                        Some(end..start)
 3070                    } else {
 3071                        Some(start..end)
 3072                    }
 3073                } else {
 3074                    None
 3075                }
 3076            })
 3077            .collect::<Vec<_>>();
 3078
 3079        self.change_selections(None, cx, |s| {
 3080            s.select_ranges(selection_ranges);
 3081        });
 3082        cx.notify();
 3083    }
 3084
 3085    pub fn has_pending_nonempty_selection(&self) -> bool {
 3086        let pending_nonempty_selection = match self.selections.pending_anchor() {
 3087            Some(Selection { start, end, .. }) => start != end,
 3088            None => false,
 3089        };
 3090
 3091        pending_nonempty_selection
 3092            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 3093    }
 3094
 3095    pub fn has_pending_selection(&self) -> bool {
 3096        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 3097    }
 3098
 3099    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 3100        if self.clear_expanded_diff_hunks(cx) {
 3101            cx.notify();
 3102            return;
 3103        }
 3104        if self.dismiss_menus_and_popups(true, cx) {
 3105            return;
 3106        }
 3107
 3108        if self.mode == EditorMode::Full
 3109            && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
 3110        {
 3111            return;
 3112        }
 3113
 3114        cx.propagate();
 3115    }
 3116
 3117    pub fn dismiss_menus_and_popups(
 3118        &mut self,
 3119        should_report_inline_completion_event: bool,
 3120        cx: &mut ViewContext<Self>,
 3121    ) -> bool {
 3122        if self.take_rename(false, cx).is_some() {
 3123            return true;
 3124        }
 3125
 3126        if hide_hover(self, cx) {
 3127            return true;
 3128        }
 3129
 3130        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 3131            return true;
 3132        }
 3133
 3134        if self.hide_context_menu(cx).is_some() {
 3135            return true;
 3136        }
 3137
 3138        if self.mouse_context_menu.take().is_some() {
 3139            return true;
 3140        }
 3141
 3142        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 3143            return true;
 3144        }
 3145
 3146        if self.snippet_stack.pop().is_some() {
 3147            return true;
 3148        }
 3149
 3150        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 3151            self.dismiss_diagnostics(cx);
 3152            return true;
 3153        }
 3154
 3155        false
 3156    }
 3157
 3158    fn linked_editing_ranges_for(
 3159        &self,
 3160        selection: Range<text::Anchor>,
 3161        cx: &AppContext,
 3162    ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
 3163        if self.linked_edit_ranges.is_empty() {
 3164            return None;
 3165        }
 3166        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 3167            selection.end.buffer_id.and_then(|end_buffer_id| {
 3168                if selection.start.buffer_id != Some(end_buffer_id) {
 3169                    return None;
 3170                }
 3171                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 3172                let snapshot = buffer.read(cx).snapshot();
 3173                self.linked_edit_ranges
 3174                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 3175                    .map(|ranges| (ranges, snapshot, buffer))
 3176            })?;
 3177        use text::ToOffset as TO;
 3178        // find offset from the start of current range to current cursor position
 3179        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 3180
 3181        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 3182        let start_difference = start_offset - start_byte_offset;
 3183        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 3184        let end_difference = end_offset - start_byte_offset;
 3185        // Current range has associated linked ranges.
 3186        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3187        for range in linked_ranges.iter() {
 3188            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 3189            let end_offset = start_offset + end_difference;
 3190            let start_offset = start_offset + start_difference;
 3191            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 3192                continue;
 3193            }
 3194            if self.selections.disjoint_anchor_ranges().iter().any(|s| {
 3195                if s.start.buffer_id != selection.start.buffer_id
 3196                    || s.end.buffer_id != selection.end.buffer_id
 3197                {
 3198                    return false;
 3199                }
 3200                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 3201                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 3202            }) {
 3203                continue;
 3204            }
 3205            let start = buffer_snapshot.anchor_after(start_offset);
 3206            let end = buffer_snapshot.anchor_after(end_offset);
 3207            linked_edits
 3208                .entry(buffer.clone())
 3209                .or_default()
 3210                .push(start..end);
 3211        }
 3212        Some(linked_edits)
 3213    }
 3214
 3215    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3216        let text: Arc<str> = text.into();
 3217
 3218        if self.read_only(cx) {
 3219            return;
 3220        }
 3221
 3222        let selections = self.selections.all_adjusted(cx);
 3223        let mut bracket_inserted = false;
 3224        let mut edits = Vec::new();
 3225        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3226        let mut new_selections = Vec::with_capacity(selections.len());
 3227        let mut new_autoclose_regions = Vec::new();
 3228        let snapshot = self.buffer.read(cx).read(cx);
 3229
 3230        for (selection, autoclose_region) in
 3231            self.selections_with_autoclose_regions(selections, &snapshot)
 3232        {
 3233            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 3234                // Determine if the inserted text matches the opening or closing
 3235                // bracket of any of this language's bracket pairs.
 3236                let mut bracket_pair = None;
 3237                let mut is_bracket_pair_start = false;
 3238                let mut is_bracket_pair_end = false;
 3239                if !text.is_empty() {
 3240                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 3241                    //  and they are removing the character that triggered IME popup.
 3242                    for (pair, enabled) in scope.brackets() {
 3243                        if !pair.close && !pair.surround {
 3244                            continue;
 3245                        }
 3246
 3247                        if enabled && pair.start.ends_with(text.as_ref()) {
 3248                            bracket_pair = Some(pair.clone());
 3249                            is_bracket_pair_start = true;
 3250                            break;
 3251                        }
 3252                        if pair.end.as_str() == text.as_ref() {
 3253                            bracket_pair = Some(pair.clone());
 3254                            is_bracket_pair_end = true;
 3255                            break;
 3256                        }
 3257                    }
 3258                }
 3259
 3260                if let Some(bracket_pair) = bracket_pair {
 3261                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 3262                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 3263                    let auto_surround =
 3264                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 3265                    if selection.is_empty() {
 3266                        if is_bracket_pair_start {
 3267                            let prefix_len = bracket_pair.start.len() - text.len();
 3268
 3269                            // If the inserted text is a suffix of an opening bracket and the
 3270                            // selection is preceded by the rest of the opening bracket, then
 3271                            // insert the closing bracket.
 3272                            let following_text_allows_autoclose = snapshot
 3273                                .chars_at(selection.start)
 3274                                .next()
 3275                                .map_or(true, |c| scope.should_autoclose_before(c));
 3276                            let preceding_text_matches_prefix = prefix_len == 0
 3277                                || (selection.start.column >= (prefix_len as u32)
 3278                                    && snapshot.contains_str_at(
 3279                                        Point::new(
 3280                                            selection.start.row,
 3281                                            selection.start.column - (prefix_len as u32),
 3282                                        ),
 3283                                        &bracket_pair.start[..prefix_len],
 3284                                    ));
 3285
 3286                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 3287                                && bracket_pair.start.len() == 1
 3288                            {
 3289                                let target = bracket_pair.start.chars().next().unwrap();
 3290                                let current_line_count = snapshot
 3291                                    .reversed_chars_at(selection.start)
 3292                                    .take_while(|&c| c != '\n')
 3293                                    .filter(|&c| c == target)
 3294                                    .count();
 3295                                current_line_count % 2 == 1
 3296                            } else {
 3297                                false
 3298                            };
 3299
 3300                            if autoclose
 3301                                && bracket_pair.close
 3302                                && following_text_allows_autoclose
 3303                                && preceding_text_matches_prefix
 3304                                && !is_closing_quote
 3305                            {
 3306                                let anchor = snapshot.anchor_before(selection.end);
 3307                                new_selections.push((selection.map(|_| anchor), text.len()));
 3308                                new_autoclose_regions.push((
 3309                                    anchor,
 3310                                    text.len(),
 3311                                    selection.id,
 3312                                    bracket_pair.clone(),
 3313                                ));
 3314                                edits.push((
 3315                                    selection.range(),
 3316                                    format!("{}{}", text, bracket_pair.end).into(),
 3317                                ));
 3318                                bracket_inserted = true;
 3319                                continue;
 3320                            }
 3321                        }
 3322
 3323                        if let Some(region) = autoclose_region {
 3324                            // If the selection is followed by an auto-inserted closing bracket,
 3325                            // then don't insert that closing bracket again; just move the selection
 3326                            // past the closing bracket.
 3327                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3328                                && text.as_ref() == region.pair.end.as_str();
 3329                            if should_skip {
 3330                                let anchor = snapshot.anchor_after(selection.end);
 3331                                new_selections
 3332                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3333                                continue;
 3334                            }
 3335                        }
 3336
 3337                        let always_treat_brackets_as_autoclosed = snapshot
 3338                            .settings_at(selection.start, cx)
 3339                            .always_treat_brackets_as_autoclosed;
 3340                        if always_treat_brackets_as_autoclosed
 3341                            && is_bracket_pair_end
 3342                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3343                        {
 3344                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3345                            // and the inserted text is a closing bracket and the selection is followed
 3346                            // by the closing bracket then move the selection past the closing bracket.
 3347                            let anchor = snapshot.anchor_after(selection.end);
 3348                            new_selections.push((selection.map(|_| anchor), text.len()));
 3349                            continue;
 3350                        }
 3351                    }
 3352                    // If an opening bracket is 1 character long and is typed while
 3353                    // text is selected, then surround that text with the bracket pair.
 3354                    else if auto_surround
 3355                        && bracket_pair.surround
 3356                        && is_bracket_pair_start
 3357                        && bracket_pair.start.chars().count() == 1
 3358                    {
 3359                        edits.push((selection.start..selection.start, text.clone()));
 3360                        edits.push((
 3361                            selection.end..selection.end,
 3362                            bracket_pair.end.as_str().into(),
 3363                        ));
 3364                        bracket_inserted = true;
 3365                        new_selections.push((
 3366                            Selection {
 3367                                id: selection.id,
 3368                                start: snapshot.anchor_after(selection.start),
 3369                                end: snapshot.anchor_before(selection.end),
 3370                                reversed: selection.reversed,
 3371                                goal: selection.goal,
 3372                            },
 3373                            0,
 3374                        ));
 3375                        continue;
 3376                    }
 3377                }
 3378            }
 3379
 3380            if self.auto_replace_emoji_shortcode
 3381                && selection.is_empty()
 3382                && text.as_ref().ends_with(':')
 3383            {
 3384                if let Some(possible_emoji_short_code) =
 3385                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3386                {
 3387                    if !possible_emoji_short_code.is_empty() {
 3388                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3389                            let emoji_shortcode_start = Point::new(
 3390                                selection.start.row,
 3391                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3392                            );
 3393
 3394                            // Remove shortcode from buffer
 3395                            edits.push((
 3396                                emoji_shortcode_start..selection.start,
 3397                                "".to_string().into(),
 3398                            ));
 3399                            new_selections.push((
 3400                                Selection {
 3401                                    id: selection.id,
 3402                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3403                                    end: snapshot.anchor_before(selection.start),
 3404                                    reversed: selection.reversed,
 3405                                    goal: selection.goal,
 3406                                },
 3407                                0,
 3408                            ));
 3409
 3410                            // Insert emoji
 3411                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3412                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3413                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3414
 3415                            continue;
 3416                        }
 3417                    }
 3418                }
 3419            }
 3420
 3421            // If not handling any auto-close operation, then just replace the selected
 3422            // text with the given input and move the selection to the end of the
 3423            // newly inserted text.
 3424            let anchor = snapshot.anchor_after(selection.end);
 3425            if !self.linked_edit_ranges.is_empty() {
 3426                let start_anchor = snapshot.anchor_before(selection.start);
 3427
 3428                let is_word_char = text.chars().next().map_or(true, |char| {
 3429                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3430                    classifier.is_word(char)
 3431                });
 3432
 3433                if is_word_char {
 3434                    if let Some(ranges) = self
 3435                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3436                    {
 3437                        for (buffer, edits) in ranges {
 3438                            linked_edits
 3439                                .entry(buffer.clone())
 3440                                .or_default()
 3441                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3442                        }
 3443                    }
 3444                }
 3445            }
 3446
 3447            new_selections.push((selection.map(|_| anchor), 0));
 3448            edits.push((selection.start..selection.end, text.clone()));
 3449        }
 3450
 3451        drop(snapshot);
 3452
 3453        self.transact(cx, |this, cx| {
 3454            this.buffer.update(cx, |buffer, cx| {
 3455                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3456            });
 3457            for (buffer, edits) in linked_edits {
 3458                buffer.update(cx, |buffer, cx| {
 3459                    let snapshot = buffer.snapshot();
 3460                    let edits = edits
 3461                        .into_iter()
 3462                        .map(|(range, text)| {
 3463                            use text::ToPoint as TP;
 3464                            let end_point = TP::to_point(&range.end, &snapshot);
 3465                            let start_point = TP::to_point(&range.start, &snapshot);
 3466                            (start_point..end_point, text)
 3467                        })
 3468                        .sorted_by_key(|(range, _)| range.start)
 3469                        .collect::<Vec<_>>();
 3470                    buffer.edit(edits, None, cx);
 3471                })
 3472            }
 3473            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3474            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3475            let snapshot = this.buffer.read(cx).read(cx);
 3476            let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
 3477                .zip(new_selection_deltas)
 3478                .map(|(selection, delta)| Selection {
 3479                    id: selection.id,
 3480                    start: selection.start + delta,
 3481                    end: selection.end + delta,
 3482                    reversed: selection.reversed,
 3483                    goal: SelectionGoal::None,
 3484                })
 3485                .collect::<Vec<_>>();
 3486
 3487            let mut i = 0;
 3488            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3489                let position = position.to_offset(&snapshot) + delta;
 3490                let start = snapshot.anchor_before(position);
 3491                let end = snapshot.anchor_after(position);
 3492                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3493                    match existing_state.range.start.cmp(&start, &snapshot) {
 3494                        Ordering::Less => i += 1,
 3495                        Ordering::Greater => break,
 3496                        Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
 3497                            Ordering::Less => i += 1,
 3498                            Ordering::Equal => break,
 3499                            Ordering::Greater => break,
 3500                        },
 3501                    }
 3502                }
 3503                this.autoclose_regions.insert(
 3504                    i,
 3505                    AutocloseRegion {
 3506                        selection_id,
 3507                        range: start..end,
 3508                        pair,
 3509                    },
 3510                );
 3511            }
 3512
 3513            drop(snapshot);
 3514            let had_active_inline_completion = this.has_active_inline_completion(cx);
 3515            this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
 3516                s.select(new_selections)
 3517            });
 3518
 3519            if !bracket_inserted {
 3520                if let Some(on_type_format_task) =
 3521                    this.trigger_on_type_formatting(text.to_string(), cx)
 3522                {
 3523                    on_type_format_task.detach_and_log_err(cx);
 3524                }
 3525            }
 3526
 3527            let editor_settings = EditorSettings::get_global(cx);
 3528            if bracket_inserted
 3529                && (editor_settings.auto_signature_help
 3530                    || editor_settings.show_signature_help_after_edits)
 3531            {
 3532                this.show_signature_help(&ShowSignatureHelp, cx);
 3533            }
 3534
 3535            let trigger_in_words = !had_active_inline_completion;
 3536            this.trigger_completion_on_input(&text, trigger_in_words, cx);
 3537            linked_editing_ranges::refresh_linked_ranges(this, cx);
 3538            this.refresh_inline_completion(true, false, cx);
 3539        });
 3540    }
 3541
 3542    fn find_possible_emoji_shortcode_at_position(
 3543        snapshot: &MultiBufferSnapshot,
 3544        position: Point,
 3545    ) -> Option<String> {
 3546        let mut chars = Vec::new();
 3547        let mut found_colon = false;
 3548        for char in snapshot.reversed_chars_at(position).take(100) {
 3549            // Found a possible emoji shortcode in the middle of the buffer
 3550            if found_colon {
 3551                if char.is_whitespace() {
 3552                    chars.reverse();
 3553                    return Some(chars.iter().collect());
 3554                }
 3555                // If the previous character is not a whitespace, we are in the middle of a word
 3556                // and we only want to complete the shortcode if the word is made up of other emojis
 3557                let mut containing_word = String::new();
 3558                for ch in snapshot
 3559                    .reversed_chars_at(position)
 3560                    .skip(chars.len() + 1)
 3561                    .take(100)
 3562                {
 3563                    if ch.is_whitespace() {
 3564                        break;
 3565                    }
 3566                    containing_word.push(ch);
 3567                }
 3568                let containing_word = containing_word.chars().rev().collect::<String>();
 3569                if util::word_consists_of_emojis(containing_word.as_str()) {
 3570                    chars.reverse();
 3571                    return Some(chars.iter().collect());
 3572                }
 3573            }
 3574
 3575            if char.is_whitespace() || !char.is_ascii() {
 3576                return None;
 3577            }
 3578            if char == ':' {
 3579                found_colon = true;
 3580            } else {
 3581                chars.push(char);
 3582            }
 3583        }
 3584        // Found a possible emoji shortcode at the beginning of the buffer
 3585        chars.reverse();
 3586        Some(chars.iter().collect())
 3587    }
 3588
 3589    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 3590        self.transact(cx, |this, cx| {
 3591            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3592                let selections = this.selections.all::<usize>(cx);
 3593                let multi_buffer = this.buffer.read(cx);
 3594                let buffer = multi_buffer.snapshot(cx);
 3595                selections
 3596                    .iter()
 3597                    .map(|selection| {
 3598                        let start_point = selection.start.to_point(&buffer);
 3599                        let mut indent =
 3600                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3601                        indent.len = cmp::min(indent.len, start_point.column);
 3602                        let start = selection.start;
 3603                        let end = selection.end;
 3604                        let selection_is_empty = start == end;
 3605                        let language_scope = buffer.language_scope_at(start);
 3606                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3607                            &language_scope
 3608                        {
 3609                            let leading_whitespace_len = buffer
 3610                                .reversed_chars_at(start)
 3611                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3612                                .map(|c| c.len_utf8())
 3613                                .sum::<usize>();
 3614
 3615                            let trailing_whitespace_len = buffer
 3616                                .chars_at(end)
 3617                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3618                                .map(|c| c.len_utf8())
 3619                                .sum::<usize>();
 3620
 3621                            let insert_extra_newline =
 3622                                language.brackets().any(|(pair, enabled)| {
 3623                                    let pair_start = pair.start.trim_end();
 3624                                    let pair_end = pair.end.trim_start();
 3625
 3626                                    enabled
 3627                                        && pair.newline
 3628                                        && buffer.contains_str_at(
 3629                                            end + trailing_whitespace_len,
 3630                                            pair_end,
 3631                                        )
 3632                                        && buffer.contains_str_at(
 3633                                            (start - leading_whitespace_len)
 3634                                                .saturating_sub(pair_start.len()),
 3635                                            pair_start,
 3636                                        )
 3637                                });
 3638
 3639                            // Comment extension on newline is allowed only for cursor selections
 3640                            let comment_delimiter = maybe!({
 3641                                if !selection_is_empty {
 3642                                    return None;
 3643                                }
 3644
 3645                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3646                                    return None;
 3647                                }
 3648
 3649                                let delimiters = language.line_comment_prefixes();
 3650                                let max_len_of_delimiter =
 3651                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3652                                let (snapshot, range) =
 3653                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3654
 3655                                let mut index_of_first_non_whitespace = 0;
 3656                                let comment_candidate = snapshot
 3657                                    .chars_for_range(range)
 3658                                    .skip_while(|c| {
 3659                                        let should_skip = c.is_whitespace();
 3660                                        if should_skip {
 3661                                            index_of_first_non_whitespace += 1;
 3662                                        }
 3663                                        should_skip
 3664                                    })
 3665                                    .take(max_len_of_delimiter)
 3666                                    .collect::<String>();
 3667                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3668                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3669                                })?;
 3670                                let cursor_is_placed_after_comment_marker =
 3671                                    index_of_first_non_whitespace + comment_prefix.len()
 3672                                        <= start_point.column as usize;
 3673                                if cursor_is_placed_after_comment_marker {
 3674                                    Some(comment_prefix.clone())
 3675                                } else {
 3676                                    None
 3677                                }
 3678                            });
 3679                            (comment_delimiter, insert_extra_newline)
 3680                        } else {
 3681                            (None, false)
 3682                        };
 3683
 3684                        let capacity_for_delimiter = comment_delimiter
 3685                            .as_deref()
 3686                            .map(str::len)
 3687                            .unwrap_or_default();
 3688                        let mut new_text =
 3689                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3690                        new_text.push('\n');
 3691                        new_text.extend(indent.chars());
 3692                        if let Some(delimiter) = &comment_delimiter {
 3693                            new_text.push_str(delimiter);
 3694                        }
 3695                        if insert_extra_newline {
 3696                            new_text = new_text.repeat(2);
 3697                        }
 3698
 3699                        let anchor = buffer.anchor_after(end);
 3700                        let new_selection = selection.map(|_| anchor);
 3701                        (
 3702                            (start..end, new_text),
 3703                            (insert_extra_newline, new_selection),
 3704                        )
 3705                    })
 3706                    .unzip()
 3707            };
 3708
 3709            this.edit_with_autoindent(edits, cx);
 3710            let buffer = this.buffer.read(cx).snapshot(cx);
 3711            let new_selections = selection_fixup_info
 3712                .into_iter()
 3713                .map(|(extra_newline_inserted, new_selection)| {
 3714                    let mut cursor = new_selection.end.to_point(&buffer);
 3715                    if extra_newline_inserted {
 3716                        cursor.row -= 1;
 3717                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3718                    }
 3719                    new_selection.map(|_| cursor)
 3720                })
 3721                .collect();
 3722
 3723            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3724            this.refresh_inline_completion(true, false, cx);
 3725        });
 3726    }
 3727
 3728    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3729        let buffer = self.buffer.read(cx);
 3730        let snapshot = buffer.snapshot(cx);
 3731
 3732        let mut edits = Vec::new();
 3733        let mut rows = Vec::new();
 3734
 3735        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3736            let cursor = selection.head();
 3737            let row = cursor.row;
 3738
 3739            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3740
 3741            let newline = "\n".to_string();
 3742            edits.push((start_of_line..start_of_line, newline));
 3743
 3744            rows.push(row + rows_inserted as u32);
 3745        }
 3746
 3747        self.transact(cx, |editor, cx| {
 3748            editor.edit(edits, cx);
 3749
 3750            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3751                let mut index = 0;
 3752                s.move_cursors_with(|map, _, _| {
 3753                    let row = rows[index];
 3754                    index += 1;
 3755
 3756                    let point = Point::new(row, 0);
 3757                    let boundary = map.next_line_boundary(point).1;
 3758                    let clipped = map.clip_point(boundary, Bias::Left);
 3759
 3760                    (clipped, SelectionGoal::None)
 3761                });
 3762            });
 3763
 3764            let mut indent_edits = Vec::new();
 3765            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3766            for row in rows {
 3767                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3768                for (row, indent) in indents {
 3769                    if indent.len == 0 {
 3770                        continue;
 3771                    }
 3772
 3773                    let text = match indent.kind {
 3774                        IndentKind::Space => " ".repeat(indent.len as usize),
 3775                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3776                    };
 3777                    let point = Point::new(row.0, 0);
 3778                    indent_edits.push((point..point, text));
 3779                }
 3780            }
 3781            editor.edit(indent_edits, cx);
 3782        });
 3783    }
 3784
 3785    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3786        let buffer = self.buffer.read(cx);
 3787        let snapshot = buffer.snapshot(cx);
 3788        //
 3789        //
 3790        //
 3791
 3792        let mut edits = Vec::new();
 3793        let mut rows = Vec::new();
 3794        let mut rows_inserted = 0;
 3795
 3796        for selection in self.selections.all_adjusted(cx) {
 3797            let cursor = selection.head();
 3798            let row = cursor.row;
 3799
 3800            let point = Point::new(row + 1, 0);
 3801            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3802
 3803            let newline = "\n".to_string();
 3804            edits.push((start_of_line..start_of_line, newline));
 3805
 3806            rows_inserted += 1;
 3807            rows.push(row + rows_inserted);
 3808        }
 3809
 3810        self.transact(cx, |editor, cx| {
 3811            editor.edit(edits, cx);
 3812
 3813            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3814                let mut index = 0;
 3815                s.move_cursors_with(|map, _, _| {
 3816                    let row = rows[index];
 3817                    index += 1;
 3818
 3819                    let point = Point::new(row, 0);
 3820                    let boundary = map.next_line_boundary(point).1;
 3821                    let clipped = map.clip_point(boundary, Bias::Left);
 3822
 3823                    (clipped, SelectionGoal::None)
 3824                });
 3825            });
 3826
 3827            let mut indent_edits = Vec::new();
 3828            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3829            for row in rows {
 3830                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3831                for (row, indent) in indents {
 3832                    if indent.len == 0 {
 3833                        continue;
 3834                    }
 3835
 3836                    let text = match indent.kind {
 3837                        IndentKind::Space => " ".repeat(indent.len as usize),
 3838                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3839                    };
 3840                    let point = Point::new(row.0, 0);
 3841                    indent_edits.push((point..point, text));
 3842                }
 3843            }
 3844            editor.edit(indent_edits, cx);
 3845        });
 3846    }
 3847
 3848    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3849        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3850            original_indent_columns: Vec::new(),
 3851        });
 3852        self.insert_with_autoindent_mode(text, autoindent, cx);
 3853    }
 3854
 3855    fn insert_with_autoindent_mode(
 3856        &mut self,
 3857        text: &str,
 3858        autoindent_mode: Option<AutoindentMode>,
 3859        cx: &mut ViewContext<Self>,
 3860    ) {
 3861        if self.read_only(cx) {
 3862            return;
 3863        }
 3864
 3865        let text: Arc<str> = text.into();
 3866        self.transact(cx, |this, cx| {
 3867            let old_selections = this.selections.all_adjusted(cx);
 3868            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3869                let anchors = {
 3870                    let snapshot = buffer.read(cx);
 3871                    old_selections
 3872                        .iter()
 3873                        .map(|s| {
 3874                            let anchor = snapshot.anchor_after(s.head());
 3875                            s.map(|_| anchor)
 3876                        })
 3877                        .collect::<Vec<_>>()
 3878                };
 3879                buffer.edit(
 3880                    old_selections
 3881                        .iter()
 3882                        .map(|s| (s.start..s.end, text.clone())),
 3883                    autoindent_mode,
 3884                    cx,
 3885                );
 3886                anchors
 3887            });
 3888
 3889            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3890                s.select_anchors(selection_anchors);
 3891            })
 3892        });
 3893    }
 3894
 3895    fn trigger_completion_on_input(
 3896        &mut self,
 3897        text: &str,
 3898        trigger_in_words: bool,
 3899        cx: &mut ViewContext<Self>,
 3900    ) {
 3901        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3902            self.show_completions(
 3903                &ShowCompletions {
 3904                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3905                },
 3906                cx,
 3907            );
 3908        } else {
 3909            self.hide_context_menu(cx);
 3910        }
 3911    }
 3912
 3913    fn is_completion_trigger(
 3914        &self,
 3915        text: &str,
 3916        trigger_in_words: bool,
 3917        cx: &mut ViewContext<Self>,
 3918    ) -> bool {
 3919        let position = self.selections.newest_anchor().head();
 3920        let multibuffer = self.buffer.read(cx);
 3921        let Some(buffer) = position
 3922            .buffer_id
 3923            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3924        else {
 3925            return false;
 3926        };
 3927
 3928        if let Some(completion_provider) = &self.completion_provider {
 3929            completion_provider.is_completion_trigger(
 3930                &buffer,
 3931                position.text_anchor,
 3932                text,
 3933                trigger_in_words,
 3934                cx,
 3935            )
 3936        } else {
 3937            false
 3938        }
 3939    }
 3940
 3941    /// If any empty selections is touching the start of its innermost containing autoclose
 3942    /// region, expand it to select the brackets.
 3943    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 3944        let selections = self.selections.all::<usize>(cx);
 3945        let buffer = self.buffer.read(cx).read(cx);
 3946        let new_selections = self
 3947            .selections_with_autoclose_regions(selections, &buffer)
 3948            .map(|(mut selection, region)| {
 3949                if !selection.is_empty() {
 3950                    return selection;
 3951                }
 3952
 3953                if let Some(region) = region {
 3954                    let mut range = region.range.to_offset(&buffer);
 3955                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3956                        range.start -= region.pair.start.len();
 3957                        if buffer.contains_str_at(range.start, &region.pair.start)
 3958                            && buffer.contains_str_at(range.end, &region.pair.end)
 3959                        {
 3960                            range.end += region.pair.end.len();
 3961                            selection.start = range.start;
 3962                            selection.end = range.end;
 3963
 3964                            return selection;
 3965                        }
 3966                    }
 3967                }
 3968
 3969                let always_treat_brackets_as_autoclosed = buffer
 3970                    .settings_at(selection.start, cx)
 3971                    .always_treat_brackets_as_autoclosed;
 3972
 3973                if !always_treat_brackets_as_autoclosed {
 3974                    return selection;
 3975                }
 3976
 3977                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3978                    for (pair, enabled) in scope.brackets() {
 3979                        if !enabled || !pair.close {
 3980                            continue;
 3981                        }
 3982
 3983                        if buffer.contains_str_at(selection.start, &pair.end) {
 3984                            let pair_start_len = pair.start.len();
 3985                            if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
 3986                            {
 3987                                selection.start -= pair_start_len;
 3988                                selection.end += pair.end.len();
 3989
 3990                                return selection;
 3991                            }
 3992                        }
 3993                    }
 3994                }
 3995
 3996                selection
 3997            })
 3998            .collect();
 3999
 4000        drop(buffer);
 4001        self.change_selections(None, cx, |selections| selections.select(new_selections));
 4002    }
 4003
 4004    /// Iterate the given selections, and for each one, find the smallest surrounding
 4005    /// autoclose region. This uses the ordering of the selections and the autoclose
 4006    /// regions to avoid repeated comparisons.
 4007    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 4008        &'a self,
 4009        selections: impl IntoIterator<Item = Selection<D>>,
 4010        buffer: &'a MultiBufferSnapshot,
 4011    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 4012        let mut i = 0;
 4013        let mut regions = self.autoclose_regions.as_slice();
 4014        selections.into_iter().map(move |selection| {
 4015            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 4016
 4017            let mut enclosing = None;
 4018            while let Some(pair_state) = regions.get(i) {
 4019                if pair_state.range.end.to_offset(buffer) < range.start {
 4020                    regions = &regions[i + 1..];
 4021                    i = 0;
 4022                } else if pair_state.range.start.to_offset(buffer) > range.end {
 4023                    break;
 4024                } else {
 4025                    if pair_state.selection_id == selection.id {
 4026                        enclosing = Some(pair_state);
 4027                    }
 4028                    i += 1;
 4029                }
 4030            }
 4031
 4032            (selection.clone(), enclosing)
 4033        })
 4034    }
 4035
 4036    /// Remove any autoclose regions that no longer contain their selection.
 4037    fn invalidate_autoclose_regions(
 4038        &mut self,
 4039        mut selections: &[Selection<Anchor>],
 4040        buffer: &MultiBufferSnapshot,
 4041    ) {
 4042        self.autoclose_regions.retain(|state| {
 4043            let mut i = 0;
 4044            while let Some(selection) = selections.get(i) {
 4045                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 4046                    selections = &selections[1..];
 4047                    continue;
 4048                }
 4049                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 4050                    break;
 4051                }
 4052                if selection.id == state.selection_id {
 4053                    return true;
 4054                } else {
 4055                    i += 1;
 4056                }
 4057            }
 4058            false
 4059        });
 4060    }
 4061
 4062    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 4063        let offset = position.to_offset(buffer);
 4064        let (word_range, kind) = buffer.surrounding_word(offset, true);
 4065        if offset > word_range.start && kind == Some(CharKind::Word) {
 4066            Some(
 4067                buffer
 4068                    .text_for_range(word_range.start..offset)
 4069                    .collect::<String>(),
 4070            )
 4071        } else {
 4072            None
 4073        }
 4074    }
 4075
 4076    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 4077        self.refresh_inlay_hints(
 4078            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 4079            cx,
 4080        );
 4081    }
 4082
 4083    pub fn inlay_hints_enabled(&self) -> bool {
 4084        self.inlay_hint_cache.enabled
 4085    }
 4086
 4087    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 4088        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 4089            return;
 4090        }
 4091
 4092        let reason_description = reason.description();
 4093        let ignore_debounce = matches!(
 4094            reason,
 4095            InlayHintRefreshReason::SettingsChange(_)
 4096                | InlayHintRefreshReason::Toggle(_)
 4097                | InlayHintRefreshReason::ExcerptsRemoved(_)
 4098        );
 4099        let (invalidate_cache, required_languages) = match reason {
 4100            InlayHintRefreshReason::Toggle(enabled) => {
 4101                self.inlay_hint_cache.enabled = enabled;
 4102                if enabled {
 4103                    (InvalidationStrategy::RefreshRequested, None)
 4104                } else {
 4105                    self.inlay_hint_cache.clear();
 4106                    self.splice_inlays(
 4107                        self.visible_inlay_hints(cx)
 4108                            .iter()
 4109                            .map(|inlay| inlay.id)
 4110                            .collect(),
 4111                        Vec::new(),
 4112                        cx,
 4113                    );
 4114                    return;
 4115                }
 4116            }
 4117            InlayHintRefreshReason::SettingsChange(new_settings) => {
 4118                match self.inlay_hint_cache.update_settings(
 4119                    &self.buffer,
 4120                    new_settings,
 4121                    self.visible_inlay_hints(cx),
 4122                    cx,
 4123                ) {
 4124                    ControlFlow::Break(Some(InlaySplice {
 4125                        to_remove,
 4126                        to_insert,
 4127                    })) => {
 4128                        self.splice_inlays(to_remove, to_insert, cx);
 4129                        return;
 4130                    }
 4131                    ControlFlow::Break(None) => return,
 4132                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 4133                }
 4134            }
 4135            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 4136                if let Some(InlaySplice {
 4137                    to_remove,
 4138                    to_insert,
 4139                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 4140                {
 4141                    self.splice_inlays(to_remove, to_insert, cx);
 4142                }
 4143                return;
 4144            }
 4145            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 4146            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 4147                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 4148            }
 4149            InlayHintRefreshReason::RefreshRequested => {
 4150                (InvalidationStrategy::RefreshRequested, None)
 4151            }
 4152        };
 4153
 4154        if let Some(InlaySplice {
 4155            to_remove,
 4156            to_insert,
 4157        }) = self.inlay_hint_cache.spawn_hint_refresh(
 4158            reason_description,
 4159            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 4160            invalidate_cache,
 4161            ignore_debounce,
 4162            cx,
 4163        ) {
 4164            self.splice_inlays(to_remove, to_insert, cx);
 4165        }
 4166    }
 4167
 4168    fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
 4169        self.display_map
 4170            .read(cx)
 4171            .current_inlays()
 4172            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 4173            .cloned()
 4174            .collect()
 4175    }
 4176
 4177    pub fn excerpts_for_inlay_hints_query(
 4178        &self,
 4179        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 4180        cx: &mut ViewContext<Editor>,
 4181    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 4182        let Some(project) = self.project.as_ref() else {
 4183            return HashMap::default();
 4184        };
 4185        let project = project.read(cx);
 4186        let multi_buffer = self.buffer().read(cx);
 4187        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 4188        let multi_buffer_visible_start = self
 4189            .scroll_manager
 4190            .anchor()
 4191            .anchor
 4192            .to_point(&multi_buffer_snapshot);
 4193        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 4194            multi_buffer_visible_start
 4195                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 4196            Bias::Left,
 4197        );
 4198        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 4199        multi_buffer
 4200            .range_to_buffer_ranges(multi_buffer_visible_range, cx)
 4201            .into_iter()
 4202            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 4203            .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
 4204                let buffer = buffer_handle.read(cx);
 4205                let buffer_file = project::File::from_dyn(buffer.file())?;
 4206                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 4207                let worktree_entry = buffer_worktree
 4208                    .read(cx)
 4209                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 4210                if worktree_entry.is_ignored {
 4211                    return None;
 4212                }
 4213
 4214                let language = buffer.language()?;
 4215                if let Some(restrict_to_languages) = restrict_to_languages {
 4216                    if !restrict_to_languages.contains(language) {
 4217                        return None;
 4218                    }
 4219                }
 4220                Some((
 4221                    excerpt_id,
 4222                    (
 4223                        buffer_handle,
 4224                        buffer.version().clone(),
 4225                        excerpt_visible_range,
 4226                    ),
 4227                ))
 4228            })
 4229            .collect()
 4230    }
 4231
 4232    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 4233        TextLayoutDetails {
 4234            text_system: cx.text_system().clone(),
 4235            editor_style: self.style.clone().unwrap(),
 4236            rem_size: cx.rem_size(),
 4237            scroll_anchor: self.scroll_manager.anchor(),
 4238            visible_rows: self.visible_line_count(),
 4239            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 4240        }
 4241    }
 4242
 4243    fn splice_inlays(
 4244        &self,
 4245        to_remove: Vec<InlayId>,
 4246        to_insert: Vec<Inlay>,
 4247        cx: &mut ViewContext<Self>,
 4248    ) {
 4249        self.display_map.update(cx, |display_map, cx| {
 4250            display_map.splice_inlays(to_remove, to_insert, cx);
 4251        });
 4252        cx.notify();
 4253    }
 4254
 4255    fn trigger_on_type_formatting(
 4256        &self,
 4257        input: String,
 4258        cx: &mut ViewContext<Self>,
 4259    ) -> Option<Task<Result<()>>> {
 4260        if input.len() != 1 {
 4261            return None;
 4262        }
 4263
 4264        let project = self.project.as_ref()?;
 4265        let position = self.selections.newest_anchor().head();
 4266        let (buffer, buffer_position) = self
 4267            .buffer
 4268            .read(cx)
 4269            .text_anchor_for_position(position, cx)?;
 4270
 4271        let settings = language_settings::language_settings(
 4272            buffer
 4273                .read(cx)
 4274                .language_at(buffer_position)
 4275                .map(|l| l.name()),
 4276            buffer.read(cx).file(),
 4277            cx,
 4278        );
 4279        if !settings.use_on_type_format {
 4280            return None;
 4281        }
 4282
 4283        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 4284        // hence we do LSP request & edit on host side only — add formats to host's history.
 4285        let push_to_lsp_host_history = true;
 4286        // If this is not the host, append its history with new edits.
 4287        let push_to_client_history = project.read(cx).is_via_collab();
 4288
 4289        let on_type_formatting = project.update(cx, |project, cx| {
 4290            project.on_type_format(
 4291                buffer.clone(),
 4292                buffer_position,
 4293                input,
 4294                push_to_lsp_host_history,
 4295                cx,
 4296            )
 4297        });
 4298        Some(cx.spawn(|editor, mut cx| async move {
 4299            if let Some(transaction) = on_type_formatting.await? {
 4300                if push_to_client_history {
 4301                    buffer
 4302                        .update(&mut cx, |buffer, _| {
 4303                            buffer.push_transaction(transaction, Instant::now());
 4304                        })
 4305                        .ok();
 4306                }
 4307                editor.update(&mut cx, |editor, cx| {
 4308                    editor.refresh_document_highlights(cx);
 4309                })?;
 4310            }
 4311            Ok(())
 4312        }))
 4313    }
 4314
 4315    pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
 4316        if self.pending_rename.is_some() {
 4317            return;
 4318        }
 4319
 4320        let Some(provider) = self.completion_provider.as_ref() else {
 4321            return;
 4322        };
 4323
 4324        let position = self.selections.newest_anchor().head();
 4325        let (buffer, buffer_position) =
 4326            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4327                output
 4328            } else {
 4329                return;
 4330            };
 4331
 4332        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4333        let is_followup_invoke = {
 4334            let context_menu_state = self.context_menu.read();
 4335            matches!(
 4336                context_menu_state.deref(),
 4337                Some(ContextMenu::Completions(_))
 4338            )
 4339        };
 4340        let trigger_kind = match (&options.trigger, is_followup_invoke) {
 4341            (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
 4342            (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4343                CompletionTriggerKind::TRIGGER_CHARACTER
 4344            }
 4345
 4346            _ => CompletionTriggerKind::INVOKED,
 4347        };
 4348        let completion_context = CompletionContext {
 4349            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 4350                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4351                    Some(String::from(trigger))
 4352                } else {
 4353                    None
 4354                }
 4355            }),
 4356            trigger_kind,
 4357        };
 4358        let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
 4359        let sort_completions = provider.sort_completions();
 4360
 4361        let id = post_inc(&mut self.next_completion_id);
 4362        let task = cx.spawn(|this, mut cx| {
 4363            async move {
 4364                this.update(&mut cx, |this, _| {
 4365                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4366                })?;
 4367                let completions = completions.await.log_err();
 4368                let menu = if let Some(completions) = completions {
 4369                    let mut menu = CompletionsMenu {
 4370                        id,
 4371                        sort_completions,
 4372                        initial_position: position,
 4373                        match_candidates: completions
 4374                            .iter()
 4375                            .enumerate()
 4376                            .map(|(id, completion)| {
 4377                                StringMatchCandidate::new(
 4378                                    id,
 4379                                    completion.label.text[completion.label.filter_range.clone()]
 4380                                        .into(),
 4381                                )
 4382                            })
 4383                            .collect(),
 4384                        buffer: buffer.clone(),
 4385                        completions: Arc::new(RwLock::new(completions.into())),
 4386                        matches: Vec::new().into(),
 4387                        selected_item: 0,
 4388                        scroll_handle: UniformListScrollHandle::new(),
 4389                        selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
 4390                            DebouncedDelay::new(),
 4391                        )),
 4392                    };
 4393                    menu.filter(query.as_deref(), cx.background_executor().clone())
 4394                        .await;
 4395
 4396                    if menu.matches.is_empty() {
 4397                        None
 4398                    } else {
 4399                        this.update(&mut cx, |editor, cx| {
 4400                            let completions = menu.completions.clone();
 4401                            let matches = menu.matches.clone();
 4402
 4403                            let delay_ms = EditorSettings::get_global(cx)
 4404                                .completion_documentation_secondary_query_debounce;
 4405                            let delay = Duration::from_millis(delay_ms);
 4406                            editor
 4407                                .completion_documentation_pre_resolve_debounce
 4408                                .fire_new(delay, cx, |editor, cx| {
 4409                                    CompletionsMenu::pre_resolve_completion_documentation(
 4410                                        buffer,
 4411                                        completions,
 4412                                        matches,
 4413                                        editor,
 4414                                        cx,
 4415                                    )
 4416                                });
 4417                        })
 4418                        .ok();
 4419                        Some(menu)
 4420                    }
 4421                } else {
 4422                    None
 4423                };
 4424
 4425                this.update(&mut cx, |this, cx| {
 4426                    let mut context_menu = this.context_menu.write();
 4427                    match context_menu.as_ref() {
 4428                        None => {}
 4429
 4430                        Some(ContextMenu::Completions(prev_menu)) => {
 4431                            if prev_menu.id > id {
 4432                                return;
 4433                            }
 4434                        }
 4435
 4436                        _ => return,
 4437                    }
 4438
 4439                    if this.focus_handle.is_focused(cx) && menu.is_some() {
 4440                        let menu = menu.unwrap();
 4441                        *context_menu = Some(ContextMenu::Completions(menu));
 4442                        drop(context_menu);
 4443                        this.discard_inline_completion(false, cx);
 4444                        cx.notify();
 4445                    } else if this.completion_tasks.len() <= 1 {
 4446                        // If there are no more completion tasks and the last menu was
 4447                        // empty, we should hide it. If it was already hidden, we should
 4448                        // also show the copilot completion when available.
 4449                        drop(context_menu);
 4450                        if this.hide_context_menu(cx).is_none() {
 4451                            this.update_visible_inline_completion(cx);
 4452                        }
 4453                    }
 4454                })?;
 4455
 4456                Ok::<_, anyhow::Error>(())
 4457            }
 4458            .log_err()
 4459        });
 4460
 4461        self.completion_tasks.push((id, task));
 4462    }
 4463
 4464    pub fn confirm_completion(
 4465        &mut self,
 4466        action: &ConfirmCompletion,
 4467        cx: &mut ViewContext<Self>,
 4468    ) -> Option<Task<Result<()>>> {
 4469        self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
 4470    }
 4471
 4472    pub fn compose_completion(
 4473        &mut self,
 4474        action: &ComposeCompletion,
 4475        cx: &mut ViewContext<Self>,
 4476    ) -> Option<Task<Result<()>>> {
 4477        self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
 4478    }
 4479
 4480    fn do_completion(
 4481        &mut self,
 4482        item_ix: Option<usize>,
 4483        intent: CompletionIntent,
 4484        cx: &mut ViewContext<Editor>,
 4485    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 4486        use language::ToOffset as _;
 4487
 4488        let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 4489            menu
 4490        } else {
 4491            return None;
 4492        };
 4493
 4494        let mat = completions_menu
 4495            .matches
 4496            .get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4497        let buffer_handle = completions_menu.buffer;
 4498        let completions = completions_menu.completions.read();
 4499        let completion = completions.get(mat.candidate_id)?;
 4500        cx.stop_propagation();
 4501
 4502        let snippet;
 4503        let text;
 4504
 4505        if completion.is_snippet() {
 4506            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4507            text = snippet.as_ref().unwrap().text.clone();
 4508        } else {
 4509            snippet = None;
 4510            text = completion.new_text.clone();
 4511        };
 4512        let selections = self.selections.all::<usize>(cx);
 4513        let buffer = buffer_handle.read(cx);
 4514        let old_range = completion.old_range.to_offset(buffer);
 4515        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4516
 4517        let newest_selection = self.selections.newest_anchor();
 4518        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4519            return None;
 4520        }
 4521
 4522        let lookbehind = newest_selection
 4523            .start
 4524            .text_anchor
 4525            .to_offset(buffer)
 4526            .saturating_sub(old_range.start);
 4527        let lookahead = old_range
 4528            .end
 4529            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4530        let mut common_prefix_len = old_text
 4531            .bytes()
 4532            .zip(text.bytes())
 4533            .take_while(|(a, b)| a == b)
 4534            .count();
 4535
 4536        let snapshot = self.buffer.read(cx).snapshot(cx);
 4537        let mut range_to_replace: Option<Range<isize>> = None;
 4538        let mut ranges = Vec::new();
 4539        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4540        for selection in &selections {
 4541            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4542                let start = selection.start.saturating_sub(lookbehind);
 4543                let end = selection.end + lookahead;
 4544                if selection.id == newest_selection.id {
 4545                    range_to_replace = Some(
 4546                        ((start + common_prefix_len) as isize - selection.start as isize)
 4547                            ..(end as isize - selection.start as isize),
 4548                    );
 4549                }
 4550                ranges.push(start + common_prefix_len..end);
 4551            } else {
 4552                common_prefix_len = 0;
 4553                ranges.clear();
 4554                ranges.extend(selections.iter().map(|s| {
 4555                    if s.id == newest_selection.id {
 4556                        range_to_replace = Some(
 4557                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4558                                - selection.start as isize
 4559                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4560                                    - selection.start as isize,
 4561                        );
 4562                        old_range.clone()
 4563                    } else {
 4564                        s.start..s.end
 4565                    }
 4566                }));
 4567                break;
 4568            }
 4569            if !self.linked_edit_ranges.is_empty() {
 4570                let start_anchor = snapshot.anchor_before(selection.head());
 4571                let end_anchor = snapshot.anchor_after(selection.tail());
 4572                if let Some(ranges) = self
 4573                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4574                {
 4575                    for (buffer, edits) in ranges {
 4576                        linked_edits.entry(buffer.clone()).or_default().extend(
 4577                            edits
 4578                                .into_iter()
 4579                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4580                        );
 4581                    }
 4582                }
 4583            }
 4584        }
 4585        let text = &text[common_prefix_len..];
 4586
 4587        cx.emit(EditorEvent::InputHandled {
 4588            utf16_range_to_replace: range_to_replace,
 4589            text: text.into(),
 4590        });
 4591
 4592        self.transact(cx, |this, cx| {
 4593            if let Some(mut snippet) = snippet {
 4594                snippet.text = text.to_string();
 4595                for tabstop in snippet.tabstops.iter_mut().flatten() {
 4596                    tabstop.start -= common_prefix_len as isize;
 4597                    tabstop.end -= common_prefix_len as isize;
 4598                }
 4599
 4600                this.insert_snippet(&ranges, snippet, cx).log_err();
 4601            } else {
 4602                this.buffer.update(cx, |buffer, cx| {
 4603                    buffer.edit(
 4604                        ranges.iter().map(|range| (range.clone(), text)),
 4605                        this.autoindent_mode.clone(),
 4606                        cx,
 4607                    );
 4608                });
 4609            }
 4610            for (buffer, edits) in linked_edits {
 4611                buffer.update(cx, |buffer, cx| {
 4612                    let snapshot = buffer.snapshot();
 4613                    let edits = edits
 4614                        .into_iter()
 4615                        .map(|(range, text)| {
 4616                            use text::ToPoint as TP;
 4617                            let end_point = TP::to_point(&range.end, &snapshot);
 4618                            let start_point = TP::to_point(&range.start, &snapshot);
 4619                            (start_point..end_point, text)
 4620                        })
 4621                        .sorted_by_key(|(range, _)| range.start)
 4622                        .collect::<Vec<_>>();
 4623                    buffer.edit(edits, None, cx);
 4624                })
 4625            }
 4626
 4627            this.refresh_inline_completion(true, false, cx);
 4628        });
 4629
 4630        let show_new_completions_on_confirm = completion
 4631            .confirm
 4632            .as_ref()
 4633            .map_or(false, |confirm| confirm(intent, cx));
 4634        if show_new_completions_on_confirm {
 4635            self.show_completions(&ShowCompletions { trigger: None }, cx);
 4636        }
 4637
 4638        let provider = self.completion_provider.as_ref()?;
 4639        let apply_edits = provider.apply_additional_edits_for_completion(
 4640            buffer_handle,
 4641            completion.clone(),
 4642            true,
 4643            cx,
 4644        );
 4645
 4646        let editor_settings = EditorSettings::get_global(cx);
 4647        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4648            // After the code completion is finished, users often want to know what signatures are needed.
 4649            // so we should automatically call signature_help
 4650            self.show_signature_help(&ShowSignatureHelp, cx);
 4651        }
 4652
 4653        Some(cx.foreground_executor().spawn(async move {
 4654            apply_edits.await?;
 4655            Ok(())
 4656        }))
 4657    }
 4658
 4659    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 4660        let mut context_menu = self.context_menu.write();
 4661        if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4662            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4663                // Toggle if we're selecting the same one
 4664                *context_menu = None;
 4665                cx.notify();
 4666                return;
 4667            } else {
 4668                // Otherwise, clear it and start a new one
 4669                *context_menu = None;
 4670                cx.notify();
 4671            }
 4672        }
 4673        drop(context_menu);
 4674        let snapshot = self.snapshot(cx);
 4675        let deployed_from_indicator = action.deployed_from_indicator;
 4676        let mut task = self.code_actions_task.take();
 4677        let action = action.clone();
 4678        cx.spawn(|editor, mut cx| async move {
 4679            while let Some(prev_task) = task {
 4680                prev_task.await.log_err();
 4681                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4682            }
 4683
 4684            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 4685                if editor.focus_handle.is_focused(cx) {
 4686                    let multibuffer_point = action
 4687                        .deployed_from_indicator
 4688                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4689                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4690                    let (buffer, buffer_row) = snapshot
 4691                        .buffer_snapshot
 4692                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4693                        .and_then(|(buffer_snapshot, range)| {
 4694                            editor
 4695                                .buffer
 4696                                .read(cx)
 4697                                .buffer(buffer_snapshot.remote_id())
 4698                                .map(|buffer| (buffer, range.start.row))
 4699                        })?;
 4700                    let (_, code_actions) = editor
 4701                        .available_code_actions
 4702                        .clone()
 4703                        .and_then(|(location, code_actions)| {
 4704                            let snapshot = location.buffer.read(cx).snapshot();
 4705                            let point_range = location.range.to_point(&snapshot);
 4706                            let point_range = point_range.start.row..=point_range.end.row;
 4707                            if point_range.contains(&buffer_row) {
 4708                                Some((location, code_actions))
 4709                            } else {
 4710                                None
 4711                            }
 4712                        })
 4713                        .unzip();
 4714                    let buffer_id = buffer.read(cx).remote_id();
 4715                    let tasks = editor
 4716                        .tasks
 4717                        .get(&(buffer_id, buffer_row))
 4718                        .map(|t| Arc::new(t.to_owned()));
 4719                    if tasks.is_none() && code_actions.is_none() {
 4720                        return None;
 4721                    }
 4722
 4723                    editor.completion_tasks.clear();
 4724                    editor.discard_inline_completion(false, cx);
 4725                    let task_context =
 4726                        tasks
 4727                            .as_ref()
 4728                            .zip(editor.project.clone())
 4729                            .map(|(tasks, project)| {
 4730                                let position = Point::new(buffer_row, tasks.column);
 4731                                let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 4732                                let location = Location {
 4733                                    buffer: buffer.clone(),
 4734                                    range: range_start..range_start,
 4735                                };
 4736                                // Fill in the environmental variables from the tree-sitter captures
 4737                                let mut captured_task_variables = TaskVariables::default();
 4738                                for (capture_name, value) in tasks.extra_variables.clone() {
 4739                                    captured_task_variables.insert(
 4740                                        task::VariableName::Custom(capture_name.into()),
 4741                                        value.clone(),
 4742                                    );
 4743                                }
 4744                                project.update(cx, |project, cx| {
 4745                                    project.task_store().update(cx, |task_store, cx| {
 4746                                        task_store.task_context_for_location(
 4747                                            captured_task_variables,
 4748                                            location,
 4749                                            cx,
 4750                                        )
 4751                                    })
 4752                                })
 4753                            });
 4754
 4755                    Some(cx.spawn(|editor, mut cx| async move {
 4756                        let task_context = match task_context {
 4757                            Some(task_context) => task_context.await,
 4758                            None => None,
 4759                        };
 4760                        let resolved_tasks =
 4761                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4762                                Arc::new(ResolvedTasks {
 4763                                    templates: tasks
 4764                                        .templates
 4765                                        .iter()
 4766                                        .filter_map(|(kind, template)| {
 4767                                            template
 4768                                                .resolve_task(&kind.to_id_base(), &task_context)
 4769                                                .map(|task| (kind.clone(), task))
 4770                                        })
 4771                                        .collect(),
 4772                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4773                                        multibuffer_point.row,
 4774                                        tasks.column,
 4775                                    )),
 4776                                })
 4777                            });
 4778                        let spawn_straight_away = resolved_tasks
 4779                            .as_ref()
 4780                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4781                            && code_actions
 4782                                .as_ref()
 4783                                .map_or(true, |actions| actions.is_empty());
 4784                        if let Ok(task) = editor.update(&mut cx, |editor, cx| {
 4785                            *editor.context_menu.write() =
 4786                                Some(ContextMenu::CodeActions(CodeActionsMenu {
 4787                                    buffer,
 4788                                    actions: CodeActionContents {
 4789                                        tasks: resolved_tasks,
 4790                                        actions: code_actions,
 4791                                    },
 4792                                    selected_item: Default::default(),
 4793                                    scroll_handle: UniformListScrollHandle::default(),
 4794                                    deployed_from_indicator,
 4795                                }));
 4796                            if spawn_straight_away {
 4797                                if let Some(task) = editor.confirm_code_action(
 4798                                    &ConfirmCodeAction { item_ix: Some(0) },
 4799                                    cx,
 4800                                ) {
 4801                                    cx.notify();
 4802                                    return task;
 4803                                }
 4804                            }
 4805                            cx.notify();
 4806                            Task::ready(Ok(()))
 4807                        }) {
 4808                            task.await
 4809                        } else {
 4810                            Ok(())
 4811                        }
 4812                    }))
 4813                } else {
 4814                    Some(Task::ready(Ok(())))
 4815                }
 4816            })?;
 4817            if let Some(task) = spawned_test_task {
 4818                task.await?;
 4819            }
 4820
 4821            Ok::<_, anyhow::Error>(())
 4822        })
 4823        .detach_and_log_err(cx);
 4824    }
 4825
 4826    pub fn confirm_code_action(
 4827        &mut self,
 4828        action: &ConfirmCodeAction,
 4829        cx: &mut ViewContext<Self>,
 4830    ) -> Option<Task<Result<()>>> {
 4831        let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4832            menu
 4833        } else {
 4834            return None;
 4835        };
 4836        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4837        let action = actions_menu.actions.get(action_ix)?;
 4838        let title = action.label();
 4839        let buffer = actions_menu.buffer;
 4840        let workspace = self.workspace()?;
 4841
 4842        match action {
 4843            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4844                workspace.update(cx, |workspace, cx| {
 4845                    workspace::tasks::schedule_resolved_task(
 4846                        workspace,
 4847                        task_source_kind,
 4848                        resolved_task,
 4849                        false,
 4850                        cx,
 4851                    );
 4852
 4853                    Some(Task::ready(Ok(())))
 4854                })
 4855            }
 4856            CodeActionsItem::CodeAction {
 4857                excerpt_id,
 4858                action,
 4859                provider,
 4860            } => {
 4861                let apply_code_action =
 4862                    provider.apply_code_action(buffer, action, excerpt_id, true, cx);
 4863                let workspace = workspace.downgrade();
 4864                Some(cx.spawn(|editor, cx| async move {
 4865                    let project_transaction = apply_code_action.await?;
 4866                    Self::open_project_transaction(
 4867                        &editor,
 4868                        workspace,
 4869                        project_transaction,
 4870                        title,
 4871                        cx,
 4872                    )
 4873                    .await
 4874                }))
 4875            }
 4876        }
 4877    }
 4878
 4879    pub async fn open_project_transaction(
 4880        this: &WeakView<Editor>,
 4881        workspace: WeakView<Workspace>,
 4882        transaction: ProjectTransaction,
 4883        title: String,
 4884        mut cx: AsyncWindowContext,
 4885    ) -> Result<()> {
 4886        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4887        cx.update(|cx| {
 4888            entries.sort_unstable_by_key(|(buffer, _)| {
 4889                buffer.read(cx).file().map(|f| f.path().clone())
 4890            });
 4891        })?;
 4892
 4893        // If the project transaction's edits are all contained within this editor, then
 4894        // avoid opening a new editor to display them.
 4895
 4896        if let Some((buffer, transaction)) = entries.first() {
 4897            if entries.len() == 1 {
 4898                let excerpt = this.update(&mut cx, |editor, cx| {
 4899                    editor
 4900                        .buffer()
 4901                        .read(cx)
 4902                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4903                })?;
 4904                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4905                    if excerpted_buffer == *buffer {
 4906                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4907                            let excerpt_range = excerpt_range.to_offset(buffer);
 4908                            buffer
 4909                                .edited_ranges_for_transaction::<usize>(transaction)
 4910                                .all(|range| {
 4911                                    excerpt_range.start <= range.start
 4912                                        && excerpt_range.end >= range.end
 4913                                })
 4914                        })?;
 4915
 4916                        if all_edits_within_excerpt {
 4917                            return Ok(());
 4918                        }
 4919                    }
 4920                }
 4921            }
 4922        } else {
 4923            return Ok(());
 4924        }
 4925
 4926        let mut ranges_to_highlight = Vec::new();
 4927        let excerpt_buffer = cx.new_model(|cx| {
 4928            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4929            for (buffer_handle, transaction) in &entries {
 4930                let buffer = buffer_handle.read(cx);
 4931                ranges_to_highlight.extend(
 4932                    multibuffer.push_excerpts_with_context_lines(
 4933                        buffer_handle.clone(),
 4934                        buffer
 4935                            .edited_ranges_for_transaction::<usize>(transaction)
 4936                            .collect(),
 4937                        DEFAULT_MULTIBUFFER_CONTEXT,
 4938                        cx,
 4939                    ),
 4940                );
 4941            }
 4942            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4943            multibuffer
 4944        })?;
 4945
 4946        workspace.update(&mut cx, |workspace, cx| {
 4947            let project = workspace.project().clone();
 4948            let editor =
 4949                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 4950            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 4951            editor.update(cx, |editor, cx| {
 4952                editor.highlight_background::<Self>(
 4953                    &ranges_to_highlight,
 4954                    |theme| theme.editor_highlighted_line_background,
 4955                    cx,
 4956                );
 4957            });
 4958        })?;
 4959
 4960        Ok(())
 4961    }
 4962
 4963    pub fn clear_code_action_providers(&mut self) {
 4964        self.code_action_providers.clear();
 4965        self.available_code_actions.take();
 4966    }
 4967
 4968    pub fn push_code_action_provider(
 4969        &mut self,
 4970        provider: Arc<dyn CodeActionProvider>,
 4971        cx: &mut ViewContext<Self>,
 4972    ) {
 4973        self.code_action_providers.push(provider);
 4974        self.refresh_code_actions(cx);
 4975    }
 4976
 4977    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4978        let buffer = self.buffer.read(cx);
 4979        let newest_selection = self.selections.newest_anchor().clone();
 4980        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4981        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4982        if start_buffer != end_buffer {
 4983            return None;
 4984        }
 4985
 4986        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 4987            cx.background_executor()
 4988                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4989                .await;
 4990
 4991            let (providers, tasks) = this.update(&mut cx, |this, cx| {
 4992                let providers = this.code_action_providers.clone();
 4993                let tasks = this
 4994                    .code_action_providers
 4995                    .iter()
 4996                    .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
 4997                    .collect::<Vec<_>>();
 4998                (providers, tasks)
 4999            })?;
 5000
 5001            let mut actions = Vec::new();
 5002            for (provider, provider_actions) in
 5003                providers.into_iter().zip(future::join_all(tasks).await)
 5004            {
 5005                if let Some(provider_actions) = provider_actions.log_err() {
 5006                    actions.extend(provider_actions.into_iter().map(|action| {
 5007                        AvailableCodeAction {
 5008                            excerpt_id: newest_selection.start.excerpt_id,
 5009                            action,
 5010                            provider: provider.clone(),
 5011                        }
 5012                    }));
 5013                }
 5014            }
 5015
 5016            this.update(&mut cx, |this, cx| {
 5017                this.available_code_actions = if actions.is_empty() {
 5018                    None
 5019                } else {
 5020                    Some((
 5021                        Location {
 5022                            buffer: start_buffer,
 5023                            range: start..end,
 5024                        },
 5025                        actions.into(),
 5026                    ))
 5027                };
 5028                cx.notify();
 5029            })
 5030        }));
 5031        None
 5032    }
 5033
 5034    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 5035        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 5036            self.show_git_blame_inline = false;
 5037
 5038            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 5039                cx.background_executor().timer(delay).await;
 5040
 5041                this.update(&mut cx, |this, cx| {
 5042                    this.show_git_blame_inline = true;
 5043                    cx.notify();
 5044                })
 5045                .log_err();
 5046            }));
 5047        }
 5048    }
 5049
 5050    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 5051        if self.pending_rename.is_some() {
 5052            return None;
 5053        }
 5054
 5055        let provider = self.semantics_provider.clone()?;
 5056        let buffer = self.buffer.read(cx);
 5057        let newest_selection = self.selections.newest_anchor().clone();
 5058        let cursor_position = newest_selection.head();
 5059        let (cursor_buffer, cursor_buffer_position) =
 5060            buffer.text_anchor_for_position(cursor_position, cx)?;
 5061        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 5062        if cursor_buffer != tail_buffer {
 5063            return None;
 5064        }
 5065
 5066        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 5067            cx.background_executor()
 5068                .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
 5069                .await;
 5070
 5071            let highlights = if let Some(highlights) = cx
 5072                .update(|cx| {
 5073                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 5074                })
 5075                .ok()
 5076                .flatten()
 5077            {
 5078                highlights.await.log_err()
 5079            } else {
 5080                None
 5081            };
 5082
 5083            if let Some(highlights) = highlights {
 5084                this.update(&mut cx, |this, cx| {
 5085                    if this.pending_rename.is_some() {
 5086                        return;
 5087                    }
 5088
 5089                    let buffer_id = cursor_position.buffer_id;
 5090                    let buffer = this.buffer.read(cx);
 5091                    if !buffer
 5092                        .text_anchor_for_position(cursor_position, cx)
 5093                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 5094                    {
 5095                        return;
 5096                    }
 5097
 5098                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 5099                    let mut write_ranges = Vec::new();
 5100                    let mut read_ranges = Vec::new();
 5101                    for highlight in highlights {
 5102                        for (excerpt_id, excerpt_range) in
 5103                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 5104                        {
 5105                            let start = highlight
 5106                                .range
 5107                                .start
 5108                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 5109                            let end = highlight
 5110                                .range
 5111                                .end
 5112                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 5113                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 5114                                continue;
 5115                            }
 5116
 5117                            let range = Anchor {
 5118                                buffer_id,
 5119                                excerpt_id,
 5120                                text_anchor: start,
 5121                            }..Anchor {
 5122                                buffer_id,
 5123                                excerpt_id,
 5124                                text_anchor: end,
 5125                            };
 5126                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 5127                                write_ranges.push(range);
 5128                            } else {
 5129                                read_ranges.push(range);
 5130                            }
 5131                        }
 5132                    }
 5133
 5134                    this.highlight_background::<DocumentHighlightRead>(
 5135                        &read_ranges,
 5136                        |theme| theme.editor_document_highlight_read_background,
 5137                        cx,
 5138                    );
 5139                    this.highlight_background::<DocumentHighlightWrite>(
 5140                        &write_ranges,
 5141                        |theme| theme.editor_document_highlight_write_background,
 5142                        cx,
 5143                    );
 5144                    cx.notify();
 5145                })
 5146                .log_err();
 5147            }
 5148        }));
 5149        None
 5150    }
 5151
 5152    pub fn refresh_inline_completion(
 5153        &mut self,
 5154        debounce: bool,
 5155        user_requested: bool,
 5156        cx: &mut ViewContext<Self>,
 5157    ) -> Option<()> {
 5158        let provider = self.inline_completion_provider()?;
 5159        let cursor = self.selections.newest_anchor().head();
 5160        let (buffer, cursor_buffer_position) =
 5161            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5162
 5163        if !user_requested
 5164            && (!self.enable_inline_completions
 5165                || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx))
 5166        {
 5167            self.discard_inline_completion(false, cx);
 5168            return None;
 5169        }
 5170
 5171        self.update_visible_inline_completion(cx);
 5172        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 5173        Some(())
 5174    }
 5175
 5176    fn cycle_inline_completion(
 5177        &mut self,
 5178        direction: Direction,
 5179        cx: &mut ViewContext<Self>,
 5180    ) -> Option<()> {
 5181        let provider = self.inline_completion_provider()?;
 5182        let cursor = self.selections.newest_anchor().head();
 5183        let (buffer, cursor_buffer_position) =
 5184            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5185        if !self.enable_inline_completions
 5186            || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 5187        {
 5188            return None;
 5189        }
 5190
 5191        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5192        self.update_visible_inline_completion(cx);
 5193
 5194        Some(())
 5195    }
 5196
 5197    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 5198        if !self.has_active_inline_completion(cx) {
 5199            self.refresh_inline_completion(false, true, cx);
 5200            return;
 5201        }
 5202
 5203        self.update_visible_inline_completion(cx);
 5204    }
 5205
 5206    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 5207        self.show_cursor_names(cx);
 5208    }
 5209
 5210    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 5211        self.show_cursor_names = true;
 5212        cx.notify();
 5213        cx.spawn(|this, mut cx| async move {
 5214            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5215            this.update(&mut cx, |this, cx| {
 5216                this.show_cursor_names = false;
 5217                cx.notify()
 5218            })
 5219            .ok()
 5220        })
 5221        .detach();
 5222    }
 5223
 5224    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 5225        if self.has_active_inline_completion(cx) {
 5226            self.cycle_inline_completion(Direction::Next, cx);
 5227        } else {
 5228            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5229            if is_copilot_disabled {
 5230                cx.propagate();
 5231            }
 5232        }
 5233    }
 5234
 5235    pub fn previous_inline_completion(
 5236        &mut self,
 5237        _: &PreviousInlineCompletion,
 5238        cx: &mut ViewContext<Self>,
 5239    ) {
 5240        if self.has_active_inline_completion(cx) {
 5241            self.cycle_inline_completion(Direction::Prev, cx);
 5242        } else {
 5243            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5244            if is_copilot_disabled {
 5245                cx.propagate();
 5246            }
 5247        }
 5248    }
 5249
 5250    pub fn accept_inline_completion(
 5251        &mut self,
 5252        _: &AcceptInlineCompletion,
 5253        cx: &mut ViewContext<Self>,
 5254    ) {
 5255        let Some(completion) = self.take_active_inline_completion(cx) else {
 5256            return;
 5257        };
 5258        if let Some(provider) = self.inline_completion_provider() {
 5259            provider.accept(cx);
 5260        }
 5261
 5262        cx.emit(EditorEvent::InputHandled {
 5263            utf16_range_to_replace: None,
 5264            text: completion.text.to_string().into(),
 5265        });
 5266
 5267        if let Some(range) = completion.delete_range {
 5268            self.change_selections(None, cx, |s| s.select_ranges([range]))
 5269        }
 5270        self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
 5271        self.refresh_inline_completion(true, true, cx);
 5272        cx.notify();
 5273    }
 5274
 5275    pub fn accept_partial_inline_completion(
 5276        &mut self,
 5277        _: &AcceptPartialInlineCompletion,
 5278        cx: &mut ViewContext<Self>,
 5279    ) {
 5280        if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
 5281            if let Some(completion) = self.take_active_inline_completion(cx) {
 5282                let mut partial_completion = completion
 5283                    .text
 5284                    .chars()
 5285                    .by_ref()
 5286                    .take_while(|c| c.is_alphabetic())
 5287                    .collect::<String>();
 5288                if partial_completion.is_empty() {
 5289                    partial_completion = completion
 5290                        .text
 5291                        .chars()
 5292                        .by_ref()
 5293                        .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5294                        .collect::<String>();
 5295                }
 5296
 5297                cx.emit(EditorEvent::InputHandled {
 5298                    utf16_range_to_replace: None,
 5299                    text: partial_completion.clone().into(),
 5300                });
 5301
 5302                if let Some(range) = completion.delete_range {
 5303                    self.change_selections(None, cx, |s| s.select_ranges([range]))
 5304                }
 5305                self.insert_with_autoindent_mode(&partial_completion, None, cx);
 5306
 5307                self.refresh_inline_completion(true, true, cx);
 5308                cx.notify();
 5309            }
 5310        }
 5311    }
 5312
 5313    fn discard_inline_completion(
 5314        &mut self,
 5315        should_report_inline_completion_event: bool,
 5316        cx: &mut ViewContext<Self>,
 5317    ) -> bool {
 5318        if let Some(provider) = self.inline_completion_provider() {
 5319            provider.discard(should_report_inline_completion_event, cx);
 5320        }
 5321
 5322        self.take_active_inline_completion(cx).is_some()
 5323    }
 5324
 5325    pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
 5326        if let Some(completion) = self.active_inline_completion.as_ref() {
 5327            let buffer = self.buffer.read(cx).read(cx);
 5328            completion.position.is_valid(&buffer)
 5329        } else {
 5330            false
 5331        }
 5332    }
 5333
 5334    fn take_active_inline_completion(
 5335        &mut self,
 5336        cx: &mut ViewContext<Self>,
 5337    ) -> Option<CompletionState> {
 5338        let completion = self.active_inline_completion.take()?;
 5339        let render_inlay_ids = completion.render_inlay_ids.clone();
 5340        self.display_map.update(cx, |map, cx| {
 5341            map.splice_inlays(render_inlay_ids, Default::default(), cx);
 5342        });
 5343        let buffer = self.buffer.read(cx).read(cx);
 5344
 5345        if completion.position.is_valid(&buffer) {
 5346            Some(completion)
 5347        } else {
 5348            None
 5349        }
 5350    }
 5351
 5352    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
 5353        let selection = self.selections.newest_anchor();
 5354        let cursor = selection.head();
 5355
 5356        let excerpt_id = cursor.excerpt_id;
 5357
 5358        if self.context_menu.read().is_none()
 5359            && self.completion_tasks.is_empty()
 5360            && selection.start == selection.end
 5361        {
 5362            if let Some(provider) = self.inline_completion_provider() {
 5363                if let Some((buffer, cursor_buffer_position)) =
 5364                    self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5365                {
 5366                    if let Some(proposal) =
 5367                        provider.active_completion_text(&buffer, cursor_buffer_position, cx)
 5368                    {
 5369                        let mut to_remove = Vec::new();
 5370                        if let Some(completion) = self.active_inline_completion.take() {
 5371                            to_remove.extend(completion.render_inlay_ids.iter());
 5372                        }
 5373
 5374                        let to_add = proposal
 5375                            .inlays
 5376                            .iter()
 5377                            .filter_map(|inlay| {
 5378                                let snapshot = self.buffer.read(cx).snapshot(cx);
 5379                                let id = post_inc(&mut self.next_inlay_id);
 5380                                match inlay {
 5381                                    InlayProposal::Hint(position, hint) => {
 5382                                        let position =
 5383                                            snapshot.anchor_in_excerpt(excerpt_id, *position)?;
 5384                                        Some(Inlay::hint(id, position, hint))
 5385                                    }
 5386                                    InlayProposal::Suggestion(position, text) => {
 5387                                        let position =
 5388                                            snapshot.anchor_in_excerpt(excerpt_id, *position)?;
 5389                                        Some(Inlay::suggestion(id, position, text.clone()))
 5390                                    }
 5391                                }
 5392                            })
 5393                            .collect_vec();
 5394
 5395                        self.active_inline_completion = Some(CompletionState {
 5396                            position: cursor,
 5397                            text: proposal.text,
 5398                            delete_range: proposal.delete_range.and_then(|range| {
 5399                                let snapshot = self.buffer.read(cx).snapshot(cx);
 5400                                let start = snapshot.anchor_in_excerpt(excerpt_id, range.start);
 5401                                let end = snapshot.anchor_in_excerpt(excerpt_id, range.end);
 5402                                Some(start?..end?)
 5403                            }),
 5404                            render_inlay_ids: to_add.iter().map(|i| i.id).collect(),
 5405                        });
 5406
 5407                        self.display_map
 5408                            .update(cx, move |map, cx| map.splice_inlays(to_remove, to_add, cx));
 5409
 5410                        cx.notify();
 5411                        return;
 5412                    }
 5413                }
 5414            }
 5415        }
 5416
 5417        self.discard_inline_completion(false, cx);
 5418    }
 5419
 5420    fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5421        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 5422    }
 5423
 5424    fn render_code_actions_indicator(
 5425        &self,
 5426        _style: &EditorStyle,
 5427        row: DisplayRow,
 5428        is_active: bool,
 5429        cx: &mut ViewContext<Self>,
 5430    ) -> Option<IconButton> {
 5431        if self.available_code_actions.is_some() {
 5432            Some(
 5433                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5434                    .shape(ui::IconButtonShape::Square)
 5435                    .icon_size(IconSize::XSmall)
 5436                    .icon_color(Color::Muted)
 5437                    .selected(is_active)
 5438                    .tooltip({
 5439                        let focus_handle = self.focus_handle.clone();
 5440                        move |cx| {
 5441                            Tooltip::for_action_in(
 5442                                "Toggle Code Actions",
 5443                                &ToggleCodeActions {
 5444                                    deployed_from_indicator: None,
 5445                                },
 5446                                &focus_handle,
 5447                                cx,
 5448                            )
 5449                        }
 5450                    })
 5451                    .on_click(cx.listener(move |editor, _e, cx| {
 5452                        editor.focus(cx);
 5453                        editor.toggle_code_actions(
 5454                            &ToggleCodeActions {
 5455                                deployed_from_indicator: Some(row),
 5456                            },
 5457                            cx,
 5458                        );
 5459                    })),
 5460            )
 5461        } else {
 5462            None
 5463        }
 5464    }
 5465
 5466    fn clear_tasks(&mut self) {
 5467        self.tasks.clear()
 5468    }
 5469
 5470    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5471        if self.tasks.insert(key, value).is_some() {
 5472            // This case should hopefully be rare, but just in case...
 5473            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5474        }
 5475    }
 5476
 5477    fn render_run_indicator(
 5478        &self,
 5479        _style: &EditorStyle,
 5480        is_active: bool,
 5481        row: DisplayRow,
 5482        cx: &mut ViewContext<Self>,
 5483    ) -> IconButton {
 5484        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5485            .shape(ui::IconButtonShape::Square)
 5486            .icon_size(IconSize::XSmall)
 5487            .icon_color(Color::Muted)
 5488            .selected(is_active)
 5489            .on_click(cx.listener(move |editor, _e, cx| {
 5490                editor.focus(cx);
 5491                editor.toggle_code_actions(
 5492                    &ToggleCodeActions {
 5493                        deployed_from_indicator: Some(row),
 5494                    },
 5495                    cx,
 5496                );
 5497            }))
 5498    }
 5499
 5500    pub fn context_menu_visible(&self) -> bool {
 5501        self.context_menu
 5502            .read()
 5503            .as_ref()
 5504            .map_or(false, |menu| menu.visible())
 5505    }
 5506
 5507    fn render_context_menu(
 5508        &self,
 5509        cursor_position: DisplayPoint,
 5510        style: &EditorStyle,
 5511        max_height: Pixels,
 5512        cx: &mut ViewContext<Editor>,
 5513    ) -> Option<(ContextMenuOrigin, AnyElement)> {
 5514        self.context_menu.read().as_ref().map(|menu| {
 5515            menu.render(
 5516                cursor_position,
 5517                style,
 5518                max_height,
 5519                self.workspace.as_ref().map(|(w, _)| w.clone()),
 5520                cx,
 5521            )
 5522        })
 5523    }
 5524
 5525    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
 5526        cx.notify();
 5527        self.completion_tasks.clear();
 5528        let context_menu = self.context_menu.write().take();
 5529        if context_menu.is_some() {
 5530            self.update_visible_inline_completion(cx);
 5531        }
 5532        context_menu
 5533    }
 5534
 5535    pub fn insert_snippet(
 5536        &mut self,
 5537        insertion_ranges: &[Range<usize>],
 5538        snippet: Snippet,
 5539        cx: &mut ViewContext<Self>,
 5540    ) -> Result<()> {
 5541        struct Tabstop<T> {
 5542            is_end_tabstop: bool,
 5543            ranges: Vec<Range<T>>,
 5544        }
 5545
 5546        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5547            let snippet_text: Arc<str> = snippet.text.clone().into();
 5548            buffer.edit(
 5549                insertion_ranges
 5550                    .iter()
 5551                    .cloned()
 5552                    .map(|range| (range, snippet_text.clone())),
 5553                Some(AutoindentMode::EachLine),
 5554                cx,
 5555            );
 5556
 5557            let snapshot = &*buffer.read(cx);
 5558            let snippet = &snippet;
 5559            snippet
 5560                .tabstops
 5561                .iter()
 5562                .map(|tabstop| {
 5563                    let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
 5564                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5565                    });
 5566                    let mut tabstop_ranges = tabstop
 5567                        .iter()
 5568                        .flat_map(|tabstop_range| {
 5569                            let mut delta = 0_isize;
 5570                            insertion_ranges.iter().map(move |insertion_range| {
 5571                                let insertion_start = insertion_range.start as isize + delta;
 5572                                delta +=
 5573                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5574
 5575                                let start = ((insertion_start + tabstop_range.start) as usize)
 5576                                    .min(snapshot.len());
 5577                                let end = ((insertion_start + tabstop_range.end) as usize)
 5578                                    .min(snapshot.len());
 5579                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5580                            })
 5581                        })
 5582                        .collect::<Vec<_>>();
 5583                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5584
 5585                    Tabstop {
 5586                        is_end_tabstop,
 5587                        ranges: tabstop_ranges,
 5588                    }
 5589                })
 5590                .collect::<Vec<_>>()
 5591        });
 5592        if let Some(tabstop) = tabstops.first() {
 5593            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5594                s.select_ranges(tabstop.ranges.iter().cloned());
 5595            });
 5596
 5597            // If we're already at the last tabstop and it's at the end of the snippet,
 5598            // we're done, we don't need to keep the state around.
 5599            if !tabstop.is_end_tabstop {
 5600                let ranges = tabstops
 5601                    .into_iter()
 5602                    .map(|tabstop| tabstop.ranges)
 5603                    .collect::<Vec<_>>();
 5604                self.snippet_stack.push(SnippetState {
 5605                    active_index: 0,
 5606                    ranges,
 5607                });
 5608            }
 5609
 5610            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5611            if self.autoclose_regions.is_empty() {
 5612                let snapshot = self.buffer.read(cx).snapshot(cx);
 5613                for selection in &mut self.selections.all::<Point>(cx) {
 5614                    let selection_head = selection.head();
 5615                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5616                        continue;
 5617                    };
 5618
 5619                    let mut bracket_pair = None;
 5620                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5621                    let prev_chars = snapshot
 5622                        .reversed_chars_at(selection_head)
 5623                        .collect::<String>();
 5624                    for (pair, enabled) in scope.brackets() {
 5625                        if enabled
 5626                            && pair.close
 5627                            && prev_chars.starts_with(pair.start.as_str())
 5628                            && next_chars.starts_with(pair.end.as_str())
 5629                        {
 5630                            bracket_pair = Some(pair.clone());
 5631                            break;
 5632                        }
 5633                    }
 5634                    if let Some(pair) = bracket_pair {
 5635                        let start = snapshot.anchor_after(selection_head);
 5636                        let end = snapshot.anchor_after(selection_head);
 5637                        self.autoclose_regions.push(AutocloseRegion {
 5638                            selection_id: selection.id,
 5639                            range: start..end,
 5640                            pair,
 5641                        });
 5642                    }
 5643                }
 5644            }
 5645        }
 5646        Ok(())
 5647    }
 5648
 5649    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5650        self.move_to_snippet_tabstop(Bias::Right, cx)
 5651    }
 5652
 5653    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5654        self.move_to_snippet_tabstop(Bias::Left, cx)
 5655    }
 5656
 5657    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5658        if let Some(mut snippet) = self.snippet_stack.pop() {
 5659            match bias {
 5660                Bias::Left => {
 5661                    if snippet.active_index > 0 {
 5662                        snippet.active_index -= 1;
 5663                    } else {
 5664                        self.snippet_stack.push(snippet);
 5665                        return false;
 5666                    }
 5667                }
 5668                Bias::Right => {
 5669                    if snippet.active_index + 1 < snippet.ranges.len() {
 5670                        snippet.active_index += 1;
 5671                    } else {
 5672                        self.snippet_stack.push(snippet);
 5673                        return false;
 5674                    }
 5675                }
 5676            }
 5677            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5678                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5679                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5680                });
 5681                // If snippet state is not at the last tabstop, push it back on the stack
 5682                if snippet.active_index + 1 < snippet.ranges.len() {
 5683                    self.snippet_stack.push(snippet);
 5684                }
 5685                return true;
 5686            }
 5687        }
 5688
 5689        false
 5690    }
 5691
 5692    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 5693        self.transact(cx, |this, cx| {
 5694            this.select_all(&SelectAll, cx);
 5695            this.insert("", cx);
 5696        });
 5697    }
 5698
 5699    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 5700        self.transact(cx, |this, cx| {
 5701            this.select_autoclose_pair(cx);
 5702            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5703            if !this.linked_edit_ranges.is_empty() {
 5704                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5705                let snapshot = this.buffer.read(cx).snapshot(cx);
 5706
 5707                for selection in selections.iter() {
 5708                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5709                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 5710                    if selection_start.buffer_id != selection_end.buffer_id {
 5711                        continue;
 5712                    }
 5713                    if let Some(ranges) =
 5714                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 5715                    {
 5716                        for (buffer, entries) in ranges {
 5717                            linked_ranges.entry(buffer).or_default().extend(entries);
 5718                        }
 5719                    }
 5720                }
 5721            }
 5722
 5723            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 5724            if !this.selections.line_mode {
 5725                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 5726                for selection in &mut selections {
 5727                    if selection.is_empty() {
 5728                        let old_head = selection.head();
 5729                        let mut new_head =
 5730                            movement::left(&display_map, old_head.to_display_point(&display_map))
 5731                                .to_point(&display_map);
 5732                        if let Some((buffer, line_buffer_range)) = display_map
 5733                            .buffer_snapshot
 5734                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 5735                        {
 5736                            let indent_size =
 5737                                buffer.indent_size_for_line(line_buffer_range.start.row);
 5738                            let indent_len = match indent_size.kind {
 5739                                IndentKind::Space => {
 5740                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 5741                                }
 5742                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 5743                            };
 5744                            if old_head.column <= indent_size.len && old_head.column > 0 {
 5745                                let indent_len = indent_len.get();
 5746                                new_head = cmp::min(
 5747                                    new_head,
 5748                                    MultiBufferPoint::new(
 5749                                        old_head.row,
 5750                                        ((old_head.column - 1) / indent_len) * indent_len,
 5751                                    ),
 5752                                );
 5753                            }
 5754                        }
 5755
 5756                        selection.set_head(new_head, SelectionGoal::None);
 5757                    }
 5758                }
 5759            }
 5760
 5761            this.signature_help_state.set_backspace_pressed(true);
 5762            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5763            this.insert("", cx);
 5764            let empty_str: Arc<str> = Arc::from("");
 5765            for (buffer, edits) in linked_ranges {
 5766                let snapshot = buffer.read(cx).snapshot();
 5767                use text::ToPoint as TP;
 5768
 5769                let edits = edits
 5770                    .into_iter()
 5771                    .map(|range| {
 5772                        let end_point = TP::to_point(&range.end, &snapshot);
 5773                        let mut start_point = TP::to_point(&range.start, &snapshot);
 5774
 5775                        if end_point == start_point {
 5776                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 5777                                .saturating_sub(1);
 5778                            start_point = TP::to_point(&offset, &snapshot);
 5779                        };
 5780
 5781                        (start_point..end_point, empty_str.clone())
 5782                    })
 5783                    .sorted_by_key(|(range, _)| range.start)
 5784                    .collect::<Vec<_>>();
 5785                buffer.update(cx, |this, cx| {
 5786                    this.edit(edits, None, cx);
 5787                })
 5788            }
 5789            this.refresh_inline_completion(true, false, cx);
 5790            linked_editing_ranges::refresh_linked_ranges(this, cx);
 5791        });
 5792    }
 5793
 5794    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 5795        self.transact(cx, |this, cx| {
 5796            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5797                let line_mode = s.line_mode;
 5798                s.move_with(|map, selection| {
 5799                    if selection.is_empty() && !line_mode {
 5800                        let cursor = movement::right(map, selection.head());
 5801                        selection.end = cursor;
 5802                        selection.reversed = true;
 5803                        selection.goal = SelectionGoal::None;
 5804                    }
 5805                })
 5806            });
 5807            this.insert("", cx);
 5808            this.refresh_inline_completion(true, false, cx);
 5809        });
 5810    }
 5811
 5812    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 5813        if self.move_to_prev_snippet_tabstop(cx) {
 5814            return;
 5815        }
 5816
 5817        self.outdent(&Outdent, cx);
 5818    }
 5819
 5820    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 5821        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 5822            return;
 5823        }
 5824
 5825        let mut selections = self.selections.all_adjusted(cx);
 5826        let buffer = self.buffer.read(cx);
 5827        let snapshot = buffer.snapshot(cx);
 5828        let rows_iter = selections.iter().map(|s| s.head().row);
 5829        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 5830
 5831        let mut edits = Vec::new();
 5832        let mut prev_edited_row = 0;
 5833        let mut row_delta = 0;
 5834        for selection in &mut selections {
 5835            if selection.start.row != prev_edited_row {
 5836                row_delta = 0;
 5837            }
 5838            prev_edited_row = selection.end.row;
 5839
 5840            // If the selection is non-empty, then increase the indentation of the selected lines.
 5841            if !selection.is_empty() {
 5842                row_delta =
 5843                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5844                continue;
 5845            }
 5846
 5847            // If the selection is empty and the cursor is in the leading whitespace before the
 5848            // suggested indentation, then auto-indent the line.
 5849            let cursor = selection.head();
 5850            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 5851            if let Some(suggested_indent) =
 5852                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 5853            {
 5854                if cursor.column < suggested_indent.len
 5855                    && cursor.column <= current_indent.len
 5856                    && current_indent.len <= suggested_indent.len
 5857                {
 5858                    selection.start = Point::new(cursor.row, suggested_indent.len);
 5859                    selection.end = selection.start;
 5860                    if row_delta == 0 {
 5861                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 5862                            cursor.row,
 5863                            current_indent,
 5864                            suggested_indent,
 5865                        ));
 5866                        row_delta = suggested_indent.len - current_indent.len;
 5867                    }
 5868                    continue;
 5869                }
 5870            }
 5871
 5872            // Otherwise, insert a hard or soft tab.
 5873            let settings = buffer.settings_at(cursor, cx);
 5874            let tab_size = if settings.hard_tabs {
 5875                IndentSize::tab()
 5876            } else {
 5877                let tab_size = settings.tab_size.get();
 5878                let char_column = snapshot
 5879                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 5880                    .flat_map(str::chars)
 5881                    .count()
 5882                    + row_delta as usize;
 5883                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 5884                IndentSize::spaces(chars_to_next_tab_stop)
 5885            };
 5886            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 5887            selection.end = selection.start;
 5888            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 5889            row_delta += tab_size.len;
 5890        }
 5891
 5892        self.transact(cx, |this, cx| {
 5893            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5894            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5895            this.refresh_inline_completion(true, false, cx);
 5896        });
 5897    }
 5898
 5899    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 5900        if self.read_only(cx) {
 5901            return;
 5902        }
 5903        let mut selections = self.selections.all::<Point>(cx);
 5904        let mut prev_edited_row = 0;
 5905        let mut row_delta = 0;
 5906        let mut edits = Vec::new();
 5907        let buffer = self.buffer.read(cx);
 5908        let snapshot = buffer.snapshot(cx);
 5909        for selection in &mut selections {
 5910            if selection.start.row != prev_edited_row {
 5911                row_delta = 0;
 5912            }
 5913            prev_edited_row = selection.end.row;
 5914
 5915            row_delta =
 5916                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5917        }
 5918
 5919        self.transact(cx, |this, cx| {
 5920            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5921            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5922        });
 5923    }
 5924
 5925    fn indent_selection(
 5926        buffer: &MultiBuffer,
 5927        snapshot: &MultiBufferSnapshot,
 5928        selection: &mut Selection<Point>,
 5929        edits: &mut Vec<(Range<Point>, String)>,
 5930        delta_for_start_row: u32,
 5931        cx: &AppContext,
 5932    ) -> u32 {
 5933        let settings = buffer.settings_at(selection.start, cx);
 5934        let tab_size = settings.tab_size.get();
 5935        let indent_kind = if settings.hard_tabs {
 5936            IndentKind::Tab
 5937        } else {
 5938            IndentKind::Space
 5939        };
 5940        let mut start_row = selection.start.row;
 5941        let mut end_row = selection.end.row + 1;
 5942
 5943        // If a selection ends at the beginning of a line, don't indent
 5944        // that last line.
 5945        if selection.end.column == 0 && selection.end.row > selection.start.row {
 5946            end_row -= 1;
 5947        }
 5948
 5949        // Avoid re-indenting a row that has already been indented by a
 5950        // previous selection, but still update this selection's column
 5951        // to reflect that indentation.
 5952        if delta_for_start_row > 0 {
 5953            start_row += 1;
 5954            selection.start.column += delta_for_start_row;
 5955            if selection.end.row == selection.start.row {
 5956                selection.end.column += delta_for_start_row;
 5957            }
 5958        }
 5959
 5960        let mut delta_for_end_row = 0;
 5961        let has_multiple_rows = start_row + 1 != end_row;
 5962        for row in start_row..end_row {
 5963            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 5964            let indent_delta = match (current_indent.kind, indent_kind) {
 5965                (IndentKind::Space, IndentKind::Space) => {
 5966                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 5967                    IndentSize::spaces(columns_to_next_tab_stop)
 5968                }
 5969                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 5970                (_, IndentKind::Tab) => IndentSize::tab(),
 5971            };
 5972
 5973            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 5974                0
 5975            } else {
 5976                selection.start.column
 5977            };
 5978            let row_start = Point::new(row, start);
 5979            edits.push((
 5980                row_start..row_start,
 5981                indent_delta.chars().collect::<String>(),
 5982            ));
 5983
 5984            // Update this selection's endpoints to reflect the indentation.
 5985            if row == selection.start.row {
 5986                selection.start.column += indent_delta.len;
 5987            }
 5988            if row == selection.end.row {
 5989                selection.end.column += indent_delta.len;
 5990                delta_for_end_row = indent_delta.len;
 5991            }
 5992        }
 5993
 5994        if selection.start.row == selection.end.row {
 5995            delta_for_start_row + delta_for_end_row
 5996        } else {
 5997            delta_for_end_row
 5998        }
 5999    }
 6000
 6001    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 6002        if self.read_only(cx) {
 6003            return;
 6004        }
 6005        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6006        let selections = self.selections.all::<Point>(cx);
 6007        let mut deletion_ranges = Vec::new();
 6008        let mut last_outdent = None;
 6009        {
 6010            let buffer = self.buffer.read(cx);
 6011            let snapshot = buffer.snapshot(cx);
 6012            for selection in &selections {
 6013                let settings = buffer.settings_at(selection.start, cx);
 6014                let tab_size = settings.tab_size.get();
 6015                let mut rows = selection.spanned_rows(false, &display_map);
 6016
 6017                // Avoid re-outdenting a row that has already been outdented by a
 6018                // previous selection.
 6019                if let Some(last_row) = last_outdent {
 6020                    if last_row == rows.start {
 6021                        rows.start = rows.start.next_row();
 6022                    }
 6023                }
 6024                let has_multiple_rows = rows.len() > 1;
 6025                for row in rows.iter_rows() {
 6026                    let indent_size = snapshot.indent_size_for_line(row);
 6027                    if indent_size.len > 0 {
 6028                        let deletion_len = match indent_size.kind {
 6029                            IndentKind::Space => {
 6030                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 6031                                if columns_to_prev_tab_stop == 0 {
 6032                                    tab_size
 6033                                } else {
 6034                                    columns_to_prev_tab_stop
 6035                                }
 6036                            }
 6037                            IndentKind::Tab => 1,
 6038                        };
 6039                        let start = if has_multiple_rows
 6040                            || deletion_len > selection.start.column
 6041                            || indent_size.len < selection.start.column
 6042                        {
 6043                            0
 6044                        } else {
 6045                            selection.start.column - deletion_len
 6046                        };
 6047                        deletion_ranges.push(
 6048                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 6049                        );
 6050                        last_outdent = Some(row);
 6051                    }
 6052                }
 6053            }
 6054        }
 6055
 6056        self.transact(cx, |this, cx| {
 6057            this.buffer.update(cx, |buffer, cx| {
 6058                let empty_str: Arc<str> = Arc::default();
 6059                buffer.edit(
 6060                    deletion_ranges
 6061                        .into_iter()
 6062                        .map(|range| (range, empty_str.clone())),
 6063                    None,
 6064                    cx,
 6065                );
 6066            });
 6067            let selections = this.selections.all::<usize>(cx);
 6068            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6069        });
 6070    }
 6071
 6072    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 6073        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6074        let selections = self.selections.all::<Point>(cx);
 6075
 6076        let mut new_cursors = Vec::new();
 6077        let mut edit_ranges = Vec::new();
 6078        let mut selections = selections.iter().peekable();
 6079        while let Some(selection) = selections.next() {
 6080            let mut rows = selection.spanned_rows(false, &display_map);
 6081            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6082
 6083            // Accumulate contiguous regions of rows that we want to delete.
 6084            while let Some(next_selection) = selections.peek() {
 6085                let next_rows = next_selection.spanned_rows(false, &display_map);
 6086                if next_rows.start <= rows.end {
 6087                    rows.end = next_rows.end;
 6088                    selections.next().unwrap();
 6089                } else {
 6090                    break;
 6091                }
 6092            }
 6093
 6094            let buffer = &display_map.buffer_snapshot;
 6095            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6096            let edit_end;
 6097            let cursor_buffer_row;
 6098            if buffer.max_point().row >= rows.end.0 {
 6099                // If there's a line after the range, delete the \n from the end of the row range
 6100                // and position the cursor on the next line.
 6101                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6102                cursor_buffer_row = rows.end;
 6103            } else {
 6104                // If there isn't a line after the range, delete the \n from the line before the
 6105                // start of the row range and position the cursor there.
 6106                edit_start = edit_start.saturating_sub(1);
 6107                edit_end = buffer.len();
 6108                cursor_buffer_row = rows.start.previous_row();
 6109            }
 6110
 6111            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6112            *cursor.column_mut() =
 6113                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6114
 6115            new_cursors.push((
 6116                selection.id,
 6117                buffer.anchor_after(cursor.to_point(&display_map)),
 6118            ));
 6119            edit_ranges.push(edit_start..edit_end);
 6120        }
 6121
 6122        self.transact(cx, |this, cx| {
 6123            let buffer = this.buffer.update(cx, |buffer, cx| {
 6124                let empty_str: Arc<str> = Arc::default();
 6125                buffer.edit(
 6126                    edit_ranges
 6127                        .into_iter()
 6128                        .map(|range| (range, empty_str.clone())),
 6129                    None,
 6130                    cx,
 6131                );
 6132                buffer.snapshot(cx)
 6133            });
 6134            let new_selections = new_cursors
 6135                .into_iter()
 6136                .map(|(id, cursor)| {
 6137                    let cursor = cursor.to_point(&buffer);
 6138                    Selection {
 6139                        id,
 6140                        start: cursor,
 6141                        end: cursor,
 6142                        reversed: false,
 6143                        goal: SelectionGoal::None,
 6144                    }
 6145                })
 6146                .collect();
 6147
 6148            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6149                s.select(new_selections);
 6150            });
 6151        });
 6152    }
 6153
 6154    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 6155        if self.read_only(cx) {
 6156            return;
 6157        }
 6158        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6159        for selection in self.selections.all::<Point>(cx) {
 6160            let start = MultiBufferRow(selection.start.row);
 6161            let end = if selection.start.row == selection.end.row {
 6162                MultiBufferRow(selection.start.row + 1)
 6163            } else {
 6164                MultiBufferRow(selection.end.row)
 6165            };
 6166
 6167            if let Some(last_row_range) = row_ranges.last_mut() {
 6168                if start <= last_row_range.end {
 6169                    last_row_range.end = end;
 6170                    continue;
 6171                }
 6172            }
 6173            row_ranges.push(start..end);
 6174        }
 6175
 6176        let snapshot = self.buffer.read(cx).snapshot(cx);
 6177        let mut cursor_positions = Vec::new();
 6178        for row_range in &row_ranges {
 6179            let anchor = snapshot.anchor_before(Point::new(
 6180                row_range.end.previous_row().0,
 6181                snapshot.line_len(row_range.end.previous_row()),
 6182            ));
 6183            cursor_positions.push(anchor..anchor);
 6184        }
 6185
 6186        self.transact(cx, |this, cx| {
 6187            for row_range in row_ranges.into_iter().rev() {
 6188                for row in row_range.iter_rows().rev() {
 6189                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6190                    let next_line_row = row.next_row();
 6191                    let indent = snapshot.indent_size_for_line(next_line_row);
 6192                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 6193
 6194                    let replace = if snapshot.line_len(next_line_row) > indent.len {
 6195                        " "
 6196                    } else {
 6197                        ""
 6198                    };
 6199
 6200                    this.buffer.update(cx, |buffer, cx| {
 6201                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6202                    });
 6203                }
 6204            }
 6205
 6206            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6207                s.select_anchor_ranges(cursor_positions)
 6208            });
 6209        });
 6210    }
 6211
 6212    pub fn sort_lines_case_sensitive(
 6213        &mut self,
 6214        _: &SortLinesCaseSensitive,
 6215        cx: &mut ViewContext<Self>,
 6216    ) {
 6217        self.manipulate_lines(cx, |lines| lines.sort())
 6218    }
 6219
 6220    pub fn sort_lines_case_insensitive(
 6221        &mut self,
 6222        _: &SortLinesCaseInsensitive,
 6223        cx: &mut ViewContext<Self>,
 6224    ) {
 6225        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 6226    }
 6227
 6228    pub fn unique_lines_case_insensitive(
 6229        &mut self,
 6230        _: &UniqueLinesCaseInsensitive,
 6231        cx: &mut ViewContext<Self>,
 6232    ) {
 6233        self.manipulate_lines(cx, |lines| {
 6234            let mut seen = HashSet::default();
 6235            lines.retain(|line| seen.insert(line.to_lowercase()));
 6236        })
 6237    }
 6238
 6239    pub fn unique_lines_case_sensitive(
 6240        &mut self,
 6241        _: &UniqueLinesCaseSensitive,
 6242        cx: &mut ViewContext<Self>,
 6243    ) {
 6244        self.manipulate_lines(cx, |lines| {
 6245            let mut seen = HashSet::default();
 6246            lines.retain(|line| seen.insert(*line));
 6247        })
 6248    }
 6249
 6250    pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
 6251        let mut revert_changes = HashMap::default();
 6252        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 6253        for hunk in hunks_for_rows(
 6254            Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
 6255            &multi_buffer_snapshot,
 6256        ) {
 6257            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 6258        }
 6259        if !revert_changes.is_empty() {
 6260            self.transact(cx, |editor, cx| {
 6261                editor.revert(revert_changes, cx);
 6262            });
 6263        }
 6264    }
 6265
 6266    pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
 6267        let Some(project) = self.project.clone() else {
 6268            return;
 6269        };
 6270        self.reload(project, cx).detach_and_notify_err(cx);
 6271    }
 6272
 6273    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 6274        let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
 6275        if !revert_changes.is_empty() {
 6276            self.transact(cx, |editor, cx| {
 6277                editor.revert(revert_changes, cx);
 6278            });
 6279        }
 6280    }
 6281
 6282    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 6283        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6284            let project_path = buffer.read(cx).project_path(cx)?;
 6285            let project = self.project.as_ref()?.read(cx);
 6286            let entry = project.entry_for_path(&project_path, cx)?;
 6287            let parent = match &entry.canonical_path {
 6288                Some(canonical_path) => canonical_path.to_path_buf(),
 6289                None => project.absolute_path(&project_path, cx)?,
 6290            }
 6291            .parent()?
 6292            .to_path_buf();
 6293            Some(parent)
 6294        }) {
 6295            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 6296        }
 6297    }
 6298
 6299    fn gather_revert_changes(
 6300        &mut self,
 6301        selections: &[Selection<Anchor>],
 6302        cx: &mut ViewContext<'_, Editor>,
 6303    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 6304        let mut revert_changes = HashMap::default();
 6305        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 6306        for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
 6307            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 6308        }
 6309        revert_changes
 6310    }
 6311
 6312    pub fn prepare_revert_change(
 6313        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6314        multi_buffer: &Model<MultiBuffer>,
 6315        hunk: &MultiBufferDiffHunk,
 6316        cx: &AppContext,
 6317    ) -> Option<()> {
 6318        let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
 6319        let buffer = buffer.read(cx);
 6320        let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
 6321        let buffer_snapshot = buffer.snapshot();
 6322        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6323        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6324            probe
 6325                .0
 6326                .start
 6327                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6328                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6329        }) {
 6330            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6331            Some(())
 6332        } else {
 6333            None
 6334        }
 6335    }
 6336
 6337    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 6338        self.manipulate_lines(cx, |lines| lines.reverse())
 6339    }
 6340
 6341    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 6342        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 6343    }
 6344
 6345    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6346    where
 6347        Fn: FnMut(&mut Vec<&str>),
 6348    {
 6349        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6350        let buffer = self.buffer.read(cx).snapshot(cx);
 6351
 6352        let mut edits = Vec::new();
 6353
 6354        let selections = self.selections.all::<Point>(cx);
 6355        let mut selections = selections.iter().peekable();
 6356        let mut contiguous_row_selections = Vec::new();
 6357        let mut new_selections = Vec::new();
 6358        let mut added_lines = 0;
 6359        let mut removed_lines = 0;
 6360
 6361        while let Some(selection) = selections.next() {
 6362            let (start_row, end_row) = consume_contiguous_rows(
 6363                &mut contiguous_row_selections,
 6364                selection,
 6365                &display_map,
 6366                &mut selections,
 6367            );
 6368
 6369            let start_point = Point::new(start_row.0, 0);
 6370            let end_point = Point::new(
 6371                end_row.previous_row().0,
 6372                buffer.line_len(end_row.previous_row()),
 6373            );
 6374            let text = buffer
 6375                .text_for_range(start_point..end_point)
 6376                .collect::<String>();
 6377
 6378            let mut lines = text.split('\n').collect_vec();
 6379
 6380            let lines_before = lines.len();
 6381            callback(&mut lines);
 6382            let lines_after = lines.len();
 6383
 6384            edits.push((start_point..end_point, lines.join("\n")));
 6385
 6386            // Selections must change based on added and removed line count
 6387            let start_row =
 6388                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6389            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6390            new_selections.push(Selection {
 6391                id: selection.id,
 6392                start: start_row,
 6393                end: end_row,
 6394                goal: SelectionGoal::None,
 6395                reversed: selection.reversed,
 6396            });
 6397
 6398            if lines_after > lines_before {
 6399                added_lines += lines_after - lines_before;
 6400            } else if lines_before > lines_after {
 6401                removed_lines += lines_before - lines_after;
 6402            }
 6403        }
 6404
 6405        self.transact(cx, |this, cx| {
 6406            let buffer = this.buffer.update(cx, |buffer, cx| {
 6407                buffer.edit(edits, None, cx);
 6408                buffer.snapshot(cx)
 6409            });
 6410
 6411            // Recalculate offsets on newly edited buffer
 6412            let new_selections = new_selections
 6413                .iter()
 6414                .map(|s| {
 6415                    let start_point = Point::new(s.start.0, 0);
 6416                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6417                    Selection {
 6418                        id: s.id,
 6419                        start: buffer.point_to_offset(start_point),
 6420                        end: buffer.point_to_offset(end_point),
 6421                        goal: s.goal,
 6422                        reversed: s.reversed,
 6423                    }
 6424                })
 6425                .collect();
 6426
 6427            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6428                s.select(new_selections);
 6429            });
 6430
 6431            this.request_autoscroll(Autoscroll::fit(), cx);
 6432        });
 6433    }
 6434
 6435    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 6436        self.manipulate_text(cx, |text| text.to_uppercase())
 6437    }
 6438
 6439    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 6440        self.manipulate_text(cx, |text| text.to_lowercase())
 6441    }
 6442
 6443    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 6444        self.manipulate_text(cx, |text| {
 6445            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6446            // https://github.com/rutrum/convert-case/issues/16
 6447            text.split('\n')
 6448                .map(|line| line.to_case(Case::Title))
 6449                .join("\n")
 6450        })
 6451    }
 6452
 6453    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6454        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6455    }
 6456
 6457    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6458        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6459    }
 6460
 6461    pub fn convert_to_upper_camel_case(
 6462        &mut self,
 6463        _: &ConvertToUpperCamelCase,
 6464        cx: &mut ViewContext<Self>,
 6465    ) {
 6466        self.manipulate_text(cx, |text| {
 6467            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6468            // https://github.com/rutrum/convert-case/issues/16
 6469            text.split('\n')
 6470                .map(|line| line.to_case(Case::UpperCamel))
 6471                .join("\n")
 6472        })
 6473    }
 6474
 6475    pub fn convert_to_lower_camel_case(
 6476        &mut self,
 6477        _: &ConvertToLowerCamelCase,
 6478        cx: &mut ViewContext<Self>,
 6479    ) {
 6480        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6481    }
 6482
 6483    pub fn convert_to_opposite_case(
 6484        &mut self,
 6485        _: &ConvertToOppositeCase,
 6486        cx: &mut ViewContext<Self>,
 6487    ) {
 6488        self.manipulate_text(cx, |text| {
 6489            text.chars()
 6490                .fold(String::with_capacity(text.len()), |mut t, c| {
 6491                    if c.is_uppercase() {
 6492                        t.extend(c.to_lowercase());
 6493                    } else {
 6494                        t.extend(c.to_uppercase());
 6495                    }
 6496                    t
 6497                })
 6498        })
 6499    }
 6500
 6501    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6502    where
 6503        Fn: FnMut(&str) -> String,
 6504    {
 6505        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6506        let buffer = self.buffer.read(cx).snapshot(cx);
 6507
 6508        let mut new_selections = Vec::new();
 6509        let mut edits = Vec::new();
 6510        let mut selection_adjustment = 0i32;
 6511
 6512        for selection in self.selections.all::<usize>(cx) {
 6513            let selection_is_empty = selection.is_empty();
 6514
 6515            let (start, end) = if selection_is_empty {
 6516                let word_range = movement::surrounding_word(
 6517                    &display_map,
 6518                    selection.start.to_display_point(&display_map),
 6519                );
 6520                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6521                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6522                (start, end)
 6523            } else {
 6524                (selection.start, selection.end)
 6525            };
 6526
 6527            let text = buffer.text_for_range(start..end).collect::<String>();
 6528            let old_length = text.len() as i32;
 6529            let text = callback(&text);
 6530
 6531            new_selections.push(Selection {
 6532                start: (start as i32 - selection_adjustment) as usize,
 6533                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6534                goal: SelectionGoal::None,
 6535                ..selection
 6536            });
 6537
 6538            selection_adjustment += old_length - text.len() as i32;
 6539
 6540            edits.push((start..end, text));
 6541        }
 6542
 6543        self.transact(cx, |this, cx| {
 6544            this.buffer.update(cx, |buffer, cx| {
 6545                buffer.edit(edits, None, cx);
 6546            });
 6547
 6548            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6549                s.select(new_selections);
 6550            });
 6551
 6552            this.request_autoscroll(Autoscroll::fit(), cx);
 6553        });
 6554    }
 6555
 6556    pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
 6557        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6558        let buffer = &display_map.buffer_snapshot;
 6559        let selections = self.selections.all::<Point>(cx);
 6560
 6561        let mut edits = Vec::new();
 6562        let mut selections_iter = selections.iter().peekable();
 6563        while let Some(selection) = selections_iter.next() {
 6564            // Avoid duplicating the same lines twice.
 6565            let mut rows = selection.spanned_rows(false, &display_map);
 6566
 6567            while let Some(next_selection) = selections_iter.peek() {
 6568                let next_rows = next_selection.spanned_rows(false, &display_map);
 6569                if next_rows.start < rows.end {
 6570                    rows.end = next_rows.end;
 6571                    selections_iter.next().unwrap();
 6572                } else {
 6573                    break;
 6574                }
 6575            }
 6576
 6577            // Copy the text from the selected row region and splice it either at the start
 6578            // or end of the region.
 6579            let start = Point::new(rows.start.0, 0);
 6580            let end = Point::new(
 6581                rows.end.previous_row().0,
 6582                buffer.line_len(rows.end.previous_row()),
 6583            );
 6584            let text = buffer
 6585                .text_for_range(start..end)
 6586                .chain(Some("\n"))
 6587                .collect::<String>();
 6588            let insert_location = if upwards {
 6589                Point::new(rows.end.0, 0)
 6590            } else {
 6591                start
 6592            };
 6593            edits.push((insert_location..insert_location, text));
 6594        }
 6595
 6596        self.transact(cx, |this, cx| {
 6597            this.buffer.update(cx, |buffer, cx| {
 6598                buffer.edit(edits, None, cx);
 6599            });
 6600
 6601            this.request_autoscroll(Autoscroll::fit(), cx);
 6602        });
 6603    }
 6604
 6605    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6606        self.duplicate_line(true, cx);
 6607    }
 6608
 6609    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6610        self.duplicate_line(false, cx);
 6611    }
 6612
 6613    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6614        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6615        let buffer = self.buffer.read(cx).snapshot(cx);
 6616
 6617        let mut edits = Vec::new();
 6618        let mut unfold_ranges = Vec::new();
 6619        let mut refold_ranges = Vec::new();
 6620
 6621        let selections = self.selections.all::<Point>(cx);
 6622        let mut selections = selections.iter().peekable();
 6623        let mut contiguous_row_selections = Vec::new();
 6624        let mut new_selections = Vec::new();
 6625
 6626        while let Some(selection) = selections.next() {
 6627            // Find all the selections that span a contiguous row range
 6628            let (start_row, end_row) = consume_contiguous_rows(
 6629                &mut contiguous_row_selections,
 6630                selection,
 6631                &display_map,
 6632                &mut selections,
 6633            );
 6634
 6635            // Move the text spanned by the row range to be before the line preceding the row range
 6636            if start_row.0 > 0 {
 6637                let range_to_move = Point::new(
 6638                    start_row.previous_row().0,
 6639                    buffer.line_len(start_row.previous_row()),
 6640                )
 6641                    ..Point::new(
 6642                        end_row.previous_row().0,
 6643                        buffer.line_len(end_row.previous_row()),
 6644                    );
 6645                let insertion_point = display_map
 6646                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6647                    .0;
 6648
 6649                // Don't move lines across excerpts
 6650                if buffer
 6651                    .excerpt_boundaries_in_range((
 6652                        Bound::Excluded(insertion_point),
 6653                        Bound::Included(range_to_move.end),
 6654                    ))
 6655                    .next()
 6656                    .is_none()
 6657                {
 6658                    let text = buffer
 6659                        .text_for_range(range_to_move.clone())
 6660                        .flat_map(|s| s.chars())
 6661                        .skip(1)
 6662                        .chain(['\n'])
 6663                        .collect::<String>();
 6664
 6665                    edits.push((
 6666                        buffer.anchor_after(range_to_move.start)
 6667                            ..buffer.anchor_before(range_to_move.end),
 6668                        String::new(),
 6669                    ));
 6670                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6671                    edits.push((insertion_anchor..insertion_anchor, text));
 6672
 6673                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6674
 6675                    // Move selections up
 6676                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6677                        |mut selection| {
 6678                            selection.start.row -= row_delta;
 6679                            selection.end.row -= row_delta;
 6680                            selection
 6681                        },
 6682                    ));
 6683
 6684                    // Move folds up
 6685                    unfold_ranges.push(range_to_move.clone());
 6686                    for fold in display_map.folds_in_range(
 6687                        buffer.anchor_before(range_to_move.start)
 6688                            ..buffer.anchor_after(range_to_move.end),
 6689                    ) {
 6690                        let mut start = fold.range.start.to_point(&buffer);
 6691                        let mut end = fold.range.end.to_point(&buffer);
 6692                        start.row -= row_delta;
 6693                        end.row -= row_delta;
 6694                        refold_ranges.push((start..end, fold.placeholder.clone()));
 6695                    }
 6696                }
 6697            }
 6698
 6699            // If we didn't move line(s), preserve the existing selections
 6700            new_selections.append(&mut contiguous_row_selections);
 6701        }
 6702
 6703        self.transact(cx, |this, cx| {
 6704            this.unfold_ranges(unfold_ranges, true, true, cx);
 6705            this.buffer.update(cx, |buffer, cx| {
 6706                for (range, text) in edits {
 6707                    buffer.edit([(range, text)], None, cx);
 6708                }
 6709            });
 6710            this.fold_ranges(refold_ranges, true, cx);
 6711            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6712                s.select(new_selections);
 6713            })
 6714        });
 6715    }
 6716
 6717    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 6718        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6719        let buffer = self.buffer.read(cx).snapshot(cx);
 6720
 6721        let mut edits = Vec::new();
 6722        let mut unfold_ranges = Vec::new();
 6723        let mut refold_ranges = Vec::new();
 6724
 6725        let selections = self.selections.all::<Point>(cx);
 6726        let mut selections = selections.iter().peekable();
 6727        let mut contiguous_row_selections = Vec::new();
 6728        let mut new_selections = Vec::new();
 6729
 6730        while let Some(selection) = selections.next() {
 6731            // Find all the selections that span a contiguous row range
 6732            let (start_row, end_row) = consume_contiguous_rows(
 6733                &mut contiguous_row_selections,
 6734                selection,
 6735                &display_map,
 6736                &mut selections,
 6737            );
 6738
 6739            // Move the text spanned by the row range to be after the last line of the row range
 6740            if end_row.0 <= buffer.max_point().row {
 6741                let range_to_move =
 6742                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 6743                let insertion_point = display_map
 6744                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 6745                    .0;
 6746
 6747                // Don't move lines across excerpt boundaries
 6748                if buffer
 6749                    .excerpt_boundaries_in_range((
 6750                        Bound::Excluded(range_to_move.start),
 6751                        Bound::Included(insertion_point),
 6752                    ))
 6753                    .next()
 6754                    .is_none()
 6755                {
 6756                    let mut text = String::from("\n");
 6757                    text.extend(buffer.text_for_range(range_to_move.clone()));
 6758                    text.pop(); // Drop trailing newline
 6759                    edits.push((
 6760                        buffer.anchor_after(range_to_move.start)
 6761                            ..buffer.anchor_before(range_to_move.end),
 6762                        String::new(),
 6763                    ));
 6764                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6765                    edits.push((insertion_anchor..insertion_anchor, text));
 6766
 6767                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 6768
 6769                    // Move selections down
 6770                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6771                        |mut selection| {
 6772                            selection.start.row += row_delta;
 6773                            selection.end.row += row_delta;
 6774                            selection
 6775                        },
 6776                    ));
 6777
 6778                    // Move folds down
 6779                    unfold_ranges.push(range_to_move.clone());
 6780                    for fold in display_map.folds_in_range(
 6781                        buffer.anchor_before(range_to_move.start)
 6782                            ..buffer.anchor_after(range_to_move.end),
 6783                    ) {
 6784                        let mut start = fold.range.start.to_point(&buffer);
 6785                        let mut end = fold.range.end.to_point(&buffer);
 6786                        start.row += row_delta;
 6787                        end.row += row_delta;
 6788                        refold_ranges.push((start..end, fold.placeholder.clone()));
 6789                    }
 6790                }
 6791            }
 6792
 6793            // If we didn't move line(s), preserve the existing selections
 6794            new_selections.append(&mut contiguous_row_selections);
 6795        }
 6796
 6797        self.transact(cx, |this, cx| {
 6798            this.unfold_ranges(unfold_ranges, true, true, cx);
 6799            this.buffer.update(cx, |buffer, cx| {
 6800                for (range, text) in edits {
 6801                    buffer.edit([(range, text)], None, cx);
 6802                }
 6803            });
 6804            this.fold_ranges(refold_ranges, true, cx);
 6805            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 6806        });
 6807    }
 6808
 6809    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 6810        let text_layout_details = &self.text_layout_details(cx);
 6811        self.transact(cx, |this, cx| {
 6812            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6813                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 6814                let line_mode = s.line_mode;
 6815                s.move_with(|display_map, selection| {
 6816                    if !selection.is_empty() || line_mode {
 6817                        return;
 6818                    }
 6819
 6820                    let mut head = selection.head();
 6821                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 6822                    if head.column() == display_map.line_len(head.row()) {
 6823                        transpose_offset = display_map
 6824                            .buffer_snapshot
 6825                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6826                    }
 6827
 6828                    if transpose_offset == 0 {
 6829                        return;
 6830                    }
 6831
 6832                    *head.column_mut() += 1;
 6833                    head = display_map.clip_point(head, Bias::Right);
 6834                    let goal = SelectionGoal::HorizontalPosition(
 6835                        display_map
 6836                            .x_for_display_point(head, text_layout_details)
 6837                            .into(),
 6838                    );
 6839                    selection.collapse_to(head, goal);
 6840
 6841                    let transpose_start = display_map
 6842                        .buffer_snapshot
 6843                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6844                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 6845                        let transpose_end = display_map
 6846                            .buffer_snapshot
 6847                            .clip_offset(transpose_offset + 1, Bias::Right);
 6848                        if let Some(ch) =
 6849                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 6850                        {
 6851                            edits.push((transpose_start..transpose_offset, String::new()));
 6852                            edits.push((transpose_end..transpose_end, ch.to_string()));
 6853                        }
 6854                    }
 6855                });
 6856                edits
 6857            });
 6858            this.buffer
 6859                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6860            let selections = this.selections.all::<usize>(cx);
 6861            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6862                s.select(selections);
 6863            });
 6864        });
 6865    }
 6866
 6867    pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
 6868        self.rewrap_impl(true, cx)
 6869    }
 6870
 6871    pub fn rewrap_impl(&mut self, only_text: bool, cx: &mut ViewContext<Self>) {
 6872        let buffer = self.buffer.read(cx).snapshot(cx);
 6873        let selections = self.selections.all::<Point>(cx);
 6874        let mut selections = selections.iter().peekable();
 6875
 6876        let mut edits = Vec::new();
 6877        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 6878
 6879        while let Some(selection) = selections.next() {
 6880            let mut start_row = selection.start.row;
 6881            let mut end_row = selection.end.row;
 6882
 6883            // Skip selections that overlap with a range that has already been rewrapped.
 6884            let selection_range = start_row..end_row;
 6885            if rewrapped_row_ranges
 6886                .iter()
 6887                .any(|range| range.overlaps(&selection_range))
 6888            {
 6889                continue;
 6890            }
 6891
 6892            let mut should_rewrap = !only_text;
 6893
 6894            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 6895                match language_scope.language_name().0.as_ref() {
 6896                    "Markdown" | "Plain Text" => {
 6897                        should_rewrap = true;
 6898                    }
 6899                    _ => {}
 6900                }
 6901            }
 6902
 6903            // Since not all lines in the selection may be at the same indent
 6904            // level, choose the indent size that is the most common between all
 6905            // of the lines.
 6906            //
 6907            // If there is a tie, we use the deepest indent.
 6908            let (indent_size, indent_end) = {
 6909                let mut indent_size_occurrences = HashMap::default();
 6910                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 6911
 6912                for row in start_row..=end_row {
 6913                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 6914                    rows_by_indent_size.entry(indent).or_default().push(row);
 6915                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 6916                }
 6917
 6918                let indent_size = indent_size_occurrences
 6919                    .into_iter()
 6920                    .max_by_key(|(indent, count)| (*count, indent.len))
 6921                    .map(|(indent, _)| indent)
 6922                    .unwrap_or_default();
 6923                let row = rows_by_indent_size[&indent_size][0];
 6924                let indent_end = Point::new(row, indent_size.len);
 6925
 6926                (indent_size, indent_end)
 6927            };
 6928
 6929            let mut line_prefix = indent_size.chars().collect::<String>();
 6930
 6931            if let Some(comment_prefix) =
 6932                buffer
 6933                    .language_scope_at(selection.head())
 6934                    .and_then(|language| {
 6935                        language
 6936                            .line_comment_prefixes()
 6937                            .iter()
 6938                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 6939                            .cloned()
 6940                    })
 6941            {
 6942                line_prefix.push_str(&comment_prefix);
 6943                should_rewrap = true;
 6944            }
 6945
 6946            if selection.is_empty() {
 6947                'expand_upwards: while start_row > 0 {
 6948                    let prev_row = start_row - 1;
 6949                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 6950                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 6951                    {
 6952                        start_row = prev_row;
 6953                    } else {
 6954                        break 'expand_upwards;
 6955                    }
 6956                }
 6957
 6958                'expand_downwards: while end_row < buffer.max_point().row {
 6959                    let next_row = end_row + 1;
 6960                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 6961                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 6962                    {
 6963                        end_row = next_row;
 6964                    } else {
 6965                        break 'expand_downwards;
 6966                    }
 6967                }
 6968            }
 6969
 6970            if !should_rewrap {
 6971                continue;
 6972            }
 6973
 6974            let start = Point::new(start_row, 0);
 6975            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 6976            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 6977            let Some(lines_without_prefixes) = selection_text
 6978                .lines()
 6979                .map(|line| {
 6980                    line.strip_prefix(&line_prefix)
 6981                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 6982                        .ok_or_else(|| {
 6983                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 6984                        })
 6985                })
 6986                .collect::<Result<Vec<_>, _>>()
 6987                .log_err()
 6988            else {
 6989                continue;
 6990            };
 6991
 6992            let unwrapped_text = lines_without_prefixes.join(" ");
 6993            let wrap_column = buffer
 6994                .settings_at(Point::new(start_row, 0), cx)
 6995                .preferred_line_length as usize;
 6996            let mut wrapped_text = String::new();
 6997            let mut current_line = line_prefix.clone();
 6998            for word in unwrapped_text.split_whitespace() {
 6999                if current_line.len() + word.len() >= wrap_column {
 7000                    wrapped_text.push_str(&current_line);
 7001                    wrapped_text.push('\n');
 7002                    current_line.truncate(line_prefix.len());
 7003                }
 7004
 7005                if current_line.len() > line_prefix.len() {
 7006                    current_line.push(' ');
 7007                }
 7008
 7009                current_line.push_str(word);
 7010            }
 7011
 7012            if !current_line.is_empty() {
 7013                wrapped_text.push_str(&current_line);
 7014            }
 7015
 7016            let diff = TextDiff::from_lines(&selection_text, &wrapped_text);
 7017            let mut offset = start.to_offset(&buffer);
 7018            let mut moved_since_edit = true;
 7019
 7020            for change in diff.iter_all_changes() {
 7021                let value = change.value();
 7022                match change.tag() {
 7023                    ChangeTag::Equal => {
 7024                        offset += value.len();
 7025                        moved_since_edit = true;
 7026                    }
 7027                    ChangeTag::Delete => {
 7028                        let start = buffer.anchor_after(offset);
 7029                        let end = buffer.anchor_before(offset + value.len());
 7030
 7031                        if moved_since_edit {
 7032                            edits.push((start..end, String::new()));
 7033                        } else {
 7034                            edits.last_mut().unwrap().0.end = end;
 7035                        }
 7036
 7037                        offset += value.len();
 7038                        moved_since_edit = false;
 7039                    }
 7040                    ChangeTag::Insert => {
 7041                        if moved_since_edit {
 7042                            let anchor = buffer.anchor_after(offset);
 7043                            edits.push((anchor..anchor, value.to_string()));
 7044                        } else {
 7045                            edits.last_mut().unwrap().1.push_str(value);
 7046                        }
 7047
 7048                        moved_since_edit = false;
 7049                    }
 7050                }
 7051            }
 7052
 7053            rewrapped_row_ranges.push(start_row..=end_row);
 7054        }
 7055
 7056        self.buffer
 7057            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7058    }
 7059
 7060    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 7061        let mut text = String::new();
 7062        let buffer = self.buffer.read(cx).snapshot(cx);
 7063        let mut selections = self.selections.all::<Point>(cx);
 7064        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7065        {
 7066            let max_point = buffer.max_point();
 7067            let mut is_first = true;
 7068            for selection in &mut selections {
 7069                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7070                if is_entire_line {
 7071                    selection.start = Point::new(selection.start.row, 0);
 7072                    if !selection.is_empty() && selection.end.column == 0 {
 7073                        selection.end = cmp::min(max_point, selection.end);
 7074                    } else {
 7075                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7076                    }
 7077                    selection.goal = SelectionGoal::None;
 7078                }
 7079                if is_first {
 7080                    is_first = false;
 7081                } else {
 7082                    text += "\n";
 7083                }
 7084                let mut len = 0;
 7085                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7086                    text.push_str(chunk);
 7087                    len += chunk.len();
 7088                }
 7089                clipboard_selections.push(ClipboardSelection {
 7090                    len,
 7091                    is_entire_line,
 7092                    first_line_indent: buffer
 7093                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7094                        .len,
 7095                });
 7096            }
 7097        }
 7098
 7099        self.transact(cx, |this, cx| {
 7100            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7101                s.select(selections);
 7102            });
 7103            this.insert("", cx);
 7104            cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7105                text,
 7106                clipboard_selections,
 7107            ));
 7108        });
 7109    }
 7110
 7111    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 7112        let selections = self.selections.all::<Point>(cx);
 7113        let buffer = self.buffer.read(cx).read(cx);
 7114        let mut text = String::new();
 7115
 7116        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7117        {
 7118            let max_point = buffer.max_point();
 7119            let mut is_first = true;
 7120            for selection in selections.iter() {
 7121                let mut start = selection.start;
 7122                let mut end = selection.end;
 7123                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7124                if is_entire_line {
 7125                    start = Point::new(start.row, 0);
 7126                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 7127                }
 7128                if is_first {
 7129                    is_first = false;
 7130                } else {
 7131                    text += "\n";
 7132                }
 7133                let mut len = 0;
 7134                for chunk in buffer.text_for_range(start..end) {
 7135                    text.push_str(chunk);
 7136                    len += chunk.len();
 7137                }
 7138                clipboard_selections.push(ClipboardSelection {
 7139                    len,
 7140                    is_entire_line,
 7141                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 7142                });
 7143            }
 7144        }
 7145
 7146        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7147            text,
 7148            clipboard_selections,
 7149        ));
 7150    }
 7151
 7152    pub fn do_paste(
 7153        &mut self,
 7154        text: &String,
 7155        clipboard_selections: Option<Vec<ClipboardSelection>>,
 7156        handle_entire_lines: bool,
 7157        cx: &mut ViewContext<Self>,
 7158    ) {
 7159        if self.read_only(cx) {
 7160            return;
 7161        }
 7162
 7163        let clipboard_text = Cow::Borrowed(text);
 7164
 7165        self.transact(cx, |this, cx| {
 7166            if let Some(mut clipboard_selections) = clipboard_selections {
 7167                let old_selections = this.selections.all::<usize>(cx);
 7168                let all_selections_were_entire_line =
 7169                    clipboard_selections.iter().all(|s| s.is_entire_line);
 7170                let first_selection_indent_column =
 7171                    clipboard_selections.first().map(|s| s.first_line_indent);
 7172                if clipboard_selections.len() != old_selections.len() {
 7173                    clipboard_selections.drain(..);
 7174                }
 7175
 7176                this.buffer.update(cx, |buffer, cx| {
 7177                    let snapshot = buffer.read(cx);
 7178                    let mut start_offset = 0;
 7179                    let mut edits = Vec::new();
 7180                    let mut original_indent_columns = Vec::new();
 7181                    for (ix, selection) in old_selections.iter().enumerate() {
 7182                        let to_insert;
 7183                        let entire_line;
 7184                        let original_indent_column;
 7185                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 7186                            let end_offset = start_offset + clipboard_selection.len;
 7187                            to_insert = &clipboard_text[start_offset..end_offset];
 7188                            entire_line = clipboard_selection.is_entire_line;
 7189                            start_offset = end_offset + 1;
 7190                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7191                        } else {
 7192                            to_insert = clipboard_text.as_str();
 7193                            entire_line = all_selections_were_entire_line;
 7194                            original_indent_column = first_selection_indent_column
 7195                        }
 7196
 7197                        // If the corresponding selection was empty when this slice of the
 7198                        // clipboard text was written, then the entire line containing the
 7199                        // selection was copied. If this selection is also currently empty,
 7200                        // then paste the line before the current line of the buffer.
 7201                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7202                            let column = selection.start.to_point(&snapshot).column as usize;
 7203                            let line_start = selection.start - column;
 7204                            line_start..line_start
 7205                        } else {
 7206                            selection.range()
 7207                        };
 7208
 7209                        edits.push((range, to_insert));
 7210                        original_indent_columns.extend(original_indent_column);
 7211                    }
 7212                    drop(snapshot);
 7213
 7214                    buffer.edit(
 7215                        edits,
 7216                        Some(AutoindentMode::Block {
 7217                            original_indent_columns,
 7218                        }),
 7219                        cx,
 7220                    );
 7221                });
 7222
 7223                let selections = this.selections.all::<usize>(cx);
 7224                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 7225            } else {
 7226                this.insert(&clipboard_text, cx);
 7227            }
 7228        });
 7229    }
 7230
 7231    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 7232        if let Some(item) = cx.read_from_clipboard() {
 7233            let entries = item.entries();
 7234
 7235            match entries.first() {
 7236                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7237                // of all the pasted entries.
 7238                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7239                    .do_paste(
 7240                        clipboard_string.text(),
 7241                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7242                        true,
 7243                        cx,
 7244                    ),
 7245                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
 7246            }
 7247        }
 7248    }
 7249
 7250    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 7251        if self.read_only(cx) {
 7252            return;
 7253        }
 7254
 7255        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7256            if let Some((selections, _)) =
 7257                self.selection_history.transaction(transaction_id).cloned()
 7258            {
 7259                self.change_selections(None, cx, |s| {
 7260                    s.select_anchors(selections.to_vec());
 7261                });
 7262            }
 7263            self.request_autoscroll(Autoscroll::fit(), cx);
 7264            self.unmark_text(cx);
 7265            self.refresh_inline_completion(true, false, cx);
 7266            cx.emit(EditorEvent::Edited { transaction_id });
 7267            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7268        }
 7269    }
 7270
 7271    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 7272        if self.read_only(cx) {
 7273            return;
 7274        }
 7275
 7276        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7277            if let Some((_, Some(selections))) =
 7278                self.selection_history.transaction(transaction_id).cloned()
 7279            {
 7280                self.change_selections(None, cx, |s| {
 7281                    s.select_anchors(selections.to_vec());
 7282                });
 7283            }
 7284            self.request_autoscroll(Autoscroll::fit(), cx);
 7285            self.unmark_text(cx);
 7286            self.refresh_inline_completion(true, false, cx);
 7287            cx.emit(EditorEvent::Edited { transaction_id });
 7288        }
 7289    }
 7290
 7291    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 7292        self.buffer
 7293            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7294    }
 7295
 7296    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 7297        self.buffer
 7298            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7299    }
 7300
 7301    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 7302        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7303            let line_mode = s.line_mode;
 7304            s.move_with(|map, selection| {
 7305                let cursor = if selection.is_empty() && !line_mode {
 7306                    movement::left(map, selection.start)
 7307                } else {
 7308                    selection.start
 7309                };
 7310                selection.collapse_to(cursor, SelectionGoal::None);
 7311            });
 7312        })
 7313    }
 7314
 7315    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 7316        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7317            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7318        })
 7319    }
 7320
 7321    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 7322        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7323            let line_mode = s.line_mode;
 7324            s.move_with(|map, selection| {
 7325                let cursor = if selection.is_empty() && !line_mode {
 7326                    movement::right(map, selection.end)
 7327                } else {
 7328                    selection.end
 7329                };
 7330                selection.collapse_to(cursor, SelectionGoal::None)
 7331            });
 7332        })
 7333    }
 7334
 7335    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 7336        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7337            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7338        })
 7339    }
 7340
 7341    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 7342        if self.take_rename(true, cx).is_some() {
 7343            return;
 7344        }
 7345
 7346        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7347            cx.propagate();
 7348            return;
 7349        }
 7350
 7351        let text_layout_details = &self.text_layout_details(cx);
 7352        let selection_count = self.selections.count();
 7353        let first_selection = self.selections.first_anchor();
 7354
 7355        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7356            let line_mode = s.line_mode;
 7357            s.move_with(|map, selection| {
 7358                if !selection.is_empty() && !line_mode {
 7359                    selection.goal = SelectionGoal::None;
 7360                }
 7361                let (cursor, goal) = movement::up(
 7362                    map,
 7363                    selection.start,
 7364                    selection.goal,
 7365                    false,
 7366                    text_layout_details,
 7367                );
 7368                selection.collapse_to(cursor, goal);
 7369            });
 7370        });
 7371
 7372        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7373        {
 7374            cx.propagate();
 7375        }
 7376    }
 7377
 7378    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 7379        if self.take_rename(true, cx).is_some() {
 7380            return;
 7381        }
 7382
 7383        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7384            cx.propagate();
 7385            return;
 7386        }
 7387
 7388        let text_layout_details = &self.text_layout_details(cx);
 7389
 7390        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7391            let line_mode = s.line_mode;
 7392            s.move_with(|map, selection| {
 7393                if !selection.is_empty() && !line_mode {
 7394                    selection.goal = SelectionGoal::None;
 7395                }
 7396                let (cursor, goal) = movement::up_by_rows(
 7397                    map,
 7398                    selection.start,
 7399                    action.lines,
 7400                    selection.goal,
 7401                    false,
 7402                    text_layout_details,
 7403                );
 7404                selection.collapse_to(cursor, goal);
 7405            });
 7406        })
 7407    }
 7408
 7409    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 7410        if self.take_rename(true, cx).is_some() {
 7411            return;
 7412        }
 7413
 7414        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7415            cx.propagate();
 7416            return;
 7417        }
 7418
 7419        let text_layout_details = &self.text_layout_details(cx);
 7420
 7421        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7422            let line_mode = s.line_mode;
 7423            s.move_with(|map, selection| {
 7424                if !selection.is_empty() && !line_mode {
 7425                    selection.goal = SelectionGoal::None;
 7426                }
 7427                let (cursor, goal) = movement::down_by_rows(
 7428                    map,
 7429                    selection.start,
 7430                    action.lines,
 7431                    selection.goal,
 7432                    false,
 7433                    text_layout_details,
 7434                );
 7435                selection.collapse_to(cursor, goal);
 7436            });
 7437        })
 7438    }
 7439
 7440    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 7441        let text_layout_details = &self.text_layout_details(cx);
 7442        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7443            s.move_heads_with(|map, head, goal| {
 7444                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7445            })
 7446        })
 7447    }
 7448
 7449    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 7450        let text_layout_details = &self.text_layout_details(cx);
 7451        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7452            s.move_heads_with(|map, head, goal| {
 7453                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7454            })
 7455        })
 7456    }
 7457
 7458    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 7459        let Some(row_count) = self.visible_row_count() else {
 7460            return;
 7461        };
 7462
 7463        let text_layout_details = &self.text_layout_details(cx);
 7464
 7465        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7466            s.move_heads_with(|map, head, goal| {
 7467                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7468            })
 7469        })
 7470    }
 7471
 7472    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 7473        if self.take_rename(true, cx).is_some() {
 7474            return;
 7475        }
 7476
 7477        if self
 7478            .context_menu
 7479            .write()
 7480            .as_mut()
 7481            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 7482            .unwrap_or(false)
 7483        {
 7484            return;
 7485        }
 7486
 7487        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7488            cx.propagate();
 7489            return;
 7490        }
 7491
 7492        let Some(row_count) = self.visible_row_count() else {
 7493            return;
 7494        };
 7495
 7496        let autoscroll = if action.center_cursor {
 7497            Autoscroll::center()
 7498        } else {
 7499            Autoscroll::fit()
 7500        };
 7501
 7502        let text_layout_details = &self.text_layout_details(cx);
 7503
 7504        self.change_selections(Some(autoscroll), cx, |s| {
 7505            let line_mode = s.line_mode;
 7506            s.move_with(|map, selection| {
 7507                if !selection.is_empty() && !line_mode {
 7508                    selection.goal = SelectionGoal::None;
 7509                }
 7510                let (cursor, goal) = movement::up_by_rows(
 7511                    map,
 7512                    selection.end,
 7513                    row_count,
 7514                    selection.goal,
 7515                    false,
 7516                    text_layout_details,
 7517                );
 7518                selection.collapse_to(cursor, goal);
 7519            });
 7520        });
 7521    }
 7522
 7523    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 7524        let text_layout_details = &self.text_layout_details(cx);
 7525        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7526            s.move_heads_with(|map, head, goal| {
 7527                movement::up(map, head, goal, false, text_layout_details)
 7528            })
 7529        })
 7530    }
 7531
 7532    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 7533        self.take_rename(true, cx);
 7534
 7535        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7536            cx.propagate();
 7537            return;
 7538        }
 7539
 7540        let text_layout_details = &self.text_layout_details(cx);
 7541        let selection_count = self.selections.count();
 7542        let first_selection = self.selections.first_anchor();
 7543
 7544        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7545            let line_mode = s.line_mode;
 7546            s.move_with(|map, selection| {
 7547                if !selection.is_empty() && !line_mode {
 7548                    selection.goal = SelectionGoal::None;
 7549                }
 7550                let (cursor, goal) = movement::down(
 7551                    map,
 7552                    selection.end,
 7553                    selection.goal,
 7554                    false,
 7555                    text_layout_details,
 7556                );
 7557                selection.collapse_to(cursor, goal);
 7558            });
 7559        });
 7560
 7561        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7562        {
 7563            cx.propagate();
 7564        }
 7565    }
 7566
 7567    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 7568        let Some(row_count) = self.visible_row_count() else {
 7569            return;
 7570        };
 7571
 7572        let text_layout_details = &self.text_layout_details(cx);
 7573
 7574        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7575            s.move_heads_with(|map, head, goal| {
 7576                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 7577            })
 7578        })
 7579    }
 7580
 7581    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 7582        if self.take_rename(true, cx).is_some() {
 7583            return;
 7584        }
 7585
 7586        if self
 7587            .context_menu
 7588            .write()
 7589            .as_mut()
 7590            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 7591            .unwrap_or(false)
 7592        {
 7593            return;
 7594        }
 7595
 7596        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7597            cx.propagate();
 7598            return;
 7599        }
 7600
 7601        let Some(row_count) = self.visible_row_count() else {
 7602            return;
 7603        };
 7604
 7605        let autoscroll = if action.center_cursor {
 7606            Autoscroll::center()
 7607        } else {
 7608            Autoscroll::fit()
 7609        };
 7610
 7611        let text_layout_details = &self.text_layout_details(cx);
 7612        self.change_selections(Some(autoscroll), cx, |s| {
 7613            let line_mode = s.line_mode;
 7614            s.move_with(|map, selection| {
 7615                if !selection.is_empty() && !line_mode {
 7616                    selection.goal = SelectionGoal::None;
 7617                }
 7618                let (cursor, goal) = movement::down_by_rows(
 7619                    map,
 7620                    selection.end,
 7621                    row_count,
 7622                    selection.goal,
 7623                    false,
 7624                    text_layout_details,
 7625                );
 7626                selection.collapse_to(cursor, goal);
 7627            });
 7628        });
 7629    }
 7630
 7631    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 7632        let text_layout_details = &self.text_layout_details(cx);
 7633        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7634            s.move_heads_with(|map, head, goal| {
 7635                movement::down(map, head, goal, false, text_layout_details)
 7636            })
 7637        });
 7638    }
 7639
 7640    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 7641        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7642            context_menu.select_first(self.completion_provider.as_deref(), cx);
 7643        }
 7644    }
 7645
 7646    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 7647        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7648            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 7649        }
 7650    }
 7651
 7652    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7653        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7654            context_menu.select_next(self.completion_provider.as_deref(), cx);
 7655        }
 7656    }
 7657
 7658    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 7659        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7660            context_menu.select_last(self.completion_provider.as_deref(), cx);
 7661        }
 7662    }
 7663
 7664    pub fn move_to_previous_word_start(
 7665        &mut self,
 7666        _: &MoveToPreviousWordStart,
 7667        cx: &mut ViewContext<Self>,
 7668    ) {
 7669        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7670            s.move_cursors_with(|map, head, _| {
 7671                (
 7672                    movement::previous_word_start(map, head),
 7673                    SelectionGoal::None,
 7674                )
 7675            });
 7676        })
 7677    }
 7678
 7679    pub fn move_to_previous_subword_start(
 7680        &mut self,
 7681        _: &MoveToPreviousSubwordStart,
 7682        cx: &mut ViewContext<Self>,
 7683    ) {
 7684        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7685            s.move_cursors_with(|map, head, _| {
 7686                (
 7687                    movement::previous_subword_start(map, head),
 7688                    SelectionGoal::None,
 7689                )
 7690            });
 7691        })
 7692    }
 7693
 7694    pub fn select_to_previous_word_start(
 7695        &mut self,
 7696        _: &SelectToPreviousWordStart,
 7697        cx: &mut ViewContext<Self>,
 7698    ) {
 7699        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7700            s.move_heads_with(|map, head, _| {
 7701                (
 7702                    movement::previous_word_start(map, head),
 7703                    SelectionGoal::None,
 7704                )
 7705            });
 7706        })
 7707    }
 7708
 7709    pub fn select_to_previous_subword_start(
 7710        &mut self,
 7711        _: &SelectToPreviousSubwordStart,
 7712        cx: &mut ViewContext<Self>,
 7713    ) {
 7714        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7715            s.move_heads_with(|map, head, _| {
 7716                (
 7717                    movement::previous_subword_start(map, head),
 7718                    SelectionGoal::None,
 7719                )
 7720            });
 7721        })
 7722    }
 7723
 7724    pub fn delete_to_previous_word_start(
 7725        &mut self,
 7726        action: &DeleteToPreviousWordStart,
 7727        cx: &mut ViewContext<Self>,
 7728    ) {
 7729        self.transact(cx, |this, cx| {
 7730            this.select_autoclose_pair(cx);
 7731            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7732                let line_mode = s.line_mode;
 7733                s.move_with(|map, selection| {
 7734                    if selection.is_empty() && !line_mode {
 7735                        let cursor = if action.ignore_newlines {
 7736                            movement::previous_word_start(map, selection.head())
 7737                        } else {
 7738                            movement::previous_word_start_or_newline(map, selection.head())
 7739                        };
 7740                        selection.set_head(cursor, SelectionGoal::None);
 7741                    }
 7742                });
 7743            });
 7744            this.insert("", cx);
 7745        });
 7746    }
 7747
 7748    pub fn delete_to_previous_subword_start(
 7749        &mut self,
 7750        _: &DeleteToPreviousSubwordStart,
 7751        cx: &mut ViewContext<Self>,
 7752    ) {
 7753        self.transact(cx, |this, cx| {
 7754            this.select_autoclose_pair(cx);
 7755            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7756                let line_mode = s.line_mode;
 7757                s.move_with(|map, selection| {
 7758                    if selection.is_empty() && !line_mode {
 7759                        let cursor = movement::previous_subword_start(map, selection.head());
 7760                        selection.set_head(cursor, SelectionGoal::None);
 7761                    }
 7762                });
 7763            });
 7764            this.insert("", cx);
 7765        });
 7766    }
 7767
 7768    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 7769        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7770            s.move_cursors_with(|map, head, _| {
 7771                (movement::next_word_end(map, head), SelectionGoal::None)
 7772            });
 7773        })
 7774    }
 7775
 7776    pub fn move_to_next_subword_end(
 7777        &mut self,
 7778        _: &MoveToNextSubwordEnd,
 7779        cx: &mut ViewContext<Self>,
 7780    ) {
 7781        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7782            s.move_cursors_with(|map, head, _| {
 7783                (movement::next_subword_end(map, head), SelectionGoal::None)
 7784            });
 7785        })
 7786    }
 7787
 7788    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 7789        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7790            s.move_heads_with(|map, head, _| {
 7791                (movement::next_word_end(map, head), SelectionGoal::None)
 7792            });
 7793        })
 7794    }
 7795
 7796    pub fn select_to_next_subword_end(
 7797        &mut self,
 7798        _: &SelectToNextSubwordEnd,
 7799        cx: &mut ViewContext<Self>,
 7800    ) {
 7801        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7802            s.move_heads_with(|map, head, _| {
 7803                (movement::next_subword_end(map, head), SelectionGoal::None)
 7804            });
 7805        })
 7806    }
 7807
 7808    pub fn delete_to_next_word_end(
 7809        &mut self,
 7810        action: &DeleteToNextWordEnd,
 7811        cx: &mut ViewContext<Self>,
 7812    ) {
 7813        self.transact(cx, |this, cx| {
 7814            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7815                let line_mode = s.line_mode;
 7816                s.move_with(|map, selection| {
 7817                    if selection.is_empty() && !line_mode {
 7818                        let cursor = if action.ignore_newlines {
 7819                            movement::next_word_end(map, selection.head())
 7820                        } else {
 7821                            movement::next_word_end_or_newline(map, selection.head())
 7822                        };
 7823                        selection.set_head(cursor, SelectionGoal::None);
 7824                    }
 7825                });
 7826            });
 7827            this.insert("", cx);
 7828        });
 7829    }
 7830
 7831    pub fn delete_to_next_subword_end(
 7832        &mut self,
 7833        _: &DeleteToNextSubwordEnd,
 7834        cx: &mut ViewContext<Self>,
 7835    ) {
 7836        self.transact(cx, |this, cx| {
 7837            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7838                s.move_with(|map, selection| {
 7839                    if selection.is_empty() {
 7840                        let cursor = movement::next_subword_end(map, selection.head());
 7841                        selection.set_head(cursor, SelectionGoal::None);
 7842                    }
 7843                });
 7844            });
 7845            this.insert("", cx);
 7846        });
 7847    }
 7848
 7849    pub fn move_to_beginning_of_line(
 7850        &mut self,
 7851        action: &MoveToBeginningOfLine,
 7852        cx: &mut ViewContext<Self>,
 7853    ) {
 7854        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7855            s.move_cursors_with(|map, head, _| {
 7856                (
 7857                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7858                    SelectionGoal::None,
 7859                )
 7860            });
 7861        })
 7862    }
 7863
 7864    pub fn select_to_beginning_of_line(
 7865        &mut self,
 7866        action: &SelectToBeginningOfLine,
 7867        cx: &mut ViewContext<Self>,
 7868    ) {
 7869        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7870            s.move_heads_with(|map, head, _| {
 7871                (
 7872                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7873                    SelectionGoal::None,
 7874                )
 7875            });
 7876        });
 7877    }
 7878
 7879    pub fn delete_to_beginning_of_line(
 7880        &mut self,
 7881        _: &DeleteToBeginningOfLine,
 7882        cx: &mut ViewContext<Self>,
 7883    ) {
 7884        self.transact(cx, |this, cx| {
 7885            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7886                s.move_with(|_, selection| {
 7887                    selection.reversed = true;
 7888                });
 7889            });
 7890
 7891            this.select_to_beginning_of_line(
 7892                &SelectToBeginningOfLine {
 7893                    stop_at_soft_wraps: false,
 7894                },
 7895                cx,
 7896            );
 7897            this.backspace(&Backspace, cx);
 7898        });
 7899    }
 7900
 7901    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 7902        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7903            s.move_cursors_with(|map, head, _| {
 7904                (
 7905                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7906                    SelectionGoal::None,
 7907                )
 7908            });
 7909        })
 7910    }
 7911
 7912    pub fn select_to_end_of_line(
 7913        &mut self,
 7914        action: &SelectToEndOfLine,
 7915        cx: &mut ViewContext<Self>,
 7916    ) {
 7917        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7918            s.move_heads_with(|map, head, _| {
 7919                (
 7920                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7921                    SelectionGoal::None,
 7922                )
 7923            });
 7924        })
 7925    }
 7926
 7927    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 7928        self.transact(cx, |this, cx| {
 7929            this.select_to_end_of_line(
 7930                &SelectToEndOfLine {
 7931                    stop_at_soft_wraps: false,
 7932                },
 7933                cx,
 7934            );
 7935            this.delete(&Delete, cx);
 7936        });
 7937    }
 7938
 7939    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 7940        self.transact(cx, |this, cx| {
 7941            this.select_to_end_of_line(
 7942                &SelectToEndOfLine {
 7943                    stop_at_soft_wraps: false,
 7944                },
 7945                cx,
 7946            );
 7947            this.cut(&Cut, cx);
 7948        });
 7949    }
 7950
 7951    pub fn move_to_start_of_paragraph(
 7952        &mut self,
 7953        _: &MoveToStartOfParagraph,
 7954        cx: &mut ViewContext<Self>,
 7955    ) {
 7956        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7957            cx.propagate();
 7958            return;
 7959        }
 7960
 7961        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7962            s.move_with(|map, selection| {
 7963                selection.collapse_to(
 7964                    movement::start_of_paragraph(map, selection.head(), 1),
 7965                    SelectionGoal::None,
 7966                )
 7967            });
 7968        })
 7969    }
 7970
 7971    pub fn move_to_end_of_paragraph(
 7972        &mut self,
 7973        _: &MoveToEndOfParagraph,
 7974        cx: &mut ViewContext<Self>,
 7975    ) {
 7976        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7977            cx.propagate();
 7978            return;
 7979        }
 7980
 7981        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7982            s.move_with(|map, selection| {
 7983                selection.collapse_to(
 7984                    movement::end_of_paragraph(map, selection.head(), 1),
 7985                    SelectionGoal::None,
 7986                )
 7987            });
 7988        })
 7989    }
 7990
 7991    pub fn select_to_start_of_paragraph(
 7992        &mut self,
 7993        _: &SelectToStartOfParagraph,
 7994        cx: &mut ViewContext<Self>,
 7995    ) {
 7996        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7997            cx.propagate();
 7998            return;
 7999        }
 8000
 8001        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8002            s.move_heads_with(|map, head, _| {
 8003                (
 8004                    movement::start_of_paragraph(map, head, 1),
 8005                    SelectionGoal::None,
 8006                )
 8007            });
 8008        })
 8009    }
 8010
 8011    pub fn select_to_end_of_paragraph(
 8012        &mut self,
 8013        _: &SelectToEndOfParagraph,
 8014        cx: &mut ViewContext<Self>,
 8015    ) {
 8016        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8017            cx.propagate();
 8018            return;
 8019        }
 8020
 8021        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8022            s.move_heads_with(|map, head, _| {
 8023                (
 8024                    movement::end_of_paragraph(map, head, 1),
 8025                    SelectionGoal::None,
 8026                )
 8027            });
 8028        })
 8029    }
 8030
 8031    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 8032        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8033            cx.propagate();
 8034            return;
 8035        }
 8036
 8037        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8038            s.select_ranges(vec![0..0]);
 8039        });
 8040    }
 8041
 8042    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 8043        let mut selection = self.selections.last::<Point>(cx);
 8044        selection.set_head(Point::zero(), SelectionGoal::None);
 8045
 8046        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8047            s.select(vec![selection]);
 8048        });
 8049    }
 8050
 8051    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 8052        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8053            cx.propagate();
 8054            return;
 8055        }
 8056
 8057        let cursor = self.buffer.read(cx).read(cx).len();
 8058        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8059            s.select_ranges(vec![cursor..cursor])
 8060        });
 8061    }
 8062
 8063    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 8064        self.nav_history = nav_history;
 8065    }
 8066
 8067    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 8068        self.nav_history.as_ref()
 8069    }
 8070
 8071    fn push_to_nav_history(
 8072        &mut self,
 8073        cursor_anchor: Anchor,
 8074        new_position: Option<Point>,
 8075        cx: &mut ViewContext<Self>,
 8076    ) {
 8077        if let Some(nav_history) = self.nav_history.as_mut() {
 8078            let buffer = self.buffer.read(cx).read(cx);
 8079            let cursor_position = cursor_anchor.to_point(&buffer);
 8080            let scroll_state = self.scroll_manager.anchor();
 8081            let scroll_top_row = scroll_state.top_row(&buffer);
 8082            drop(buffer);
 8083
 8084            if let Some(new_position) = new_position {
 8085                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 8086                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 8087                    return;
 8088                }
 8089            }
 8090
 8091            nav_history.push(
 8092                Some(NavigationData {
 8093                    cursor_anchor,
 8094                    cursor_position,
 8095                    scroll_anchor: scroll_state,
 8096                    scroll_top_row,
 8097                }),
 8098                cx,
 8099            );
 8100        }
 8101    }
 8102
 8103    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 8104        let buffer = self.buffer.read(cx).snapshot(cx);
 8105        let mut selection = self.selections.first::<usize>(cx);
 8106        selection.set_head(buffer.len(), SelectionGoal::None);
 8107        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8108            s.select(vec![selection]);
 8109        });
 8110    }
 8111
 8112    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 8113        let end = self.buffer.read(cx).read(cx).len();
 8114        self.change_selections(None, cx, |s| {
 8115            s.select_ranges(vec![0..end]);
 8116        });
 8117    }
 8118
 8119    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 8120        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8121        let mut selections = self.selections.all::<Point>(cx);
 8122        let max_point = display_map.buffer_snapshot.max_point();
 8123        for selection in &mut selections {
 8124            let rows = selection.spanned_rows(true, &display_map);
 8125            selection.start = Point::new(rows.start.0, 0);
 8126            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 8127            selection.reversed = false;
 8128        }
 8129        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8130            s.select(selections);
 8131        });
 8132    }
 8133
 8134    pub fn split_selection_into_lines(
 8135        &mut self,
 8136        _: &SplitSelectionIntoLines,
 8137        cx: &mut ViewContext<Self>,
 8138    ) {
 8139        let mut to_unfold = Vec::new();
 8140        let mut new_selection_ranges = Vec::new();
 8141        {
 8142            let selections = self.selections.all::<Point>(cx);
 8143            let buffer = self.buffer.read(cx).read(cx);
 8144            for selection in selections {
 8145                for row in selection.start.row..selection.end.row {
 8146                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 8147                    new_selection_ranges.push(cursor..cursor);
 8148                }
 8149                new_selection_ranges.push(selection.end..selection.end);
 8150                to_unfold.push(selection.start..selection.end);
 8151            }
 8152        }
 8153        self.unfold_ranges(to_unfold, true, true, cx);
 8154        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8155            s.select_ranges(new_selection_ranges);
 8156        });
 8157    }
 8158
 8159    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 8160        self.add_selection(true, cx);
 8161    }
 8162
 8163    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 8164        self.add_selection(false, cx);
 8165    }
 8166
 8167    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 8168        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8169        let mut selections = self.selections.all::<Point>(cx);
 8170        let text_layout_details = self.text_layout_details(cx);
 8171        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 8172            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 8173            let range = oldest_selection.display_range(&display_map).sorted();
 8174
 8175            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 8176            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 8177            let positions = start_x.min(end_x)..start_x.max(end_x);
 8178
 8179            selections.clear();
 8180            let mut stack = Vec::new();
 8181            for row in range.start.row().0..=range.end.row().0 {
 8182                if let Some(selection) = self.selections.build_columnar_selection(
 8183                    &display_map,
 8184                    DisplayRow(row),
 8185                    &positions,
 8186                    oldest_selection.reversed,
 8187                    &text_layout_details,
 8188                ) {
 8189                    stack.push(selection.id);
 8190                    selections.push(selection);
 8191                }
 8192            }
 8193
 8194            if above {
 8195                stack.reverse();
 8196            }
 8197
 8198            AddSelectionsState { above, stack }
 8199        });
 8200
 8201        let last_added_selection = *state.stack.last().unwrap();
 8202        let mut new_selections = Vec::new();
 8203        if above == state.above {
 8204            let end_row = if above {
 8205                DisplayRow(0)
 8206            } else {
 8207                display_map.max_point().row()
 8208            };
 8209
 8210            'outer: for selection in selections {
 8211                if selection.id == last_added_selection {
 8212                    let range = selection.display_range(&display_map).sorted();
 8213                    debug_assert_eq!(range.start.row(), range.end.row());
 8214                    let mut row = range.start.row();
 8215                    let positions =
 8216                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 8217                            px(start)..px(end)
 8218                        } else {
 8219                            let start_x =
 8220                                display_map.x_for_display_point(range.start, &text_layout_details);
 8221                            let end_x =
 8222                                display_map.x_for_display_point(range.end, &text_layout_details);
 8223                            start_x.min(end_x)..start_x.max(end_x)
 8224                        };
 8225
 8226                    while row != end_row {
 8227                        if above {
 8228                            row.0 -= 1;
 8229                        } else {
 8230                            row.0 += 1;
 8231                        }
 8232
 8233                        if let Some(new_selection) = self.selections.build_columnar_selection(
 8234                            &display_map,
 8235                            row,
 8236                            &positions,
 8237                            selection.reversed,
 8238                            &text_layout_details,
 8239                        ) {
 8240                            state.stack.push(new_selection.id);
 8241                            if above {
 8242                                new_selections.push(new_selection);
 8243                                new_selections.push(selection);
 8244                            } else {
 8245                                new_selections.push(selection);
 8246                                new_selections.push(new_selection);
 8247                            }
 8248
 8249                            continue 'outer;
 8250                        }
 8251                    }
 8252                }
 8253
 8254                new_selections.push(selection);
 8255            }
 8256        } else {
 8257            new_selections = selections;
 8258            new_selections.retain(|s| s.id != last_added_selection);
 8259            state.stack.pop();
 8260        }
 8261
 8262        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8263            s.select(new_selections);
 8264        });
 8265        if state.stack.len() > 1 {
 8266            self.add_selections_state = Some(state);
 8267        }
 8268    }
 8269
 8270    pub fn select_next_match_internal(
 8271        &mut self,
 8272        display_map: &DisplaySnapshot,
 8273        replace_newest: bool,
 8274        autoscroll: Option<Autoscroll>,
 8275        cx: &mut ViewContext<Self>,
 8276    ) -> Result<()> {
 8277        fn select_next_match_ranges(
 8278            this: &mut Editor,
 8279            range: Range<usize>,
 8280            replace_newest: bool,
 8281            auto_scroll: Option<Autoscroll>,
 8282            cx: &mut ViewContext<Editor>,
 8283        ) {
 8284            this.unfold_ranges([range.clone()], false, true, cx);
 8285            this.change_selections(auto_scroll, cx, |s| {
 8286                if replace_newest {
 8287                    s.delete(s.newest_anchor().id);
 8288                }
 8289                s.insert_range(range.clone());
 8290            });
 8291        }
 8292
 8293        let buffer = &display_map.buffer_snapshot;
 8294        let mut selections = self.selections.all::<usize>(cx);
 8295        if let Some(mut select_next_state) = self.select_next_state.take() {
 8296            let query = &select_next_state.query;
 8297            if !select_next_state.done {
 8298                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8299                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8300                let mut next_selected_range = None;
 8301
 8302                let bytes_after_last_selection =
 8303                    buffer.bytes_in_range(last_selection.end..buffer.len());
 8304                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 8305                let query_matches = query
 8306                    .stream_find_iter(bytes_after_last_selection)
 8307                    .map(|result| (last_selection.end, result))
 8308                    .chain(
 8309                        query
 8310                            .stream_find_iter(bytes_before_first_selection)
 8311                            .map(|result| (0, result)),
 8312                    );
 8313
 8314                for (start_offset, query_match) in query_matches {
 8315                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8316                    let offset_range =
 8317                        start_offset + query_match.start()..start_offset + query_match.end();
 8318                    let display_range = offset_range.start.to_display_point(display_map)
 8319                        ..offset_range.end.to_display_point(display_map);
 8320
 8321                    if !select_next_state.wordwise
 8322                        || (!movement::is_inside_word(display_map, display_range.start)
 8323                            && !movement::is_inside_word(display_map, display_range.end))
 8324                    {
 8325                        // TODO: This is n^2, because we might check all the selections
 8326                        if !selections
 8327                            .iter()
 8328                            .any(|selection| selection.range().overlaps(&offset_range))
 8329                        {
 8330                            next_selected_range = Some(offset_range);
 8331                            break;
 8332                        }
 8333                    }
 8334                }
 8335
 8336                if let Some(next_selected_range) = next_selected_range {
 8337                    select_next_match_ranges(
 8338                        self,
 8339                        next_selected_range,
 8340                        replace_newest,
 8341                        autoscroll,
 8342                        cx,
 8343                    );
 8344                } else {
 8345                    select_next_state.done = true;
 8346                }
 8347            }
 8348
 8349            self.select_next_state = Some(select_next_state);
 8350        } else {
 8351            let mut only_carets = true;
 8352            let mut same_text_selected = true;
 8353            let mut selected_text = None;
 8354
 8355            let mut selections_iter = selections.iter().peekable();
 8356            while let Some(selection) = selections_iter.next() {
 8357                if selection.start != selection.end {
 8358                    only_carets = false;
 8359                }
 8360
 8361                if same_text_selected {
 8362                    if selected_text.is_none() {
 8363                        selected_text =
 8364                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8365                    }
 8366
 8367                    if let Some(next_selection) = selections_iter.peek() {
 8368                        if next_selection.range().len() == selection.range().len() {
 8369                            let next_selected_text = buffer
 8370                                .text_for_range(next_selection.range())
 8371                                .collect::<String>();
 8372                            if Some(next_selected_text) != selected_text {
 8373                                same_text_selected = false;
 8374                                selected_text = None;
 8375                            }
 8376                        } else {
 8377                            same_text_selected = false;
 8378                            selected_text = None;
 8379                        }
 8380                    }
 8381                }
 8382            }
 8383
 8384            if only_carets {
 8385                for selection in &mut selections {
 8386                    let word_range = movement::surrounding_word(
 8387                        display_map,
 8388                        selection.start.to_display_point(display_map),
 8389                    );
 8390                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 8391                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 8392                    selection.goal = SelectionGoal::None;
 8393                    selection.reversed = false;
 8394                    select_next_match_ranges(
 8395                        self,
 8396                        selection.start..selection.end,
 8397                        replace_newest,
 8398                        autoscroll,
 8399                        cx,
 8400                    );
 8401                }
 8402
 8403                if selections.len() == 1 {
 8404                    let selection = selections
 8405                        .last()
 8406                        .expect("ensured that there's only one selection");
 8407                    let query = buffer
 8408                        .text_for_range(selection.start..selection.end)
 8409                        .collect::<String>();
 8410                    let is_empty = query.is_empty();
 8411                    let select_state = SelectNextState {
 8412                        query: AhoCorasick::new(&[query])?,
 8413                        wordwise: true,
 8414                        done: is_empty,
 8415                    };
 8416                    self.select_next_state = Some(select_state);
 8417                } else {
 8418                    self.select_next_state = None;
 8419                }
 8420            } else if let Some(selected_text) = selected_text {
 8421                self.select_next_state = Some(SelectNextState {
 8422                    query: AhoCorasick::new(&[selected_text])?,
 8423                    wordwise: false,
 8424                    done: false,
 8425                });
 8426                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 8427            }
 8428        }
 8429        Ok(())
 8430    }
 8431
 8432    pub fn select_all_matches(
 8433        &mut self,
 8434        _action: &SelectAllMatches,
 8435        cx: &mut ViewContext<Self>,
 8436    ) -> Result<()> {
 8437        self.push_to_selection_history();
 8438        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8439
 8440        self.select_next_match_internal(&display_map, false, None, cx)?;
 8441        let Some(select_next_state) = self.select_next_state.as_mut() else {
 8442            return Ok(());
 8443        };
 8444        if select_next_state.done {
 8445            return Ok(());
 8446        }
 8447
 8448        let mut new_selections = self.selections.all::<usize>(cx);
 8449
 8450        let buffer = &display_map.buffer_snapshot;
 8451        let query_matches = select_next_state
 8452            .query
 8453            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 8454
 8455        for query_match in query_matches {
 8456            let query_match = query_match.unwrap(); // can only fail due to I/O
 8457            let offset_range = query_match.start()..query_match.end();
 8458            let display_range = offset_range.start.to_display_point(&display_map)
 8459                ..offset_range.end.to_display_point(&display_map);
 8460
 8461            if !select_next_state.wordwise
 8462                || (!movement::is_inside_word(&display_map, display_range.start)
 8463                    && !movement::is_inside_word(&display_map, display_range.end))
 8464            {
 8465                self.selections.change_with(cx, |selections| {
 8466                    new_selections.push(Selection {
 8467                        id: selections.new_selection_id(),
 8468                        start: offset_range.start,
 8469                        end: offset_range.end,
 8470                        reversed: false,
 8471                        goal: SelectionGoal::None,
 8472                    });
 8473                });
 8474            }
 8475        }
 8476
 8477        new_selections.sort_by_key(|selection| selection.start);
 8478        let mut ix = 0;
 8479        while ix + 1 < new_selections.len() {
 8480            let current_selection = &new_selections[ix];
 8481            let next_selection = &new_selections[ix + 1];
 8482            if current_selection.range().overlaps(&next_selection.range()) {
 8483                if current_selection.id < next_selection.id {
 8484                    new_selections.remove(ix + 1);
 8485                } else {
 8486                    new_selections.remove(ix);
 8487                }
 8488            } else {
 8489                ix += 1;
 8490            }
 8491        }
 8492
 8493        select_next_state.done = true;
 8494        self.unfold_ranges(
 8495            new_selections.iter().map(|selection| selection.range()),
 8496            false,
 8497            false,
 8498            cx,
 8499        );
 8500        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 8501            selections.select(new_selections)
 8502        });
 8503
 8504        Ok(())
 8505    }
 8506
 8507    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 8508        self.push_to_selection_history();
 8509        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8510        self.select_next_match_internal(
 8511            &display_map,
 8512            action.replace_newest,
 8513            Some(Autoscroll::newest()),
 8514            cx,
 8515        )?;
 8516        Ok(())
 8517    }
 8518
 8519    pub fn select_previous(
 8520        &mut self,
 8521        action: &SelectPrevious,
 8522        cx: &mut ViewContext<Self>,
 8523    ) -> Result<()> {
 8524        self.push_to_selection_history();
 8525        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8526        let buffer = &display_map.buffer_snapshot;
 8527        let mut selections = self.selections.all::<usize>(cx);
 8528        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8529            let query = &select_prev_state.query;
 8530            if !select_prev_state.done {
 8531                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8532                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8533                let mut next_selected_range = None;
 8534                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8535                let bytes_before_last_selection =
 8536                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8537                let bytes_after_first_selection =
 8538                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8539                let query_matches = query
 8540                    .stream_find_iter(bytes_before_last_selection)
 8541                    .map(|result| (last_selection.start, result))
 8542                    .chain(
 8543                        query
 8544                            .stream_find_iter(bytes_after_first_selection)
 8545                            .map(|result| (buffer.len(), result)),
 8546                    );
 8547                for (end_offset, query_match) in query_matches {
 8548                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8549                    let offset_range =
 8550                        end_offset - query_match.end()..end_offset - query_match.start();
 8551                    let display_range = offset_range.start.to_display_point(&display_map)
 8552                        ..offset_range.end.to_display_point(&display_map);
 8553
 8554                    if !select_prev_state.wordwise
 8555                        || (!movement::is_inside_word(&display_map, display_range.start)
 8556                            && !movement::is_inside_word(&display_map, display_range.end))
 8557                    {
 8558                        next_selected_range = Some(offset_range);
 8559                        break;
 8560                    }
 8561                }
 8562
 8563                if let Some(next_selected_range) = next_selected_range {
 8564                    self.unfold_ranges([next_selected_range.clone()], false, true, cx);
 8565                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8566                        if action.replace_newest {
 8567                            s.delete(s.newest_anchor().id);
 8568                        }
 8569                        s.insert_range(next_selected_range);
 8570                    });
 8571                } else {
 8572                    select_prev_state.done = true;
 8573                }
 8574            }
 8575
 8576            self.select_prev_state = Some(select_prev_state);
 8577        } else {
 8578            let mut only_carets = true;
 8579            let mut same_text_selected = true;
 8580            let mut selected_text = None;
 8581
 8582            let mut selections_iter = selections.iter().peekable();
 8583            while let Some(selection) = selections_iter.next() {
 8584                if selection.start != selection.end {
 8585                    only_carets = false;
 8586                }
 8587
 8588                if same_text_selected {
 8589                    if selected_text.is_none() {
 8590                        selected_text =
 8591                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8592                    }
 8593
 8594                    if let Some(next_selection) = selections_iter.peek() {
 8595                        if next_selection.range().len() == selection.range().len() {
 8596                            let next_selected_text = buffer
 8597                                .text_for_range(next_selection.range())
 8598                                .collect::<String>();
 8599                            if Some(next_selected_text) != selected_text {
 8600                                same_text_selected = false;
 8601                                selected_text = None;
 8602                            }
 8603                        } else {
 8604                            same_text_selected = false;
 8605                            selected_text = None;
 8606                        }
 8607                    }
 8608                }
 8609            }
 8610
 8611            if only_carets {
 8612                for selection in &mut selections {
 8613                    let word_range = movement::surrounding_word(
 8614                        &display_map,
 8615                        selection.start.to_display_point(&display_map),
 8616                    );
 8617                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8618                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8619                    selection.goal = SelectionGoal::None;
 8620                    selection.reversed = false;
 8621                }
 8622                if selections.len() == 1 {
 8623                    let selection = selections
 8624                        .last()
 8625                        .expect("ensured that there's only one selection");
 8626                    let query = buffer
 8627                        .text_for_range(selection.start..selection.end)
 8628                        .collect::<String>();
 8629                    let is_empty = query.is_empty();
 8630                    let select_state = SelectNextState {
 8631                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8632                        wordwise: true,
 8633                        done: is_empty,
 8634                    };
 8635                    self.select_prev_state = Some(select_state);
 8636                } else {
 8637                    self.select_prev_state = None;
 8638                }
 8639
 8640                self.unfold_ranges(
 8641                    selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8642                    false,
 8643                    true,
 8644                    cx,
 8645                );
 8646                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8647                    s.select(selections);
 8648                });
 8649            } else if let Some(selected_text) = selected_text {
 8650                self.select_prev_state = Some(SelectNextState {
 8651                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8652                    wordwise: false,
 8653                    done: false,
 8654                });
 8655                self.select_previous(action, cx)?;
 8656            }
 8657        }
 8658        Ok(())
 8659    }
 8660
 8661    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 8662        let text_layout_details = &self.text_layout_details(cx);
 8663        self.transact(cx, |this, cx| {
 8664            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8665            let mut edits = Vec::new();
 8666            let mut selection_edit_ranges = Vec::new();
 8667            let mut last_toggled_row = None;
 8668            let snapshot = this.buffer.read(cx).read(cx);
 8669            let empty_str: Arc<str> = Arc::default();
 8670            let mut suffixes_inserted = Vec::new();
 8671
 8672            fn comment_prefix_range(
 8673                snapshot: &MultiBufferSnapshot,
 8674                row: MultiBufferRow,
 8675                comment_prefix: &str,
 8676                comment_prefix_whitespace: &str,
 8677            ) -> Range<Point> {
 8678                let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
 8679
 8680                let mut line_bytes = snapshot
 8681                    .bytes_in_range(start..snapshot.max_point())
 8682                    .flatten()
 8683                    .copied();
 8684
 8685                // If this line currently begins with the line comment prefix, then record
 8686                // the range containing the prefix.
 8687                if line_bytes
 8688                    .by_ref()
 8689                    .take(comment_prefix.len())
 8690                    .eq(comment_prefix.bytes())
 8691                {
 8692                    // Include any whitespace that matches the comment prefix.
 8693                    let matching_whitespace_len = line_bytes
 8694                        .zip(comment_prefix_whitespace.bytes())
 8695                        .take_while(|(a, b)| a == b)
 8696                        .count() as u32;
 8697                    let end = Point::new(
 8698                        start.row,
 8699                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 8700                    );
 8701                    start..end
 8702                } else {
 8703                    start..start
 8704                }
 8705            }
 8706
 8707            fn comment_suffix_range(
 8708                snapshot: &MultiBufferSnapshot,
 8709                row: MultiBufferRow,
 8710                comment_suffix: &str,
 8711                comment_suffix_has_leading_space: bool,
 8712            ) -> Range<Point> {
 8713                let end = Point::new(row.0, snapshot.line_len(row));
 8714                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 8715
 8716                let mut line_end_bytes = snapshot
 8717                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 8718                    .flatten()
 8719                    .copied();
 8720
 8721                let leading_space_len = if suffix_start_column > 0
 8722                    && line_end_bytes.next() == Some(b' ')
 8723                    && comment_suffix_has_leading_space
 8724                {
 8725                    1
 8726                } else {
 8727                    0
 8728                };
 8729
 8730                // If this line currently begins with the line comment prefix, then record
 8731                // the range containing the prefix.
 8732                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 8733                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 8734                    start..end
 8735                } else {
 8736                    end..end
 8737                }
 8738            }
 8739
 8740            // TODO: Handle selections that cross excerpts
 8741            for selection in &mut selections {
 8742                let start_column = snapshot
 8743                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 8744                    .len;
 8745                let language = if let Some(language) =
 8746                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 8747                {
 8748                    language
 8749                } else {
 8750                    continue;
 8751                };
 8752
 8753                selection_edit_ranges.clear();
 8754
 8755                // If multiple selections contain a given row, avoid processing that
 8756                // row more than once.
 8757                let mut start_row = MultiBufferRow(selection.start.row);
 8758                if last_toggled_row == Some(start_row) {
 8759                    start_row = start_row.next_row();
 8760                }
 8761                let end_row =
 8762                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 8763                        MultiBufferRow(selection.end.row - 1)
 8764                    } else {
 8765                        MultiBufferRow(selection.end.row)
 8766                    };
 8767                last_toggled_row = Some(end_row);
 8768
 8769                if start_row > end_row {
 8770                    continue;
 8771                }
 8772
 8773                // If the language has line comments, toggle those.
 8774                let full_comment_prefixes = language.line_comment_prefixes();
 8775                if !full_comment_prefixes.is_empty() {
 8776                    let first_prefix = full_comment_prefixes
 8777                        .first()
 8778                        .expect("prefixes is non-empty");
 8779                    let prefix_trimmed_lengths = full_comment_prefixes
 8780                        .iter()
 8781                        .map(|p| p.trim_end_matches(' ').len())
 8782                        .collect::<SmallVec<[usize; 4]>>();
 8783
 8784                    let mut all_selection_lines_are_comments = true;
 8785
 8786                    for row in start_row.0..=end_row.0 {
 8787                        let row = MultiBufferRow(row);
 8788                        if start_row < end_row && snapshot.is_line_blank(row) {
 8789                            continue;
 8790                        }
 8791
 8792                        let prefix_range = full_comment_prefixes
 8793                            .iter()
 8794                            .zip(prefix_trimmed_lengths.iter().copied())
 8795                            .map(|(prefix, trimmed_prefix_len)| {
 8796                                comment_prefix_range(
 8797                                    snapshot.deref(),
 8798                                    row,
 8799                                    &prefix[..trimmed_prefix_len],
 8800                                    &prefix[trimmed_prefix_len..],
 8801                                )
 8802                            })
 8803                            .max_by_key(|range| range.end.column - range.start.column)
 8804                            .expect("prefixes is non-empty");
 8805
 8806                        if prefix_range.is_empty() {
 8807                            all_selection_lines_are_comments = false;
 8808                        }
 8809
 8810                        selection_edit_ranges.push(prefix_range);
 8811                    }
 8812
 8813                    if all_selection_lines_are_comments {
 8814                        edits.extend(
 8815                            selection_edit_ranges
 8816                                .iter()
 8817                                .cloned()
 8818                                .map(|range| (range, empty_str.clone())),
 8819                        );
 8820                    } else {
 8821                        let min_column = selection_edit_ranges
 8822                            .iter()
 8823                            .map(|range| range.start.column)
 8824                            .min()
 8825                            .unwrap_or(0);
 8826                        edits.extend(selection_edit_ranges.iter().map(|range| {
 8827                            let position = Point::new(range.start.row, min_column);
 8828                            (position..position, first_prefix.clone())
 8829                        }));
 8830                    }
 8831                } else if let Some((full_comment_prefix, comment_suffix)) =
 8832                    language.block_comment_delimiters()
 8833                {
 8834                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 8835                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 8836                    let prefix_range = comment_prefix_range(
 8837                        snapshot.deref(),
 8838                        start_row,
 8839                        comment_prefix,
 8840                        comment_prefix_whitespace,
 8841                    );
 8842                    let suffix_range = comment_suffix_range(
 8843                        snapshot.deref(),
 8844                        end_row,
 8845                        comment_suffix.trim_start_matches(' '),
 8846                        comment_suffix.starts_with(' '),
 8847                    );
 8848
 8849                    if prefix_range.is_empty() || suffix_range.is_empty() {
 8850                        edits.push((
 8851                            prefix_range.start..prefix_range.start,
 8852                            full_comment_prefix.clone(),
 8853                        ));
 8854                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 8855                        suffixes_inserted.push((end_row, comment_suffix.len()));
 8856                    } else {
 8857                        edits.push((prefix_range, empty_str.clone()));
 8858                        edits.push((suffix_range, empty_str.clone()));
 8859                    }
 8860                } else {
 8861                    continue;
 8862                }
 8863            }
 8864
 8865            drop(snapshot);
 8866            this.buffer.update(cx, |buffer, cx| {
 8867                buffer.edit(edits, None, cx);
 8868            });
 8869
 8870            // Adjust selections so that they end before any comment suffixes that
 8871            // were inserted.
 8872            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 8873            let mut selections = this.selections.all::<Point>(cx);
 8874            let snapshot = this.buffer.read(cx).read(cx);
 8875            for selection in &mut selections {
 8876                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 8877                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 8878                        Ordering::Less => {
 8879                            suffixes_inserted.next();
 8880                            continue;
 8881                        }
 8882                        Ordering::Greater => break,
 8883                        Ordering::Equal => {
 8884                            if selection.end.column == snapshot.line_len(row) {
 8885                                if selection.is_empty() {
 8886                                    selection.start.column -= suffix_len as u32;
 8887                                }
 8888                                selection.end.column -= suffix_len as u32;
 8889                            }
 8890                            break;
 8891                        }
 8892                    }
 8893                }
 8894            }
 8895
 8896            drop(snapshot);
 8897            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 8898
 8899            let selections = this.selections.all::<Point>(cx);
 8900            let selections_on_single_row = selections.windows(2).all(|selections| {
 8901                selections[0].start.row == selections[1].start.row
 8902                    && selections[0].end.row == selections[1].end.row
 8903                    && selections[0].start.row == selections[0].end.row
 8904            });
 8905            let selections_selecting = selections
 8906                .iter()
 8907                .any(|selection| selection.start != selection.end);
 8908            let advance_downwards = action.advance_downwards
 8909                && selections_on_single_row
 8910                && !selections_selecting
 8911                && !matches!(this.mode, EditorMode::SingleLine { .. });
 8912
 8913            if advance_downwards {
 8914                let snapshot = this.buffer.read(cx).snapshot(cx);
 8915
 8916                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8917                    s.move_cursors_with(|display_snapshot, display_point, _| {
 8918                        let mut point = display_point.to_point(display_snapshot);
 8919                        point.row += 1;
 8920                        point = snapshot.clip_point(point, Bias::Left);
 8921                        let display_point = point.to_display_point(display_snapshot);
 8922                        let goal = SelectionGoal::HorizontalPosition(
 8923                            display_snapshot
 8924                                .x_for_display_point(display_point, text_layout_details)
 8925                                .into(),
 8926                        );
 8927                        (display_point, goal)
 8928                    })
 8929                });
 8930            }
 8931        });
 8932    }
 8933
 8934    pub fn select_enclosing_symbol(
 8935        &mut self,
 8936        _: &SelectEnclosingSymbol,
 8937        cx: &mut ViewContext<Self>,
 8938    ) {
 8939        let buffer = self.buffer.read(cx).snapshot(cx);
 8940        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8941
 8942        fn update_selection(
 8943            selection: &Selection<usize>,
 8944            buffer_snap: &MultiBufferSnapshot,
 8945        ) -> Option<Selection<usize>> {
 8946            let cursor = selection.head();
 8947            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 8948            for symbol in symbols.iter().rev() {
 8949                let start = symbol.range.start.to_offset(buffer_snap);
 8950                let end = symbol.range.end.to_offset(buffer_snap);
 8951                let new_range = start..end;
 8952                if start < selection.start || end > selection.end {
 8953                    return Some(Selection {
 8954                        id: selection.id,
 8955                        start: new_range.start,
 8956                        end: new_range.end,
 8957                        goal: SelectionGoal::None,
 8958                        reversed: selection.reversed,
 8959                    });
 8960                }
 8961            }
 8962            None
 8963        }
 8964
 8965        let mut selected_larger_symbol = false;
 8966        let new_selections = old_selections
 8967            .iter()
 8968            .map(|selection| match update_selection(selection, &buffer) {
 8969                Some(new_selection) => {
 8970                    if new_selection.range() != selection.range() {
 8971                        selected_larger_symbol = true;
 8972                    }
 8973                    new_selection
 8974                }
 8975                None => selection.clone(),
 8976            })
 8977            .collect::<Vec<_>>();
 8978
 8979        if selected_larger_symbol {
 8980            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8981                s.select(new_selections);
 8982            });
 8983        }
 8984    }
 8985
 8986    pub fn select_larger_syntax_node(
 8987        &mut self,
 8988        _: &SelectLargerSyntaxNode,
 8989        cx: &mut ViewContext<Self>,
 8990    ) {
 8991        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8992        let buffer = self.buffer.read(cx).snapshot(cx);
 8993        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8994
 8995        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8996        let mut selected_larger_node = false;
 8997        let new_selections = old_selections
 8998            .iter()
 8999            .map(|selection| {
 9000                let old_range = selection.start..selection.end;
 9001                let mut new_range = old_range.clone();
 9002                while let Some(containing_range) =
 9003                    buffer.range_for_syntax_ancestor(new_range.clone())
 9004                {
 9005                    new_range = containing_range;
 9006                    if !display_map.intersects_fold(new_range.start)
 9007                        && !display_map.intersects_fold(new_range.end)
 9008                    {
 9009                        break;
 9010                    }
 9011                }
 9012
 9013                selected_larger_node |= new_range != old_range;
 9014                Selection {
 9015                    id: selection.id,
 9016                    start: new_range.start,
 9017                    end: new_range.end,
 9018                    goal: SelectionGoal::None,
 9019                    reversed: selection.reversed,
 9020                }
 9021            })
 9022            .collect::<Vec<_>>();
 9023
 9024        if selected_larger_node {
 9025            stack.push(old_selections);
 9026            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9027                s.select(new_selections);
 9028            });
 9029        }
 9030        self.select_larger_syntax_node_stack = stack;
 9031    }
 9032
 9033    pub fn select_smaller_syntax_node(
 9034        &mut self,
 9035        _: &SelectSmallerSyntaxNode,
 9036        cx: &mut ViewContext<Self>,
 9037    ) {
 9038        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9039        if let Some(selections) = stack.pop() {
 9040            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9041                s.select(selections.to_vec());
 9042            });
 9043        }
 9044        self.select_larger_syntax_node_stack = stack;
 9045    }
 9046
 9047    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 9048        if !EditorSettings::get_global(cx).gutter.runnables {
 9049            self.clear_tasks();
 9050            return Task::ready(());
 9051        }
 9052        let project = self.project.clone();
 9053        cx.spawn(|this, mut cx| async move {
 9054            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 9055                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 9056            }) else {
 9057                return;
 9058            };
 9059
 9060            let Some(project) = project else {
 9061                return;
 9062            };
 9063
 9064            let hide_runnables = project
 9065                .update(&mut cx, |project, cx| {
 9066                    // Do not display any test indicators in non-dev server remote projects.
 9067                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 9068                })
 9069                .unwrap_or(true);
 9070            if hide_runnables {
 9071                return;
 9072            }
 9073            let new_rows =
 9074                cx.background_executor()
 9075                    .spawn({
 9076                        let snapshot = display_snapshot.clone();
 9077                        async move {
 9078                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 9079                        }
 9080                    })
 9081                    .await;
 9082            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 9083
 9084            this.update(&mut cx, |this, _| {
 9085                this.clear_tasks();
 9086                for (key, value) in rows {
 9087                    this.insert_tasks(key, value);
 9088                }
 9089            })
 9090            .ok();
 9091        })
 9092    }
 9093    fn fetch_runnable_ranges(
 9094        snapshot: &DisplaySnapshot,
 9095        range: Range<Anchor>,
 9096    ) -> Vec<language::RunnableRange> {
 9097        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 9098    }
 9099
 9100    fn runnable_rows(
 9101        project: Model<Project>,
 9102        snapshot: DisplaySnapshot,
 9103        runnable_ranges: Vec<RunnableRange>,
 9104        mut cx: AsyncWindowContext,
 9105    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 9106        runnable_ranges
 9107            .into_iter()
 9108            .filter_map(|mut runnable| {
 9109                let tasks = cx
 9110                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 9111                    .ok()?;
 9112                if tasks.is_empty() {
 9113                    return None;
 9114                }
 9115
 9116                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 9117
 9118                let row = snapshot
 9119                    .buffer_snapshot
 9120                    .buffer_line_for_row(MultiBufferRow(point.row))?
 9121                    .1
 9122                    .start
 9123                    .row;
 9124
 9125                let context_range =
 9126                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 9127                Some((
 9128                    (runnable.buffer_id, row),
 9129                    RunnableTasks {
 9130                        templates: tasks,
 9131                        offset: MultiBufferOffset(runnable.run_range.start),
 9132                        context_range,
 9133                        column: point.column,
 9134                        extra_variables: runnable.extra_captures,
 9135                    },
 9136                ))
 9137            })
 9138            .collect()
 9139    }
 9140
 9141    fn templates_with_tags(
 9142        project: &Model<Project>,
 9143        runnable: &mut Runnable,
 9144        cx: &WindowContext<'_>,
 9145    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 9146        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 9147            let (worktree_id, file) = project
 9148                .buffer_for_id(runnable.buffer, cx)
 9149                .and_then(|buffer| buffer.read(cx).file())
 9150                .map(|file| (file.worktree_id(cx), file.clone()))
 9151                .unzip();
 9152
 9153            (
 9154                project.task_store().read(cx).task_inventory().cloned(),
 9155                worktree_id,
 9156                file,
 9157            )
 9158        });
 9159
 9160        let tags = mem::take(&mut runnable.tags);
 9161        let mut tags: Vec<_> = tags
 9162            .into_iter()
 9163            .flat_map(|tag| {
 9164                let tag = tag.0.clone();
 9165                inventory
 9166                    .as_ref()
 9167                    .into_iter()
 9168                    .flat_map(|inventory| {
 9169                        inventory.read(cx).list_tasks(
 9170                            file.clone(),
 9171                            Some(runnable.language.clone()),
 9172                            worktree_id,
 9173                            cx,
 9174                        )
 9175                    })
 9176                    .filter(move |(_, template)| {
 9177                        template.tags.iter().any(|source_tag| source_tag == &tag)
 9178                    })
 9179            })
 9180            .sorted_by_key(|(kind, _)| kind.to_owned())
 9181            .collect();
 9182        if let Some((leading_tag_source, _)) = tags.first() {
 9183            // Strongest source wins; if we have worktree tag binding, prefer that to
 9184            // global and language bindings;
 9185            // if we have a global binding, prefer that to language binding.
 9186            let first_mismatch = tags
 9187                .iter()
 9188                .position(|(tag_source, _)| tag_source != leading_tag_source);
 9189            if let Some(index) = first_mismatch {
 9190                tags.truncate(index);
 9191            }
 9192        }
 9193
 9194        tags
 9195    }
 9196
 9197    pub fn move_to_enclosing_bracket(
 9198        &mut self,
 9199        _: &MoveToEnclosingBracket,
 9200        cx: &mut ViewContext<Self>,
 9201    ) {
 9202        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9203            s.move_offsets_with(|snapshot, selection| {
 9204                let Some(enclosing_bracket_ranges) =
 9205                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 9206                else {
 9207                    return;
 9208                };
 9209
 9210                let mut best_length = usize::MAX;
 9211                let mut best_inside = false;
 9212                let mut best_in_bracket_range = false;
 9213                let mut best_destination = None;
 9214                for (open, close) in enclosing_bracket_ranges {
 9215                    let close = close.to_inclusive();
 9216                    let length = close.end() - open.start;
 9217                    let inside = selection.start >= open.end && selection.end <= *close.start();
 9218                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 9219                        || close.contains(&selection.head());
 9220
 9221                    // If best is next to a bracket and current isn't, skip
 9222                    if !in_bracket_range && best_in_bracket_range {
 9223                        continue;
 9224                    }
 9225
 9226                    // Prefer smaller lengths unless best is inside and current isn't
 9227                    if length > best_length && (best_inside || !inside) {
 9228                        continue;
 9229                    }
 9230
 9231                    best_length = length;
 9232                    best_inside = inside;
 9233                    best_in_bracket_range = in_bracket_range;
 9234                    best_destination = Some(
 9235                        if close.contains(&selection.start) && close.contains(&selection.end) {
 9236                            if inside {
 9237                                open.end
 9238                            } else {
 9239                                open.start
 9240                            }
 9241                        } else if inside {
 9242                            *close.start()
 9243                        } else {
 9244                            *close.end()
 9245                        },
 9246                    );
 9247                }
 9248
 9249                if let Some(destination) = best_destination {
 9250                    selection.collapse_to(destination, SelectionGoal::None);
 9251                }
 9252            })
 9253        });
 9254    }
 9255
 9256    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 9257        self.end_selection(cx);
 9258        self.selection_history.mode = SelectionHistoryMode::Undoing;
 9259        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 9260            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9261            self.select_next_state = entry.select_next_state;
 9262            self.select_prev_state = entry.select_prev_state;
 9263            self.add_selections_state = entry.add_selections_state;
 9264            self.request_autoscroll(Autoscroll::newest(), cx);
 9265        }
 9266        self.selection_history.mode = SelectionHistoryMode::Normal;
 9267    }
 9268
 9269    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 9270        self.end_selection(cx);
 9271        self.selection_history.mode = SelectionHistoryMode::Redoing;
 9272        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 9273            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9274            self.select_next_state = entry.select_next_state;
 9275            self.select_prev_state = entry.select_prev_state;
 9276            self.add_selections_state = entry.add_selections_state;
 9277            self.request_autoscroll(Autoscroll::newest(), cx);
 9278        }
 9279        self.selection_history.mode = SelectionHistoryMode::Normal;
 9280    }
 9281
 9282    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 9283        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 9284    }
 9285
 9286    pub fn expand_excerpts_down(
 9287        &mut self,
 9288        action: &ExpandExcerptsDown,
 9289        cx: &mut ViewContext<Self>,
 9290    ) {
 9291        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 9292    }
 9293
 9294    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 9295        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 9296    }
 9297
 9298    pub fn expand_excerpts_for_direction(
 9299        &mut self,
 9300        lines: u32,
 9301        direction: ExpandExcerptDirection,
 9302        cx: &mut ViewContext<Self>,
 9303    ) {
 9304        let selections = self.selections.disjoint_anchors();
 9305
 9306        let lines = if lines == 0 {
 9307            EditorSettings::get_global(cx).expand_excerpt_lines
 9308        } else {
 9309            lines
 9310        };
 9311
 9312        self.buffer.update(cx, |buffer, cx| {
 9313            buffer.expand_excerpts(
 9314                selections
 9315                    .iter()
 9316                    .map(|selection| selection.head().excerpt_id)
 9317                    .dedup(),
 9318                lines,
 9319                direction,
 9320                cx,
 9321            )
 9322        })
 9323    }
 9324
 9325    pub fn expand_excerpt(
 9326        &mut self,
 9327        excerpt: ExcerptId,
 9328        direction: ExpandExcerptDirection,
 9329        cx: &mut ViewContext<Self>,
 9330    ) {
 9331        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 9332        self.buffer.update(cx, |buffer, cx| {
 9333            buffer.expand_excerpts([excerpt], lines, direction, cx)
 9334        })
 9335    }
 9336
 9337    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 9338        self.go_to_diagnostic_impl(Direction::Next, cx)
 9339    }
 9340
 9341    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 9342        self.go_to_diagnostic_impl(Direction::Prev, cx)
 9343    }
 9344
 9345    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 9346        let buffer = self.buffer.read(cx).snapshot(cx);
 9347        let selection = self.selections.newest::<usize>(cx);
 9348
 9349        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 9350        if direction == Direction::Next {
 9351            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 9352                let (group_id, jump_to) = popover.activation_info();
 9353                if self.activate_diagnostics(group_id, cx) {
 9354                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9355                        let mut new_selection = s.newest_anchor().clone();
 9356                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 9357                        s.select_anchors(vec![new_selection.clone()]);
 9358                    });
 9359                }
 9360                return;
 9361            }
 9362        }
 9363
 9364        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 9365            active_diagnostics
 9366                .primary_range
 9367                .to_offset(&buffer)
 9368                .to_inclusive()
 9369        });
 9370        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 9371            if active_primary_range.contains(&selection.head()) {
 9372                *active_primary_range.start()
 9373            } else {
 9374                selection.head()
 9375            }
 9376        } else {
 9377            selection.head()
 9378        };
 9379        let snapshot = self.snapshot(cx);
 9380        loop {
 9381            let diagnostics = if direction == Direction::Prev {
 9382                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 9383            } else {
 9384                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 9385            }
 9386            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 9387            let group = diagnostics
 9388                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 9389                // be sorted in a stable way
 9390                // skip until we are at current active diagnostic, if it exists
 9391                .skip_while(|entry| {
 9392                    (match direction {
 9393                        Direction::Prev => entry.range.start >= search_start,
 9394                        Direction::Next => entry.range.start <= search_start,
 9395                    }) && self
 9396                        .active_diagnostics
 9397                        .as_ref()
 9398                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 9399                })
 9400                .find_map(|entry| {
 9401                    if entry.diagnostic.is_primary
 9402                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 9403                        && !entry.range.is_empty()
 9404                        // if we match with the active diagnostic, skip it
 9405                        && Some(entry.diagnostic.group_id)
 9406                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 9407                    {
 9408                        Some((entry.range, entry.diagnostic.group_id))
 9409                    } else {
 9410                        None
 9411                    }
 9412                });
 9413
 9414            if let Some((primary_range, group_id)) = group {
 9415                if self.activate_diagnostics(group_id, cx) {
 9416                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9417                        s.select(vec![Selection {
 9418                            id: selection.id,
 9419                            start: primary_range.start,
 9420                            end: primary_range.start,
 9421                            reversed: false,
 9422                            goal: SelectionGoal::None,
 9423                        }]);
 9424                    });
 9425                }
 9426                break;
 9427            } else {
 9428                // Cycle around to the start of the buffer, potentially moving back to the start of
 9429                // the currently active diagnostic.
 9430                active_primary_range.take();
 9431                if direction == Direction::Prev {
 9432                    if search_start == buffer.len() {
 9433                        break;
 9434                    } else {
 9435                        search_start = buffer.len();
 9436                    }
 9437                } else if search_start == 0 {
 9438                    break;
 9439                } else {
 9440                    search_start = 0;
 9441                }
 9442            }
 9443        }
 9444    }
 9445
 9446    fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 9447        let snapshot = self
 9448            .display_map
 9449            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9450        let selection = self.selections.newest::<Point>(cx);
 9451        self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
 9452    }
 9453
 9454    fn go_to_hunk_after_position(
 9455        &mut self,
 9456        snapshot: &DisplaySnapshot,
 9457        position: Point,
 9458        cx: &mut ViewContext<'_, Editor>,
 9459    ) -> Option<MultiBufferDiffHunk> {
 9460        if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9461            snapshot,
 9462            position,
 9463            false,
 9464            snapshot
 9465                .buffer_snapshot
 9466                .git_diff_hunks_in_range(MultiBufferRow(position.row + 1)..MultiBufferRow::MAX),
 9467            cx,
 9468        ) {
 9469            return Some(hunk);
 9470        }
 9471
 9472        let wrapped_point = Point::zero();
 9473        self.go_to_next_hunk_in_direction(
 9474            snapshot,
 9475            wrapped_point,
 9476            true,
 9477            snapshot.buffer_snapshot.git_diff_hunks_in_range(
 9478                MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
 9479            ),
 9480            cx,
 9481        )
 9482    }
 9483
 9484    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 9485        let snapshot = self
 9486            .display_map
 9487            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9488        let selection = self.selections.newest::<Point>(cx);
 9489
 9490        self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
 9491    }
 9492
 9493    fn go_to_hunk_before_position(
 9494        &mut self,
 9495        snapshot: &DisplaySnapshot,
 9496        position: Point,
 9497        cx: &mut ViewContext<'_, Editor>,
 9498    ) -> Option<MultiBufferDiffHunk> {
 9499        if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9500            snapshot,
 9501            position,
 9502            false,
 9503            snapshot
 9504                .buffer_snapshot
 9505                .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(position.row)),
 9506            cx,
 9507        ) {
 9508            return Some(hunk);
 9509        }
 9510
 9511        let wrapped_point = snapshot.buffer_snapshot.max_point();
 9512        self.go_to_next_hunk_in_direction(
 9513            snapshot,
 9514            wrapped_point,
 9515            true,
 9516            snapshot
 9517                .buffer_snapshot
 9518                .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(wrapped_point.row)),
 9519            cx,
 9520        )
 9521    }
 9522
 9523    fn go_to_next_hunk_in_direction(
 9524        &mut self,
 9525        snapshot: &DisplaySnapshot,
 9526        initial_point: Point,
 9527        is_wrapped: bool,
 9528        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
 9529        cx: &mut ViewContext<Editor>,
 9530    ) -> Option<MultiBufferDiffHunk> {
 9531        let display_point = initial_point.to_display_point(snapshot);
 9532        let mut hunks = hunks
 9533            .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
 9534            .filter(|(display_hunk, _)| {
 9535                is_wrapped || !display_hunk.contains_display_row(display_point.row())
 9536            })
 9537            .dedup();
 9538
 9539        if let Some((display_hunk, hunk)) = hunks.next() {
 9540            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9541                let row = display_hunk.start_display_row();
 9542                let point = DisplayPoint::new(row, 0);
 9543                s.select_display_ranges([point..point]);
 9544            });
 9545
 9546            Some(hunk)
 9547        } else {
 9548            None
 9549        }
 9550    }
 9551
 9552    pub fn go_to_definition(
 9553        &mut self,
 9554        _: &GoToDefinition,
 9555        cx: &mut ViewContext<Self>,
 9556    ) -> Task<Result<Navigated>> {
 9557        let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
 9558        cx.spawn(|editor, mut cx| async move {
 9559            if definition.await? == Navigated::Yes {
 9560                return Ok(Navigated::Yes);
 9561            }
 9562            match editor.update(&mut cx, |editor, cx| {
 9563                editor.find_all_references(&FindAllReferences, cx)
 9564            })? {
 9565                Some(references) => references.await,
 9566                None => Ok(Navigated::No),
 9567            }
 9568        })
 9569    }
 9570
 9571    pub fn go_to_declaration(
 9572        &mut self,
 9573        _: &GoToDeclaration,
 9574        cx: &mut ViewContext<Self>,
 9575    ) -> Task<Result<Navigated>> {
 9576        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
 9577    }
 9578
 9579    pub fn go_to_declaration_split(
 9580        &mut self,
 9581        _: &GoToDeclaration,
 9582        cx: &mut ViewContext<Self>,
 9583    ) -> Task<Result<Navigated>> {
 9584        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
 9585    }
 9586
 9587    pub fn go_to_implementation(
 9588        &mut self,
 9589        _: &GoToImplementation,
 9590        cx: &mut ViewContext<Self>,
 9591    ) -> Task<Result<Navigated>> {
 9592        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 9593    }
 9594
 9595    pub fn go_to_implementation_split(
 9596        &mut self,
 9597        _: &GoToImplementationSplit,
 9598        cx: &mut ViewContext<Self>,
 9599    ) -> Task<Result<Navigated>> {
 9600        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 9601    }
 9602
 9603    pub fn go_to_type_definition(
 9604        &mut self,
 9605        _: &GoToTypeDefinition,
 9606        cx: &mut ViewContext<Self>,
 9607    ) -> Task<Result<Navigated>> {
 9608        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 9609    }
 9610
 9611    pub fn go_to_definition_split(
 9612        &mut self,
 9613        _: &GoToDefinitionSplit,
 9614        cx: &mut ViewContext<Self>,
 9615    ) -> Task<Result<Navigated>> {
 9616        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 9617    }
 9618
 9619    pub fn go_to_type_definition_split(
 9620        &mut self,
 9621        _: &GoToTypeDefinitionSplit,
 9622        cx: &mut ViewContext<Self>,
 9623    ) -> Task<Result<Navigated>> {
 9624        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 9625    }
 9626
 9627    fn go_to_definition_of_kind(
 9628        &mut self,
 9629        kind: GotoDefinitionKind,
 9630        split: bool,
 9631        cx: &mut ViewContext<Self>,
 9632    ) -> Task<Result<Navigated>> {
 9633        let Some(provider) = self.semantics_provider.clone() else {
 9634            return Task::ready(Ok(Navigated::No));
 9635        };
 9636        let buffer = self.buffer.read(cx);
 9637        let head = self.selections.newest::<usize>(cx).head();
 9638        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 9639            text_anchor
 9640        } else {
 9641            return Task::ready(Ok(Navigated::No));
 9642        };
 9643
 9644        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
 9645            return Task::ready(Ok(Navigated::No));
 9646        };
 9647
 9648        cx.spawn(|editor, mut cx| async move {
 9649            let definitions = definitions.await?;
 9650            let navigated = editor
 9651                .update(&mut cx, |editor, cx| {
 9652                    editor.navigate_to_hover_links(
 9653                        Some(kind),
 9654                        definitions
 9655                            .into_iter()
 9656                            .filter(|location| {
 9657                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 9658                            })
 9659                            .map(HoverLink::Text)
 9660                            .collect::<Vec<_>>(),
 9661                        split,
 9662                        cx,
 9663                    )
 9664                })?
 9665                .await?;
 9666            anyhow::Ok(navigated)
 9667        })
 9668    }
 9669
 9670    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 9671        let position = self.selections.newest_anchor().head();
 9672        let Some((buffer, buffer_position)) =
 9673            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9674        else {
 9675            return;
 9676        };
 9677
 9678        cx.spawn(|editor, mut cx| async move {
 9679            if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
 9680                editor.update(&mut cx, |_, cx| {
 9681                    cx.open_url(&url);
 9682                })
 9683            } else {
 9684                Ok(())
 9685            }
 9686        })
 9687        .detach();
 9688    }
 9689
 9690    pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
 9691        let Some(workspace) = self.workspace() else {
 9692            return;
 9693        };
 9694
 9695        let position = self.selections.newest_anchor().head();
 9696
 9697        let Some((buffer, buffer_position)) =
 9698            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9699        else {
 9700            return;
 9701        };
 9702
 9703        let project = self.project.clone();
 9704
 9705        cx.spawn(|_, mut cx| async move {
 9706            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
 9707
 9708            if let Some((_, path)) = result {
 9709                workspace
 9710                    .update(&mut cx, |workspace, cx| {
 9711                        workspace.open_resolved_path(path, cx)
 9712                    })?
 9713                    .await?;
 9714            }
 9715            anyhow::Ok(())
 9716        })
 9717        .detach();
 9718    }
 9719
 9720    pub(crate) fn navigate_to_hover_links(
 9721        &mut self,
 9722        kind: Option<GotoDefinitionKind>,
 9723        mut definitions: Vec<HoverLink>,
 9724        split: bool,
 9725        cx: &mut ViewContext<Editor>,
 9726    ) -> Task<Result<Navigated>> {
 9727        // If there is one definition, just open it directly
 9728        if definitions.len() == 1 {
 9729            let definition = definitions.pop().unwrap();
 9730
 9731            enum TargetTaskResult {
 9732                Location(Option<Location>),
 9733                AlreadyNavigated,
 9734            }
 9735
 9736            let target_task = match definition {
 9737                HoverLink::Text(link) => {
 9738                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
 9739                }
 9740                HoverLink::InlayHint(lsp_location, server_id) => {
 9741                    let computation = self.compute_target_location(lsp_location, server_id, cx);
 9742                    cx.background_executor().spawn(async move {
 9743                        let location = computation.await?;
 9744                        Ok(TargetTaskResult::Location(location))
 9745                    })
 9746                }
 9747                HoverLink::Url(url) => {
 9748                    cx.open_url(&url);
 9749                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
 9750                }
 9751                HoverLink::File(path) => {
 9752                    if let Some(workspace) = self.workspace() {
 9753                        cx.spawn(|_, mut cx| async move {
 9754                            workspace
 9755                                .update(&mut cx, |workspace, cx| {
 9756                                    workspace.open_resolved_path(path, cx)
 9757                                })?
 9758                                .await
 9759                                .map(|_| TargetTaskResult::AlreadyNavigated)
 9760                        })
 9761                    } else {
 9762                        Task::ready(Ok(TargetTaskResult::Location(None)))
 9763                    }
 9764                }
 9765            };
 9766            cx.spawn(|editor, mut cx| async move {
 9767                let target = match target_task.await.context("target resolution task")? {
 9768                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
 9769                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
 9770                    TargetTaskResult::Location(Some(target)) => target,
 9771                };
 9772
 9773                editor.update(&mut cx, |editor, cx| {
 9774                    let Some(workspace) = editor.workspace() else {
 9775                        return Navigated::No;
 9776                    };
 9777                    let pane = workspace.read(cx).active_pane().clone();
 9778
 9779                    let range = target.range.to_offset(target.buffer.read(cx));
 9780                    let range = editor.range_for_match(&range);
 9781
 9782                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 9783                        let buffer = target.buffer.read(cx);
 9784                        let range = check_multiline_range(buffer, range);
 9785                        editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9786                            s.select_ranges([range]);
 9787                        });
 9788                    } else {
 9789                        cx.window_context().defer(move |cx| {
 9790                            let target_editor: View<Self> =
 9791                                workspace.update(cx, |workspace, cx| {
 9792                                    let pane = if split {
 9793                                        workspace.adjacent_pane(cx)
 9794                                    } else {
 9795                                        workspace.active_pane().clone()
 9796                                    };
 9797
 9798                                    workspace.open_project_item(
 9799                                        pane,
 9800                                        target.buffer.clone(),
 9801                                        true,
 9802                                        true,
 9803                                        cx,
 9804                                    )
 9805                                });
 9806                            target_editor.update(cx, |target_editor, cx| {
 9807                                // When selecting a definition in a different buffer, disable the nav history
 9808                                // to avoid creating a history entry at the previous cursor location.
 9809                                pane.update(cx, |pane, _| pane.disable_history());
 9810                                let buffer = target.buffer.read(cx);
 9811                                let range = check_multiline_range(buffer, range);
 9812                                target_editor.change_selections(
 9813                                    Some(Autoscroll::focused()),
 9814                                    cx,
 9815                                    |s| {
 9816                                        s.select_ranges([range]);
 9817                                    },
 9818                                );
 9819                                pane.update(cx, |pane, _| pane.enable_history());
 9820                            });
 9821                        });
 9822                    }
 9823                    Navigated::Yes
 9824                })
 9825            })
 9826        } else if !definitions.is_empty() {
 9827            cx.spawn(|editor, mut cx| async move {
 9828                let (title, location_tasks, workspace) = editor
 9829                    .update(&mut cx, |editor, cx| {
 9830                        let tab_kind = match kind {
 9831                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 9832                            _ => "Definitions",
 9833                        };
 9834                        let title = definitions
 9835                            .iter()
 9836                            .find_map(|definition| match definition {
 9837                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 9838                                    let buffer = origin.buffer.read(cx);
 9839                                    format!(
 9840                                        "{} for {}",
 9841                                        tab_kind,
 9842                                        buffer
 9843                                            .text_for_range(origin.range.clone())
 9844                                            .collect::<String>()
 9845                                    )
 9846                                }),
 9847                                HoverLink::InlayHint(_, _) => None,
 9848                                HoverLink::Url(_) => None,
 9849                                HoverLink::File(_) => None,
 9850                            })
 9851                            .unwrap_or(tab_kind.to_string());
 9852                        let location_tasks = definitions
 9853                            .into_iter()
 9854                            .map(|definition| match definition {
 9855                                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 9856                                HoverLink::InlayHint(lsp_location, server_id) => {
 9857                                    editor.compute_target_location(lsp_location, server_id, cx)
 9858                                }
 9859                                HoverLink::Url(_) => Task::ready(Ok(None)),
 9860                                HoverLink::File(_) => Task::ready(Ok(None)),
 9861                            })
 9862                            .collect::<Vec<_>>();
 9863                        (title, location_tasks, editor.workspace().clone())
 9864                    })
 9865                    .context("location tasks preparation")?;
 9866
 9867                let locations = future::join_all(location_tasks)
 9868                    .await
 9869                    .into_iter()
 9870                    .filter_map(|location| location.transpose())
 9871                    .collect::<Result<_>>()
 9872                    .context("location tasks")?;
 9873
 9874                let Some(workspace) = workspace else {
 9875                    return Ok(Navigated::No);
 9876                };
 9877                let opened = workspace
 9878                    .update(&mut cx, |workspace, cx| {
 9879                        Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
 9880                    })
 9881                    .ok();
 9882
 9883                anyhow::Ok(Navigated::from_bool(opened.is_some()))
 9884            })
 9885        } else {
 9886            Task::ready(Ok(Navigated::No))
 9887        }
 9888    }
 9889
 9890    fn compute_target_location(
 9891        &self,
 9892        lsp_location: lsp::Location,
 9893        server_id: LanguageServerId,
 9894        cx: &mut ViewContext<Self>,
 9895    ) -> Task<anyhow::Result<Option<Location>>> {
 9896        let Some(project) = self.project.clone() else {
 9897            return Task::Ready(Some(Ok(None)));
 9898        };
 9899
 9900        cx.spawn(move |editor, mut cx| async move {
 9901            let location_task = editor.update(&mut cx, |_, cx| {
 9902                project.update(cx, |project, cx| {
 9903                    let language_server_name = project
 9904                        .language_server_statuses(cx)
 9905                        .find(|(id, _)| server_id == *id)
 9906                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
 9907                    language_server_name.map(|language_server_name| {
 9908                        project.open_local_buffer_via_lsp(
 9909                            lsp_location.uri.clone(),
 9910                            server_id,
 9911                            language_server_name,
 9912                            cx,
 9913                        )
 9914                    })
 9915                })
 9916            })?;
 9917            let location = match location_task {
 9918                Some(task) => Some({
 9919                    let target_buffer_handle = task.await.context("open local buffer")?;
 9920                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
 9921                        let target_start = target_buffer
 9922                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
 9923                        let target_end = target_buffer
 9924                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
 9925                        target_buffer.anchor_after(target_start)
 9926                            ..target_buffer.anchor_before(target_end)
 9927                    })?;
 9928                    Location {
 9929                        buffer: target_buffer_handle,
 9930                        range,
 9931                    }
 9932                }),
 9933                None => None,
 9934            };
 9935            Ok(location)
 9936        })
 9937    }
 9938
 9939    pub fn find_all_references(
 9940        &mut self,
 9941        _: &FindAllReferences,
 9942        cx: &mut ViewContext<Self>,
 9943    ) -> Option<Task<Result<Navigated>>> {
 9944        let multi_buffer = self.buffer.read(cx);
 9945        let selection = self.selections.newest::<usize>(cx);
 9946        let head = selection.head();
 9947
 9948        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 9949        let head_anchor = multi_buffer_snapshot.anchor_at(
 9950            head,
 9951            if head < selection.tail() {
 9952                Bias::Right
 9953            } else {
 9954                Bias::Left
 9955            },
 9956        );
 9957
 9958        match self
 9959            .find_all_references_task_sources
 9960            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
 9961        {
 9962            Ok(_) => {
 9963                log::info!(
 9964                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
 9965                );
 9966                return None;
 9967            }
 9968            Err(i) => {
 9969                self.find_all_references_task_sources.insert(i, head_anchor);
 9970            }
 9971        }
 9972
 9973        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
 9974        let workspace = self.workspace()?;
 9975        let project = workspace.read(cx).project().clone();
 9976        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
 9977        Some(cx.spawn(|editor, mut cx| async move {
 9978            let _cleanup = defer({
 9979                let mut cx = cx.clone();
 9980                move || {
 9981                    let _ = editor.update(&mut cx, |editor, _| {
 9982                        if let Ok(i) =
 9983                            editor
 9984                                .find_all_references_task_sources
 9985                                .binary_search_by(|anchor| {
 9986                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
 9987                                })
 9988                        {
 9989                            editor.find_all_references_task_sources.remove(i);
 9990                        }
 9991                    });
 9992                }
 9993            });
 9994
 9995            let locations = references.await?;
 9996            if locations.is_empty() {
 9997                return anyhow::Ok(Navigated::No);
 9998            }
 9999
10000            workspace.update(&mut cx, |workspace, cx| {
10001                let title = locations
10002                    .first()
10003                    .as_ref()
10004                    .map(|location| {
10005                        let buffer = location.buffer.read(cx);
10006                        format!(
10007                            "References to `{}`",
10008                            buffer
10009                                .text_for_range(location.range.clone())
10010                                .collect::<String>()
10011                        )
10012                    })
10013                    .unwrap();
10014                Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
10015                Navigated::Yes
10016            })
10017        }))
10018    }
10019
10020    /// Opens a multibuffer with the given project locations in it
10021    pub fn open_locations_in_multibuffer(
10022        workspace: &mut Workspace,
10023        mut locations: Vec<Location>,
10024        title: String,
10025        split: bool,
10026        cx: &mut ViewContext<Workspace>,
10027    ) {
10028        // If there are multiple definitions, open them in a multibuffer
10029        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10030        let mut locations = locations.into_iter().peekable();
10031        let mut ranges_to_highlight = Vec::new();
10032        let capability = workspace.project().read(cx).capability();
10033
10034        let excerpt_buffer = cx.new_model(|cx| {
10035            let mut multibuffer = MultiBuffer::new(capability);
10036            while let Some(location) = locations.next() {
10037                let buffer = location.buffer.read(cx);
10038                let mut ranges_for_buffer = Vec::new();
10039                let range = location.range.to_offset(buffer);
10040                ranges_for_buffer.push(range.clone());
10041
10042                while let Some(next_location) = locations.peek() {
10043                    if next_location.buffer == location.buffer {
10044                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
10045                        locations.next();
10046                    } else {
10047                        break;
10048                    }
10049                }
10050
10051                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10052                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
10053                    location.buffer.clone(),
10054                    ranges_for_buffer,
10055                    DEFAULT_MULTIBUFFER_CONTEXT,
10056                    cx,
10057                ))
10058            }
10059
10060            multibuffer.with_title(title)
10061        });
10062
10063        let editor = cx.new_view(|cx| {
10064            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
10065        });
10066        editor.update(cx, |editor, cx| {
10067            if let Some(first_range) = ranges_to_highlight.first() {
10068                editor.change_selections(None, cx, |selections| {
10069                    selections.clear_disjoint();
10070                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10071                });
10072            }
10073            editor.highlight_background::<Self>(
10074                &ranges_to_highlight,
10075                |theme| theme.editor_highlighted_line_background,
10076                cx,
10077            );
10078        });
10079
10080        let item = Box::new(editor);
10081        let item_id = item.item_id();
10082
10083        if split {
10084            workspace.split_item(SplitDirection::Right, item.clone(), cx);
10085        } else {
10086            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10087                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10088                    pane.close_current_preview_item(cx)
10089                } else {
10090                    None
10091                }
10092            });
10093            workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
10094        }
10095        workspace.active_pane().update(cx, |pane, cx| {
10096            pane.set_preview_item_id(Some(item_id), cx);
10097        });
10098    }
10099
10100    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10101        use language::ToOffset as _;
10102
10103        let provider = self.semantics_provider.clone()?;
10104        let selection = self.selections.newest_anchor().clone();
10105        let (cursor_buffer, cursor_buffer_position) = self
10106            .buffer
10107            .read(cx)
10108            .text_anchor_for_position(selection.head(), cx)?;
10109        let (tail_buffer, cursor_buffer_position_end) = self
10110            .buffer
10111            .read(cx)
10112            .text_anchor_for_position(selection.tail(), cx)?;
10113        if tail_buffer != cursor_buffer {
10114            return None;
10115        }
10116
10117        let snapshot = cursor_buffer.read(cx).snapshot();
10118        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10119        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10120        let prepare_rename = provider
10121            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10122            .unwrap_or_else(|| Task::ready(Ok(None)));
10123        drop(snapshot);
10124
10125        Some(cx.spawn(|this, mut cx| async move {
10126            let rename_range = if let Some(range) = prepare_rename.await? {
10127                Some(range)
10128            } else {
10129                this.update(&mut cx, |this, cx| {
10130                    let buffer = this.buffer.read(cx).snapshot(cx);
10131                    let mut buffer_highlights = this
10132                        .document_highlights_for_position(selection.head(), &buffer)
10133                        .filter(|highlight| {
10134                            highlight.start.excerpt_id == selection.head().excerpt_id
10135                                && highlight.end.excerpt_id == selection.head().excerpt_id
10136                        });
10137                    buffer_highlights
10138                        .next()
10139                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10140                })?
10141            };
10142            if let Some(rename_range) = rename_range {
10143                this.update(&mut cx, |this, cx| {
10144                    let snapshot = cursor_buffer.read(cx).snapshot();
10145                    let rename_buffer_range = rename_range.to_offset(&snapshot);
10146                    let cursor_offset_in_rename_range =
10147                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10148                    let cursor_offset_in_rename_range_end =
10149                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10150
10151                    this.take_rename(false, cx);
10152                    let buffer = this.buffer.read(cx).read(cx);
10153                    let cursor_offset = selection.head().to_offset(&buffer);
10154                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10155                    let rename_end = rename_start + rename_buffer_range.len();
10156                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10157                    let mut old_highlight_id = None;
10158                    let old_name: Arc<str> = buffer
10159                        .chunks(rename_start..rename_end, true)
10160                        .map(|chunk| {
10161                            if old_highlight_id.is_none() {
10162                                old_highlight_id = chunk.syntax_highlight_id;
10163                            }
10164                            chunk.text
10165                        })
10166                        .collect::<String>()
10167                        .into();
10168
10169                    drop(buffer);
10170
10171                    // Position the selection in the rename editor so that it matches the current selection.
10172                    this.show_local_selections = false;
10173                    let rename_editor = cx.new_view(|cx| {
10174                        let mut editor = Editor::single_line(cx);
10175                        editor.buffer.update(cx, |buffer, cx| {
10176                            buffer.edit([(0..0, old_name.clone())], None, cx)
10177                        });
10178                        let rename_selection_range = match cursor_offset_in_rename_range
10179                            .cmp(&cursor_offset_in_rename_range_end)
10180                        {
10181                            Ordering::Equal => {
10182                                editor.select_all(&SelectAll, cx);
10183                                return editor;
10184                            }
10185                            Ordering::Less => {
10186                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10187                            }
10188                            Ordering::Greater => {
10189                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10190                            }
10191                        };
10192                        if rename_selection_range.end > old_name.len() {
10193                            editor.select_all(&SelectAll, cx);
10194                        } else {
10195                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10196                                s.select_ranges([rename_selection_range]);
10197                            });
10198                        }
10199                        editor
10200                    });
10201                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10202                        if e == &EditorEvent::Focused {
10203                            cx.emit(EditorEvent::FocusedIn)
10204                        }
10205                    })
10206                    .detach();
10207
10208                    let write_highlights =
10209                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10210                    let read_highlights =
10211                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
10212                    let ranges = write_highlights
10213                        .iter()
10214                        .flat_map(|(_, ranges)| ranges.iter())
10215                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10216                        .cloned()
10217                        .collect();
10218
10219                    this.highlight_text::<Rename>(
10220                        ranges,
10221                        HighlightStyle {
10222                            fade_out: Some(0.6),
10223                            ..Default::default()
10224                        },
10225                        cx,
10226                    );
10227                    let rename_focus_handle = rename_editor.focus_handle(cx);
10228                    cx.focus(&rename_focus_handle);
10229                    let block_id = this.insert_blocks(
10230                        [BlockProperties {
10231                            style: BlockStyle::Flex,
10232                            placement: BlockPlacement::Below(range.start),
10233                            height: 1,
10234                            render: Box::new({
10235                                let rename_editor = rename_editor.clone();
10236                                move |cx: &mut BlockContext| {
10237                                    let mut text_style = cx.editor_style.text.clone();
10238                                    if let Some(highlight_style) = old_highlight_id
10239                                        .and_then(|h| h.style(&cx.editor_style.syntax))
10240                                    {
10241                                        text_style = text_style.highlight(highlight_style);
10242                                    }
10243                                    div()
10244                                        .pl(cx.anchor_x)
10245                                        .child(EditorElement::new(
10246                                            &rename_editor,
10247                                            EditorStyle {
10248                                                background: cx.theme().system().transparent,
10249                                                local_player: cx.editor_style.local_player,
10250                                                text: text_style,
10251                                                scrollbar_width: cx.editor_style.scrollbar_width,
10252                                                syntax: cx.editor_style.syntax.clone(),
10253                                                status: cx.editor_style.status.clone(),
10254                                                inlay_hints_style: HighlightStyle {
10255                                                    font_weight: Some(FontWeight::BOLD),
10256                                                    ..make_inlay_hints_style(cx)
10257                                                },
10258                                                suggestions_style: HighlightStyle {
10259                                                    color: Some(cx.theme().status().predictive),
10260                                                    ..HighlightStyle::default()
10261                                                },
10262                                                ..EditorStyle::default()
10263                                            },
10264                                        ))
10265                                        .into_any_element()
10266                                }
10267                            }),
10268                            priority: 0,
10269                        }],
10270                        Some(Autoscroll::fit()),
10271                        cx,
10272                    )[0];
10273                    this.pending_rename = Some(RenameState {
10274                        range,
10275                        old_name,
10276                        editor: rename_editor,
10277                        block_id,
10278                    });
10279                })?;
10280            }
10281
10282            Ok(())
10283        }))
10284    }
10285
10286    pub fn confirm_rename(
10287        &mut self,
10288        _: &ConfirmRename,
10289        cx: &mut ViewContext<Self>,
10290    ) -> Option<Task<Result<()>>> {
10291        let rename = self.take_rename(false, cx)?;
10292        let workspace = self.workspace()?.downgrade();
10293        let (buffer, start) = self
10294            .buffer
10295            .read(cx)
10296            .text_anchor_for_position(rename.range.start, cx)?;
10297        let (end_buffer, _) = self
10298            .buffer
10299            .read(cx)
10300            .text_anchor_for_position(rename.range.end, cx)?;
10301        if buffer != end_buffer {
10302            return None;
10303        }
10304
10305        let old_name = rename.old_name;
10306        let new_name = rename.editor.read(cx).text(cx);
10307
10308        let rename = self.semantics_provider.as_ref()?.perform_rename(
10309            &buffer,
10310            start,
10311            new_name.clone(),
10312            cx,
10313        )?;
10314
10315        Some(cx.spawn(|editor, mut cx| async move {
10316            let project_transaction = rename.await?;
10317            Self::open_project_transaction(
10318                &editor,
10319                workspace,
10320                project_transaction,
10321                format!("Rename: {}{}", old_name, new_name),
10322                cx.clone(),
10323            )
10324            .await?;
10325
10326            editor.update(&mut cx, |editor, cx| {
10327                editor.refresh_document_highlights(cx);
10328            })?;
10329            Ok(())
10330        }))
10331    }
10332
10333    fn take_rename(
10334        &mut self,
10335        moving_cursor: bool,
10336        cx: &mut ViewContext<Self>,
10337    ) -> Option<RenameState> {
10338        let rename = self.pending_rename.take()?;
10339        if rename.editor.focus_handle(cx).is_focused(cx) {
10340            cx.focus(&self.focus_handle);
10341        }
10342
10343        self.remove_blocks(
10344            [rename.block_id].into_iter().collect(),
10345            Some(Autoscroll::fit()),
10346            cx,
10347        );
10348        self.clear_highlights::<Rename>(cx);
10349        self.show_local_selections = true;
10350
10351        if moving_cursor {
10352            let rename_editor = rename.editor.read(cx);
10353            let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
10354
10355            // Update the selection to match the position of the selection inside
10356            // the rename editor.
10357            let snapshot = self.buffer.read(cx).read(cx);
10358            let rename_range = rename.range.to_offset(&snapshot);
10359            let cursor_in_editor = snapshot
10360                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10361                .min(rename_range.end);
10362            drop(snapshot);
10363
10364            self.change_selections(None, cx, |s| {
10365                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10366            });
10367        } else {
10368            self.refresh_document_highlights(cx);
10369        }
10370
10371        Some(rename)
10372    }
10373
10374    pub fn pending_rename(&self) -> Option<&RenameState> {
10375        self.pending_rename.as_ref()
10376    }
10377
10378    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10379        let project = match &self.project {
10380            Some(project) => project.clone(),
10381            None => return None,
10382        };
10383
10384        Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10385    }
10386
10387    fn format_selections(
10388        &mut self,
10389        _: &FormatSelections,
10390        cx: &mut ViewContext<Self>,
10391    ) -> Option<Task<Result<()>>> {
10392        let project = match &self.project {
10393            Some(project) => project.clone(),
10394            None => return None,
10395        };
10396
10397        let selections = self
10398            .selections
10399            .all_adjusted(cx)
10400            .into_iter()
10401            .filter(|s| !s.is_empty())
10402            .collect_vec();
10403
10404        Some(self.perform_format(
10405            project,
10406            FormatTrigger::Manual,
10407            FormatTarget::Ranges(selections),
10408            cx,
10409        ))
10410    }
10411
10412    fn perform_format(
10413        &mut self,
10414        project: Model<Project>,
10415        trigger: FormatTrigger,
10416        target: FormatTarget,
10417        cx: &mut ViewContext<Self>,
10418    ) -> Task<Result<()>> {
10419        let buffer = self.buffer().clone();
10420        let mut buffers = buffer.read(cx).all_buffers();
10421        if trigger == FormatTrigger::Save {
10422            buffers.retain(|buffer| buffer.read(cx).is_dirty());
10423        }
10424
10425        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10426        let format = project.update(cx, |project, cx| {
10427            project.format(buffers, true, trigger, target, cx)
10428        });
10429
10430        cx.spawn(|_, mut cx| async move {
10431            let transaction = futures::select_biased! {
10432                () = timeout => {
10433                    log::warn!("timed out waiting for formatting");
10434                    None
10435                }
10436                transaction = format.log_err().fuse() => transaction,
10437            };
10438
10439            buffer
10440                .update(&mut cx, |buffer, cx| {
10441                    if let Some(transaction) = transaction {
10442                        if !buffer.is_singleton() {
10443                            buffer.push_transaction(&transaction.0, cx);
10444                        }
10445                    }
10446
10447                    cx.notify();
10448                })
10449                .ok();
10450
10451            Ok(())
10452        })
10453    }
10454
10455    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10456        if let Some(project) = self.project.clone() {
10457            self.buffer.update(cx, |multi_buffer, cx| {
10458                project.update(cx, |project, cx| {
10459                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10460                });
10461            })
10462        }
10463    }
10464
10465    fn cancel_language_server_work(
10466        &mut self,
10467        _: &CancelLanguageServerWork,
10468        cx: &mut ViewContext<Self>,
10469    ) {
10470        if let Some(project) = self.project.clone() {
10471            self.buffer.update(cx, |multi_buffer, cx| {
10472                project.update(cx, |project, cx| {
10473                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10474                });
10475            })
10476        }
10477    }
10478
10479    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10480        cx.show_character_palette();
10481    }
10482
10483    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10484        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10485            let buffer = self.buffer.read(cx).snapshot(cx);
10486            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10487            let is_valid = buffer
10488                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10489                .any(|entry| {
10490                    entry.diagnostic.is_primary
10491                        && !entry.range.is_empty()
10492                        && entry.range.start == primary_range_start
10493                        && entry.diagnostic.message == active_diagnostics.primary_message
10494                });
10495
10496            if is_valid != active_diagnostics.is_valid {
10497                active_diagnostics.is_valid = is_valid;
10498                let mut new_styles = HashMap::default();
10499                for (block_id, diagnostic) in &active_diagnostics.blocks {
10500                    new_styles.insert(
10501                        *block_id,
10502                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10503                    );
10504                }
10505                self.display_map.update(cx, |display_map, _cx| {
10506                    display_map.replace_blocks(new_styles)
10507                });
10508            }
10509        }
10510    }
10511
10512    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10513        self.dismiss_diagnostics(cx);
10514        let snapshot = self.snapshot(cx);
10515        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10516            let buffer = self.buffer.read(cx).snapshot(cx);
10517
10518            let mut primary_range = None;
10519            let mut primary_message = None;
10520            let mut group_end = Point::zero();
10521            let diagnostic_group = buffer
10522                .diagnostic_group::<MultiBufferPoint>(group_id)
10523                .filter_map(|entry| {
10524                    if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10525                        && (entry.range.start.row == entry.range.end.row
10526                            || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10527                    {
10528                        return None;
10529                    }
10530                    if entry.range.end > group_end {
10531                        group_end = entry.range.end;
10532                    }
10533                    if entry.diagnostic.is_primary {
10534                        primary_range = Some(entry.range.clone());
10535                        primary_message = Some(entry.diagnostic.message.clone());
10536                    }
10537                    Some(entry)
10538                })
10539                .collect::<Vec<_>>();
10540            let primary_range = primary_range?;
10541            let primary_message = primary_message?;
10542            let primary_range =
10543                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10544
10545            let blocks = display_map
10546                .insert_blocks(
10547                    diagnostic_group.iter().map(|entry| {
10548                        let diagnostic = entry.diagnostic.clone();
10549                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10550                        BlockProperties {
10551                            style: BlockStyle::Fixed,
10552                            placement: BlockPlacement::Below(
10553                                buffer.anchor_after(entry.range.start),
10554                            ),
10555                            height: message_height,
10556                            render: diagnostic_block_renderer(diagnostic, None, true, true),
10557                            priority: 0,
10558                        }
10559                    }),
10560                    cx,
10561                )
10562                .into_iter()
10563                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10564                .collect();
10565
10566            Some(ActiveDiagnosticGroup {
10567                primary_range,
10568                primary_message,
10569                group_id,
10570                blocks,
10571                is_valid: true,
10572            })
10573        });
10574        self.active_diagnostics.is_some()
10575    }
10576
10577    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10578        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10579            self.display_map.update(cx, |display_map, cx| {
10580                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10581            });
10582            cx.notify();
10583        }
10584    }
10585
10586    pub fn set_selections_from_remote(
10587        &mut self,
10588        selections: Vec<Selection<Anchor>>,
10589        pending_selection: Option<Selection<Anchor>>,
10590        cx: &mut ViewContext<Self>,
10591    ) {
10592        let old_cursor_position = self.selections.newest_anchor().head();
10593        self.selections.change_with(cx, |s| {
10594            s.select_anchors(selections);
10595            if let Some(pending_selection) = pending_selection {
10596                s.set_pending(pending_selection, SelectMode::Character);
10597            } else {
10598                s.clear_pending();
10599            }
10600        });
10601        self.selections_did_change(false, &old_cursor_position, true, cx);
10602    }
10603
10604    fn push_to_selection_history(&mut self) {
10605        self.selection_history.push(SelectionHistoryEntry {
10606            selections: self.selections.disjoint_anchors(),
10607            select_next_state: self.select_next_state.clone(),
10608            select_prev_state: self.select_prev_state.clone(),
10609            add_selections_state: self.add_selections_state.clone(),
10610        });
10611    }
10612
10613    pub fn transact(
10614        &mut self,
10615        cx: &mut ViewContext<Self>,
10616        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10617    ) -> Option<TransactionId> {
10618        self.start_transaction_at(Instant::now(), cx);
10619        update(self, cx);
10620        self.end_transaction_at(Instant::now(), cx)
10621    }
10622
10623    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10624        self.end_selection(cx);
10625        if let Some(tx_id) = self
10626            .buffer
10627            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10628        {
10629            self.selection_history
10630                .insert_transaction(tx_id, self.selections.disjoint_anchors());
10631            cx.emit(EditorEvent::TransactionBegun {
10632                transaction_id: tx_id,
10633            })
10634        }
10635    }
10636
10637    fn end_transaction_at(
10638        &mut self,
10639        now: Instant,
10640        cx: &mut ViewContext<Self>,
10641    ) -> Option<TransactionId> {
10642        if let Some(transaction_id) = self
10643            .buffer
10644            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10645        {
10646            if let Some((_, end_selections)) =
10647                self.selection_history.transaction_mut(transaction_id)
10648            {
10649                *end_selections = Some(self.selections.disjoint_anchors());
10650            } else {
10651                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10652            }
10653
10654            cx.emit(EditorEvent::Edited { transaction_id });
10655            Some(transaction_id)
10656        } else {
10657            None
10658        }
10659    }
10660
10661    pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10662        let selection = self.selections.newest::<Point>(cx);
10663
10664        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10665        let range = if selection.is_empty() {
10666            let point = selection.head().to_display_point(&display_map);
10667            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10668            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10669                .to_point(&display_map);
10670            start..end
10671        } else {
10672            selection.range()
10673        };
10674        if display_map.folds_in_range(range).next().is_some() {
10675            self.unfold_lines(&Default::default(), cx)
10676        } else {
10677            self.fold(&Default::default(), cx)
10678        }
10679    }
10680
10681    pub fn toggle_fold_recursive(
10682        &mut self,
10683        _: &actions::ToggleFoldRecursive,
10684        cx: &mut ViewContext<Self>,
10685    ) {
10686        let selection = self.selections.newest::<Point>(cx);
10687
10688        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10689        let range = if selection.is_empty() {
10690            let point = selection.head().to_display_point(&display_map);
10691            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10692            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10693                .to_point(&display_map);
10694            start..end
10695        } else {
10696            selection.range()
10697        };
10698        if display_map.folds_in_range(range).next().is_some() {
10699            self.unfold_recursive(&Default::default(), cx)
10700        } else {
10701            self.fold_recursive(&Default::default(), cx)
10702        }
10703    }
10704
10705    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10706        let mut fold_ranges = Vec::new();
10707        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10708        let selections = self.selections.all_adjusted(cx);
10709
10710        for selection in selections {
10711            let range = selection.range().sorted();
10712            let buffer_start_row = range.start.row;
10713
10714            if range.start.row != range.end.row {
10715                let mut found = false;
10716                let mut row = range.start.row;
10717                while row <= range.end.row {
10718                    if let Some((foldable_range, fold_text)) =
10719                        { display_map.foldable_range(MultiBufferRow(row)) }
10720                    {
10721                        found = true;
10722                        row = foldable_range.end.row + 1;
10723                        fold_ranges.push((foldable_range, fold_text));
10724                    } else {
10725                        row += 1
10726                    }
10727                }
10728                if found {
10729                    continue;
10730                }
10731            }
10732
10733            for row in (0..=range.start.row).rev() {
10734                if let Some((foldable_range, fold_text)) =
10735                    display_map.foldable_range(MultiBufferRow(row))
10736                {
10737                    if foldable_range.end.row >= buffer_start_row {
10738                        fold_ranges.push((foldable_range, fold_text));
10739                        if row <= range.start.row {
10740                            break;
10741                        }
10742                    }
10743                }
10744            }
10745        }
10746
10747        self.fold_ranges(fold_ranges, true, cx);
10748    }
10749
10750    fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10751        let fold_at_level = fold_at.level;
10752        let snapshot = self.buffer.read(cx).snapshot(cx);
10753        let mut fold_ranges = Vec::new();
10754        let mut stack = vec![(0, snapshot.max_buffer_row().0, 1)];
10755
10756        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10757            while start_row < end_row {
10758                match self.snapshot(cx).foldable_range(MultiBufferRow(start_row)) {
10759                    Some(foldable_range) => {
10760                        let nested_start_row = foldable_range.0.start.row + 1;
10761                        let nested_end_row = foldable_range.0.end.row;
10762
10763                        if current_level == fold_at_level {
10764                            fold_ranges.push(foldable_range);
10765                        }
10766
10767                        if current_level <= fold_at_level {
10768                            stack.push((nested_start_row, nested_end_row, current_level + 1));
10769                        }
10770
10771                        start_row = nested_end_row + 1;
10772                    }
10773                    None => start_row += 1,
10774                }
10775            }
10776        }
10777
10778        self.fold_ranges(fold_ranges, true, cx);
10779    }
10780
10781    pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10782        let mut fold_ranges = Vec::new();
10783        let snapshot = self.buffer.read(cx).snapshot(cx);
10784
10785        for row in 0..snapshot.max_buffer_row().0 {
10786            if let Some(foldable_range) = self.snapshot(cx).foldable_range(MultiBufferRow(row)) {
10787                fold_ranges.push(foldable_range);
10788            }
10789        }
10790
10791        self.fold_ranges(fold_ranges, true, cx);
10792    }
10793
10794    pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10795        let mut fold_ranges = Vec::new();
10796        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10797        let selections = self.selections.all_adjusted(cx);
10798
10799        for selection in selections {
10800            let range = selection.range().sorted();
10801            let buffer_start_row = range.start.row;
10802
10803            if range.start.row != range.end.row {
10804                let mut found = false;
10805                for row in range.start.row..=range.end.row {
10806                    if let Some((foldable_range, fold_text)) =
10807                        { display_map.foldable_range(MultiBufferRow(row)) }
10808                    {
10809                        found = true;
10810                        fold_ranges.push((foldable_range, fold_text));
10811                    }
10812                }
10813                if found {
10814                    continue;
10815                }
10816            }
10817
10818            for row in (0..=range.start.row).rev() {
10819                if let Some((foldable_range, fold_text)) =
10820                    display_map.foldable_range(MultiBufferRow(row))
10821                {
10822                    if foldable_range.end.row >= buffer_start_row {
10823                        fold_ranges.push((foldable_range, fold_text));
10824                    } else {
10825                        break;
10826                    }
10827                }
10828            }
10829        }
10830
10831        self.fold_ranges(fold_ranges, true, cx);
10832    }
10833
10834    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10835        let buffer_row = fold_at.buffer_row;
10836        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10837
10838        if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
10839            let autoscroll = self
10840                .selections
10841                .all::<Point>(cx)
10842                .iter()
10843                .any(|selection| fold_range.overlaps(&selection.range()));
10844
10845            self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
10846        }
10847    }
10848
10849    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10850        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10851        let buffer = &display_map.buffer_snapshot;
10852        let selections = self.selections.all::<Point>(cx);
10853        let ranges = selections
10854            .iter()
10855            .map(|s| {
10856                let range = s.display_range(&display_map).sorted();
10857                let mut start = range.start.to_point(&display_map);
10858                let mut end = range.end.to_point(&display_map);
10859                start.column = 0;
10860                end.column = buffer.line_len(MultiBufferRow(end.row));
10861                start..end
10862            })
10863            .collect::<Vec<_>>();
10864
10865        self.unfold_ranges(ranges, true, true, cx);
10866    }
10867
10868    pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10869        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10870        let selections = self.selections.all::<Point>(cx);
10871        let ranges = selections
10872            .iter()
10873            .map(|s| {
10874                let mut range = s.display_range(&display_map).sorted();
10875                *range.start.column_mut() = 0;
10876                *range.end.column_mut() = display_map.line_len(range.end.row());
10877                let start = range.start.to_point(&display_map);
10878                let end = range.end.to_point(&display_map);
10879                start..end
10880            })
10881            .collect::<Vec<_>>();
10882
10883        self.unfold_ranges(ranges, true, true, cx);
10884    }
10885
10886    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10887        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10888
10889        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10890            ..Point::new(
10891                unfold_at.buffer_row.0,
10892                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10893            );
10894
10895        let autoscroll = self
10896            .selections
10897            .all::<Point>(cx)
10898            .iter()
10899            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10900
10901        self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
10902    }
10903
10904    pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10905        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10906        self.unfold_ranges(
10907            [Point::zero()..display_map.max_point().to_point(&display_map)],
10908            true,
10909            true,
10910            cx,
10911        );
10912    }
10913
10914    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10915        let selections = self.selections.all::<Point>(cx);
10916        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10917        let line_mode = self.selections.line_mode;
10918        let ranges = selections.into_iter().map(|s| {
10919            if line_mode {
10920                let start = Point::new(s.start.row, 0);
10921                let end = Point::new(
10922                    s.end.row,
10923                    display_map
10924                        .buffer_snapshot
10925                        .line_len(MultiBufferRow(s.end.row)),
10926                );
10927                (start..end, display_map.fold_placeholder.clone())
10928            } else {
10929                (s.start..s.end, display_map.fold_placeholder.clone())
10930            }
10931        });
10932        self.fold_ranges(ranges, true, cx);
10933    }
10934
10935    pub fn fold_ranges<T: ToOffset + Clone>(
10936        &mut self,
10937        ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
10938        auto_scroll: bool,
10939        cx: &mut ViewContext<Self>,
10940    ) {
10941        let mut fold_ranges = Vec::new();
10942        let mut buffers_affected = HashMap::default();
10943        let multi_buffer = self.buffer().read(cx);
10944        for (fold_range, fold_text) in ranges {
10945            if let Some((_, buffer, _)) =
10946                multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
10947            {
10948                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10949            };
10950            fold_ranges.push((fold_range, fold_text));
10951        }
10952
10953        let mut ranges = fold_ranges.into_iter().peekable();
10954        if ranges.peek().is_some() {
10955            self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
10956
10957            if auto_scroll {
10958                self.request_autoscroll(Autoscroll::fit(), cx);
10959            }
10960
10961            for buffer in buffers_affected.into_values() {
10962                self.sync_expanded_diff_hunks(buffer, cx);
10963            }
10964
10965            cx.notify();
10966
10967            if let Some(active_diagnostics) = self.active_diagnostics.take() {
10968                // Clear diagnostics block when folding a range that contains it.
10969                let snapshot = self.snapshot(cx);
10970                if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10971                    drop(snapshot);
10972                    self.active_diagnostics = Some(active_diagnostics);
10973                    self.dismiss_diagnostics(cx);
10974                } else {
10975                    self.active_diagnostics = Some(active_diagnostics);
10976                }
10977            }
10978
10979            self.scrollbar_marker_state.dirty = true;
10980        }
10981    }
10982
10983    pub fn unfold_ranges<T: ToOffset + Clone>(
10984        &mut self,
10985        ranges: impl IntoIterator<Item = Range<T>>,
10986        inclusive: bool,
10987        auto_scroll: bool,
10988        cx: &mut ViewContext<Self>,
10989    ) {
10990        let mut unfold_ranges = Vec::new();
10991        let mut buffers_affected = HashMap::default();
10992        let multi_buffer = self.buffer().read(cx);
10993        for range in ranges {
10994            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10995                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10996            };
10997            unfold_ranges.push(range);
10998        }
10999
11000        let mut ranges = unfold_ranges.into_iter().peekable();
11001        if ranges.peek().is_some() {
11002            self.display_map
11003                .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
11004            if auto_scroll {
11005                self.request_autoscroll(Autoscroll::fit(), cx);
11006            }
11007
11008            for buffer in buffers_affected.into_values() {
11009                self.sync_expanded_diff_hunks(buffer, cx);
11010            }
11011
11012            cx.notify();
11013            self.scrollbar_marker_state.dirty = true;
11014            self.active_indent_guides_state.dirty = true;
11015        }
11016    }
11017
11018    pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
11019        self.display_map.read(cx).fold_placeholder.clone()
11020    }
11021
11022    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11023        if hovered != self.gutter_hovered {
11024            self.gutter_hovered = hovered;
11025            cx.notify();
11026        }
11027    }
11028
11029    pub fn insert_blocks(
11030        &mut self,
11031        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11032        autoscroll: Option<Autoscroll>,
11033        cx: &mut ViewContext<Self>,
11034    ) -> Vec<CustomBlockId> {
11035        let blocks = self
11036            .display_map
11037            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11038        if let Some(autoscroll) = autoscroll {
11039            self.request_autoscroll(autoscroll, cx);
11040        }
11041        cx.notify();
11042        blocks
11043    }
11044
11045    pub fn resize_blocks(
11046        &mut self,
11047        heights: HashMap<CustomBlockId, u32>,
11048        autoscroll: Option<Autoscroll>,
11049        cx: &mut ViewContext<Self>,
11050    ) {
11051        self.display_map
11052            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11053        if let Some(autoscroll) = autoscroll {
11054            self.request_autoscroll(autoscroll, cx);
11055        }
11056        cx.notify();
11057    }
11058
11059    pub fn replace_blocks(
11060        &mut self,
11061        renderers: HashMap<CustomBlockId, RenderBlock>,
11062        autoscroll: Option<Autoscroll>,
11063        cx: &mut ViewContext<Self>,
11064    ) {
11065        self.display_map
11066            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11067        if let Some(autoscroll) = autoscroll {
11068            self.request_autoscroll(autoscroll, cx);
11069        }
11070        cx.notify();
11071    }
11072
11073    pub fn remove_blocks(
11074        &mut self,
11075        block_ids: HashSet<CustomBlockId>,
11076        autoscroll: Option<Autoscroll>,
11077        cx: &mut ViewContext<Self>,
11078    ) {
11079        self.display_map.update(cx, |display_map, cx| {
11080            display_map.remove_blocks(block_ids, cx)
11081        });
11082        if let Some(autoscroll) = autoscroll {
11083            self.request_autoscroll(autoscroll, cx);
11084        }
11085        cx.notify();
11086    }
11087
11088    pub fn row_for_block(
11089        &self,
11090        block_id: CustomBlockId,
11091        cx: &mut ViewContext<Self>,
11092    ) -> Option<DisplayRow> {
11093        self.display_map
11094            .update(cx, |map, cx| map.row_for_block(block_id, cx))
11095    }
11096
11097    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11098        self.focused_block = Some(focused_block);
11099    }
11100
11101    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11102        self.focused_block.take()
11103    }
11104
11105    pub fn insert_creases(
11106        &mut self,
11107        creases: impl IntoIterator<Item = Crease>,
11108        cx: &mut ViewContext<Self>,
11109    ) -> Vec<CreaseId> {
11110        self.display_map
11111            .update(cx, |map, cx| map.insert_creases(creases, cx))
11112    }
11113
11114    pub fn remove_creases(
11115        &mut self,
11116        ids: impl IntoIterator<Item = CreaseId>,
11117        cx: &mut ViewContext<Self>,
11118    ) {
11119        self.display_map
11120            .update(cx, |map, cx| map.remove_creases(ids, cx));
11121    }
11122
11123    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11124        self.display_map
11125            .update(cx, |map, cx| map.snapshot(cx))
11126            .longest_row()
11127    }
11128
11129    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11130        self.display_map
11131            .update(cx, |map, cx| map.snapshot(cx))
11132            .max_point()
11133    }
11134
11135    pub fn text(&self, cx: &AppContext) -> String {
11136        self.buffer.read(cx).read(cx).text()
11137    }
11138
11139    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11140        let text = self.text(cx);
11141        let text = text.trim();
11142
11143        if text.is_empty() {
11144            return None;
11145        }
11146
11147        Some(text.to_string())
11148    }
11149
11150    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11151        self.transact(cx, |this, cx| {
11152            this.buffer
11153                .read(cx)
11154                .as_singleton()
11155                .expect("you can only call set_text on editors for singleton buffers")
11156                .update(cx, |buffer, cx| buffer.set_text(text, cx));
11157        });
11158    }
11159
11160    pub fn display_text(&self, cx: &mut AppContext) -> String {
11161        self.display_map
11162            .update(cx, |map, cx| map.snapshot(cx))
11163            .text()
11164    }
11165
11166    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11167        let mut wrap_guides = smallvec::smallvec![];
11168
11169        if self.show_wrap_guides == Some(false) {
11170            return wrap_guides;
11171        }
11172
11173        let settings = self.buffer.read(cx).settings_at(0, cx);
11174        if settings.show_wrap_guides {
11175            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11176                wrap_guides.push((soft_wrap as usize, true));
11177            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11178                wrap_guides.push((soft_wrap as usize, true));
11179            }
11180            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11181        }
11182
11183        wrap_guides
11184    }
11185
11186    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11187        let settings = self.buffer.read(cx).settings_at(0, cx);
11188        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11189        match mode {
11190            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11191                SoftWrap::None
11192            }
11193            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11194            language_settings::SoftWrap::PreferredLineLength => {
11195                SoftWrap::Column(settings.preferred_line_length)
11196            }
11197            language_settings::SoftWrap::Bounded => {
11198                SoftWrap::Bounded(settings.preferred_line_length)
11199            }
11200        }
11201    }
11202
11203    pub fn set_soft_wrap_mode(
11204        &mut self,
11205        mode: language_settings::SoftWrap,
11206        cx: &mut ViewContext<Self>,
11207    ) {
11208        self.soft_wrap_mode_override = Some(mode);
11209        cx.notify();
11210    }
11211
11212    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11213        self.text_style_refinement = Some(style);
11214    }
11215
11216    /// called by the Element so we know what style we were most recently rendered with.
11217    pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11218        let rem_size = cx.rem_size();
11219        self.display_map.update(cx, |map, cx| {
11220            map.set_font(
11221                style.text.font(),
11222                style.text.font_size.to_pixels(rem_size),
11223                cx,
11224            )
11225        });
11226        self.style = Some(style);
11227    }
11228
11229    pub fn style(&self) -> Option<&EditorStyle> {
11230        self.style.as_ref()
11231    }
11232
11233    // Called by the element. This method is not designed to be called outside of the editor
11234    // element's layout code because it does not notify when rewrapping is computed synchronously.
11235    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11236        self.display_map
11237            .update(cx, |map, cx| map.set_wrap_width(width, cx))
11238    }
11239
11240    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11241        if self.soft_wrap_mode_override.is_some() {
11242            self.soft_wrap_mode_override.take();
11243        } else {
11244            let soft_wrap = match self.soft_wrap_mode(cx) {
11245                SoftWrap::GitDiff => return,
11246                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11247                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11248                    language_settings::SoftWrap::None
11249                }
11250            };
11251            self.soft_wrap_mode_override = Some(soft_wrap);
11252        }
11253        cx.notify();
11254    }
11255
11256    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11257        let Some(workspace) = self.workspace() else {
11258            return;
11259        };
11260        let fs = workspace.read(cx).app_state().fs.clone();
11261        let current_show = TabBarSettings::get_global(cx).show;
11262        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11263            setting.show = Some(!current_show);
11264        });
11265    }
11266
11267    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11268        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11269            self.buffer
11270                .read(cx)
11271                .settings_at(0, cx)
11272                .indent_guides
11273                .enabled
11274        });
11275        self.show_indent_guides = Some(!currently_enabled);
11276        cx.notify();
11277    }
11278
11279    fn should_show_indent_guides(&self) -> Option<bool> {
11280        self.show_indent_guides
11281    }
11282
11283    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11284        let mut editor_settings = EditorSettings::get_global(cx).clone();
11285        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11286        EditorSettings::override_global(editor_settings, cx);
11287    }
11288
11289    pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11290        self.use_relative_line_numbers
11291            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11292    }
11293
11294    pub fn toggle_relative_line_numbers(
11295        &mut self,
11296        _: &ToggleRelativeLineNumbers,
11297        cx: &mut ViewContext<Self>,
11298    ) {
11299        let is_relative = self.should_use_relative_line_numbers(cx);
11300        self.set_relative_line_number(Some(!is_relative), cx)
11301    }
11302
11303    pub fn set_relative_line_number(
11304        &mut self,
11305        is_relative: Option<bool>,
11306        cx: &mut ViewContext<Self>,
11307    ) {
11308        self.use_relative_line_numbers = is_relative;
11309        cx.notify();
11310    }
11311
11312    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11313        self.show_gutter = show_gutter;
11314        cx.notify();
11315    }
11316
11317    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11318        self.show_line_numbers = Some(show_line_numbers);
11319        cx.notify();
11320    }
11321
11322    pub fn set_show_git_diff_gutter(
11323        &mut self,
11324        show_git_diff_gutter: bool,
11325        cx: &mut ViewContext<Self>,
11326    ) {
11327        self.show_git_diff_gutter = Some(show_git_diff_gutter);
11328        cx.notify();
11329    }
11330
11331    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11332        self.show_code_actions = Some(show_code_actions);
11333        cx.notify();
11334    }
11335
11336    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11337        self.show_runnables = Some(show_runnables);
11338        cx.notify();
11339    }
11340
11341    pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11342        if self.display_map.read(cx).masked != masked {
11343            self.display_map.update(cx, |map, _| map.masked = masked);
11344        }
11345        cx.notify()
11346    }
11347
11348    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11349        self.show_wrap_guides = Some(show_wrap_guides);
11350        cx.notify();
11351    }
11352
11353    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11354        self.show_indent_guides = Some(show_indent_guides);
11355        cx.notify();
11356    }
11357
11358    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11359        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11360            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11361                if let Some(dir) = file.abs_path(cx).parent() {
11362                    return Some(dir.to_owned());
11363                }
11364            }
11365
11366            if let Some(project_path) = buffer.read(cx).project_path(cx) {
11367                return Some(project_path.path.to_path_buf());
11368            }
11369        }
11370
11371        None
11372    }
11373
11374    fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11375        self.active_excerpt(cx)?
11376            .1
11377            .read(cx)
11378            .file()
11379            .and_then(|f| f.as_local())
11380    }
11381
11382    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11383        if let Some(target) = self.target_file(cx) {
11384            cx.reveal_path(&target.abs_path(cx));
11385        }
11386    }
11387
11388    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11389        if let Some(file) = self.target_file(cx) {
11390            if let Some(path) = file.abs_path(cx).to_str() {
11391                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11392            }
11393        }
11394    }
11395
11396    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11397        if let Some(file) = self.target_file(cx) {
11398            if let Some(path) = file.path().to_str() {
11399                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11400            }
11401        }
11402    }
11403
11404    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11405        self.show_git_blame_gutter = !self.show_git_blame_gutter;
11406
11407        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11408            self.start_git_blame(true, cx);
11409        }
11410
11411        cx.notify();
11412    }
11413
11414    pub fn toggle_git_blame_inline(
11415        &mut self,
11416        _: &ToggleGitBlameInline,
11417        cx: &mut ViewContext<Self>,
11418    ) {
11419        self.toggle_git_blame_inline_internal(true, cx);
11420        cx.notify();
11421    }
11422
11423    pub fn git_blame_inline_enabled(&self) -> bool {
11424        self.git_blame_inline_enabled
11425    }
11426
11427    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11428        self.show_selection_menu = self
11429            .show_selection_menu
11430            .map(|show_selections_menu| !show_selections_menu)
11431            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11432
11433        cx.notify();
11434    }
11435
11436    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11437        self.show_selection_menu
11438            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11439    }
11440
11441    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11442        if let Some(project) = self.project.as_ref() {
11443            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11444                return;
11445            };
11446
11447            if buffer.read(cx).file().is_none() {
11448                return;
11449            }
11450
11451            let focused = self.focus_handle(cx).contains_focused(cx);
11452
11453            let project = project.clone();
11454            let blame =
11455                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11456            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11457            self.blame = Some(blame);
11458        }
11459    }
11460
11461    fn toggle_git_blame_inline_internal(
11462        &mut self,
11463        user_triggered: bool,
11464        cx: &mut ViewContext<Self>,
11465    ) {
11466        if self.git_blame_inline_enabled {
11467            self.git_blame_inline_enabled = false;
11468            self.show_git_blame_inline = false;
11469            self.show_git_blame_inline_delay_task.take();
11470        } else {
11471            self.git_blame_inline_enabled = true;
11472            self.start_git_blame_inline(user_triggered, cx);
11473        }
11474
11475        cx.notify();
11476    }
11477
11478    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11479        self.start_git_blame(user_triggered, cx);
11480
11481        if ProjectSettings::get_global(cx)
11482            .git
11483            .inline_blame_delay()
11484            .is_some()
11485        {
11486            self.start_inline_blame_timer(cx);
11487        } else {
11488            self.show_git_blame_inline = true
11489        }
11490    }
11491
11492    pub fn blame(&self) -> Option<&Model<GitBlame>> {
11493        self.blame.as_ref()
11494    }
11495
11496    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11497        self.show_git_blame_gutter && self.has_blame_entries(cx)
11498    }
11499
11500    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11501        self.show_git_blame_inline
11502            && self.focus_handle.is_focused(cx)
11503            && !self.newest_selection_head_on_empty_line(cx)
11504            && self.has_blame_entries(cx)
11505    }
11506
11507    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11508        self.blame()
11509            .map_or(false, |blame| blame.read(cx).has_generated_entries())
11510    }
11511
11512    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11513        let cursor_anchor = self.selections.newest_anchor().head();
11514
11515        let snapshot = self.buffer.read(cx).snapshot(cx);
11516        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11517
11518        snapshot.line_len(buffer_row) == 0
11519    }
11520
11521    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11522        let buffer_and_selection = maybe!({
11523            let selection = self.selections.newest::<Point>(cx);
11524            let selection_range = selection.range();
11525
11526            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11527                (buffer, selection_range.start.row..selection_range.end.row)
11528            } else {
11529                let buffer_ranges = self
11530                    .buffer()
11531                    .read(cx)
11532                    .range_to_buffer_ranges(selection_range, cx);
11533
11534                let (buffer, range, _) = if selection.reversed {
11535                    buffer_ranges.first()
11536                } else {
11537                    buffer_ranges.last()
11538                }?;
11539
11540                let snapshot = buffer.read(cx).snapshot();
11541                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11542                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
11543                (buffer.clone(), selection)
11544            };
11545
11546            Some((buffer, selection))
11547        });
11548
11549        let Some((buffer, selection)) = buffer_and_selection else {
11550            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11551        };
11552
11553        let Some(project) = self.project.as_ref() else {
11554            return Task::ready(Err(anyhow!("editor does not have project")));
11555        };
11556
11557        project.update(cx, |project, cx| {
11558            project.get_permalink_to_line(&buffer, selection, cx)
11559        })
11560    }
11561
11562    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11563        let permalink_task = self.get_permalink_to_line(cx);
11564        let workspace = self.workspace();
11565
11566        cx.spawn(|_, mut cx| async move {
11567            match permalink_task.await {
11568                Ok(permalink) => {
11569                    cx.update(|cx| {
11570                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11571                    })
11572                    .ok();
11573                }
11574                Err(err) => {
11575                    let message = format!("Failed to copy permalink: {err}");
11576
11577                    Err::<(), anyhow::Error>(err).log_err();
11578
11579                    if let Some(workspace) = workspace {
11580                        workspace
11581                            .update(&mut cx, |workspace, cx| {
11582                                struct CopyPermalinkToLine;
11583
11584                                workspace.show_toast(
11585                                    Toast::new(
11586                                        NotificationId::unique::<CopyPermalinkToLine>(),
11587                                        message,
11588                                    ),
11589                                    cx,
11590                                )
11591                            })
11592                            .ok();
11593                    }
11594                }
11595            }
11596        })
11597        .detach();
11598    }
11599
11600    pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11601        if let Some(file) = self.target_file(cx) {
11602            if let Some(path) = file.path().to_str() {
11603                let selection = self.selections.newest::<Point>(cx).start.row + 1;
11604                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11605            }
11606        }
11607    }
11608
11609    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11610        let permalink_task = self.get_permalink_to_line(cx);
11611        let workspace = self.workspace();
11612
11613        cx.spawn(|_, mut cx| async move {
11614            match permalink_task.await {
11615                Ok(permalink) => {
11616                    cx.update(|cx| {
11617                        cx.open_url(permalink.as_ref());
11618                    })
11619                    .ok();
11620                }
11621                Err(err) => {
11622                    let message = format!("Failed to open permalink: {err}");
11623
11624                    Err::<(), anyhow::Error>(err).log_err();
11625
11626                    if let Some(workspace) = workspace {
11627                        workspace
11628                            .update(&mut cx, |workspace, cx| {
11629                                struct OpenPermalinkToLine;
11630
11631                                workspace.show_toast(
11632                                    Toast::new(
11633                                        NotificationId::unique::<OpenPermalinkToLine>(),
11634                                        message,
11635                                    ),
11636                                    cx,
11637                                )
11638                            })
11639                            .ok();
11640                    }
11641                }
11642            }
11643        })
11644        .detach();
11645    }
11646
11647    /// Adds a row highlight for the given range. If a row has multiple highlights, the
11648    /// last highlight added will be used.
11649    ///
11650    /// If the range ends at the beginning of a line, then that line will not be highlighted.
11651    pub fn highlight_rows<T: 'static>(
11652        &mut self,
11653        range: Range<Anchor>,
11654        color: Hsla,
11655        should_autoscroll: bool,
11656        cx: &mut ViewContext<Self>,
11657    ) {
11658        let snapshot = self.buffer().read(cx).snapshot(cx);
11659        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11660        let ix = row_highlights.binary_search_by(|highlight| {
11661            Ordering::Equal
11662                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11663                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11664        });
11665
11666        if let Err(mut ix) = ix {
11667            let index = post_inc(&mut self.highlight_order);
11668
11669            // If this range intersects with the preceding highlight, then merge it with
11670            // the preceding highlight. Otherwise insert a new highlight.
11671            let mut merged = false;
11672            if ix > 0 {
11673                let prev_highlight = &mut row_highlights[ix - 1];
11674                if prev_highlight
11675                    .range
11676                    .end
11677                    .cmp(&range.start, &snapshot)
11678                    .is_ge()
11679                {
11680                    ix -= 1;
11681                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11682                        prev_highlight.range.end = range.end;
11683                    }
11684                    merged = true;
11685                    prev_highlight.index = index;
11686                    prev_highlight.color = color;
11687                    prev_highlight.should_autoscroll = should_autoscroll;
11688                }
11689            }
11690
11691            if !merged {
11692                row_highlights.insert(
11693                    ix,
11694                    RowHighlight {
11695                        range: range.clone(),
11696                        index,
11697                        color,
11698                        should_autoscroll,
11699                    },
11700                );
11701            }
11702
11703            // If any of the following highlights intersect with this one, merge them.
11704            while let Some(next_highlight) = row_highlights.get(ix + 1) {
11705                let highlight = &row_highlights[ix];
11706                if next_highlight
11707                    .range
11708                    .start
11709                    .cmp(&highlight.range.end, &snapshot)
11710                    .is_le()
11711                {
11712                    if next_highlight
11713                        .range
11714                        .end
11715                        .cmp(&highlight.range.end, &snapshot)
11716                        .is_gt()
11717                    {
11718                        row_highlights[ix].range.end = next_highlight.range.end;
11719                    }
11720                    row_highlights.remove(ix + 1);
11721                } else {
11722                    break;
11723                }
11724            }
11725        }
11726    }
11727
11728    /// Remove any highlighted row ranges of the given type that intersect the
11729    /// given ranges.
11730    pub fn remove_highlighted_rows<T: 'static>(
11731        &mut self,
11732        ranges_to_remove: Vec<Range<Anchor>>,
11733        cx: &mut ViewContext<Self>,
11734    ) {
11735        let snapshot = self.buffer().read(cx).snapshot(cx);
11736        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11737        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11738        row_highlights.retain(|highlight| {
11739            while let Some(range_to_remove) = ranges_to_remove.peek() {
11740                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11741                    Ordering::Less | Ordering::Equal => {
11742                        ranges_to_remove.next();
11743                    }
11744                    Ordering::Greater => {
11745                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11746                            Ordering::Less | Ordering::Equal => {
11747                                return false;
11748                            }
11749                            Ordering::Greater => break,
11750                        }
11751                    }
11752                }
11753            }
11754
11755            true
11756        })
11757    }
11758
11759    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11760    pub fn clear_row_highlights<T: 'static>(&mut self) {
11761        self.highlighted_rows.remove(&TypeId::of::<T>());
11762    }
11763
11764    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11765    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11766        self.highlighted_rows
11767            .get(&TypeId::of::<T>())
11768            .map_or(&[] as &[_], |vec| vec.as_slice())
11769            .iter()
11770            .map(|highlight| (highlight.range.clone(), highlight.color))
11771    }
11772
11773    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11774    /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11775    /// Allows to ignore certain kinds of highlights.
11776    pub fn highlighted_display_rows(
11777        &mut self,
11778        cx: &mut WindowContext,
11779    ) -> BTreeMap<DisplayRow, Hsla> {
11780        let snapshot = self.snapshot(cx);
11781        let mut used_highlight_orders = HashMap::default();
11782        self.highlighted_rows
11783            .iter()
11784            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11785            .fold(
11786                BTreeMap::<DisplayRow, Hsla>::new(),
11787                |mut unique_rows, highlight| {
11788                    let start = highlight.range.start.to_display_point(&snapshot);
11789                    let end = highlight.range.end.to_display_point(&snapshot);
11790                    let start_row = start.row().0;
11791                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11792                        && end.column() == 0
11793                    {
11794                        end.row().0.saturating_sub(1)
11795                    } else {
11796                        end.row().0
11797                    };
11798                    for row in start_row..=end_row {
11799                        let used_index =
11800                            used_highlight_orders.entry(row).or_insert(highlight.index);
11801                        if highlight.index >= *used_index {
11802                            *used_index = highlight.index;
11803                            unique_rows.insert(DisplayRow(row), highlight.color);
11804                        }
11805                    }
11806                    unique_rows
11807                },
11808            )
11809    }
11810
11811    pub fn highlighted_display_row_for_autoscroll(
11812        &self,
11813        snapshot: &DisplaySnapshot,
11814    ) -> Option<DisplayRow> {
11815        self.highlighted_rows
11816            .values()
11817            .flat_map(|highlighted_rows| highlighted_rows.iter())
11818            .filter_map(|highlight| {
11819                if highlight.should_autoscroll {
11820                    Some(highlight.range.start.to_display_point(snapshot).row())
11821                } else {
11822                    None
11823                }
11824            })
11825            .min()
11826    }
11827
11828    pub fn set_search_within_ranges(
11829        &mut self,
11830        ranges: &[Range<Anchor>],
11831        cx: &mut ViewContext<Self>,
11832    ) {
11833        self.highlight_background::<SearchWithinRange>(
11834            ranges,
11835            |colors| colors.editor_document_highlight_read_background,
11836            cx,
11837        )
11838    }
11839
11840    pub fn set_breadcrumb_header(&mut self, new_header: String) {
11841        self.breadcrumb_header = Some(new_header);
11842    }
11843
11844    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11845        self.clear_background_highlights::<SearchWithinRange>(cx);
11846    }
11847
11848    pub fn highlight_background<T: 'static>(
11849        &mut self,
11850        ranges: &[Range<Anchor>],
11851        color_fetcher: fn(&ThemeColors) -> Hsla,
11852        cx: &mut ViewContext<Self>,
11853    ) {
11854        self.background_highlights
11855            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11856        self.scrollbar_marker_state.dirty = true;
11857        cx.notify();
11858    }
11859
11860    pub fn clear_background_highlights<T: 'static>(
11861        &mut self,
11862        cx: &mut ViewContext<Self>,
11863    ) -> Option<BackgroundHighlight> {
11864        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11865        if !text_highlights.1.is_empty() {
11866            self.scrollbar_marker_state.dirty = true;
11867            cx.notify();
11868        }
11869        Some(text_highlights)
11870    }
11871
11872    pub fn highlight_gutter<T: 'static>(
11873        &mut self,
11874        ranges: &[Range<Anchor>],
11875        color_fetcher: fn(&AppContext) -> Hsla,
11876        cx: &mut ViewContext<Self>,
11877    ) {
11878        self.gutter_highlights
11879            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11880        cx.notify();
11881    }
11882
11883    pub fn clear_gutter_highlights<T: 'static>(
11884        &mut self,
11885        cx: &mut ViewContext<Self>,
11886    ) -> Option<GutterHighlight> {
11887        cx.notify();
11888        self.gutter_highlights.remove(&TypeId::of::<T>())
11889    }
11890
11891    #[cfg(feature = "test-support")]
11892    pub fn all_text_background_highlights(
11893        &mut self,
11894        cx: &mut ViewContext<Self>,
11895    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11896        let snapshot = self.snapshot(cx);
11897        let buffer = &snapshot.buffer_snapshot;
11898        let start = buffer.anchor_before(0);
11899        let end = buffer.anchor_after(buffer.len());
11900        let theme = cx.theme().colors();
11901        self.background_highlights_in_range(start..end, &snapshot, theme)
11902    }
11903
11904    #[cfg(feature = "test-support")]
11905    pub fn search_background_highlights(
11906        &mut self,
11907        cx: &mut ViewContext<Self>,
11908    ) -> Vec<Range<Point>> {
11909        let snapshot = self.buffer().read(cx).snapshot(cx);
11910
11911        let highlights = self
11912            .background_highlights
11913            .get(&TypeId::of::<items::BufferSearchHighlights>());
11914
11915        if let Some((_color, ranges)) = highlights {
11916            ranges
11917                .iter()
11918                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11919                .collect_vec()
11920        } else {
11921            vec![]
11922        }
11923    }
11924
11925    fn document_highlights_for_position<'a>(
11926        &'a self,
11927        position: Anchor,
11928        buffer: &'a MultiBufferSnapshot,
11929    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
11930        let read_highlights = self
11931            .background_highlights
11932            .get(&TypeId::of::<DocumentHighlightRead>())
11933            .map(|h| &h.1);
11934        let write_highlights = self
11935            .background_highlights
11936            .get(&TypeId::of::<DocumentHighlightWrite>())
11937            .map(|h| &h.1);
11938        let left_position = position.bias_left(buffer);
11939        let right_position = position.bias_right(buffer);
11940        read_highlights
11941            .into_iter()
11942            .chain(write_highlights)
11943            .flat_map(move |ranges| {
11944                let start_ix = match ranges.binary_search_by(|probe| {
11945                    let cmp = probe.end.cmp(&left_position, buffer);
11946                    if cmp.is_ge() {
11947                        Ordering::Greater
11948                    } else {
11949                        Ordering::Less
11950                    }
11951                }) {
11952                    Ok(i) | Err(i) => i,
11953                };
11954
11955                ranges[start_ix..]
11956                    .iter()
11957                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11958            })
11959    }
11960
11961    pub fn has_background_highlights<T: 'static>(&self) -> bool {
11962        self.background_highlights
11963            .get(&TypeId::of::<T>())
11964            .map_or(false, |(_, highlights)| !highlights.is_empty())
11965    }
11966
11967    pub fn background_highlights_in_range(
11968        &self,
11969        search_range: Range<Anchor>,
11970        display_snapshot: &DisplaySnapshot,
11971        theme: &ThemeColors,
11972    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11973        let mut results = Vec::new();
11974        for (color_fetcher, ranges) in self.background_highlights.values() {
11975            let color = color_fetcher(theme);
11976            let start_ix = match ranges.binary_search_by(|probe| {
11977                let cmp = probe
11978                    .end
11979                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11980                if cmp.is_gt() {
11981                    Ordering::Greater
11982                } else {
11983                    Ordering::Less
11984                }
11985            }) {
11986                Ok(i) | Err(i) => i,
11987            };
11988            for range in &ranges[start_ix..] {
11989                if range
11990                    .start
11991                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11992                    .is_ge()
11993                {
11994                    break;
11995                }
11996
11997                let start = range.start.to_display_point(display_snapshot);
11998                let end = range.end.to_display_point(display_snapshot);
11999                results.push((start..end, color))
12000            }
12001        }
12002        results
12003    }
12004
12005    pub fn background_highlight_row_ranges<T: 'static>(
12006        &self,
12007        search_range: Range<Anchor>,
12008        display_snapshot: &DisplaySnapshot,
12009        count: usize,
12010    ) -> Vec<RangeInclusive<DisplayPoint>> {
12011        let mut results = Vec::new();
12012        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12013            return vec![];
12014        };
12015
12016        let start_ix = match ranges.binary_search_by(|probe| {
12017            let cmp = probe
12018                .end
12019                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12020            if cmp.is_gt() {
12021                Ordering::Greater
12022            } else {
12023                Ordering::Less
12024            }
12025        }) {
12026            Ok(i) | Err(i) => i,
12027        };
12028        let mut push_region = |start: Option<Point>, end: Option<Point>| {
12029            if let (Some(start_display), Some(end_display)) = (start, end) {
12030                results.push(
12031                    start_display.to_display_point(display_snapshot)
12032                        ..=end_display.to_display_point(display_snapshot),
12033                );
12034            }
12035        };
12036        let mut start_row: Option<Point> = None;
12037        let mut end_row: Option<Point> = None;
12038        if ranges.len() > count {
12039            return Vec::new();
12040        }
12041        for range in &ranges[start_ix..] {
12042            if range
12043                .start
12044                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12045                .is_ge()
12046            {
12047                break;
12048            }
12049            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12050            if let Some(current_row) = &end_row {
12051                if end.row == current_row.row {
12052                    continue;
12053                }
12054            }
12055            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12056            if start_row.is_none() {
12057                assert_eq!(end_row, None);
12058                start_row = Some(start);
12059                end_row = Some(end);
12060                continue;
12061            }
12062            if let Some(current_end) = end_row.as_mut() {
12063                if start.row > current_end.row + 1 {
12064                    push_region(start_row, end_row);
12065                    start_row = Some(start);
12066                    end_row = Some(end);
12067                } else {
12068                    // Merge two hunks.
12069                    *current_end = end;
12070                }
12071            } else {
12072                unreachable!();
12073            }
12074        }
12075        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12076        push_region(start_row, end_row);
12077        results
12078    }
12079
12080    pub fn gutter_highlights_in_range(
12081        &self,
12082        search_range: Range<Anchor>,
12083        display_snapshot: &DisplaySnapshot,
12084        cx: &AppContext,
12085    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12086        let mut results = Vec::new();
12087        for (color_fetcher, ranges) in self.gutter_highlights.values() {
12088            let color = color_fetcher(cx);
12089            let start_ix = match ranges.binary_search_by(|probe| {
12090                let cmp = probe
12091                    .end
12092                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12093                if cmp.is_gt() {
12094                    Ordering::Greater
12095                } else {
12096                    Ordering::Less
12097                }
12098            }) {
12099                Ok(i) | Err(i) => i,
12100            };
12101            for range in &ranges[start_ix..] {
12102                if range
12103                    .start
12104                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12105                    .is_ge()
12106                {
12107                    break;
12108                }
12109
12110                let start = range.start.to_display_point(display_snapshot);
12111                let end = range.end.to_display_point(display_snapshot);
12112                results.push((start..end, color))
12113            }
12114        }
12115        results
12116    }
12117
12118    /// Get the text ranges corresponding to the redaction query
12119    pub fn redacted_ranges(
12120        &self,
12121        search_range: Range<Anchor>,
12122        display_snapshot: &DisplaySnapshot,
12123        cx: &WindowContext,
12124    ) -> Vec<Range<DisplayPoint>> {
12125        display_snapshot
12126            .buffer_snapshot
12127            .redacted_ranges(search_range, |file| {
12128                if let Some(file) = file {
12129                    file.is_private()
12130                        && EditorSettings::get(
12131                            Some(SettingsLocation {
12132                                worktree_id: file.worktree_id(cx),
12133                                path: file.path().as_ref(),
12134                            }),
12135                            cx,
12136                        )
12137                        .redact_private_values
12138                } else {
12139                    false
12140                }
12141            })
12142            .map(|range| {
12143                range.start.to_display_point(display_snapshot)
12144                    ..range.end.to_display_point(display_snapshot)
12145            })
12146            .collect()
12147    }
12148
12149    pub fn highlight_text<T: 'static>(
12150        &mut self,
12151        ranges: Vec<Range<Anchor>>,
12152        style: HighlightStyle,
12153        cx: &mut ViewContext<Self>,
12154    ) {
12155        self.display_map.update(cx, |map, _| {
12156            map.highlight_text(TypeId::of::<T>(), ranges, style)
12157        });
12158        cx.notify();
12159    }
12160
12161    pub(crate) fn highlight_inlays<T: 'static>(
12162        &mut self,
12163        highlights: Vec<InlayHighlight>,
12164        style: HighlightStyle,
12165        cx: &mut ViewContext<Self>,
12166    ) {
12167        self.display_map.update(cx, |map, _| {
12168            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12169        });
12170        cx.notify();
12171    }
12172
12173    pub fn text_highlights<'a, T: 'static>(
12174        &'a self,
12175        cx: &'a AppContext,
12176    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12177        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12178    }
12179
12180    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12181        let cleared = self
12182            .display_map
12183            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12184        if cleared {
12185            cx.notify();
12186        }
12187    }
12188
12189    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12190        (self.read_only(cx) || self.blink_manager.read(cx).visible())
12191            && self.focus_handle.is_focused(cx)
12192    }
12193
12194    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12195        self.show_cursor_when_unfocused = is_enabled;
12196        cx.notify();
12197    }
12198
12199    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12200        cx.notify();
12201    }
12202
12203    fn on_buffer_event(
12204        &mut self,
12205        multibuffer: Model<MultiBuffer>,
12206        event: &multi_buffer::Event,
12207        cx: &mut ViewContext<Self>,
12208    ) {
12209        match event {
12210            multi_buffer::Event::Edited {
12211                singleton_buffer_edited,
12212            } => {
12213                self.scrollbar_marker_state.dirty = true;
12214                self.active_indent_guides_state.dirty = true;
12215                self.refresh_active_diagnostics(cx);
12216                self.refresh_code_actions(cx);
12217                if self.has_active_inline_completion(cx) {
12218                    self.update_visible_inline_completion(cx);
12219                }
12220                cx.emit(EditorEvent::BufferEdited);
12221                cx.emit(SearchEvent::MatchesInvalidated);
12222                if *singleton_buffer_edited {
12223                    if let Some(project) = &self.project {
12224                        let project = project.read(cx);
12225                        #[allow(clippy::mutable_key_type)]
12226                        let languages_affected = multibuffer
12227                            .read(cx)
12228                            .all_buffers()
12229                            .into_iter()
12230                            .filter_map(|buffer| {
12231                                let buffer = buffer.read(cx);
12232                                let language = buffer.language()?;
12233                                if project.is_local()
12234                                    && project.language_servers_for_buffer(buffer, cx).count() == 0
12235                                {
12236                                    None
12237                                } else {
12238                                    Some(language)
12239                                }
12240                            })
12241                            .cloned()
12242                            .collect::<HashSet<_>>();
12243                        if !languages_affected.is_empty() {
12244                            self.refresh_inlay_hints(
12245                                InlayHintRefreshReason::BufferEdited(languages_affected),
12246                                cx,
12247                            );
12248                        }
12249                    }
12250                }
12251
12252                let Some(project) = &self.project else { return };
12253                let (telemetry, is_via_ssh) = {
12254                    let project = project.read(cx);
12255                    let telemetry = project.client().telemetry().clone();
12256                    let is_via_ssh = project.is_via_ssh();
12257                    (telemetry, is_via_ssh)
12258                };
12259                refresh_linked_ranges(self, cx);
12260                telemetry.log_edit_event("editor", is_via_ssh);
12261            }
12262            multi_buffer::Event::ExcerptsAdded {
12263                buffer,
12264                predecessor,
12265                excerpts,
12266            } => {
12267                self.tasks_update_task = Some(self.refresh_runnables(cx));
12268                cx.emit(EditorEvent::ExcerptsAdded {
12269                    buffer: buffer.clone(),
12270                    predecessor: *predecessor,
12271                    excerpts: excerpts.clone(),
12272                });
12273                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12274            }
12275            multi_buffer::Event::ExcerptsRemoved { ids } => {
12276                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12277                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12278            }
12279            multi_buffer::Event::ExcerptsEdited { ids } => {
12280                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12281            }
12282            multi_buffer::Event::ExcerptsExpanded { ids } => {
12283                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12284            }
12285            multi_buffer::Event::Reparsed(buffer_id) => {
12286                self.tasks_update_task = Some(self.refresh_runnables(cx));
12287
12288                cx.emit(EditorEvent::Reparsed(*buffer_id));
12289            }
12290            multi_buffer::Event::LanguageChanged(buffer_id) => {
12291                linked_editing_ranges::refresh_linked_ranges(self, cx);
12292                cx.emit(EditorEvent::Reparsed(*buffer_id));
12293                cx.notify();
12294            }
12295            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12296            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12297            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12298                cx.emit(EditorEvent::TitleChanged)
12299            }
12300            multi_buffer::Event::DiffBaseChanged => {
12301                self.scrollbar_marker_state.dirty = true;
12302                cx.emit(EditorEvent::DiffBaseChanged);
12303                cx.notify();
12304            }
12305            multi_buffer::Event::DiffUpdated { buffer } => {
12306                self.sync_expanded_diff_hunks(buffer.clone(), cx);
12307                cx.notify();
12308            }
12309            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12310            multi_buffer::Event::DiagnosticsUpdated => {
12311                self.refresh_active_diagnostics(cx);
12312                self.scrollbar_marker_state.dirty = true;
12313                cx.notify();
12314            }
12315            _ => {}
12316        };
12317    }
12318
12319    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12320        cx.notify();
12321    }
12322
12323    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12324        self.tasks_update_task = Some(self.refresh_runnables(cx));
12325        self.refresh_inline_completion(true, false, cx);
12326        self.refresh_inlay_hints(
12327            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12328                self.selections.newest_anchor().head(),
12329                &self.buffer.read(cx).snapshot(cx),
12330                cx,
12331            )),
12332            cx,
12333        );
12334
12335        let old_cursor_shape = self.cursor_shape;
12336
12337        {
12338            let editor_settings = EditorSettings::get_global(cx);
12339            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12340            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12341            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12342        }
12343
12344        if old_cursor_shape != self.cursor_shape {
12345            cx.emit(EditorEvent::CursorShapeChanged);
12346        }
12347
12348        let project_settings = ProjectSettings::get_global(cx);
12349        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12350
12351        if self.mode == EditorMode::Full {
12352            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12353            if self.git_blame_inline_enabled != inline_blame_enabled {
12354                self.toggle_git_blame_inline_internal(false, cx);
12355            }
12356        }
12357
12358        cx.notify();
12359    }
12360
12361    pub fn set_searchable(&mut self, searchable: bool) {
12362        self.searchable = searchable;
12363    }
12364
12365    pub fn searchable(&self) -> bool {
12366        self.searchable
12367    }
12368
12369    fn open_proposed_changes_editor(
12370        &mut self,
12371        _: &OpenProposedChangesEditor,
12372        cx: &mut ViewContext<Self>,
12373    ) {
12374        let Some(workspace) = self.workspace() else {
12375            cx.propagate();
12376            return;
12377        };
12378
12379        let buffer = self.buffer.read(cx);
12380        let mut new_selections_by_buffer = HashMap::default();
12381        for selection in self.selections.all::<usize>(cx) {
12382            for (buffer, range, _) in
12383                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12384            {
12385                let mut range = range.to_point(buffer.read(cx));
12386                range.start.column = 0;
12387                range.end.column = buffer.read(cx).line_len(range.end.row);
12388                new_selections_by_buffer
12389                    .entry(buffer)
12390                    .or_insert(Vec::new())
12391                    .push(range)
12392            }
12393        }
12394
12395        let proposed_changes_buffers = new_selections_by_buffer
12396            .into_iter()
12397            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12398            .collect::<Vec<_>>();
12399        let proposed_changes_editor = cx.new_view(|cx| {
12400            ProposedChangesEditor::new(
12401                "Proposed changes",
12402                proposed_changes_buffers,
12403                self.project.clone(),
12404                cx,
12405            )
12406        });
12407
12408        cx.window_context().defer(move |cx| {
12409            workspace.update(cx, |workspace, cx| {
12410                workspace.active_pane().update(cx, |pane, cx| {
12411                    pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12412                });
12413            });
12414        });
12415    }
12416
12417    fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12418        self.open_excerpts_common(true, cx)
12419    }
12420
12421    fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12422        self.open_excerpts_common(false, cx)
12423    }
12424
12425    fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
12426        let buffer = self.buffer.read(cx);
12427        if buffer.is_singleton() {
12428            cx.propagate();
12429            return;
12430        }
12431
12432        let Some(workspace) = self.workspace() else {
12433            cx.propagate();
12434            return;
12435        };
12436
12437        let mut new_selections_by_buffer = HashMap::default();
12438        for selection in self.selections.all::<usize>(cx) {
12439            for (mut buffer_handle, mut range, _) in
12440                buffer.range_to_buffer_ranges(selection.range(), cx)
12441            {
12442                // When editing branch buffers, jump to the corresponding location
12443                // in their base buffer.
12444                let buffer = buffer_handle.read(cx);
12445                if let Some(base_buffer) = buffer.diff_base_buffer() {
12446                    range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12447                    buffer_handle = base_buffer;
12448                }
12449
12450                if selection.reversed {
12451                    mem::swap(&mut range.start, &mut range.end);
12452                }
12453                new_selections_by_buffer
12454                    .entry(buffer_handle)
12455                    .or_insert(Vec::new())
12456                    .push(range)
12457            }
12458        }
12459
12460        // We defer the pane interaction because we ourselves are a workspace item
12461        // and activating a new item causes the pane to call a method on us reentrantly,
12462        // which panics if we're on the stack.
12463        cx.window_context().defer(move |cx| {
12464            workspace.update(cx, |workspace, cx| {
12465                let pane = if split {
12466                    workspace.adjacent_pane(cx)
12467                } else {
12468                    workspace.active_pane().clone()
12469                };
12470
12471                for (buffer, ranges) in new_selections_by_buffer {
12472                    let editor =
12473                        workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
12474                    editor.update(cx, |editor, cx| {
12475                        editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
12476                            s.select_ranges(ranges);
12477                        });
12478                    });
12479                }
12480            })
12481        });
12482    }
12483
12484    fn jump(
12485        &mut self,
12486        path: ProjectPath,
12487        position: Point,
12488        anchor: language::Anchor,
12489        offset_from_top: u32,
12490        cx: &mut ViewContext<Self>,
12491    ) {
12492        let workspace = self.workspace();
12493        cx.spawn(|_, mut cx| async move {
12494            let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
12495            let editor = workspace.update(&mut cx, |workspace, cx| {
12496                // Reset the preview item id before opening the new item
12497                workspace.active_pane().update(cx, |pane, cx| {
12498                    pane.set_preview_item_id(None, cx);
12499                });
12500                workspace.open_path_preview(path, None, true, true, cx)
12501            })?;
12502            let editor = editor
12503                .await?
12504                .downcast::<Editor>()
12505                .ok_or_else(|| anyhow!("opened item was not an editor"))?
12506                .downgrade();
12507            editor.update(&mut cx, |editor, cx| {
12508                let buffer = editor
12509                    .buffer()
12510                    .read(cx)
12511                    .as_singleton()
12512                    .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
12513                let buffer = buffer.read(cx);
12514                let cursor = if buffer.can_resolve(&anchor) {
12515                    language::ToPoint::to_point(&anchor, buffer)
12516                } else {
12517                    buffer.clip_point(position, Bias::Left)
12518                };
12519
12520                let nav_history = editor.nav_history.take();
12521                editor.change_selections(
12522                    Some(Autoscroll::top_relative(offset_from_top as usize)),
12523                    cx,
12524                    |s| {
12525                        s.select_ranges([cursor..cursor]);
12526                    },
12527                );
12528                editor.nav_history = nav_history;
12529
12530                anyhow::Ok(())
12531            })??;
12532
12533            anyhow::Ok(())
12534        })
12535        .detach_and_log_err(cx);
12536    }
12537
12538    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12539        let snapshot = self.buffer.read(cx).read(cx);
12540        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12541        Some(
12542            ranges
12543                .iter()
12544                .map(move |range| {
12545                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12546                })
12547                .collect(),
12548        )
12549    }
12550
12551    fn selection_replacement_ranges(
12552        &self,
12553        range: Range<OffsetUtf16>,
12554        cx: &AppContext,
12555    ) -> Vec<Range<OffsetUtf16>> {
12556        let selections = self.selections.all::<OffsetUtf16>(cx);
12557        let newest_selection = selections
12558            .iter()
12559            .max_by_key(|selection| selection.id)
12560            .unwrap();
12561        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12562        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12563        let snapshot = self.buffer.read(cx).read(cx);
12564        selections
12565            .into_iter()
12566            .map(|mut selection| {
12567                selection.start.0 =
12568                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
12569                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12570                snapshot.clip_offset_utf16(selection.start, Bias::Left)
12571                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12572            })
12573            .collect()
12574    }
12575
12576    fn report_editor_event(
12577        &self,
12578        operation: &'static str,
12579        file_extension: Option<String>,
12580        cx: &AppContext,
12581    ) {
12582        if cfg!(any(test, feature = "test-support")) {
12583            return;
12584        }
12585
12586        let Some(project) = &self.project else { return };
12587
12588        // If None, we are in a file without an extension
12589        let file = self
12590            .buffer
12591            .read(cx)
12592            .as_singleton()
12593            .and_then(|b| b.read(cx).file());
12594        let file_extension = file_extension.or(file
12595            .as_ref()
12596            .and_then(|file| Path::new(file.file_name(cx)).extension())
12597            .and_then(|e| e.to_str())
12598            .map(|a| a.to_string()));
12599
12600        let vim_mode = cx
12601            .global::<SettingsStore>()
12602            .raw_user_settings()
12603            .get("vim_mode")
12604            == Some(&serde_json::Value::Bool(true));
12605
12606        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12607            == language::language_settings::InlineCompletionProvider::Copilot;
12608        let copilot_enabled_for_language = self
12609            .buffer
12610            .read(cx)
12611            .settings_at(0, cx)
12612            .show_inline_completions;
12613
12614        let project = project.read(cx);
12615        let telemetry = project.client().telemetry().clone();
12616        telemetry.report_editor_event(
12617            file_extension,
12618            vim_mode,
12619            operation,
12620            copilot_enabled,
12621            copilot_enabled_for_language,
12622            project.is_via_ssh(),
12623        )
12624    }
12625
12626    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12627    /// with each line being an array of {text, highlight} objects.
12628    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12629        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12630            return;
12631        };
12632
12633        #[derive(Serialize)]
12634        struct Chunk<'a> {
12635            text: String,
12636            highlight: Option<&'a str>,
12637        }
12638
12639        let snapshot = buffer.read(cx).snapshot();
12640        let range = self
12641            .selected_text_range(false, cx)
12642            .and_then(|selection| {
12643                if selection.range.is_empty() {
12644                    None
12645                } else {
12646                    Some(selection.range)
12647                }
12648            })
12649            .unwrap_or_else(|| 0..snapshot.len());
12650
12651        let chunks = snapshot.chunks(range, true);
12652        let mut lines = Vec::new();
12653        let mut line: VecDeque<Chunk> = VecDeque::new();
12654
12655        let Some(style) = self.style.as_ref() else {
12656            return;
12657        };
12658
12659        for chunk in chunks {
12660            let highlight = chunk
12661                .syntax_highlight_id
12662                .and_then(|id| id.name(&style.syntax));
12663            let mut chunk_lines = chunk.text.split('\n').peekable();
12664            while let Some(text) = chunk_lines.next() {
12665                let mut merged_with_last_token = false;
12666                if let Some(last_token) = line.back_mut() {
12667                    if last_token.highlight == highlight {
12668                        last_token.text.push_str(text);
12669                        merged_with_last_token = true;
12670                    }
12671                }
12672
12673                if !merged_with_last_token {
12674                    line.push_back(Chunk {
12675                        text: text.into(),
12676                        highlight,
12677                    });
12678                }
12679
12680                if chunk_lines.peek().is_some() {
12681                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
12682                        line.pop_front();
12683                    }
12684                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
12685                        line.pop_back();
12686                    }
12687
12688                    lines.push(mem::take(&mut line));
12689                }
12690            }
12691        }
12692
12693        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12694            return;
12695        };
12696        cx.write_to_clipboard(ClipboardItem::new_string(lines));
12697    }
12698
12699    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12700        &self.inlay_hint_cache
12701    }
12702
12703    pub fn replay_insert_event(
12704        &mut self,
12705        text: &str,
12706        relative_utf16_range: Option<Range<isize>>,
12707        cx: &mut ViewContext<Self>,
12708    ) {
12709        if !self.input_enabled {
12710            cx.emit(EditorEvent::InputIgnored { text: text.into() });
12711            return;
12712        }
12713        if let Some(relative_utf16_range) = relative_utf16_range {
12714            let selections = self.selections.all::<OffsetUtf16>(cx);
12715            self.change_selections(None, cx, |s| {
12716                let new_ranges = selections.into_iter().map(|range| {
12717                    let start = OffsetUtf16(
12718                        range
12719                            .head()
12720                            .0
12721                            .saturating_add_signed(relative_utf16_range.start),
12722                    );
12723                    let end = OffsetUtf16(
12724                        range
12725                            .head()
12726                            .0
12727                            .saturating_add_signed(relative_utf16_range.end),
12728                    );
12729                    start..end
12730                });
12731                s.select_ranges(new_ranges);
12732            });
12733        }
12734
12735        self.handle_input(text, cx);
12736    }
12737
12738    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12739        let Some(provider) = self.semantics_provider.as_ref() else {
12740            return false;
12741        };
12742
12743        let mut supports = false;
12744        self.buffer().read(cx).for_each_buffer(|buffer| {
12745            supports |= provider.supports_inlay_hints(buffer, cx);
12746        });
12747        supports
12748    }
12749
12750    pub fn focus(&self, cx: &mut WindowContext) {
12751        cx.focus(&self.focus_handle)
12752    }
12753
12754    pub fn is_focused(&self, cx: &WindowContext) -> bool {
12755        self.focus_handle.is_focused(cx)
12756    }
12757
12758    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12759        cx.emit(EditorEvent::Focused);
12760
12761        if let Some(descendant) = self
12762            .last_focused_descendant
12763            .take()
12764            .and_then(|descendant| descendant.upgrade())
12765        {
12766            cx.focus(&descendant);
12767        } else {
12768            if let Some(blame) = self.blame.as_ref() {
12769                blame.update(cx, GitBlame::focus)
12770            }
12771
12772            self.blink_manager.update(cx, BlinkManager::enable);
12773            self.show_cursor_names(cx);
12774            self.buffer.update(cx, |buffer, cx| {
12775                buffer.finalize_last_transaction(cx);
12776                if self.leader_peer_id.is_none() {
12777                    buffer.set_active_selections(
12778                        &self.selections.disjoint_anchors(),
12779                        self.selections.line_mode,
12780                        self.cursor_shape,
12781                        cx,
12782                    );
12783                }
12784            });
12785        }
12786    }
12787
12788    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12789        cx.emit(EditorEvent::FocusedIn)
12790    }
12791
12792    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12793        if event.blurred != self.focus_handle {
12794            self.last_focused_descendant = Some(event.blurred);
12795        }
12796    }
12797
12798    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12799        self.blink_manager.update(cx, BlinkManager::disable);
12800        self.buffer
12801            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12802
12803        if let Some(blame) = self.blame.as_ref() {
12804            blame.update(cx, GitBlame::blur)
12805        }
12806        if !self.hover_state.focused(cx) {
12807            hide_hover(self, cx);
12808        }
12809
12810        self.hide_context_menu(cx);
12811        cx.emit(EditorEvent::Blurred);
12812        cx.notify();
12813    }
12814
12815    pub fn register_action<A: Action>(
12816        &mut self,
12817        listener: impl Fn(&A, &mut WindowContext) + 'static,
12818    ) -> Subscription {
12819        let id = self.next_editor_action_id.post_inc();
12820        let listener = Arc::new(listener);
12821        self.editor_actions.borrow_mut().insert(
12822            id,
12823            Box::new(move |cx| {
12824                let cx = cx.window_context();
12825                let listener = listener.clone();
12826                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12827                    let action = action.downcast_ref().unwrap();
12828                    if phase == DispatchPhase::Bubble {
12829                        listener(action, cx)
12830                    }
12831                })
12832            }),
12833        );
12834
12835        let editor_actions = self.editor_actions.clone();
12836        Subscription::new(move || {
12837            editor_actions.borrow_mut().remove(&id);
12838        })
12839    }
12840
12841    pub fn file_header_size(&self) -> u32 {
12842        FILE_HEADER_HEIGHT
12843    }
12844
12845    pub fn revert(
12846        &mut self,
12847        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12848        cx: &mut ViewContext<Self>,
12849    ) {
12850        self.buffer().update(cx, |multi_buffer, cx| {
12851            for (buffer_id, changes) in revert_changes {
12852                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12853                    buffer.update(cx, |buffer, cx| {
12854                        buffer.edit(
12855                            changes.into_iter().map(|(range, text)| {
12856                                (range, text.to_string().map(Arc::<str>::from))
12857                            }),
12858                            None,
12859                            cx,
12860                        );
12861                    });
12862                }
12863            }
12864        });
12865        self.change_selections(None, cx, |selections| selections.refresh());
12866    }
12867
12868    pub fn to_pixel_point(
12869        &mut self,
12870        source: multi_buffer::Anchor,
12871        editor_snapshot: &EditorSnapshot,
12872        cx: &mut ViewContext<Self>,
12873    ) -> Option<gpui::Point<Pixels>> {
12874        let source_point = source.to_display_point(editor_snapshot);
12875        self.display_to_pixel_point(source_point, editor_snapshot, cx)
12876    }
12877
12878    pub fn display_to_pixel_point(
12879        &mut self,
12880        source: DisplayPoint,
12881        editor_snapshot: &EditorSnapshot,
12882        cx: &mut ViewContext<Self>,
12883    ) -> Option<gpui::Point<Pixels>> {
12884        let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12885        let text_layout_details = self.text_layout_details(cx);
12886        let scroll_top = text_layout_details
12887            .scroll_anchor
12888            .scroll_position(editor_snapshot)
12889            .y;
12890
12891        if source.row().as_f32() < scroll_top.floor() {
12892            return None;
12893        }
12894        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12895        let source_y = line_height * (source.row().as_f32() - scroll_top);
12896        Some(gpui::Point::new(source_x, source_y))
12897    }
12898
12899    pub fn has_active_completions_menu(&self) -> bool {
12900        self.context_menu.read().as_ref().map_or(false, |menu| {
12901            menu.visible() && matches!(menu, ContextMenu::Completions(_))
12902        })
12903    }
12904
12905    pub fn register_addon<T: Addon>(&mut self, instance: T) {
12906        self.addons
12907            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12908    }
12909
12910    pub fn unregister_addon<T: Addon>(&mut self) {
12911        self.addons.remove(&std::any::TypeId::of::<T>());
12912    }
12913
12914    pub fn addon<T: Addon>(&self) -> Option<&T> {
12915        let type_id = std::any::TypeId::of::<T>();
12916        self.addons
12917            .get(&type_id)
12918            .and_then(|item| item.to_any().downcast_ref::<T>())
12919    }
12920}
12921
12922fn hunks_for_selections(
12923    multi_buffer_snapshot: &MultiBufferSnapshot,
12924    selections: &[Selection<Anchor>],
12925) -> Vec<MultiBufferDiffHunk> {
12926    let buffer_rows_for_selections = selections.iter().map(|selection| {
12927        let head = selection.head();
12928        let tail = selection.tail();
12929        let start = MultiBufferRow(tail.to_point(multi_buffer_snapshot).row);
12930        let end = MultiBufferRow(head.to_point(multi_buffer_snapshot).row);
12931        if start > end {
12932            end..start
12933        } else {
12934            start..end
12935        }
12936    });
12937
12938    hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
12939}
12940
12941pub fn hunks_for_rows(
12942    rows: impl Iterator<Item = Range<MultiBufferRow>>,
12943    multi_buffer_snapshot: &MultiBufferSnapshot,
12944) -> Vec<MultiBufferDiffHunk> {
12945    let mut hunks = Vec::new();
12946    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
12947        HashMap::default();
12948    for selected_multi_buffer_rows in rows {
12949        let query_rows =
12950            selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
12951        for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
12952            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
12953            // when the caret is just above or just below the deleted hunk.
12954            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
12955            let related_to_selection = if allow_adjacent {
12956                hunk.row_range.overlaps(&query_rows)
12957                    || hunk.row_range.start == query_rows.end
12958                    || hunk.row_range.end == query_rows.start
12959            } else {
12960                // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
12961                // `hunk.row_range` is exclusive (e.g. [2..3] means 2nd row is selected)
12962                hunk.row_range.overlaps(&selected_multi_buffer_rows)
12963                    || selected_multi_buffer_rows.end == hunk.row_range.start
12964            };
12965            if related_to_selection {
12966                if !processed_buffer_rows
12967                    .entry(hunk.buffer_id)
12968                    .or_default()
12969                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
12970                {
12971                    continue;
12972                }
12973                hunks.push(hunk);
12974            }
12975        }
12976    }
12977
12978    hunks
12979}
12980
12981pub trait CollaborationHub {
12982    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
12983    fn user_participant_indices<'a>(
12984        &self,
12985        cx: &'a AppContext,
12986    ) -> &'a HashMap<u64, ParticipantIndex>;
12987    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
12988}
12989
12990impl CollaborationHub for Model<Project> {
12991    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
12992        self.read(cx).collaborators()
12993    }
12994
12995    fn user_participant_indices<'a>(
12996        &self,
12997        cx: &'a AppContext,
12998    ) -> &'a HashMap<u64, ParticipantIndex> {
12999        self.read(cx).user_store().read(cx).participant_indices()
13000    }
13001
13002    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13003        let this = self.read(cx);
13004        let user_ids = this.collaborators().values().map(|c| c.user_id);
13005        this.user_store().read_with(cx, |user_store, cx| {
13006            user_store.participant_names(user_ids, cx)
13007        })
13008    }
13009}
13010
13011pub trait SemanticsProvider {
13012    fn hover(
13013        &self,
13014        buffer: &Model<Buffer>,
13015        position: text::Anchor,
13016        cx: &mut AppContext,
13017    ) -> Option<Task<Vec<project::Hover>>>;
13018
13019    fn inlay_hints(
13020        &self,
13021        buffer_handle: Model<Buffer>,
13022        range: Range<text::Anchor>,
13023        cx: &mut AppContext,
13024    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13025
13026    fn resolve_inlay_hint(
13027        &self,
13028        hint: InlayHint,
13029        buffer_handle: Model<Buffer>,
13030        server_id: LanguageServerId,
13031        cx: &mut AppContext,
13032    ) -> Option<Task<anyhow::Result<InlayHint>>>;
13033
13034    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13035
13036    fn document_highlights(
13037        &self,
13038        buffer: &Model<Buffer>,
13039        position: text::Anchor,
13040        cx: &mut AppContext,
13041    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13042
13043    fn definitions(
13044        &self,
13045        buffer: &Model<Buffer>,
13046        position: text::Anchor,
13047        kind: GotoDefinitionKind,
13048        cx: &mut AppContext,
13049    ) -> Option<Task<Result<Vec<LocationLink>>>>;
13050
13051    fn range_for_rename(
13052        &self,
13053        buffer: &Model<Buffer>,
13054        position: text::Anchor,
13055        cx: &mut AppContext,
13056    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13057
13058    fn perform_rename(
13059        &self,
13060        buffer: &Model<Buffer>,
13061        position: text::Anchor,
13062        new_name: String,
13063        cx: &mut AppContext,
13064    ) -> Option<Task<Result<ProjectTransaction>>>;
13065}
13066
13067pub trait CompletionProvider {
13068    fn completions(
13069        &self,
13070        buffer: &Model<Buffer>,
13071        buffer_position: text::Anchor,
13072        trigger: CompletionContext,
13073        cx: &mut ViewContext<Editor>,
13074    ) -> Task<Result<Vec<Completion>>>;
13075
13076    fn resolve_completions(
13077        &self,
13078        buffer: Model<Buffer>,
13079        completion_indices: Vec<usize>,
13080        completions: Arc<RwLock<Box<[Completion]>>>,
13081        cx: &mut ViewContext<Editor>,
13082    ) -> Task<Result<bool>>;
13083
13084    fn apply_additional_edits_for_completion(
13085        &self,
13086        buffer: Model<Buffer>,
13087        completion: Completion,
13088        push_to_history: bool,
13089        cx: &mut ViewContext<Editor>,
13090    ) -> Task<Result<Option<language::Transaction>>>;
13091
13092    fn is_completion_trigger(
13093        &self,
13094        buffer: &Model<Buffer>,
13095        position: language::Anchor,
13096        text: &str,
13097        trigger_in_words: bool,
13098        cx: &mut ViewContext<Editor>,
13099    ) -> bool;
13100
13101    fn sort_completions(&self) -> bool {
13102        true
13103    }
13104}
13105
13106pub trait CodeActionProvider {
13107    fn code_actions(
13108        &self,
13109        buffer: &Model<Buffer>,
13110        range: Range<text::Anchor>,
13111        cx: &mut WindowContext,
13112    ) -> Task<Result<Vec<CodeAction>>>;
13113
13114    fn apply_code_action(
13115        &self,
13116        buffer_handle: Model<Buffer>,
13117        action: CodeAction,
13118        excerpt_id: ExcerptId,
13119        push_to_history: bool,
13120        cx: &mut WindowContext,
13121    ) -> Task<Result<ProjectTransaction>>;
13122}
13123
13124impl CodeActionProvider for Model<Project> {
13125    fn code_actions(
13126        &self,
13127        buffer: &Model<Buffer>,
13128        range: Range<text::Anchor>,
13129        cx: &mut WindowContext,
13130    ) -> Task<Result<Vec<CodeAction>>> {
13131        self.update(cx, |project, cx| project.code_actions(buffer, range, cx))
13132    }
13133
13134    fn apply_code_action(
13135        &self,
13136        buffer_handle: Model<Buffer>,
13137        action: CodeAction,
13138        _excerpt_id: ExcerptId,
13139        push_to_history: bool,
13140        cx: &mut WindowContext,
13141    ) -> Task<Result<ProjectTransaction>> {
13142        self.update(cx, |project, cx| {
13143            project.apply_code_action(buffer_handle, action, push_to_history, cx)
13144        })
13145    }
13146}
13147
13148fn snippet_completions(
13149    project: &Project,
13150    buffer: &Model<Buffer>,
13151    buffer_position: text::Anchor,
13152    cx: &mut AppContext,
13153) -> Vec<Completion> {
13154    let language = buffer.read(cx).language_at(buffer_position);
13155    let language_name = language.as_ref().map(|language| language.lsp_id());
13156    let snippet_store = project.snippets().read(cx);
13157    let snippets = snippet_store.snippets_for(language_name, cx);
13158
13159    if snippets.is_empty() {
13160        return vec![];
13161    }
13162    let snapshot = buffer.read(cx).text_snapshot();
13163    let chars = snapshot.reversed_chars_for_range(text::Anchor::MIN..buffer_position);
13164
13165    let scope = language.map(|language| language.default_scope());
13166    let classifier = CharClassifier::new(scope).for_completion(true);
13167    let mut last_word = chars
13168        .take_while(|c| classifier.is_word(*c))
13169        .collect::<String>();
13170    last_word = last_word.chars().rev().collect();
13171    let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13172    let to_lsp = |point: &text::Anchor| {
13173        let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13174        point_to_lsp(end)
13175    };
13176    let lsp_end = to_lsp(&buffer_position);
13177    snippets
13178        .into_iter()
13179        .filter_map(|snippet| {
13180            let matching_prefix = snippet
13181                .prefix
13182                .iter()
13183                .find(|prefix| prefix.starts_with(&last_word))?;
13184            let start = as_offset - last_word.len();
13185            let start = snapshot.anchor_before(start);
13186            let range = start..buffer_position;
13187            let lsp_start = to_lsp(&start);
13188            let lsp_range = lsp::Range {
13189                start: lsp_start,
13190                end: lsp_end,
13191            };
13192            Some(Completion {
13193                old_range: range,
13194                new_text: snippet.body.clone(),
13195                label: CodeLabel {
13196                    text: matching_prefix.clone(),
13197                    runs: vec![],
13198                    filter_range: 0..matching_prefix.len(),
13199                },
13200                server_id: LanguageServerId(usize::MAX),
13201                documentation: snippet.description.clone().map(Documentation::SingleLine),
13202                lsp_completion: lsp::CompletionItem {
13203                    label: snippet.prefix.first().unwrap().clone(),
13204                    kind: Some(CompletionItemKind::SNIPPET),
13205                    label_details: snippet.description.as_ref().map(|description| {
13206                        lsp::CompletionItemLabelDetails {
13207                            detail: Some(description.clone()),
13208                            description: None,
13209                        }
13210                    }),
13211                    insert_text_format: Some(InsertTextFormat::SNIPPET),
13212                    text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13213                        lsp::InsertReplaceEdit {
13214                            new_text: snippet.body.clone(),
13215                            insert: lsp_range,
13216                            replace: lsp_range,
13217                        },
13218                    )),
13219                    filter_text: Some(snippet.body.clone()),
13220                    sort_text: Some(char::MAX.to_string()),
13221                    ..Default::default()
13222                },
13223                confirm: None,
13224            })
13225        })
13226        .collect()
13227}
13228
13229impl CompletionProvider for Model<Project> {
13230    fn completions(
13231        &self,
13232        buffer: &Model<Buffer>,
13233        buffer_position: text::Anchor,
13234        options: CompletionContext,
13235        cx: &mut ViewContext<Editor>,
13236    ) -> Task<Result<Vec<Completion>>> {
13237        self.update(cx, |project, cx| {
13238            let snippets = snippet_completions(project, buffer, buffer_position, cx);
13239            let project_completions = project.completions(buffer, buffer_position, options, cx);
13240            cx.background_executor().spawn(async move {
13241                let mut completions = project_completions.await?;
13242                //let snippets = snippets.into_iter().;
13243                completions.extend(snippets);
13244                Ok(completions)
13245            })
13246        })
13247    }
13248
13249    fn resolve_completions(
13250        &self,
13251        buffer: Model<Buffer>,
13252        completion_indices: Vec<usize>,
13253        completions: Arc<RwLock<Box<[Completion]>>>,
13254        cx: &mut ViewContext<Editor>,
13255    ) -> Task<Result<bool>> {
13256        self.update(cx, |project, cx| {
13257            project.resolve_completions(buffer, completion_indices, completions, cx)
13258        })
13259    }
13260
13261    fn apply_additional_edits_for_completion(
13262        &self,
13263        buffer: Model<Buffer>,
13264        completion: Completion,
13265        push_to_history: bool,
13266        cx: &mut ViewContext<Editor>,
13267    ) -> Task<Result<Option<language::Transaction>>> {
13268        self.update(cx, |project, cx| {
13269            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13270        })
13271    }
13272
13273    fn is_completion_trigger(
13274        &self,
13275        buffer: &Model<Buffer>,
13276        position: language::Anchor,
13277        text: &str,
13278        trigger_in_words: bool,
13279        cx: &mut ViewContext<Editor>,
13280    ) -> bool {
13281        if !EditorSettings::get_global(cx).show_completions_on_input {
13282            return false;
13283        }
13284
13285        let mut chars = text.chars();
13286        let char = if let Some(char) = chars.next() {
13287            char
13288        } else {
13289            return false;
13290        };
13291        if chars.next().is_some() {
13292            return false;
13293        }
13294
13295        let buffer = buffer.read(cx);
13296        let classifier = buffer
13297            .snapshot()
13298            .char_classifier_at(position)
13299            .for_completion(true);
13300        if trigger_in_words && classifier.is_word(char) {
13301            return true;
13302        }
13303
13304        buffer
13305            .completion_triggers()
13306            .iter()
13307            .any(|string| string == text)
13308    }
13309}
13310
13311impl SemanticsProvider for Model<Project> {
13312    fn hover(
13313        &self,
13314        buffer: &Model<Buffer>,
13315        position: text::Anchor,
13316        cx: &mut AppContext,
13317    ) -> Option<Task<Vec<project::Hover>>> {
13318        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13319    }
13320
13321    fn document_highlights(
13322        &self,
13323        buffer: &Model<Buffer>,
13324        position: text::Anchor,
13325        cx: &mut AppContext,
13326    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13327        Some(self.update(cx, |project, cx| {
13328            project.document_highlights(buffer, position, cx)
13329        }))
13330    }
13331
13332    fn definitions(
13333        &self,
13334        buffer: &Model<Buffer>,
13335        position: text::Anchor,
13336        kind: GotoDefinitionKind,
13337        cx: &mut AppContext,
13338    ) -> Option<Task<Result<Vec<LocationLink>>>> {
13339        Some(self.update(cx, |project, cx| match kind {
13340            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13341            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13342            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13343            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13344        }))
13345    }
13346
13347    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13348        // TODO: make this work for remote projects
13349        self.read(cx)
13350            .language_servers_for_buffer(buffer.read(cx), cx)
13351            .any(
13352                |(_, server)| match server.capabilities().inlay_hint_provider {
13353                    Some(lsp::OneOf::Left(enabled)) => enabled,
13354                    Some(lsp::OneOf::Right(_)) => true,
13355                    None => false,
13356                },
13357            )
13358    }
13359
13360    fn inlay_hints(
13361        &self,
13362        buffer_handle: Model<Buffer>,
13363        range: Range<text::Anchor>,
13364        cx: &mut AppContext,
13365    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13366        Some(self.update(cx, |project, cx| {
13367            project.inlay_hints(buffer_handle, range, cx)
13368        }))
13369    }
13370
13371    fn resolve_inlay_hint(
13372        &self,
13373        hint: InlayHint,
13374        buffer_handle: Model<Buffer>,
13375        server_id: LanguageServerId,
13376        cx: &mut AppContext,
13377    ) -> Option<Task<anyhow::Result<InlayHint>>> {
13378        Some(self.update(cx, |project, cx| {
13379            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13380        }))
13381    }
13382
13383    fn range_for_rename(
13384        &self,
13385        buffer: &Model<Buffer>,
13386        position: text::Anchor,
13387        cx: &mut AppContext,
13388    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13389        Some(self.update(cx, |project, cx| {
13390            project.prepare_rename(buffer.clone(), position, cx)
13391        }))
13392    }
13393
13394    fn perform_rename(
13395        &self,
13396        buffer: &Model<Buffer>,
13397        position: text::Anchor,
13398        new_name: String,
13399        cx: &mut AppContext,
13400    ) -> Option<Task<Result<ProjectTransaction>>> {
13401        Some(self.update(cx, |project, cx| {
13402            project.perform_rename(buffer.clone(), position, new_name, cx)
13403        }))
13404    }
13405}
13406
13407fn inlay_hint_settings(
13408    location: Anchor,
13409    snapshot: &MultiBufferSnapshot,
13410    cx: &mut ViewContext<'_, Editor>,
13411) -> InlayHintSettings {
13412    let file = snapshot.file_at(location);
13413    let language = snapshot.language_at(location).map(|l| l.name());
13414    language_settings(language, file, cx).inlay_hints
13415}
13416
13417fn consume_contiguous_rows(
13418    contiguous_row_selections: &mut Vec<Selection<Point>>,
13419    selection: &Selection<Point>,
13420    display_map: &DisplaySnapshot,
13421    selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
13422) -> (MultiBufferRow, MultiBufferRow) {
13423    contiguous_row_selections.push(selection.clone());
13424    let start_row = MultiBufferRow(selection.start.row);
13425    let mut end_row = ending_row(selection, display_map);
13426
13427    while let Some(next_selection) = selections.peek() {
13428        if next_selection.start.row <= end_row.0 {
13429            end_row = ending_row(next_selection, display_map);
13430            contiguous_row_selections.push(selections.next().unwrap().clone());
13431        } else {
13432            break;
13433        }
13434    }
13435    (start_row, end_row)
13436}
13437
13438fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13439    if next_selection.end.column > 0 || next_selection.is_empty() {
13440        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13441    } else {
13442        MultiBufferRow(next_selection.end.row)
13443    }
13444}
13445
13446impl EditorSnapshot {
13447    pub fn remote_selections_in_range<'a>(
13448        &'a self,
13449        range: &'a Range<Anchor>,
13450        collaboration_hub: &dyn CollaborationHub,
13451        cx: &'a AppContext,
13452    ) -> impl 'a + Iterator<Item = RemoteSelection> {
13453        let participant_names = collaboration_hub.user_names(cx);
13454        let participant_indices = collaboration_hub.user_participant_indices(cx);
13455        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
13456        let collaborators_by_replica_id = collaborators_by_peer_id
13457            .iter()
13458            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
13459            .collect::<HashMap<_, _>>();
13460        self.buffer_snapshot
13461            .selections_in_range(range, false)
13462            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
13463                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
13464                let participant_index = participant_indices.get(&collaborator.user_id).copied();
13465                let user_name = participant_names.get(&collaborator.user_id).cloned();
13466                Some(RemoteSelection {
13467                    replica_id,
13468                    selection,
13469                    cursor_shape,
13470                    line_mode,
13471                    participant_index,
13472                    peer_id: collaborator.peer_id,
13473                    user_name,
13474                })
13475            })
13476    }
13477
13478    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
13479        self.display_snapshot.buffer_snapshot.language_at(position)
13480    }
13481
13482    pub fn is_focused(&self) -> bool {
13483        self.is_focused
13484    }
13485
13486    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
13487        self.placeholder_text.as_ref()
13488    }
13489
13490    pub fn scroll_position(&self) -> gpui::Point<f32> {
13491        self.scroll_anchor.scroll_position(&self.display_snapshot)
13492    }
13493
13494    fn gutter_dimensions(
13495        &self,
13496        font_id: FontId,
13497        font_size: Pixels,
13498        em_width: Pixels,
13499        em_advance: Pixels,
13500        max_line_number_width: Pixels,
13501        cx: &AppContext,
13502    ) -> GutterDimensions {
13503        if !self.show_gutter {
13504            return GutterDimensions::default();
13505        }
13506        let descent = cx.text_system().descent(font_id, font_size);
13507
13508        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
13509            matches!(
13510                ProjectSettings::get_global(cx).git.git_gutter,
13511                Some(GitGutterSetting::TrackedFiles)
13512            )
13513        });
13514        let gutter_settings = EditorSettings::get_global(cx).gutter;
13515        let show_line_numbers = self
13516            .show_line_numbers
13517            .unwrap_or(gutter_settings.line_numbers);
13518        let line_gutter_width = if show_line_numbers {
13519            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
13520            let min_width_for_number_on_gutter = em_advance * 4.0;
13521            max_line_number_width.max(min_width_for_number_on_gutter)
13522        } else {
13523            0.0.into()
13524        };
13525
13526        let show_code_actions = self
13527            .show_code_actions
13528            .unwrap_or(gutter_settings.code_actions);
13529
13530        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
13531
13532        let git_blame_entries_width =
13533            self.git_blame_gutter_max_author_length
13534                .map(|max_author_length| {
13535                    // Length of the author name, but also space for the commit hash,
13536                    // the spacing and the timestamp.
13537                    let max_char_count = max_author_length
13538                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
13539                        + 7 // length of commit sha
13540                        + 14 // length of max relative timestamp ("60 minutes ago")
13541                        + 4; // gaps and margins
13542
13543                    em_advance * max_char_count
13544                });
13545
13546        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
13547        left_padding += if show_code_actions || show_runnables {
13548            em_width * 3.0
13549        } else if show_git_gutter && show_line_numbers {
13550            em_width * 2.0
13551        } else if show_git_gutter || show_line_numbers {
13552            em_width
13553        } else {
13554            px(0.)
13555        };
13556
13557        let right_padding = if gutter_settings.folds && show_line_numbers {
13558            em_width * 4.0
13559        } else if gutter_settings.folds {
13560            em_width * 3.0
13561        } else if show_line_numbers {
13562            em_width
13563        } else {
13564            px(0.)
13565        };
13566
13567        GutterDimensions {
13568            left_padding,
13569            right_padding,
13570            width: line_gutter_width + left_padding + right_padding,
13571            margin: -descent,
13572            git_blame_entries_width,
13573        }
13574    }
13575
13576    pub fn render_fold_toggle(
13577        &self,
13578        buffer_row: MultiBufferRow,
13579        row_contains_cursor: bool,
13580        editor: View<Editor>,
13581        cx: &mut WindowContext,
13582    ) -> Option<AnyElement> {
13583        let folded = self.is_line_folded(buffer_row);
13584
13585        if let Some(crease) = self
13586            .crease_snapshot
13587            .query_row(buffer_row, &self.buffer_snapshot)
13588        {
13589            let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
13590                if folded {
13591                    editor.update(cx, |editor, cx| {
13592                        editor.fold_at(&crate::FoldAt { buffer_row }, cx)
13593                    });
13594                } else {
13595                    editor.update(cx, |editor, cx| {
13596                        editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
13597                    });
13598                }
13599            });
13600
13601            Some((crease.render_toggle)(
13602                buffer_row,
13603                folded,
13604                toggle_callback,
13605                cx,
13606            ))
13607        } else if folded
13608            || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
13609        {
13610            Some(
13611                Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
13612                    .selected(folded)
13613                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
13614                        if folded {
13615                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
13616                        } else {
13617                            this.fold_at(&FoldAt { buffer_row }, cx);
13618                        }
13619                    }))
13620                    .into_any_element(),
13621            )
13622        } else {
13623            None
13624        }
13625    }
13626
13627    pub fn render_crease_trailer(
13628        &self,
13629        buffer_row: MultiBufferRow,
13630        cx: &mut WindowContext,
13631    ) -> Option<AnyElement> {
13632        let folded = self.is_line_folded(buffer_row);
13633        let crease = self
13634            .crease_snapshot
13635            .query_row(buffer_row, &self.buffer_snapshot)?;
13636        Some((crease.render_trailer)(buffer_row, folded, cx))
13637    }
13638}
13639
13640impl Deref for EditorSnapshot {
13641    type Target = DisplaySnapshot;
13642
13643    fn deref(&self) -> &Self::Target {
13644        &self.display_snapshot
13645    }
13646}
13647
13648#[derive(Clone, Debug, PartialEq, Eq)]
13649pub enum EditorEvent {
13650    InputIgnored {
13651        text: Arc<str>,
13652    },
13653    InputHandled {
13654        utf16_range_to_replace: Option<Range<isize>>,
13655        text: Arc<str>,
13656    },
13657    ExcerptsAdded {
13658        buffer: Model<Buffer>,
13659        predecessor: ExcerptId,
13660        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
13661    },
13662    ExcerptsRemoved {
13663        ids: Vec<ExcerptId>,
13664    },
13665    ExcerptsEdited {
13666        ids: Vec<ExcerptId>,
13667    },
13668    ExcerptsExpanded {
13669        ids: Vec<ExcerptId>,
13670    },
13671    BufferEdited,
13672    Edited {
13673        transaction_id: clock::Lamport,
13674    },
13675    Reparsed(BufferId),
13676    Focused,
13677    FocusedIn,
13678    Blurred,
13679    DirtyChanged,
13680    Saved,
13681    TitleChanged,
13682    DiffBaseChanged,
13683    SelectionsChanged {
13684        local: bool,
13685    },
13686    ScrollPositionChanged {
13687        local: bool,
13688        autoscroll: bool,
13689    },
13690    Closed,
13691    TransactionUndone {
13692        transaction_id: clock::Lamport,
13693    },
13694    TransactionBegun {
13695        transaction_id: clock::Lamport,
13696    },
13697    Reloaded,
13698    CursorShapeChanged,
13699}
13700
13701impl EventEmitter<EditorEvent> for Editor {}
13702
13703impl FocusableView for Editor {
13704    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
13705        self.focus_handle.clone()
13706    }
13707}
13708
13709impl Render for Editor {
13710    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
13711        let settings = ThemeSettings::get_global(cx);
13712
13713        let mut text_style = match self.mode {
13714            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
13715                color: cx.theme().colors().editor_foreground,
13716                font_family: settings.ui_font.family.clone(),
13717                font_features: settings.ui_font.features.clone(),
13718                font_fallbacks: settings.ui_font.fallbacks.clone(),
13719                font_size: rems(0.875).into(),
13720                font_weight: settings.ui_font.weight,
13721                line_height: relative(settings.buffer_line_height.value()),
13722                ..Default::default()
13723            },
13724            EditorMode::Full => TextStyle {
13725                color: cx.theme().colors().editor_foreground,
13726                font_family: settings.buffer_font.family.clone(),
13727                font_features: settings.buffer_font.features.clone(),
13728                font_fallbacks: settings.buffer_font.fallbacks.clone(),
13729                font_size: settings.buffer_font_size(cx).into(),
13730                font_weight: settings.buffer_font.weight,
13731                line_height: relative(settings.buffer_line_height.value()),
13732                ..Default::default()
13733            },
13734        };
13735        if let Some(text_style_refinement) = &self.text_style_refinement {
13736            text_style.refine(text_style_refinement)
13737        }
13738
13739        let background = match self.mode {
13740            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
13741            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
13742            EditorMode::Full => cx.theme().colors().editor_background,
13743        };
13744
13745        EditorElement::new(
13746            cx.view(),
13747            EditorStyle {
13748                background,
13749                local_player: cx.theme().players().local(),
13750                text: text_style,
13751                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
13752                syntax: cx.theme().syntax().clone(),
13753                status: cx.theme().status().clone(),
13754                inlay_hints_style: make_inlay_hints_style(cx),
13755                suggestions_style: HighlightStyle {
13756                    color: Some(cx.theme().status().predictive),
13757                    ..HighlightStyle::default()
13758                },
13759                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
13760            },
13761        )
13762    }
13763}
13764
13765impl ViewInputHandler for Editor {
13766    fn text_for_range(
13767        &mut self,
13768        range_utf16: Range<usize>,
13769        cx: &mut ViewContext<Self>,
13770    ) -> Option<String> {
13771        Some(
13772            self.buffer
13773                .read(cx)
13774                .read(cx)
13775                .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
13776                .collect(),
13777        )
13778    }
13779
13780    fn selected_text_range(
13781        &mut self,
13782        ignore_disabled_input: bool,
13783        cx: &mut ViewContext<Self>,
13784    ) -> Option<UTF16Selection> {
13785        // Prevent the IME menu from appearing when holding down an alphabetic key
13786        // while input is disabled.
13787        if !ignore_disabled_input && !self.input_enabled {
13788            return None;
13789        }
13790
13791        let selection = self.selections.newest::<OffsetUtf16>(cx);
13792        let range = selection.range();
13793
13794        Some(UTF16Selection {
13795            range: range.start.0..range.end.0,
13796            reversed: selection.reversed,
13797        })
13798    }
13799
13800    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
13801        let snapshot = self.buffer.read(cx).read(cx);
13802        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
13803        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
13804    }
13805
13806    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
13807        self.clear_highlights::<InputComposition>(cx);
13808        self.ime_transaction.take();
13809    }
13810
13811    fn replace_text_in_range(
13812        &mut self,
13813        range_utf16: Option<Range<usize>>,
13814        text: &str,
13815        cx: &mut ViewContext<Self>,
13816    ) {
13817        if !self.input_enabled {
13818            cx.emit(EditorEvent::InputIgnored { text: text.into() });
13819            return;
13820        }
13821
13822        self.transact(cx, |this, cx| {
13823            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
13824                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13825                Some(this.selection_replacement_ranges(range_utf16, cx))
13826            } else {
13827                this.marked_text_ranges(cx)
13828            };
13829
13830            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
13831                let newest_selection_id = this.selections.newest_anchor().id;
13832                this.selections
13833                    .all::<OffsetUtf16>(cx)
13834                    .iter()
13835                    .zip(ranges_to_replace.iter())
13836                    .find_map(|(selection, range)| {
13837                        if selection.id == newest_selection_id {
13838                            Some(
13839                                (range.start.0 as isize - selection.head().0 as isize)
13840                                    ..(range.end.0 as isize - selection.head().0 as isize),
13841                            )
13842                        } else {
13843                            None
13844                        }
13845                    })
13846            });
13847
13848            cx.emit(EditorEvent::InputHandled {
13849                utf16_range_to_replace: range_to_replace,
13850                text: text.into(),
13851            });
13852
13853            if let Some(new_selected_ranges) = new_selected_ranges {
13854                this.change_selections(None, cx, |selections| {
13855                    selections.select_ranges(new_selected_ranges)
13856                });
13857                this.backspace(&Default::default(), cx);
13858            }
13859
13860            this.handle_input(text, cx);
13861        });
13862
13863        if let Some(transaction) = self.ime_transaction {
13864            self.buffer.update(cx, |buffer, cx| {
13865                buffer.group_until_transaction(transaction, cx);
13866            });
13867        }
13868
13869        self.unmark_text(cx);
13870    }
13871
13872    fn replace_and_mark_text_in_range(
13873        &mut self,
13874        range_utf16: Option<Range<usize>>,
13875        text: &str,
13876        new_selected_range_utf16: Option<Range<usize>>,
13877        cx: &mut ViewContext<Self>,
13878    ) {
13879        if !self.input_enabled {
13880            return;
13881        }
13882
13883        let transaction = self.transact(cx, |this, cx| {
13884            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
13885                let snapshot = this.buffer.read(cx).read(cx);
13886                if let Some(relative_range_utf16) = range_utf16.as_ref() {
13887                    for marked_range in &mut marked_ranges {
13888                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
13889                        marked_range.start.0 += relative_range_utf16.start;
13890                        marked_range.start =
13891                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
13892                        marked_range.end =
13893                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
13894                    }
13895                }
13896                Some(marked_ranges)
13897            } else if let Some(range_utf16) = range_utf16 {
13898                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13899                Some(this.selection_replacement_ranges(range_utf16, cx))
13900            } else {
13901                None
13902            };
13903
13904            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
13905                let newest_selection_id = this.selections.newest_anchor().id;
13906                this.selections
13907                    .all::<OffsetUtf16>(cx)
13908                    .iter()
13909                    .zip(ranges_to_replace.iter())
13910                    .find_map(|(selection, range)| {
13911                        if selection.id == newest_selection_id {
13912                            Some(
13913                                (range.start.0 as isize - selection.head().0 as isize)
13914                                    ..(range.end.0 as isize - selection.head().0 as isize),
13915                            )
13916                        } else {
13917                            None
13918                        }
13919                    })
13920            });
13921
13922            cx.emit(EditorEvent::InputHandled {
13923                utf16_range_to_replace: range_to_replace,
13924                text: text.into(),
13925            });
13926
13927            if let Some(ranges) = ranges_to_replace {
13928                this.change_selections(None, cx, |s| s.select_ranges(ranges));
13929            }
13930
13931            let marked_ranges = {
13932                let snapshot = this.buffer.read(cx).read(cx);
13933                this.selections
13934                    .disjoint_anchors()
13935                    .iter()
13936                    .map(|selection| {
13937                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
13938                    })
13939                    .collect::<Vec<_>>()
13940            };
13941
13942            if text.is_empty() {
13943                this.unmark_text(cx);
13944            } else {
13945                this.highlight_text::<InputComposition>(
13946                    marked_ranges.clone(),
13947                    HighlightStyle {
13948                        underline: Some(UnderlineStyle {
13949                            thickness: px(1.),
13950                            color: None,
13951                            wavy: false,
13952                        }),
13953                        ..Default::default()
13954                    },
13955                    cx,
13956                );
13957            }
13958
13959            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
13960            let use_autoclose = this.use_autoclose;
13961            let use_auto_surround = this.use_auto_surround;
13962            this.set_use_autoclose(false);
13963            this.set_use_auto_surround(false);
13964            this.handle_input(text, cx);
13965            this.set_use_autoclose(use_autoclose);
13966            this.set_use_auto_surround(use_auto_surround);
13967
13968            if let Some(new_selected_range) = new_selected_range_utf16 {
13969                let snapshot = this.buffer.read(cx).read(cx);
13970                let new_selected_ranges = marked_ranges
13971                    .into_iter()
13972                    .map(|marked_range| {
13973                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
13974                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
13975                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
13976                        snapshot.clip_offset_utf16(new_start, Bias::Left)
13977                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
13978                    })
13979                    .collect::<Vec<_>>();
13980
13981                drop(snapshot);
13982                this.change_selections(None, cx, |selections| {
13983                    selections.select_ranges(new_selected_ranges)
13984                });
13985            }
13986        });
13987
13988        self.ime_transaction = self.ime_transaction.or(transaction);
13989        if let Some(transaction) = self.ime_transaction {
13990            self.buffer.update(cx, |buffer, cx| {
13991                buffer.group_until_transaction(transaction, cx);
13992            });
13993        }
13994
13995        if self.text_highlights::<InputComposition>(cx).is_none() {
13996            self.ime_transaction.take();
13997        }
13998    }
13999
14000    fn bounds_for_range(
14001        &mut self,
14002        range_utf16: Range<usize>,
14003        element_bounds: gpui::Bounds<Pixels>,
14004        cx: &mut ViewContext<Self>,
14005    ) -> Option<gpui::Bounds<Pixels>> {
14006        let text_layout_details = self.text_layout_details(cx);
14007        let style = &text_layout_details.editor_style;
14008        let font_id = cx.text_system().resolve_font(&style.text.font());
14009        let font_size = style.text.font_size.to_pixels(cx.rem_size());
14010        let line_height = style.text.line_height_in_pixels(cx.rem_size());
14011
14012        let em_width = cx
14013            .text_system()
14014            .typographic_bounds(font_id, font_size, 'm')
14015            .unwrap()
14016            .size
14017            .width;
14018
14019        let snapshot = self.snapshot(cx);
14020        let scroll_position = snapshot.scroll_position();
14021        let scroll_left = scroll_position.x * em_width;
14022
14023        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14024        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14025            + self.gutter_dimensions.width;
14026        let y = line_height * (start.row().as_f32() - scroll_position.y);
14027
14028        Some(Bounds {
14029            origin: element_bounds.origin + point(x, y),
14030            size: size(em_width, line_height),
14031        })
14032    }
14033}
14034
14035trait SelectionExt {
14036    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14037    fn spanned_rows(
14038        &self,
14039        include_end_if_at_line_start: bool,
14040        map: &DisplaySnapshot,
14041    ) -> Range<MultiBufferRow>;
14042}
14043
14044impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14045    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14046        let start = self
14047            .start
14048            .to_point(&map.buffer_snapshot)
14049            .to_display_point(map);
14050        let end = self
14051            .end
14052            .to_point(&map.buffer_snapshot)
14053            .to_display_point(map);
14054        if self.reversed {
14055            end..start
14056        } else {
14057            start..end
14058        }
14059    }
14060
14061    fn spanned_rows(
14062        &self,
14063        include_end_if_at_line_start: bool,
14064        map: &DisplaySnapshot,
14065    ) -> Range<MultiBufferRow> {
14066        let start = self.start.to_point(&map.buffer_snapshot);
14067        let mut end = self.end.to_point(&map.buffer_snapshot);
14068        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14069            end.row -= 1;
14070        }
14071
14072        let buffer_start = map.prev_line_boundary(start).0;
14073        let buffer_end = map.next_line_boundary(end).0;
14074        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14075    }
14076}
14077
14078impl<T: InvalidationRegion> InvalidationStack<T> {
14079    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14080    where
14081        S: Clone + ToOffset,
14082    {
14083        while let Some(region) = self.last() {
14084            let all_selections_inside_invalidation_ranges =
14085                if selections.len() == region.ranges().len() {
14086                    selections
14087                        .iter()
14088                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14089                        .all(|(selection, invalidation_range)| {
14090                            let head = selection.head().to_offset(buffer);
14091                            invalidation_range.start <= head && invalidation_range.end >= head
14092                        })
14093                } else {
14094                    false
14095                };
14096
14097            if all_selections_inside_invalidation_ranges {
14098                break;
14099            } else {
14100                self.pop();
14101            }
14102        }
14103    }
14104}
14105
14106impl<T> Default for InvalidationStack<T> {
14107    fn default() -> Self {
14108        Self(Default::default())
14109    }
14110}
14111
14112impl<T> Deref for InvalidationStack<T> {
14113    type Target = Vec<T>;
14114
14115    fn deref(&self) -> &Self::Target {
14116        &self.0
14117    }
14118}
14119
14120impl<T> DerefMut for InvalidationStack<T> {
14121    fn deref_mut(&mut self) -> &mut Self::Target {
14122        &mut self.0
14123    }
14124}
14125
14126impl InvalidationRegion for SnippetState {
14127    fn ranges(&self) -> &[Range<Anchor>] {
14128        &self.ranges[self.active_index]
14129    }
14130}
14131
14132pub fn diagnostic_block_renderer(
14133    diagnostic: Diagnostic,
14134    max_message_rows: Option<u8>,
14135    allow_closing: bool,
14136    _is_valid: bool,
14137) -> RenderBlock {
14138    let (text_without_backticks, code_ranges) =
14139        highlight_diagnostic_message(&diagnostic, max_message_rows);
14140
14141    Box::new(move |cx: &mut BlockContext| {
14142        let group_id: SharedString = cx.block_id.to_string().into();
14143
14144        let mut text_style = cx.text_style().clone();
14145        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14146        let theme_settings = ThemeSettings::get_global(cx);
14147        text_style.font_family = theme_settings.buffer_font.family.clone();
14148        text_style.font_style = theme_settings.buffer_font.style;
14149        text_style.font_features = theme_settings.buffer_font.features.clone();
14150        text_style.font_weight = theme_settings.buffer_font.weight;
14151
14152        let multi_line_diagnostic = diagnostic.message.contains('\n');
14153
14154        let buttons = |diagnostic: &Diagnostic| {
14155            if multi_line_diagnostic {
14156                v_flex()
14157            } else {
14158                h_flex()
14159            }
14160            .when(allow_closing, |div| {
14161                div.children(diagnostic.is_primary.then(|| {
14162                    IconButton::new("close-block", IconName::XCircle)
14163                        .icon_color(Color::Muted)
14164                        .size(ButtonSize::Compact)
14165                        .style(ButtonStyle::Transparent)
14166                        .visible_on_hover(group_id.clone())
14167                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14168                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14169                }))
14170            })
14171            .child(
14172                IconButton::new("copy-block", IconName::Copy)
14173                    .icon_color(Color::Muted)
14174                    .size(ButtonSize::Compact)
14175                    .style(ButtonStyle::Transparent)
14176                    .visible_on_hover(group_id.clone())
14177                    .on_click({
14178                        let message = diagnostic.message.clone();
14179                        move |_click, cx| {
14180                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14181                        }
14182                    })
14183                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14184            )
14185        };
14186
14187        let icon_size = buttons(&diagnostic)
14188            .into_any_element()
14189            .layout_as_root(AvailableSpace::min_size(), cx);
14190
14191        h_flex()
14192            .id(cx.block_id)
14193            .group(group_id.clone())
14194            .relative()
14195            .size_full()
14196            .pl(cx.gutter_dimensions.width)
14197            .w(cx.max_width + cx.gutter_dimensions.width)
14198            .child(
14199                div()
14200                    .flex()
14201                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14202                    .flex_shrink(),
14203            )
14204            .child(buttons(&diagnostic))
14205            .child(div().flex().flex_shrink_0().child(
14206                StyledText::new(text_without_backticks.clone()).with_highlights(
14207                    &text_style,
14208                    code_ranges.iter().map(|range| {
14209                        (
14210                            range.clone(),
14211                            HighlightStyle {
14212                                font_weight: Some(FontWeight::BOLD),
14213                                ..Default::default()
14214                            },
14215                        )
14216                    }),
14217                ),
14218            ))
14219            .into_any_element()
14220    })
14221}
14222
14223pub fn highlight_diagnostic_message(
14224    diagnostic: &Diagnostic,
14225    mut max_message_rows: Option<u8>,
14226) -> (SharedString, Vec<Range<usize>>) {
14227    let mut text_without_backticks = String::new();
14228    let mut code_ranges = Vec::new();
14229
14230    if let Some(source) = &diagnostic.source {
14231        text_without_backticks.push_str(source);
14232        code_ranges.push(0..source.len());
14233        text_without_backticks.push_str(": ");
14234    }
14235
14236    let mut prev_offset = 0;
14237    let mut in_code_block = false;
14238    let has_row_limit = max_message_rows.is_some();
14239    let mut newline_indices = diagnostic
14240        .message
14241        .match_indices('\n')
14242        .filter(|_| has_row_limit)
14243        .map(|(ix, _)| ix)
14244        .fuse()
14245        .peekable();
14246
14247    for (quote_ix, _) in diagnostic
14248        .message
14249        .match_indices('`')
14250        .chain([(diagnostic.message.len(), "")])
14251    {
14252        let mut first_newline_ix = None;
14253        let mut last_newline_ix = None;
14254        while let Some(newline_ix) = newline_indices.peek() {
14255            if *newline_ix < quote_ix {
14256                if first_newline_ix.is_none() {
14257                    first_newline_ix = Some(*newline_ix);
14258                }
14259                last_newline_ix = Some(*newline_ix);
14260
14261                if let Some(rows_left) = &mut max_message_rows {
14262                    if *rows_left == 0 {
14263                        break;
14264                    } else {
14265                        *rows_left -= 1;
14266                    }
14267                }
14268                let _ = newline_indices.next();
14269            } else {
14270                break;
14271            }
14272        }
14273        let prev_len = text_without_backticks.len();
14274        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14275        text_without_backticks.push_str(new_text);
14276        if in_code_block {
14277            code_ranges.push(prev_len..text_without_backticks.len());
14278        }
14279        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14280        in_code_block = !in_code_block;
14281        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14282            text_without_backticks.push_str("...");
14283            break;
14284        }
14285    }
14286
14287    (text_without_backticks.into(), code_ranges)
14288}
14289
14290fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14291    match severity {
14292        DiagnosticSeverity::ERROR => colors.error,
14293        DiagnosticSeverity::WARNING => colors.warning,
14294        DiagnosticSeverity::INFORMATION => colors.info,
14295        DiagnosticSeverity::HINT => colors.info,
14296        _ => colors.ignored,
14297    }
14298}
14299
14300pub fn styled_runs_for_code_label<'a>(
14301    label: &'a CodeLabel,
14302    syntax_theme: &'a theme::SyntaxTheme,
14303) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14304    let fade_out = HighlightStyle {
14305        fade_out: Some(0.35),
14306        ..Default::default()
14307    };
14308
14309    let mut prev_end = label.filter_range.end;
14310    label
14311        .runs
14312        .iter()
14313        .enumerate()
14314        .flat_map(move |(ix, (range, highlight_id))| {
14315            let style = if let Some(style) = highlight_id.style(syntax_theme) {
14316                style
14317            } else {
14318                return Default::default();
14319            };
14320            let mut muted_style = style;
14321            muted_style.highlight(fade_out);
14322
14323            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14324            if range.start >= label.filter_range.end {
14325                if range.start > prev_end {
14326                    runs.push((prev_end..range.start, fade_out));
14327                }
14328                runs.push((range.clone(), muted_style));
14329            } else if range.end <= label.filter_range.end {
14330                runs.push((range.clone(), style));
14331            } else {
14332                runs.push((range.start..label.filter_range.end, style));
14333                runs.push((label.filter_range.end..range.end, muted_style));
14334            }
14335            prev_end = cmp::max(prev_end, range.end);
14336
14337            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14338                runs.push((prev_end..label.text.len(), fade_out));
14339            }
14340
14341            runs
14342        })
14343}
14344
14345pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14346    let mut prev_index = 0;
14347    let mut prev_codepoint: Option<char> = None;
14348    text.char_indices()
14349        .chain([(text.len(), '\0')])
14350        .filter_map(move |(index, codepoint)| {
14351            let prev_codepoint = prev_codepoint.replace(codepoint)?;
14352            let is_boundary = index == text.len()
14353                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14354                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14355            if is_boundary {
14356                let chunk = &text[prev_index..index];
14357                prev_index = index;
14358                Some(chunk)
14359            } else {
14360                None
14361            }
14362        })
14363}
14364
14365pub trait RangeToAnchorExt: Sized {
14366    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14367
14368    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14369        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14370        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14371    }
14372}
14373
14374impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14375    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14376        let start_offset = self.start.to_offset(snapshot);
14377        let end_offset = self.end.to_offset(snapshot);
14378        if start_offset == end_offset {
14379            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14380        } else {
14381            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14382        }
14383    }
14384}
14385
14386pub trait RowExt {
14387    fn as_f32(&self) -> f32;
14388
14389    fn next_row(&self) -> Self;
14390
14391    fn previous_row(&self) -> Self;
14392
14393    fn minus(&self, other: Self) -> u32;
14394}
14395
14396impl RowExt for DisplayRow {
14397    fn as_f32(&self) -> f32 {
14398        self.0 as f32
14399    }
14400
14401    fn next_row(&self) -> Self {
14402        Self(self.0 + 1)
14403    }
14404
14405    fn previous_row(&self) -> Self {
14406        Self(self.0.saturating_sub(1))
14407    }
14408
14409    fn minus(&self, other: Self) -> u32 {
14410        self.0 - other.0
14411    }
14412}
14413
14414impl RowExt for MultiBufferRow {
14415    fn as_f32(&self) -> f32 {
14416        self.0 as f32
14417    }
14418
14419    fn next_row(&self) -> Self {
14420        Self(self.0 + 1)
14421    }
14422
14423    fn previous_row(&self) -> Self {
14424        Self(self.0.saturating_sub(1))
14425    }
14426
14427    fn minus(&self, other: Self) -> u32 {
14428        self.0 - other.0
14429    }
14430}
14431
14432trait RowRangeExt {
14433    type Row;
14434
14435    fn len(&self) -> usize;
14436
14437    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
14438}
14439
14440impl RowRangeExt for Range<MultiBufferRow> {
14441    type Row = MultiBufferRow;
14442
14443    fn len(&self) -> usize {
14444        (self.end.0 - self.start.0) as usize
14445    }
14446
14447    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
14448        (self.start.0..self.end.0).map(MultiBufferRow)
14449    }
14450}
14451
14452impl RowRangeExt for Range<DisplayRow> {
14453    type Row = DisplayRow;
14454
14455    fn len(&self) -> usize {
14456        (self.end.0 - self.start.0) as usize
14457    }
14458
14459    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
14460        (self.start.0..self.end.0).map(DisplayRow)
14461    }
14462}
14463
14464fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
14465    if hunk.diff_base_byte_range.is_empty() {
14466        DiffHunkStatus::Added
14467    } else if hunk.row_range.is_empty() {
14468        DiffHunkStatus::Removed
14469    } else {
14470        DiffHunkStatus::Modified
14471    }
14472}
14473
14474/// If select range has more than one line, we
14475/// just point the cursor to range.start.
14476fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
14477    if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
14478        range
14479    } else {
14480        range.start..range.start
14481    }
14482}