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;
   31pub mod items;
   32mod linked_editing_ranges;
   33mod lsp_ext;
   34mod mouse_context_menu;
   35pub mod movement;
   36mod persistence;
   37mod proposed_changes_editor;
   38mod rust_analyzer_ext;
   39pub mod scroll;
   40mod selections_collection;
   41pub mod tasks;
   42
   43#[cfg(test)]
   44mod editor_tests;
   45mod signature_help;
   46#[cfg(any(test, feature = "test-support"))]
   47pub mod test;
   48
   49use ::git::diff::DiffHunkStatus;
   50pub(crate) use actions::*;
   51pub use actions::{OpenExcerpts, OpenExcerptsSplit};
   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, Global, HighlightStyle, Hsla, InteractiveText, KeyContext,
   78    ListSizingBehavior, Model, ModelContext, MouseButton, PaintQuad, ParentElement, Pixels, Render,
   79    ScrollStrategy, SharedString, Size, StrikethroughStyle, Styled, StyledText, Subscription, Task,
   80    TextStyle, 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::Direction;
   90use inline_completion::{InlayProposal, InlineCompletionProvider, InlineCompletionProviderHandle};
   91pub use items::MAX_TAB_TITLE_LEN;
   92use itertools::Itertools;
   93use language::{
   94    language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
   95    markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
   96    CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
   97    Point, Selection, SelectionGoal, TransactionId,
   98};
   99use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
  100use linked_editing_ranges::refresh_linked_ranges;
  101pub use proposed_changes_editor::{
  102    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesToolbar,
  103    ProposedChangesToolbarControls,
  104};
  105use similar::{ChangeTag, TextDiff};
  106use std::iter::Peekable;
  107use task::{ResolvedTask, TaskTemplate, TaskVariables};
  108
  109use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  110pub use lsp::CompletionContext;
  111use lsp::{
  112    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  113    LanguageServerId, LanguageServerName,
  114};
  115use mouse_context_menu::MouseContextMenu;
  116use movement::TextLayoutDetails;
  117pub use multi_buffer::{
  118    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
  119    ToPoint,
  120};
  121use multi_buffer::{
  122    ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
  123};
  124use ordered_float::OrderedFloat;
  125use parking_lot::{Mutex, RwLock};
  126use project::{
  127    lsp_store::{FormatTarget, FormatTrigger},
  128    project_settings::{GitGutterSetting, ProjectSettings},
  129    CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Item, Location,
  130    LocationLink, Project, ProjectTransaction, TaskSourceKind,
  131};
  132use rand::prelude::*;
  133use rpc::{proto::*, ErrorExt};
  134use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  135use selections_collection::{
  136    resolve_selections, MutableSelectionsCollection, SelectionsCollection,
  137};
  138use serde::{Deserialize, Serialize};
  139use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  140use smallvec::SmallVec;
  141use snippet::Snippet;
  142use std::{
  143    any::TypeId,
  144    borrow::Cow,
  145    cell::RefCell,
  146    cmp::{self, Ordering, Reverse},
  147    mem,
  148    num::NonZeroU32,
  149    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  150    path::{Path, PathBuf},
  151    rc::Rc,
  152    sync::Arc,
  153    time::{Duration, Instant},
  154};
  155pub use sum_tree::Bias;
  156use sum_tree::TreeMap;
  157use text::{BufferId, OffsetUtf16, Rope};
  158use theme::{
  159    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  160    ThemeColors, ThemeSettings,
  161};
  162use ui::{
  163    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
  164    ListItem, Popover, Tooltip,
  165};
  166use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  167use workspace::item::{ItemHandle, PreviewTabsSettings};
  168use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
  169use workspace::{
  170    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  171};
  172use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  173
  174use crate::hover_links::find_url;
  175use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  176
  177pub const FILE_HEADER_HEIGHT: u32 = 2;
  178pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  179pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  180pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  181const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  182const MAX_LINE_LEN: usize = 1024;
  183const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  184const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  185pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  186#[doc(hidden)]
  187pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  188#[doc(hidden)]
  189pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
  190
  191pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  192pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  193
  194pub fn render_parsed_markdown(
  195    element_id: impl Into<ElementId>,
  196    parsed: &language::ParsedMarkdown,
  197    editor_style: &EditorStyle,
  198    workspace: Option<WeakView<Workspace>>,
  199    cx: &mut WindowContext,
  200) -> InteractiveText {
  201    let code_span_background_color = cx
  202        .theme()
  203        .colors()
  204        .editor_document_highlight_read_background;
  205
  206    let highlights = gpui::combine_highlights(
  207        parsed.highlights.iter().filter_map(|(range, highlight)| {
  208            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  209            Some((range.clone(), highlight))
  210        }),
  211        parsed
  212            .regions
  213            .iter()
  214            .zip(&parsed.region_ranges)
  215            .filter_map(|(region, range)| {
  216                if region.code {
  217                    Some((
  218                        range.clone(),
  219                        HighlightStyle {
  220                            background_color: Some(code_span_background_color),
  221                            ..Default::default()
  222                        },
  223                    ))
  224                } else {
  225                    None
  226                }
  227            }),
  228    );
  229
  230    let mut links = Vec::new();
  231    let mut link_ranges = Vec::new();
  232    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  233        if let Some(link) = region.link.clone() {
  234            links.push(link);
  235            link_ranges.push(range.clone());
  236        }
  237    }
  238
  239    InteractiveText::new(
  240        element_id,
  241        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  242    )
  243    .on_click(link_ranges, move |clicked_range_ix, cx| {
  244        match &links[clicked_range_ix] {
  245            markdown::Link::Web { url } => cx.open_url(url),
  246            markdown::Link::Path { path } => {
  247                if let Some(workspace) = &workspace {
  248                    _ = workspace.update(cx, |workspace, cx| {
  249                        workspace.open_abs_path(path.clone(), false, cx).detach();
  250                    });
  251                }
  252            }
  253        }
  254    })
  255}
  256
  257#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  258pub(crate) enum InlayId {
  259    Suggestion(usize),
  260    Hint(usize),
  261}
  262
  263impl InlayId {
  264    fn id(&self) -> usize {
  265        match self {
  266            Self::Suggestion(id) => *id,
  267            Self::Hint(id) => *id,
  268        }
  269    }
  270}
  271
  272enum DiffRowHighlight {}
  273enum DocumentHighlightRead {}
  274enum DocumentHighlightWrite {}
  275enum InputComposition {}
  276
  277#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  278pub enum Navigated {
  279    Yes,
  280    No,
  281}
  282
  283impl Navigated {
  284    pub fn from_bool(yes: bool) -> Navigated {
  285        if yes {
  286            Navigated::Yes
  287        } else {
  288            Navigated::No
  289        }
  290    }
  291}
  292
  293pub fn init_settings(cx: &mut AppContext) {
  294    EditorSettings::register(cx);
  295}
  296
  297pub fn init(cx: &mut AppContext) {
  298    init_settings(cx);
  299
  300    workspace::register_project_item::<Editor>(cx);
  301    workspace::FollowableViewRegistry::register::<Editor>(cx);
  302    workspace::register_serializable_item::<Editor>(cx);
  303
  304    cx.observe_new_views(
  305        |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
  306            workspace.register_action(Editor::new_file);
  307            workspace.register_action(Editor::new_file_vertical);
  308            workspace.register_action(Editor::new_file_horizontal);
  309        },
  310    )
  311    .detach();
  312
  313    cx.on_action(move |_: &workspace::NewFile, cx| {
  314        let app_state = workspace::AppState::global(cx);
  315        if let Some(app_state) = app_state.upgrade() {
  316            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  317                Editor::new_file(workspace, &Default::default(), cx)
  318            })
  319            .detach();
  320        }
  321    });
  322    cx.on_action(move |_: &workspace::NewWindow, cx| {
  323        let app_state = workspace::AppState::global(cx);
  324        if let Some(app_state) = app_state.upgrade() {
  325            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  326                Editor::new_file(workspace, &Default::default(), cx)
  327            })
  328            .detach();
  329        }
  330    });
  331}
  332
  333pub struct SearchWithinRange;
  334
  335trait InvalidationRegion {
  336    fn ranges(&self) -> &[Range<Anchor>];
  337}
  338
  339#[derive(Clone, Debug, PartialEq)]
  340pub enum SelectPhase {
  341    Begin {
  342        position: DisplayPoint,
  343        add: bool,
  344        click_count: usize,
  345    },
  346    BeginColumnar {
  347        position: DisplayPoint,
  348        reset: bool,
  349        goal_column: u32,
  350    },
  351    Extend {
  352        position: DisplayPoint,
  353        click_count: usize,
  354    },
  355    Update {
  356        position: DisplayPoint,
  357        goal_column: u32,
  358        scroll_delta: gpui::Point<f32>,
  359    },
  360    End,
  361}
  362
  363#[derive(Clone, Debug)]
  364pub enum SelectMode {
  365    Character,
  366    Word(Range<Anchor>),
  367    Line(Range<Anchor>),
  368    All,
  369}
  370
  371#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  372pub enum EditorMode {
  373    SingleLine { auto_width: bool },
  374    AutoHeight { max_lines: usize },
  375    Full,
  376}
  377
  378#[derive(Copy, Clone, Debug)]
  379pub enum SoftWrap {
  380    /// Prefer not to wrap at all.
  381    ///
  382    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  383    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  384    GitDiff,
  385    /// Prefer a single line generally, unless an overly long line is encountered.
  386    None,
  387    /// Soft wrap lines that exceed the editor width.
  388    EditorWidth,
  389    /// Soft wrap lines at the preferred line length.
  390    Column(u32),
  391    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  392    Bounded(u32),
  393}
  394
  395#[derive(Clone)]
  396pub struct EditorStyle {
  397    pub background: Hsla,
  398    pub local_player: PlayerColor,
  399    pub text: TextStyle,
  400    pub scrollbar_width: Pixels,
  401    pub syntax: Arc<SyntaxTheme>,
  402    pub status: StatusColors,
  403    pub inlay_hints_style: HighlightStyle,
  404    pub suggestions_style: HighlightStyle,
  405    pub unnecessary_code_fade: f32,
  406}
  407
  408impl Default for EditorStyle {
  409    fn default() -> Self {
  410        Self {
  411            background: Hsla::default(),
  412            local_player: PlayerColor::default(),
  413            text: TextStyle::default(),
  414            scrollbar_width: Pixels::default(),
  415            syntax: Default::default(),
  416            // HACK: Status colors don't have a real default.
  417            // We should look into removing the status colors from the editor
  418            // style and retrieve them directly from the theme.
  419            status: StatusColors::dark(),
  420            inlay_hints_style: HighlightStyle::default(),
  421            suggestions_style: HighlightStyle::default(),
  422            unnecessary_code_fade: Default::default(),
  423        }
  424    }
  425}
  426
  427pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
  428    let show_background = language_settings::language_settings(None, None, cx)
  429        .inlay_hints
  430        .show_background;
  431
  432    HighlightStyle {
  433        color: Some(cx.theme().status().hint),
  434        background_color: show_background.then(|| cx.theme().status().hint_background),
  435        ..HighlightStyle::default()
  436    }
  437}
  438
  439type CompletionId = usize;
  440
  441#[derive(Clone, Debug)]
  442struct CompletionState {
  443    // render_inlay_ids represents the inlay hints that are inserted
  444    // for rendering the inline completions. They may be discontinuous
  445    // in the event that the completion provider returns some intersection
  446    // with the existing content.
  447    render_inlay_ids: Vec<InlayId>,
  448    // text is the resulting rope that is inserted when the user accepts a completion.
  449    text: Rope,
  450    // position is the position of the cursor when the completion was triggered.
  451    position: multi_buffer::Anchor,
  452    // delete_range is the range of text that this completion state covers.
  453    // if the completion is accepted, this range should be deleted.
  454    delete_range: Option<Range<multi_buffer::Anchor>>,
  455}
  456
  457#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  458struct EditorActionId(usize);
  459
  460impl EditorActionId {
  461    pub fn post_inc(&mut self) -> Self {
  462        let answer = self.0;
  463
  464        *self = Self(answer + 1);
  465
  466        Self(answer)
  467    }
  468}
  469
  470// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  471// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  472
  473type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  474type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
  475
  476#[derive(Default)]
  477struct ScrollbarMarkerState {
  478    scrollbar_size: Size<Pixels>,
  479    dirty: bool,
  480    markers: Arc<[PaintQuad]>,
  481    pending_refresh: Option<Task<Result<()>>>,
  482}
  483
  484impl ScrollbarMarkerState {
  485    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  486        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  487    }
  488}
  489
  490#[derive(Clone, Debug)]
  491struct RunnableTasks {
  492    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  493    offset: MultiBufferOffset,
  494    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  495    column: u32,
  496    // Values of all named captures, including those starting with '_'
  497    extra_variables: HashMap<String, String>,
  498    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  499    context_range: Range<BufferOffset>,
  500}
  501
  502impl RunnableTasks {
  503    fn resolve<'a>(
  504        &'a self,
  505        cx: &'a task::TaskContext,
  506    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  507        self.templates.iter().filter_map(|(kind, template)| {
  508            template
  509                .resolve_task(&kind.to_id_base(), cx)
  510                .map(|task| (kind.clone(), task))
  511        })
  512    }
  513}
  514
  515#[derive(Clone)]
  516struct ResolvedTasks {
  517    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  518    position: Anchor,
  519}
  520#[derive(Copy, Clone, Debug)]
  521struct MultiBufferOffset(usize);
  522#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  523struct BufferOffset(usize);
  524
  525// Addons allow storing per-editor state in other crates (e.g. Vim)
  526pub trait Addon: 'static {
  527    fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
  528
  529    fn to_any(&self) -> &dyn std::any::Any;
  530}
  531
  532#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  533pub enum IsVimMode {
  534    Yes,
  535    No,
  536}
  537
  538/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
  539///
  540/// See the [module level documentation](self) for more information.
  541pub struct Editor {
  542    focus_handle: FocusHandle,
  543    last_focused_descendant: Option<WeakFocusHandle>,
  544    /// The text buffer being edited
  545    buffer: Model<MultiBuffer>,
  546    /// Map of how text in the buffer should be displayed.
  547    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  548    pub display_map: Model<DisplayMap>,
  549    pub selections: SelectionsCollection,
  550    pub scroll_manager: ScrollManager,
  551    /// When inline assist editors are linked, they all render cursors because
  552    /// typing enters text into each of them, even the ones that aren't focused.
  553    pub(crate) show_cursor_when_unfocused: bool,
  554    columnar_selection_tail: Option<Anchor>,
  555    add_selections_state: Option<AddSelectionsState>,
  556    select_next_state: Option<SelectNextState>,
  557    select_prev_state: Option<SelectNextState>,
  558    selection_history: SelectionHistory,
  559    autoclose_regions: Vec<AutocloseRegion>,
  560    snippet_stack: InvalidationStack<SnippetState>,
  561    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  562    ime_transaction: Option<TransactionId>,
  563    active_diagnostics: Option<ActiveDiagnosticGroup>,
  564    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  565
  566    project: Option<Model<Project>>,
  567    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  568    completion_provider: Option<Box<dyn CompletionProvider>>,
  569    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  570    blink_manager: Model<BlinkManager>,
  571    show_cursor_names: bool,
  572    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  573    pub show_local_selections: bool,
  574    mode: EditorMode,
  575    show_breadcrumbs: bool,
  576    show_gutter: bool,
  577    show_line_numbers: Option<bool>,
  578    use_relative_line_numbers: Option<bool>,
  579    show_git_diff_gutter: Option<bool>,
  580    show_code_actions: Option<bool>,
  581    show_runnables: Option<bool>,
  582    show_wrap_guides: Option<bool>,
  583    show_indent_guides: Option<bool>,
  584    placeholder_text: Option<Arc<str>>,
  585    highlight_order: usize,
  586    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  587    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  588    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  589    scrollbar_marker_state: ScrollbarMarkerState,
  590    active_indent_guides_state: ActiveIndentGuidesState,
  591    nav_history: Option<ItemNavHistory>,
  592    context_menu: RwLock<Option<ContextMenu>>,
  593    mouse_context_menu: Option<MouseContextMenu>,
  594    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  595    signature_help_state: SignatureHelpState,
  596    auto_signature_help: Option<bool>,
  597    find_all_references_task_sources: Vec<Anchor>,
  598    next_completion_id: CompletionId,
  599    completion_documentation_pre_resolve_debounce: DebouncedDelay,
  600    available_code_actions: Option<(Location, Arc<[AvailableCodeAction]>)>,
  601    code_actions_task: Option<Task<Result<()>>>,
  602    document_highlights_task: Option<Task<()>>,
  603    linked_editing_range_task: Option<Task<Option<()>>>,
  604    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  605    pending_rename: Option<RenameState>,
  606    searchable: bool,
  607    cursor_shape: CursorShape,
  608    current_line_highlight: Option<CurrentLineHighlight>,
  609    collapse_matches: bool,
  610    autoindent_mode: Option<AutoindentMode>,
  611    workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
  612    input_enabled: bool,
  613    use_modal_editing: bool,
  614    read_only: bool,
  615    leader_peer_id: Option<PeerId>,
  616    remote_id: Option<ViewId>,
  617    hover_state: HoverState,
  618    gutter_hovered: bool,
  619    hovered_link_state: Option<HoveredLinkState>,
  620    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  621    code_action_providers: Vec<Arc<dyn CodeActionProvider>>,
  622    active_inline_completion: Option<CompletionState>,
  623    // enable_inline_completions is a switch that Vim can use to disable
  624    // inline completions based on its mode.
  625    enable_inline_completions: bool,
  626    show_inline_completions_override: Option<bool>,
  627    inlay_hint_cache: InlayHintCache,
  628    expanded_hunks: ExpandedHunks,
  629    next_inlay_id: usize,
  630    _subscriptions: Vec<Subscription>,
  631    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  632    gutter_dimensions: GutterDimensions,
  633    style: Option<EditorStyle>,
  634    text_style_refinement: Option<TextStyleRefinement>,
  635    next_editor_action_id: EditorActionId,
  636    editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
  637    use_autoclose: bool,
  638    use_auto_surround: bool,
  639    auto_replace_emoji_shortcode: bool,
  640    show_git_blame_gutter: bool,
  641    show_git_blame_inline: bool,
  642    show_git_blame_inline_delay_task: Option<Task<()>>,
  643    git_blame_inline_enabled: bool,
  644    serialize_dirty_buffers: bool,
  645    show_selection_menu: Option<bool>,
  646    blame: Option<Model<GitBlame>>,
  647    blame_subscription: Option<Subscription>,
  648    custom_context_menu: Option<
  649        Box<
  650            dyn 'static
  651                + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
  652        >,
  653    >,
  654    last_bounds: Option<Bounds<Pixels>>,
  655    expect_bounds_change: Option<Bounds<Pixels>>,
  656    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  657    tasks_update_task: Option<Task<()>>,
  658    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  659    breadcrumb_header: Option<String>,
  660    focused_block: Option<FocusedBlock>,
  661    next_scroll_position: NextScrollCursorCenterTopBottom,
  662    addons: HashMap<TypeId, Box<dyn Addon>>,
  663    _scroll_cursor_center_top_bottom_task: Task<()>,
  664}
  665
  666#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  667enum NextScrollCursorCenterTopBottom {
  668    #[default]
  669    Center,
  670    Top,
  671    Bottom,
  672}
  673
  674impl NextScrollCursorCenterTopBottom {
  675    fn next(&self) -> Self {
  676        match self {
  677            Self::Center => Self::Top,
  678            Self::Top => Self::Bottom,
  679            Self::Bottom => Self::Center,
  680        }
  681    }
  682}
  683
  684#[derive(Clone)]
  685pub struct EditorSnapshot {
  686    pub mode: EditorMode,
  687    show_gutter: bool,
  688    show_line_numbers: Option<bool>,
  689    show_git_diff_gutter: Option<bool>,
  690    show_code_actions: Option<bool>,
  691    show_runnables: Option<bool>,
  692    git_blame_gutter_max_author_length: Option<usize>,
  693    pub display_snapshot: DisplaySnapshot,
  694    pub placeholder_text: Option<Arc<str>>,
  695    is_focused: bool,
  696    scroll_anchor: ScrollAnchor,
  697    ongoing_scroll: OngoingScroll,
  698    current_line_highlight: CurrentLineHighlight,
  699    gutter_hovered: bool,
  700}
  701
  702const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  703
  704#[derive(Default, Debug, Clone, Copy)]
  705pub struct GutterDimensions {
  706    pub left_padding: Pixels,
  707    pub right_padding: Pixels,
  708    pub width: Pixels,
  709    pub margin: Pixels,
  710    pub git_blame_entries_width: Option<Pixels>,
  711}
  712
  713impl GutterDimensions {
  714    /// The full width of the space taken up by the gutter.
  715    pub fn full_width(&self) -> Pixels {
  716        self.margin + self.width
  717    }
  718
  719    /// The width of the space reserved for the fold indicators,
  720    /// use alongside 'justify_end' and `gutter_width` to
  721    /// right align content with the line numbers
  722    pub fn fold_area_width(&self) -> Pixels {
  723        self.margin + self.right_padding
  724    }
  725}
  726
  727#[derive(Debug)]
  728pub struct RemoteSelection {
  729    pub replica_id: ReplicaId,
  730    pub selection: Selection<Anchor>,
  731    pub cursor_shape: CursorShape,
  732    pub peer_id: PeerId,
  733    pub line_mode: bool,
  734    pub participant_index: Option<ParticipantIndex>,
  735    pub user_name: Option<SharedString>,
  736}
  737
  738#[derive(Clone, Debug)]
  739struct SelectionHistoryEntry {
  740    selections: Arc<[Selection<Anchor>]>,
  741    select_next_state: Option<SelectNextState>,
  742    select_prev_state: Option<SelectNextState>,
  743    add_selections_state: Option<AddSelectionsState>,
  744}
  745
  746enum SelectionHistoryMode {
  747    Normal,
  748    Undoing,
  749    Redoing,
  750}
  751
  752#[derive(Clone, PartialEq, Eq, Hash)]
  753struct HoveredCursor {
  754    replica_id: u16,
  755    selection_id: usize,
  756}
  757
  758impl Default for SelectionHistoryMode {
  759    fn default() -> Self {
  760        Self::Normal
  761    }
  762}
  763
  764#[derive(Default)]
  765struct SelectionHistory {
  766    #[allow(clippy::type_complexity)]
  767    selections_by_transaction:
  768        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  769    mode: SelectionHistoryMode,
  770    undo_stack: VecDeque<SelectionHistoryEntry>,
  771    redo_stack: VecDeque<SelectionHistoryEntry>,
  772}
  773
  774impl SelectionHistory {
  775    fn insert_transaction(
  776        &mut self,
  777        transaction_id: TransactionId,
  778        selections: Arc<[Selection<Anchor>]>,
  779    ) {
  780        self.selections_by_transaction
  781            .insert(transaction_id, (selections, None));
  782    }
  783
  784    #[allow(clippy::type_complexity)]
  785    fn transaction(
  786        &self,
  787        transaction_id: TransactionId,
  788    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  789        self.selections_by_transaction.get(&transaction_id)
  790    }
  791
  792    #[allow(clippy::type_complexity)]
  793    fn transaction_mut(
  794        &mut self,
  795        transaction_id: TransactionId,
  796    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  797        self.selections_by_transaction.get_mut(&transaction_id)
  798    }
  799
  800    fn push(&mut self, entry: SelectionHistoryEntry) {
  801        if !entry.selections.is_empty() {
  802            match self.mode {
  803                SelectionHistoryMode::Normal => {
  804                    self.push_undo(entry);
  805                    self.redo_stack.clear();
  806                }
  807                SelectionHistoryMode::Undoing => self.push_redo(entry),
  808                SelectionHistoryMode::Redoing => self.push_undo(entry),
  809            }
  810        }
  811    }
  812
  813    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  814        if self
  815            .undo_stack
  816            .back()
  817            .map_or(true, |e| e.selections != entry.selections)
  818        {
  819            self.undo_stack.push_back(entry);
  820            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  821                self.undo_stack.pop_front();
  822            }
  823        }
  824    }
  825
  826    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  827        if self
  828            .redo_stack
  829            .back()
  830            .map_or(true, |e| e.selections != entry.selections)
  831        {
  832            self.redo_stack.push_back(entry);
  833            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  834                self.redo_stack.pop_front();
  835            }
  836        }
  837    }
  838}
  839
  840struct RowHighlight {
  841    index: usize,
  842    range: Range<Anchor>,
  843    color: Hsla,
  844    should_autoscroll: bool,
  845}
  846
  847#[derive(Clone, Debug)]
  848struct AddSelectionsState {
  849    above: bool,
  850    stack: Vec<usize>,
  851}
  852
  853#[derive(Clone)]
  854struct SelectNextState {
  855    query: AhoCorasick,
  856    wordwise: bool,
  857    done: bool,
  858}
  859
  860impl std::fmt::Debug for SelectNextState {
  861    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  862        f.debug_struct(std::any::type_name::<Self>())
  863            .field("wordwise", &self.wordwise)
  864            .field("done", &self.done)
  865            .finish()
  866    }
  867}
  868
  869#[derive(Debug)]
  870struct AutocloseRegion {
  871    selection_id: usize,
  872    range: Range<Anchor>,
  873    pair: BracketPair,
  874}
  875
  876#[derive(Debug)]
  877struct SnippetState {
  878    ranges: Vec<Vec<Range<Anchor>>>,
  879    active_index: usize,
  880    choices: Vec<Option<Vec<String>>>,
  881}
  882
  883#[doc(hidden)]
  884pub struct RenameState {
  885    pub range: Range<Anchor>,
  886    pub old_name: Arc<str>,
  887    pub editor: View<Editor>,
  888    block_id: CustomBlockId,
  889}
  890
  891struct InvalidationStack<T>(Vec<T>);
  892
  893struct RegisteredInlineCompletionProvider {
  894    provider: Arc<dyn InlineCompletionProviderHandle>,
  895    _subscription: Subscription,
  896}
  897
  898enum ContextMenu {
  899    Completions(CompletionsMenu),
  900    CodeActions(CodeActionsMenu),
  901}
  902
  903impl ContextMenu {
  904    fn select_first(
  905        &mut self,
  906        provider: Option<&dyn CompletionProvider>,
  907        cx: &mut ViewContext<Editor>,
  908    ) -> bool {
  909        if self.visible() {
  910            match self {
  911                ContextMenu::Completions(menu) => menu.select_first(provider, cx),
  912                ContextMenu::CodeActions(menu) => menu.select_first(cx),
  913            }
  914            true
  915        } else {
  916            false
  917        }
  918    }
  919
  920    fn select_prev(
  921        &mut self,
  922        provider: Option<&dyn CompletionProvider>,
  923        cx: &mut ViewContext<Editor>,
  924    ) -> bool {
  925        if self.visible() {
  926            match self {
  927                ContextMenu::Completions(menu) => menu.select_prev(provider, cx),
  928                ContextMenu::CodeActions(menu) => menu.select_prev(cx),
  929            }
  930            true
  931        } else {
  932            false
  933        }
  934    }
  935
  936    fn select_next(
  937        &mut self,
  938        provider: Option<&dyn CompletionProvider>,
  939        cx: &mut ViewContext<Editor>,
  940    ) -> bool {
  941        if self.visible() {
  942            match self {
  943                ContextMenu::Completions(menu) => menu.select_next(provider, cx),
  944                ContextMenu::CodeActions(menu) => menu.select_next(cx),
  945            }
  946            true
  947        } else {
  948            false
  949        }
  950    }
  951
  952    fn select_last(
  953        &mut self,
  954        provider: Option<&dyn CompletionProvider>,
  955        cx: &mut ViewContext<Editor>,
  956    ) -> bool {
  957        if self.visible() {
  958            match self {
  959                ContextMenu::Completions(menu) => menu.select_last(provider, cx),
  960                ContextMenu::CodeActions(menu) => menu.select_last(cx),
  961            }
  962            true
  963        } else {
  964            false
  965        }
  966    }
  967
  968    fn visible(&self) -> bool {
  969        match self {
  970            ContextMenu::Completions(menu) => menu.visible(),
  971            ContextMenu::CodeActions(menu) => menu.visible(),
  972        }
  973    }
  974
  975    fn render(
  976        &self,
  977        cursor_position: DisplayPoint,
  978        style: &EditorStyle,
  979        max_height: Pixels,
  980        workspace: Option<WeakView<Workspace>>,
  981        cx: &mut ViewContext<Editor>,
  982    ) -> (ContextMenuOrigin, AnyElement) {
  983        match self {
  984            ContextMenu::Completions(menu) => (
  985                ContextMenuOrigin::EditorPoint(cursor_position),
  986                menu.render(style, max_height, workspace, cx),
  987            ),
  988            ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
  989        }
  990    }
  991}
  992
  993enum ContextMenuOrigin {
  994    EditorPoint(DisplayPoint),
  995    GutterIndicator(DisplayRow),
  996}
  997
  998#[derive(Clone, Debug)]
  999struct CompletionsMenu {
 1000    id: CompletionId,
 1001    sort_completions: bool,
 1002    initial_position: Anchor,
 1003    buffer: Model<Buffer>,
 1004    completions: Arc<RwLock<Box<[Completion]>>>,
 1005    match_candidates: Arc<[StringMatchCandidate]>,
 1006    matches: Arc<[StringMatch]>,
 1007    selected_item: usize,
 1008    scroll_handle: UniformListScrollHandle,
 1009    selected_completion_documentation_resolve_debounce: Option<Arc<Mutex<DebouncedDelay>>>,
 1010}
 1011
 1012impl CompletionsMenu {
 1013    fn new(
 1014        id: CompletionId,
 1015        sort_completions: bool,
 1016        initial_position: Anchor,
 1017        buffer: Model<Buffer>,
 1018        completions: Box<[Completion]>,
 1019    ) -> Self {
 1020        let match_candidates = completions
 1021            .iter()
 1022            .enumerate()
 1023            .map(|(id, completion)| {
 1024                StringMatchCandidate::new(
 1025                    id,
 1026                    completion.label.text[completion.label.filter_range.clone()].into(),
 1027                )
 1028            })
 1029            .collect();
 1030
 1031        Self {
 1032            id,
 1033            sort_completions,
 1034            initial_position,
 1035            buffer,
 1036            completions: Arc::new(RwLock::new(completions)),
 1037            match_candidates,
 1038            matches: Vec::new().into(),
 1039            selected_item: 0,
 1040            scroll_handle: UniformListScrollHandle::new(),
 1041            selected_completion_documentation_resolve_debounce: Some(Arc::new(Mutex::new(
 1042                DebouncedDelay::new(),
 1043            ))),
 1044        }
 1045    }
 1046
 1047    fn new_snippet_choices(
 1048        id: CompletionId,
 1049        sort_completions: bool,
 1050        choices: &Vec<String>,
 1051        selection: Range<Anchor>,
 1052        buffer: Model<Buffer>,
 1053    ) -> Self {
 1054        let completions = choices
 1055            .iter()
 1056            .map(|choice| Completion {
 1057                old_range: selection.start.text_anchor..selection.end.text_anchor,
 1058                new_text: choice.to_string(),
 1059                label: CodeLabel {
 1060                    text: choice.to_string(),
 1061                    runs: Default::default(),
 1062                    filter_range: Default::default(),
 1063                },
 1064                server_id: LanguageServerId(usize::MAX),
 1065                documentation: None,
 1066                lsp_completion: Default::default(),
 1067                confirm: None,
 1068            })
 1069            .collect();
 1070
 1071        let match_candidates = choices
 1072            .iter()
 1073            .enumerate()
 1074            .map(|(id, completion)| StringMatchCandidate::new(id, completion.to_string()))
 1075            .collect();
 1076        let matches = choices
 1077            .iter()
 1078            .enumerate()
 1079            .map(|(id, completion)| StringMatch {
 1080                candidate_id: id,
 1081                score: 1.,
 1082                positions: vec![],
 1083                string: completion.clone(),
 1084            })
 1085            .collect();
 1086        Self {
 1087            id,
 1088            sort_completions,
 1089            initial_position: selection.start,
 1090            buffer,
 1091            completions: Arc::new(RwLock::new(completions)),
 1092            match_candidates,
 1093            matches,
 1094            selected_item: 0,
 1095            scroll_handle: UniformListScrollHandle::new(),
 1096            selected_completion_documentation_resolve_debounce: Some(Arc::new(Mutex::new(
 1097                DebouncedDelay::new(),
 1098            ))),
 1099        }
 1100    }
 1101
 1102    fn suppress_documentation_resolution(mut self) -> Self {
 1103        self.selected_completion_documentation_resolve_debounce
 1104            .take();
 1105        self
 1106    }
 1107
 1108    fn select_first(
 1109        &mut self,
 1110        provider: Option<&dyn CompletionProvider>,
 1111        cx: &mut ViewContext<Editor>,
 1112    ) {
 1113        self.selected_item = 0;
 1114        self.scroll_handle
 1115            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1116        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1117        cx.notify();
 1118    }
 1119
 1120    fn select_prev(
 1121        &mut self,
 1122        provider: Option<&dyn CompletionProvider>,
 1123        cx: &mut ViewContext<Editor>,
 1124    ) {
 1125        if self.selected_item > 0 {
 1126            self.selected_item -= 1;
 1127        } else {
 1128            self.selected_item = self.matches.len() - 1;
 1129        }
 1130        self.scroll_handle
 1131            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1132        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1133        cx.notify();
 1134    }
 1135
 1136    fn select_next(
 1137        &mut self,
 1138        provider: Option<&dyn CompletionProvider>,
 1139        cx: &mut ViewContext<Editor>,
 1140    ) {
 1141        if self.selected_item + 1 < self.matches.len() {
 1142            self.selected_item += 1;
 1143        } else {
 1144            self.selected_item = 0;
 1145        }
 1146        self.scroll_handle
 1147            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1148        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1149        cx.notify();
 1150    }
 1151
 1152    fn select_last(
 1153        &mut self,
 1154        provider: Option<&dyn CompletionProvider>,
 1155        cx: &mut ViewContext<Editor>,
 1156    ) {
 1157        self.selected_item = self.matches.len() - 1;
 1158        self.scroll_handle
 1159            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1160        self.attempt_resolve_selected_completion_documentation(provider, cx);
 1161        cx.notify();
 1162    }
 1163
 1164    fn pre_resolve_completion_documentation(
 1165        buffer: Model<Buffer>,
 1166        completions: Arc<RwLock<Box<[Completion]>>>,
 1167        matches: Arc<[StringMatch]>,
 1168        editor: &Editor,
 1169        cx: &mut ViewContext<Editor>,
 1170    ) -> Task<()> {
 1171        let settings = EditorSettings::get_global(cx);
 1172        if !settings.show_completion_documentation {
 1173            return Task::ready(());
 1174        }
 1175
 1176        let Some(provider) = editor.completion_provider.as_ref() else {
 1177            return Task::ready(());
 1178        };
 1179
 1180        let resolve_task = provider.resolve_completions(
 1181            buffer,
 1182            matches.iter().map(|m| m.candidate_id).collect(),
 1183            completions.clone(),
 1184            cx,
 1185        );
 1186
 1187        cx.spawn(move |this, mut cx| async move {
 1188            if let Some(true) = resolve_task.await.log_err() {
 1189                this.update(&mut cx, |_, cx| cx.notify()).ok();
 1190            }
 1191        })
 1192    }
 1193
 1194    fn attempt_resolve_selected_completion_documentation(
 1195        &mut self,
 1196        provider: Option<&dyn CompletionProvider>,
 1197        cx: &mut ViewContext<Editor>,
 1198    ) {
 1199        let settings = EditorSettings::get_global(cx);
 1200        if !settings.show_completion_documentation {
 1201            return;
 1202        }
 1203
 1204        let completion_index = self.matches[self.selected_item].candidate_id;
 1205        let Some(provider) = provider else {
 1206            return;
 1207        };
 1208        let Some(documentation_resolve) = self
 1209            .selected_completion_documentation_resolve_debounce
 1210            .as_ref()
 1211        else {
 1212            return;
 1213        };
 1214
 1215        let resolve_task = provider.resolve_completions(
 1216            self.buffer.clone(),
 1217            vec![completion_index],
 1218            self.completions.clone(),
 1219            cx,
 1220        );
 1221
 1222        let delay_ms =
 1223            EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
 1224        let delay = Duration::from_millis(delay_ms);
 1225
 1226        documentation_resolve.lock().fire_new(delay, cx, |_, cx| {
 1227            cx.spawn(move |this, mut cx| async move {
 1228                if let Some(true) = resolve_task.await.log_err() {
 1229                    this.update(&mut cx, |_, cx| cx.notify()).ok();
 1230                }
 1231            })
 1232        });
 1233    }
 1234
 1235    fn visible(&self) -> bool {
 1236        !self.matches.is_empty()
 1237    }
 1238
 1239    fn render(
 1240        &self,
 1241        style: &EditorStyle,
 1242        max_height: Pixels,
 1243        workspace: Option<WeakView<Workspace>>,
 1244        cx: &mut ViewContext<Editor>,
 1245    ) -> AnyElement {
 1246        let settings = EditorSettings::get_global(cx);
 1247        let show_completion_documentation = settings.show_completion_documentation;
 1248
 1249        let widest_completion_ix = self
 1250            .matches
 1251            .iter()
 1252            .enumerate()
 1253            .max_by_key(|(_, mat)| {
 1254                let completions = self.completions.read();
 1255                let completion = &completions[mat.candidate_id];
 1256                let documentation = &completion.documentation;
 1257
 1258                let mut len = completion.label.text.chars().count();
 1259                if let Some(Documentation::SingleLine(text)) = documentation {
 1260                    if show_completion_documentation {
 1261                        len += text.chars().count();
 1262                    }
 1263                }
 1264
 1265                len
 1266            })
 1267            .map(|(ix, _)| ix);
 1268
 1269        let completions = self.completions.clone();
 1270        let matches = self.matches.clone();
 1271        let selected_item = self.selected_item;
 1272        let style = style.clone();
 1273
 1274        let multiline_docs = if show_completion_documentation {
 1275            let mat = &self.matches[selected_item];
 1276            let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
 1277                Some(Documentation::MultiLinePlainText(text)) => {
 1278                    Some(div().child(SharedString::from(text.clone())))
 1279                }
 1280                Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
 1281                    Some(div().child(render_parsed_markdown(
 1282                        "completions_markdown",
 1283                        parsed,
 1284                        &style,
 1285                        workspace,
 1286                        cx,
 1287                    )))
 1288                }
 1289                _ => None,
 1290            };
 1291            multiline_docs.map(|div| {
 1292                div.id("multiline_docs")
 1293                    .max_h(max_height)
 1294                    .flex_1()
 1295                    .px_1p5()
 1296                    .py_1()
 1297                    .min_w(px(260.))
 1298                    .max_w(px(640.))
 1299                    .w(px(500.))
 1300                    .overflow_y_scroll()
 1301                    .occlude()
 1302            })
 1303        } else {
 1304            None
 1305        };
 1306
 1307        let list = uniform_list(
 1308            cx.view().clone(),
 1309            "completions",
 1310            matches.len(),
 1311            move |_editor, range, cx| {
 1312                let start_ix = range.start;
 1313                let completions_guard = completions.read();
 1314
 1315                matches[range]
 1316                    .iter()
 1317                    .enumerate()
 1318                    .map(|(ix, mat)| {
 1319                        let item_ix = start_ix + ix;
 1320                        let candidate_id = mat.candidate_id;
 1321                        let completion = &completions_guard[candidate_id];
 1322
 1323                        let documentation = if show_completion_documentation {
 1324                            &completion.documentation
 1325                        } else {
 1326                            &None
 1327                        };
 1328
 1329                        let highlights = gpui::combine_highlights(
 1330                            mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
 1331                            styled_runs_for_code_label(&completion.label, &style.syntax).map(
 1332                                |(range, mut highlight)| {
 1333                                    // Ignore font weight for syntax highlighting, as we'll use it
 1334                                    // for fuzzy matches.
 1335                                    highlight.font_weight = None;
 1336
 1337                                    if completion.lsp_completion.deprecated.unwrap_or(false) {
 1338                                        highlight.strikethrough = Some(StrikethroughStyle {
 1339                                            thickness: 1.0.into(),
 1340                                            ..Default::default()
 1341                                        });
 1342                                        highlight.color = Some(cx.theme().colors().text_muted);
 1343                                    }
 1344
 1345                                    (range, highlight)
 1346                                },
 1347                            ),
 1348                        );
 1349                        let completion_label = StyledText::new(completion.label.text.clone())
 1350                            .with_highlights(&style.text, highlights);
 1351                        let documentation_label =
 1352                            if let Some(Documentation::SingleLine(text)) = documentation {
 1353                                if text.trim().is_empty() {
 1354                                    None
 1355                                } else {
 1356                                    Some(
 1357                                        Label::new(text.clone())
 1358                                            .ml_4()
 1359                                            .size(LabelSize::Small)
 1360                                            .color(Color::Muted),
 1361                                    )
 1362                                }
 1363                            } else {
 1364                                None
 1365                            };
 1366
 1367                        let color_swatch = completion
 1368                            .color()
 1369                            .map(|color| div().size_4().bg(color).rounded_sm());
 1370
 1371                        div().min_w(px(220.)).max_w(px(540.)).child(
 1372                            ListItem::new(mat.candidate_id)
 1373                                .inset(true)
 1374                                .selected(item_ix == selected_item)
 1375                                .on_click(cx.listener(move |editor, _event, cx| {
 1376                                    cx.stop_propagation();
 1377                                    if let Some(task) = editor.confirm_completion(
 1378                                        &ConfirmCompletion {
 1379                                            item_ix: Some(item_ix),
 1380                                        },
 1381                                        cx,
 1382                                    ) {
 1383                                        task.detach_and_log_err(cx)
 1384                                    }
 1385                                }))
 1386                                .start_slot::<Div>(color_swatch)
 1387                                .child(h_flex().overflow_hidden().child(completion_label))
 1388                                .end_slot::<Label>(documentation_label),
 1389                        )
 1390                    })
 1391                    .collect()
 1392            },
 1393        )
 1394        .occlude()
 1395        .max_h(max_height)
 1396        .track_scroll(self.scroll_handle.clone())
 1397        .with_width_from_item(widest_completion_ix)
 1398        .with_sizing_behavior(ListSizingBehavior::Infer);
 1399
 1400        Popover::new()
 1401            .child(list)
 1402            .when_some(multiline_docs, |popover, multiline_docs| {
 1403                popover.aside(multiline_docs)
 1404            })
 1405            .into_any_element()
 1406    }
 1407
 1408    pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
 1409        let mut matches = if let Some(query) = query {
 1410            fuzzy::match_strings(
 1411                &self.match_candidates,
 1412                query,
 1413                query.chars().any(|c| c.is_uppercase()),
 1414                100,
 1415                &Default::default(),
 1416                executor,
 1417            )
 1418            .await
 1419        } else {
 1420            self.match_candidates
 1421                .iter()
 1422                .enumerate()
 1423                .map(|(candidate_id, candidate)| StringMatch {
 1424                    candidate_id,
 1425                    score: Default::default(),
 1426                    positions: Default::default(),
 1427                    string: candidate.string.clone(),
 1428                })
 1429                .collect()
 1430        };
 1431
 1432        // Remove all candidates where the query's start does not match the start of any word in the candidate
 1433        if let Some(query) = query {
 1434            if let Some(query_start) = query.chars().next() {
 1435                matches.retain(|string_match| {
 1436                    split_words(&string_match.string).any(|word| {
 1437                        // Check that the first codepoint of the word as lowercase matches the first
 1438                        // codepoint of the query as lowercase
 1439                        word.chars()
 1440                            .flat_map(|codepoint| codepoint.to_lowercase())
 1441                            .zip(query_start.to_lowercase())
 1442                            .all(|(word_cp, query_cp)| word_cp == query_cp)
 1443                    })
 1444                });
 1445            }
 1446        }
 1447
 1448        let completions = self.completions.read();
 1449        if self.sort_completions {
 1450            matches.sort_unstable_by_key(|mat| {
 1451                // We do want to strike a balance here between what the language server tells us
 1452                // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
 1453                // `Creat` and there is a local variable called `CreateComponent`).
 1454                // So what we do is: we bucket all matches into two buckets
 1455                // - Strong matches
 1456                // - Weak matches
 1457                // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
 1458                // and the Weak matches are the rest.
 1459                //
 1460                // For the strong matches, we sort by our fuzzy-finder score first and for the weak
 1461                // matches, we prefer language-server sort_text first.
 1462                //
 1463                // The thinking behind that: we want to show strong matches first in order of relevance(fuzzy score).
 1464                // Rest of the matches(weak) can be sorted as language-server expects.
 1465
 1466                #[derive(PartialEq, Eq, PartialOrd, Ord)]
 1467                enum MatchScore<'a> {
 1468                    Strong {
 1469                        score: Reverse<OrderedFloat<f64>>,
 1470                        sort_text: Option<&'a str>,
 1471                        sort_key: (usize, &'a str),
 1472                    },
 1473                    Weak {
 1474                        sort_text: Option<&'a str>,
 1475                        score: Reverse<OrderedFloat<f64>>,
 1476                        sort_key: (usize, &'a str),
 1477                    },
 1478                }
 1479
 1480                let completion = &completions[mat.candidate_id];
 1481                let sort_key = completion.sort_key();
 1482                let sort_text = completion.lsp_completion.sort_text.as_deref();
 1483                let score = Reverse(OrderedFloat(mat.score));
 1484
 1485                if mat.score >= 0.2 {
 1486                    MatchScore::Strong {
 1487                        score,
 1488                        sort_text,
 1489                        sort_key,
 1490                    }
 1491                } else {
 1492                    MatchScore::Weak {
 1493                        sort_text,
 1494                        score,
 1495                        sort_key,
 1496                    }
 1497                }
 1498            });
 1499        }
 1500
 1501        for mat in &mut matches {
 1502            let completion = &completions[mat.candidate_id];
 1503            mat.string.clone_from(&completion.label.text);
 1504            for position in &mut mat.positions {
 1505                *position += completion.label.filter_range.start;
 1506            }
 1507        }
 1508        drop(completions);
 1509
 1510        self.matches = matches.into();
 1511        self.selected_item = 0;
 1512    }
 1513}
 1514
 1515#[derive(Clone)]
 1516struct AvailableCodeAction {
 1517    excerpt_id: ExcerptId,
 1518    action: CodeAction,
 1519    provider: Arc<dyn CodeActionProvider>,
 1520}
 1521
 1522#[derive(Clone)]
 1523struct CodeActionContents {
 1524    tasks: Option<Arc<ResolvedTasks>>,
 1525    actions: Option<Arc<[AvailableCodeAction]>>,
 1526}
 1527
 1528impl CodeActionContents {
 1529    fn len(&self) -> usize {
 1530        match (&self.tasks, &self.actions) {
 1531            (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
 1532            (Some(tasks), None) => tasks.templates.len(),
 1533            (None, Some(actions)) => actions.len(),
 1534            (None, None) => 0,
 1535        }
 1536    }
 1537
 1538    fn is_empty(&self) -> bool {
 1539        match (&self.tasks, &self.actions) {
 1540            (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
 1541            (Some(tasks), None) => tasks.templates.is_empty(),
 1542            (None, Some(actions)) => actions.is_empty(),
 1543            (None, None) => true,
 1544        }
 1545    }
 1546
 1547    fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
 1548        self.tasks
 1549            .iter()
 1550            .flat_map(|tasks| {
 1551                tasks
 1552                    .templates
 1553                    .iter()
 1554                    .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
 1555            })
 1556            .chain(self.actions.iter().flat_map(|actions| {
 1557                actions.iter().map(|available| CodeActionsItem::CodeAction {
 1558                    excerpt_id: available.excerpt_id,
 1559                    action: available.action.clone(),
 1560                    provider: available.provider.clone(),
 1561                })
 1562            }))
 1563    }
 1564    fn get(&self, index: usize) -> Option<CodeActionsItem> {
 1565        match (&self.tasks, &self.actions) {
 1566            (Some(tasks), Some(actions)) => {
 1567                if index < tasks.templates.len() {
 1568                    tasks
 1569                        .templates
 1570                        .get(index)
 1571                        .cloned()
 1572                        .map(|(kind, task)| CodeActionsItem::Task(kind, task))
 1573                } else {
 1574                    actions.get(index - tasks.templates.len()).map(|available| {
 1575                        CodeActionsItem::CodeAction {
 1576                            excerpt_id: available.excerpt_id,
 1577                            action: available.action.clone(),
 1578                            provider: available.provider.clone(),
 1579                        }
 1580                    })
 1581                }
 1582            }
 1583            (Some(tasks), None) => tasks
 1584                .templates
 1585                .get(index)
 1586                .cloned()
 1587                .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
 1588            (None, Some(actions)) => {
 1589                actions
 1590                    .get(index)
 1591                    .map(|available| CodeActionsItem::CodeAction {
 1592                        excerpt_id: available.excerpt_id,
 1593                        action: available.action.clone(),
 1594                        provider: available.provider.clone(),
 1595                    })
 1596            }
 1597            (None, None) => None,
 1598        }
 1599    }
 1600}
 1601
 1602#[allow(clippy::large_enum_variant)]
 1603#[derive(Clone)]
 1604enum CodeActionsItem {
 1605    Task(TaskSourceKind, ResolvedTask),
 1606    CodeAction {
 1607        excerpt_id: ExcerptId,
 1608        action: CodeAction,
 1609        provider: Arc<dyn CodeActionProvider>,
 1610    },
 1611}
 1612
 1613impl CodeActionsItem {
 1614    fn as_task(&self) -> Option<&ResolvedTask> {
 1615        let Self::Task(_, task) = self else {
 1616            return None;
 1617        };
 1618        Some(task)
 1619    }
 1620    fn as_code_action(&self) -> Option<&CodeAction> {
 1621        let Self::CodeAction { action, .. } = self else {
 1622            return None;
 1623        };
 1624        Some(action)
 1625    }
 1626    fn label(&self) -> String {
 1627        match self {
 1628            Self::CodeAction { action, .. } => action.lsp_action.title.clone(),
 1629            Self::Task(_, task) => task.resolved_label.clone(),
 1630        }
 1631    }
 1632}
 1633
 1634struct CodeActionsMenu {
 1635    actions: CodeActionContents,
 1636    buffer: Model<Buffer>,
 1637    selected_item: usize,
 1638    scroll_handle: UniformListScrollHandle,
 1639    deployed_from_indicator: Option<DisplayRow>,
 1640}
 1641
 1642impl CodeActionsMenu {
 1643    fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
 1644        self.selected_item = 0;
 1645        self.scroll_handle
 1646            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1647        cx.notify()
 1648    }
 1649
 1650    fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
 1651        if self.selected_item > 0 {
 1652            self.selected_item -= 1;
 1653        } else {
 1654            self.selected_item = self.actions.len() - 1;
 1655        }
 1656        self.scroll_handle
 1657            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1658        cx.notify();
 1659    }
 1660
 1661    fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
 1662        if self.selected_item + 1 < self.actions.len() {
 1663            self.selected_item += 1;
 1664        } else {
 1665            self.selected_item = 0;
 1666        }
 1667        self.scroll_handle
 1668            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1669        cx.notify();
 1670    }
 1671
 1672    fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
 1673        self.selected_item = self.actions.len() - 1;
 1674        self.scroll_handle
 1675            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1676        cx.notify()
 1677    }
 1678
 1679    fn visible(&self) -> bool {
 1680        !self.actions.is_empty()
 1681    }
 1682
 1683    fn render(
 1684        &self,
 1685        cursor_position: DisplayPoint,
 1686        _style: &EditorStyle,
 1687        max_height: Pixels,
 1688        cx: &mut ViewContext<Editor>,
 1689    ) -> (ContextMenuOrigin, AnyElement) {
 1690        let actions = self.actions.clone();
 1691        let selected_item = self.selected_item;
 1692        let element = uniform_list(
 1693            cx.view().clone(),
 1694            "code_actions_menu",
 1695            self.actions.len(),
 1696            move |_this, range, cx| {
 1697                actions
 1698                    .iter()
 1699                    .skip(range.start)
 1700                    .take(range.end - range.start)
 1701                    .enumerate()
 1702                    .map(|(ix, action)| {
 1703                        let item_ix = range.start + ix;
 1704                        let selected = selected_item == item_ix;
 1705                        let colors = cx.theme().colors();
 1706                        div()
 1707                            .px_1()
 1708                            .rounded_md()
 1709                            .text_color(colors.text)
 1710                            .when(selected, |style| {
 1711                                style
 1712                                    .bg(colors.element_active)
 1713                                    .text_color(colors.text_accent)
 1714                            })
 1715                            .hover(|style| {
 1716                                style
 1717                                    .bg(colors.element_hover)
 1718                                    .text_color(colors.text_accent)
 1719                            })
 1720                            .whitespace_nowrap()
 1721                            .when_some(action.as_code_action(), |this, action| {
 1722                                this.on_mouse_down(
 1723                                    MouseButton::Left,
 1724                                    cx.listener(move |editor, _, cx| {
 1725                                        cx.stop_propagation();
 1726                                        if let Some(task) = editor.confirm_code_action(
 1727                                            &ConfirmCodeAction {
 1728                                                item_ix: Some(item_ix),
 1729                                            },
 1730                                            cx,
 1731                                        ) {
 1732                                            task.detach_and_log_err(cx)
 1733                                        }
 1734                                    }),
 1735                                )
 1736                                // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
 1737                                .child(SharedString::from(action.lsp_action.title.clone()))
 1738                            })
 1739                            .when_some(action.as_task(), |this, task| {
 1740                                this.on_mouse_down(
 1741                                    MouseButton::Left,
 1742                                    cx.listener(move |editor, _, cx| {
 1743                                        cx.stop_propagation();
 1744                                        if let Some(task) = editor.confirm_code_action(
 1745                                            &ConfirmCodeAction {
 1746                                                item_ix: Some(item_ix),
 1747                                            },
 1748                                            cx,
 1749                                        ) {
 1750                                            task.detach_and_log_err(cx)
 1751                                        }
 1752                                    }),
 1753                                )
 1754                                .child(SharedString::from(task.resolved_label.clone()))
 1755                            })
 1756                    })
 1757                    .collect()
 1758            },
 1759        )
 1760        .elevation_1(cx)
 1761        .p_1()
 1762        .max_h(max_height)
 1763        .occlude()
 1764        .track_scroll(self.scroll_handle.clone())
 1765        .with_width_from_item(
 1766            self.actions
 1767                .iter()
 1768                .enumerate()
 1769                .max_by_key(|(_, action)| match action {
 1770                    CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
 1771                    CodeActionsItem::CodeAction { action, .. } => {
 1772                        action.lsp_action.title.chars().count()
 1773                    }
 1774                })
 1775                .map(|(ix, _)| ix),
 1776        )
 1777        .with_sizing_behavior(ListSizingBehavior::Infer)
 1778        .into_any_element();
 1779
 1780        let cursor_position = if let Some(row) = self.deployed_from_indicator {
 1781            ContextMenuOrigin::GutterIndicator(row)
 1782        } else {
 1783            ContextMenuOrigin::EditorPoint(cursor_position)
 1784        };
 1785
 1786        (cursor_position, element)
 1787    }
 1788}
 1789
 1790#[derive(Debug)]
 1791struct ActiveDiagnosticGroup {
 1792    primary_range: Range<Anchor>,
 1793    primary_message: String,
 1794    group_id: usize,
 1795    blocks: HashMap<CustomBlockId, Diagnostic>,
 1796    is_valid: bool,
 1797}
 1798
 1799#[derive(Serialize, Deserialize, Clone, Debug)]
 1800pub struct ClipboardSelection {
 1801    pub len: usize,
 1802    pub is_entire_line: bool,
 1803    pub first_line_indent: u32,
 1804}
 1805
 1806#[derive(Debug)]
 1807pub(crate) struct NavigationData {
 1808    cursor_anchor: Anchor,
 1809    cursor_position: Point,
 1810    scroll_anchor: ScrollAnchor,
 1811    scroll_top_row: u32,
 1812}
 1813
 1814#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1815pub enum GotoDefinitionKind {
 1816    Symbol,
 1817    Declaration,
 1818    Type,
 1819    Implementation,
 1820}
 1821
 1822#[derive(Debug, Clone)]
 1823enum InlayHintRefreshReason {
 1824    Toggle(bool),
 1825    SettingsChange(InlayHintSettings),
 1826    NewLinesShown,
 1827    BufferEdited(HashSet<Arc<Language>>),
 1828    RefreshRequested,
 1829    ExcerptsRemoved(Vec<ExcerptId>),
 1830}
 1831
 1832impl InlayHintRefreshReason {
 1833    fn description(&self) -> &'static str {
 1834        match self {
 1835            Self::Toggle(_) => "toggle",
 1836            Self::SettingsChange(_) => "settings change",
 1837            Self::NewLinesShown => "new lines shown",
 1838            Self::BufferEdited(_) => "buffer edited",
 1839            Self::RefreshRequested => "refresh requested",
 1840            Self::ExcerptsRemoved(_) => "excerpts removed",
 1841        }
 1842    }
 1843}
 1844
 1845pub(crate) struct FocusedBlock {
 1846    id: BlockId,
 1847    focus_handle: WeakFocusHandle,
 1848}
 1849
 1850#[derive(Clone)]
 1851struct JumpData {
 1852    excerpt_id: ExcerptId,
 1853    position: Point,
 1854    anchor: text::Anchor,
 1855    path: Option<project::ProjectPath>,
 1856    line_offset_from_top: u32,
 1857}
 1858
 1859impl Editor {
 1860    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
 1861        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1862        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1863        Self::new(
 1864            EditorMode::SingleLine { auto_width: false },
 1865            buffer,
 1866            None,
 1867            false,
 1868            cx,
 1869        )
 1870    }
 1871
 1872    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
 1873        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1874        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1875        Self::new(EditorMode::Full, buffer, None, false, cx)
 1876    }
 1877
 1878    pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
 1879        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1880        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1881        Self::new(
 1882            EditorMode::SingleLine { auto_width: true },
 1883            buffer,
 1884            None,
 1885            false,
 1886            cx,
 1887        )
 1888    }
 1889
 1890    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
 1891        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1892        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1893        Self::new(
 1894            EditorMode::AutoHeight { max_lines },
 1895            buffer,
 1896            None,
 1897            false,
 1898            cx,
 1899        )
 1900    }
 1901
 1902    pub fn for_buffer(
 1903        buffer: Model<Buffer>,
 1904        project: Option<Model<Project>>,
 1905        cx: &mut ViewContext<Self>,
 1906    ) -> Self {
 1907        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1908        Self::new(EditorMode::Full, buffer, project, false, cx)
 1909    }
 1910
 1911    pub fn for_multibuffer(
 1912        buffer: Model<MultiBuffer>,
 1913        project: Option<Model<Project>>,
 1914        show_excerpt_controls: bool,
 1915        cx: &mut ViewContext<Self>,
 1916    ) -> Self {
 1917        Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
 1918    }
 1919
 1920    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 1921        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1922        let mut clone = Self::new(
 1923            self.mode,
 1924            self.buffer.clone(),
 1925            self.project.clone(),
 1926            show_excerpt_controls,
 1927            cx,
 1928        );
 1929        self.display_map.update(cx, |display_map, cx| {
 1930            let snapshot = display_map.snapshot(cx);
 1931            clone.display_map.update(cx, |display_map, cx| {
 1932                display_map.set_state(&snapshot, cx);
 1933            });
 1934        });
 1935        clone.selections.clone_state(&self.selections);
 1936        clone.scroll_manager.clone_state(&self.scroll_manager);
 1937        clone.searchable = self.searchable;
 1938        clone
 1939    }
 1940
 1941    pub fn new(
 1942        mode: EditorMode,
 1943        buffer: Model<MultiBuffer>,
 1944        project: Option<Model<Project>>,
 1945        show_excerpt_controls: bool,
 1946        cx: &mut ViewContext<Self>,
 1947    ) -> Self {
 1948        let style = cx.text_style();
 1949        let font_size = style.font_size.to_pixels(cx.rem_size());
 1950        let editor = cx.view().downgrade();
 1951        let fold_placeholder = FoldPlaceholder {
 1952            constrain_width: true,
 1953            render: Arc::new(move |fold_id, fold_range, cx| {
 1954                let editor = editor.clone();
 1955                div()
 1956                    .id(fold_id)
 1957                    .bg(cx.theme().colors().ghost_element_background)
 1958                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1959                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1960                    .rounded_sm()
 1961                    .size_full()
 1962                    .cursor_pointer()
 1963                    .child("")
 1964                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 1965                    .on_click(move |_, cx| {
 1966                        editor
 1967                            .update(cx, |editor, cx| {
 1968                                editor.unfold_ranges(
 1969                                    &[fold_range.start..fold_range.end],
 1970                                    true,
 1971                                    false,
 1972                                    cx,
 1973                                );
 1974                                cx.stop_propagation();
 1975                            })
 1976                            .ok();
 1977                    })
 1978                    .into_any()
 1979            }),
 1980            merge_adjacent: true,
 1981            ..Default::default()
 1982        };
 1983        let display_map = cx.new_model(|cx| {
 1984            DisplayMap::new(
 1985                buffer.clone(),
 1986                style.font(),
 1987                font_size,
 1988                None,
 1989                show_excerpt_controls,
 1990                FILE_HEADER_HEIGHT,
 1991                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1992                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1993                fold_placeholder,
 1994                cx,
 1995            )
 1996        });
 1997
 1998        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1999
 2000        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 2001
 2002        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 2003            .then(|| language_settings::SoftWrap::None);
 2004
 2005        let mut project_subscriptions = Vec::new();
 2006        if mode == EditorMode::Full {
 2007            if let Some(project) = project.as_ref() {
 2008                if buffer.read(cx).is_singleton() {
 2009                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
 2010                        cx.emit(EditorEvent::TitleChanged);
 2011                    }));
 2012                }
 2013                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
 2014                    if let project::Event::RefreshInlayHints = event {
 2015                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 2016                    } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 2017                        if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 2018                            let focus_handle = editor.focus_handle(cx);
 2019                            if focus_handle.is_focused(cx) {
 2020                                let snapshot = buffer.read(cx).snapshot();
 2021                                for (range, snippet) in snippet_edits {
 2022                                    let editor_range =
 2023                                        language::range_from_lsp(*range).to_offset(&snapshot);
 2024                                    editor
 2025                                        .insert_snippet(&[editor_range], snippet.clone(), cx)
 2026                                        .ok();
 2027                                }
 2028                            }
 2029                        }
 2030                    }
 2031                }));
 2032                if let Some(task_inventory) = project
 2033                    .read(cx)
 2034                    .task_store()
 2035                    .read(cx)
 2036                    .task_inventory()
 2037                    .cloned()
 2038                {
 2039                    project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
 2040                        editor.tasks_update_task = Some(editor.refresh_runnables(cx));
 2041                    }));
 2042                }
 2043            }
 2044        }
 2045
 2046        let inlay_hint_settings = inlay_hint_settings(
 2047            selections.newest_anchor().head(),
 2048            &buffer.read(cx).snapshot(cx),
 2049            cx,
 2050        );
 2051        let focus_handle = cx.focus_handle();
 2052        cx.on_focus(&focus_handle, Self::handle_focus).detach();
 2053        cx.on_focus_in(&focus_handle, Self::handle_focus_in)
 2054            .detach();
 2055        cx.on_focus_out(&focus_handle, Self::handle_focus_out)
 2056            .detach();
 2057        cx.on_blur(&focus_handle, Self::handle_blur).detach();
 2058
 2059        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 2060            Some(false)
 2061        } else {
 2062            None
 2063        };
 2064
 2065        let mut code_action_providers = Vec::new();
 2066        if let Some(project) = project.clone() {
 2067            code_action_providers.push(Arc::new(project) as Arc<_>);
 2068        }
 2069
 2070        let mut this = Self {
 2071            focus_handle,
 2072            show_cursor_when_unfocused: false,
 2073            last_focused_descendant: None,
 2074            buffer: buffer.clone(),
 2075            display_map: display_map.clone(),
 2076            selections,
 2077            scroll_manager: ScrollManager::new(cx),
 2078            columnar_selection_tail: None,
 2079            add_selections_state: None,
 2080            select_next_state: None,
 2081            select_prev_state: None,
 2082            selection_history: Default::default(),
 2083            autoclose_regions: Default::default(),
 2084            snippet_stack: Default::default(),
 2085            select_larger_syntax_node_stack: Vec::new(),
 2086            ime_transaction: Default::default(),
 2087            active_diagnostics: None,
 2088            soft_wrap_mode_override,
 2089            completion_provider: project.clone().map(|project| Box::new(project) as _),
 2090            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 2091            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 2092            project,
 2093            blink_manager: blink_manager.clone(),
 2094            show_local_selections: true,
 2095            mode,
 2096            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 2097            show_gutter: mode == EditorMode::Full,
 2098            show_line_numbers: None,
 2099            use_relative_line_numbers: None,
 2100            show_git_diff_gutter: None,
 2101            show_code_actions: None,
 2102            show_runnables: None,
 2103            show_wrap_guides: None,
 2104            show_indent_guides,
 2105            placeholder_text: None,
 2106            highlight_order: 0,
 2107            highlighted_rows: HashMap::default(),
 2108            background_highlights: Default::default(),
 2109            gutter_highlights: TreeMap::default(),
 2110            scrollbar_marker_state: ScrollbarMarkerState::default(),
 2111            active_indent_guides_state: ActiveIndentGuidesState::default(),
 2112            nav_history: None,
 2113            context_menu: RwLock::new(None),
 2114            mouse_context_menu: None,
 2115            completion_tasks: Default::default(),
 2116            signature_help_state: SignatureHelpState::default(),
 2117            auto_signature_help: None,
 2118            find_all_references_task_sources: Vec::new(),
 2119            next_completion_id: 0,
 2120            completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
 2121            next_inlay_id: 0,
 2122            code_action_providers,
 2123            available_code_actions: Default::default(),
 2124            code_actions_task: Default::default(),
 2125            document_highlights_task: Default::default(),
 2126            linked_editing_range_task: Default::default(),
 2127            pending_rename: Default::default(),
 2128            searchable: true,
 2129            cursor_shape: EditorSettings::get_global(cx)
 2130                .cursor_shape
 2131                .unwrap_or_default(),
 2132            current_line_highlight: None,
 2133            autoindent_mode: Some(AutoindentMode::EachLine),
 2134            collapse_matches: false,
 2135            workspace: None,
 2136            input_enabled: true,
 2137            use_modal_editing: mode == EditorMode::Full,
 2138            read_only: false,
 2139            use_autoclose: true,
 2140            use_auto_surround: true,
 2141            auto_replace_emoji_shortcode: false,
 2142            leader_peer_id: None,
 2143            remote_id: None,
 2144            hover_state: Default::default(),
 2145            hovered_link_state: Default::default(),
 2146            inline_completion_provider: None,
 2147            active_inline_completion: None,
 2148            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 2149            expanded_hunks: ExpandedHunks::default(),
 2150            gutter_hovered: false,
 2151            pixel_position_of_newest_cursor: None,
 2152            last_bounds: None,
 2153            expect_bounds_change: None,
 2154            gutter_dimensions: GutterDimensions::default(),
 2155            style: None,
 2156            show_cursor_names: false,
 2157            hovered_cursors: Default::default(),
 2158            next_editor_action_id: EditorActionId::default(),
 2159            editor_actions: Rc::default(),
 2160            show_inline_completions_override: None,
 2161            enable_inline_completions: true,
 2162            custom_context_menu: None,
 2163            show_git_blame_gutter: false,
 2164            show_git_blame_inline: false,
 2165            show_selection_menu: None,
 2166            show_git_blame_inline_delay_task: None,
 2167            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 2168            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 2169                .session
 2170                .restore_unsaved_buffers,
 2171            blame: None,
 2172            blame_subscription: None,
 2173            tasks: Default::default(),
 2174            _subscriptions: vec![
 2175                cx.observe(&buffer, Self::on_buffer_changed),
 2176                cx.subscribe(&buffer, Self::on_buffer_event),
 2177                cx.observe(&display_map, Self::on_display_map_changed),
 2178                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 2179                cx.observe_global::<SettingsStore>(Self::settings_changed),
 2180                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 2181                cx.observe_window_activation(|editor, cx| {
 2182                    let active = cx.is_window_active();
 2183                    editor.blink_manager.update(cx, |blink_manager, cx| {
 2184                        if active {
 2185                            blink_manager.enable(cx);
 2186                        } else {
 2187                            blink_manager.disable(cx);
 2188                        }
 2189                    });
 2190                }),
 2191            ],
 2192            tasks_update_task: None,
 2193            linked_edit_ranges: Default::default(),
 2194            previous_search_ranges: None,
 2195            breadcrumb_header: None,
 2196            focused_block: None,
 2197            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 2198            addons: HashMap::default(),
 2199            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 2200            text_style_refinement: None,
 2201        };
 2202        this.tasks_update_task = Some(this.refresh_runnables(cx));
 2203        this._subscriptions.extend(project_subscriptions);
 2204
 2205        this.end_selection(cx);
 2206        this.scroll_manager.show_scrollbar(cx);
 2207
 2208        if mode == EditorMode::Full {
 2209            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 2210            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 2211
 2212            if this.git_blame_inline_enabled {
 2213                this.git_blame_inline_enabled = true;
 2214                this.start_git_blame_inline(false, cx);
 2215            }
 2216        }
 2217
 2218        this.report_editor_event("open", None, cx);
 2219        this
 2220    }
 2221
 2222    pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
 2223        self.mouse_context_menu
 2224            .as_ref()
 2225            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
 2226    }
 2227
 2228    fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
 2229        let mut key_context = KeyContext::new_with_defaults();
 2230        key_context.add("Editor");
 2231        let mode = match self.mode {
 2232            EditorMode::SingleLine { .. } => "single_line",
 2233            EditorMode::AutoHeight { .. } => "auto_height",
 2234            EditorMode::Full => "full",
 2235        };
 2236
 2237        if EditorSettings::jupyter_enabled(cx) {
 2238            key_context.add("jupyter");
 2239        }
 2240
 2241        key_context.set("mode", mode);
 2242        if self.pending_rename.is_some() {
 2243            key_context.add("renaming");
 2244        }
 2245        if self.context_menu_visible() {
 2246            match self.context_menu.read().as_ref() {
 2247                Some(ContextMenu::Completions(_)) => {
 2248                    key_context.add("menu");
 2249                    key_context.add("showing_completions")
 2250                }
 2251                Some(ContextMenu::CodeActions(_)) => {
 2252                    key_context.add("menu");
 2253                    key_context.add("showing_code_actions")
 2254                }
 2255                None => {}
 2256            }
 2257        }
 2258
 2259        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 2260        if !self.focus_handle(cx).contains_focused(cx)
 2261            || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
 2262        {
 2263            for addon in self.addons.values() {
 2264                addon.extend_key_context(&mut key_context, cx)
 2265            }
 2266        }
 2267
 2268        if let Some(extension) = self
 2269            .buffer
 2270            .read(cx)
 2271            .as_singleton()
 2272            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 2273        {
 2274            key_context.set("extension", extension.to_string());
 2275        }
 2276
 2277        if self.has_active_inline_completion(cx) {
 2278            key_context.add("copilot_suggestion");
 2279            key_context.add("inline_completion");
 2280        }
 2281
 2282        key_context
 2283    }
 2284
 2285    pub fn new_file(
 2286        workspace: &mut Workspace,
 2287        _: &workspace::NewFile,
 2288        cx: &mut ViewContext<Workspace>,
 2289    ) {
 2290        Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
 2291            "Failed to create buffer",
 2292            cx,
 2293            |e, _| match e.error_code() {
 2294                ErrorCode::RemoteUpgradeRequired => Some(format!(
 2295                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2296                e.error_tag("required").unwrap_or("the latest version")
 2297            )),
 2298                _ => None,
 2299            },
 2300        );
 2301    }
 2302
 2303    pub fn new_in_workspace(
 2304        workspace: &mut Workspace,
 2305        cx: &mut ViewContext<Workspace>,
 2306    ) -> Task<Result<View<Editor>>> {
 2307        let project = workspace.project().clone();
 2308        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2309
 2310        cx.spawn(|workspace, mut cx| async move {
 2311            let buffer = create.await?;
 2312            workspace.update(&mut cx, |workspace, cx| {
 2313                let editor =
 2314                    cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
 2315                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 2316                editor
 2317            })
 2318        })
 2319    }
 2320
 2321    fn new_file_vertical(
 2322        workspace: &mut Workspace,
 2323        _: &workspace::NewFileSplitVertical,
 2324        cx: &mut ViewContext<Workspace>,
 2325    ) {
 2326        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
 2327    }
 2328
 2329    fn new_file_horizontal(
 2330        workspace: &mut Workspace,
 2331        _: &workspace::NewFileSplitHorizontal,
 2332        cx: &mut ViewContext<Workspace>,
 2333    ) {
 2334        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
 2335    }
 2336
 2337    fn new_file_in_direction(
 2338        workspace: &mut Workspace,
 2339        direction: SplitDirection,
 2340        cx: &mut ViewContext<Workspace>,
 2341    ) {
 2342        let project = workspace.project().clone();
 2343        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2344
 2345        cx.spawn(|workspace, mut cx| async move {
 2346            let buffer = create.await?;
 2347            workspace.update(&mut cx, move |workspace, cx| {
 2348                workspace.split_item(
 2349                    direction,
 2350                    Box::new(
 2351                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 2352                    ),
 2353                    cx,
 2354                )
 2355            })?;
 2356            anyhow::Ok(())
 2357        })
 2358        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 2359            ErrorCode::RemoteUpgradeRequired => Some(format!(
 2360                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2361                e.error_tag("required").unwrap_or("the latest version")
 2362            )),
 2363            _ => None,
 2364        });
 2365    }
 2366
 2367    pub fn leader_peer_id(&self) -> Option<PeerId> {
 2368        self.leader_peer_id
 2369    }
 2370
 2371    pub fn buffer(&self) -> &Model<MultiBuffer> {
 2372        &self.buffer
 2373    }
 2374
 2375    pub fn workspace(&self) -> Option<View<Workspace>> {
 2376        self.workspace.as_ref()?.0.upgrade()
 2377    }
 2378
 2379    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
 2380        self.buffer().read(cx).title(cx)
 2381    }
 2382
 2383    pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
 2384        let git_blame_gutter_max_author_length = self
 2385            .render_git_blame_gutter(cx)
 2386            .then(|| {
 2387                if let Some(blame) = self.blame.as_ref() {
 2388                    let max_author_length =
 2389                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 2390                    Some(max_author_length)
 2391                } else {
 2392                    None
 2393                }
 2394            })
 2395            .flatten();
 2396
 2397        EditorSnapshot {
 2398            mode: self.mode,
 2399            show_gutter: self.show_gutter,
 2400            show_line_numbers: self.show_line_numbers,
 2401            show_git_diff_gutter: self.show_git_diff_gutter,
 2402            show_code_actions: self.show_code_actions,
 2403            show_runnables: self.show_runnables,
 2404            git_blame_gutter_max_author_length,
 2405            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 2406            scroll_anchor: self.scroll_manager.anchor(),
 2407            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 2408            placeholder_text: self.placeholder_text.clone(),
 2409            is_focused: self.focus_handle.is_focused(cx),
 2410            current_line_highlight: self
 2411                .current_line_highlight
 2412                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 2413            gutter_hovered: self.gutter_hovered,
 2414        }
 2415    }
 2416
 2417    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
 2418        self.buffer.read(cx).language_at(point, cx)
 2419    }
 2420
 2421    pub fn file_at<T: ToOffset>(
 2422        &self,
 2423        point: T,
 2424        cx: &AppContext,
 2425    ) -> Option<Arc<dyn language::File>> {
 2426        self.buffer.read(cx).read(cx).file_at(point).cloned()
 2427    }
 2428
 2429    pub fn active_excerpt(
 2430        &self,
 2431        cx: &AppContext,
 2432    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
 2433        self.buffer
 2434            .read(cx)
 2435            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 2436    }
 2437
 2438    pub fn mode(&self) -> EditorMode {
 2439        self.mode
 2440    }
 2441
 2442    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 2443        self.collaboration_hub.as_deref()
 2444    }
 2445
 2446    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 2447        self.collaboration_hub = Some(hub);
 2448    }
 2449
 2450    pub fn set_custom_context_menu(
 2451        &mut self,
 2452        f: impl 'static
 2453            + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
 2454    ) {
 2455        self.custom_context_menu = Some(Box::new(f))
 2456    }
 2457
 2458    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 2459        self.completion_provider = provider;
 2460    }
 2461
 2462    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 2463        self.semantics_provider.clone()
 2464    }
 2465
 2466    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 2467        self.semantics_provider = provider;
 2468    }
 2469
 2470    pub fn set_inline_completion_provider<T>(
 2471        &mut self,
 2472        provider: Option<Model<T>>,
 2473        cx: &mut ViewContext<Self>,
 2474    ) where
 2475        T: InlineCompletionProvider,
 2476    {
 2477        self.inline_completion_provider =
 2478            provider.map(|provider| RegisteredInlineCompletionProvider {
 2479                _subscription: cx.observe(&provider, |this, _, cx| {
 2480                    if this.focus_handle.is_focused(cx) {
 2481                        this.update_visible_inline_completion(cx);
 2482                    }
 2483                }),
 2484                provider: Arc::new(provider),
 2485            });
 2486        self.refresh_inline_completion(false, false, cx);
 2487    }
 2488
 2489    pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
 2490        self.placeholder_text.as_deref()
 2491    }
 2492
 2493    pub fn set_placeholder_text(
 2494        &mut self,
 2495        placeholder_text: impl Into<Arc<str>>,
 2496        cx: &mut ViewContext<Self>,
 2497    ) {
 2498        let placeholder_text = Some(placeholder_text.into());
 2499        if self.placeholder_text != placeholder_text {
 2500            self.placeholder_text = placeholder_text;
 2501            cx.notify();
 2502        }
 2503    }
 2504
 2505    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
 2506        self.cursor_shape = cursor_shape;
 2507
 2508        // Disrupt blink for immediate user feedback that the cursor shape has changed
 2509        self.blink_manager.update(cx, BlinkManager::show_cursor);
 2510
 2511        cx.notify();
 2512    }
 2513
 2514    pub fn set_current_line_highlight(
 2515        &mut self,
 2516        current_line_highlight: Option<CurrentLineHighlight>,
 2517    ) {
 2518        self.current_line_highlight = current_line_highlight;
 2519    }
 2520
 2521    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 2522        self.collapse_matches = collapse_matches;
 2523    }
 2524
 2525    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 2526        if self.collapse_matches {
 2527            return range.start..range.start;
 2528        }
 2529        range.clone()
 2530    }
 2531
 2532    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
 2533        if self.display_map.read(cx).clip_at_line_ends != clip {
 2534            self.display_map
 2535                .update(cx, |map, _| map.clip_at_line_ends = clip);
 2536        }
 2537    }
 2538
 2539    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 2540        self.input_enabled = input_enabled;
 2541    }
 2542
 2543    pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
 2544        self.enable_inline_completions = enabled;
 2545    }
 2546
 2547    pub fn set_autoindent(&mut self, autoindent: bool) {
 2548        if autoindent {
 2549            self.autoindent_mode = Some(AutoindentMode::EachLine);
 2550        } else {
 2551            self.autoindent_mode = None;
 2552        }
 2553    }
 2554
 2555    pub fn read_only(&self, cx: &AppContext) -> bool {
 2556        self.read_only || self.buffer.read(cx).read_only()
 2557    }
 2558
 2559    pub fn set_read_only(&mut self, read_only: bool) {
 2560        self.read_only = read_only;
 2561    }
 2562
 2563    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 2564        self.use_autoclose = autoclose;
 2565    }
 2566
 2567    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 2568        self.use_auto_surround = auto_surround;
 2569    }
 2570
 2571    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 2572        self.auto_replace_emoji_shortcode = auto_replace;
 2573    }
 2574
 2575    pub fn toggle_inline_completions(
 2576        &mut self,
 2577        _: &ToggleInlineCompletions,
 2578        cx: &mut ViewContext<Self>,
 2579    ) {
 2580        if self.show_inline_completions_override.is_some() {
 2581            self.set_show_inline_completions(None, cx);
 2582        } else {
 2583            let cursor = self.selections.newest_anchor().head();
 2584            if let Some((buffer, cursor_buffer_position)) =
 2585                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 2586            {
 2587                let show_inline_completions =
 2588                    !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
 2589                self.set_show_inline_completions(Some(show_inline_completions), cx);
 2590            }
 2591        }
 2592    }
 2593
 2594    pub fn set_show_inline_completions(
 2595        &mut self,
 2596        show_inline_completions: Option<bool>,
 2597        cx: &mut ViewContext<Self>,
 2598    ) {
 2599        self.show_inline_completions_override = show_inline_completions;
 2600        self.refresh_inline_completion(false, true, cx);
 2601    }
 2602
 2603    fn should_show_inline_completions(
 2604        &self,
 2605        buffer: &Model<Buffer>,
 2606        buffer_position: language::Anchor,
 2607        cx: &AppContext,
 2608    ) -> bool {
 2609        if !self.snippet_stack.is_empty() {
 2610            return false;
 2611        }
 2612
 2613        if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
 2614            return false;
 2615        }
 2616
 2617        if let Some(provider) = self.inline_completion_provider() {
 2618            if let Some(show_inline_completions) = self.show_inline_completions_override {
 2619                show_inline_completions
 2620            } else {
 2621                self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
 2622            }
 2623        } else {
 2624            false
 2625        }
 2626    }
 2627
 2628    fn inline_completions_disabled_in_scope(
 2629        &self,
 2630        buffer: &Model<Buffer>,
 2631        buffer_position: language::Anchor,
 2632        cx: &AppContext,
 2633    ) -> bool {
 2634        let snapshot = buffer.read(cx).snapshot();
 2635        let settings = snapshot.settings_at(buffer_position, cx);
 2636
 2637        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 2638            return false;
 2639        };
 2640
 2641        scope.override_name().map_or(false, |scope_name| {
 2642            settings
 2643                .inline_completions_disabled_in
 2644                .iter()
 2645                .any(|s| s == scope_name)
 2646        })
 2647    }
 2648
 2649    pub fn set_use_modal_editing(&mut self, to: bool) {
 2650        self.use_modal_editing = to;
 2651    }
 2652
 2653    pub fn use_modal_editing(&self) -> bool {
 2654        self.use_modal_editing
 2655    }
 2656
 2657    fn selections_did_change(
 2658        &mut self,
 2659        local: bool,
 2660        old_cursor_position: &Anchor,
 2661        show_completions: bool,
 2662        cx: &mut ViewContext<Self>,
 2663    ) {
 2664        cx.invalidate_character_coordinates();
 2665
 2666        // Copy selections to primary selection buffer
 2667        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 2668        if local {
 2669            let selections = self.selections.all::<usize>(cx);
 2670            let buffer_handle = self.buffer.read(cx).read(cx);
 2671
 2672            let mut text = String::new();
 2673            for (index, selection) in selections.iter().enumerate() {
 2674                let text_for_selection = buffer_handle
 2675                    .text_for_range(selection.start..selection.end)
 2676                    .collect::<String>();
 2677
 2678                text.push_str(&text_for_selection);
 2679                if index != selections.len() - 1 {
 2680                    text.push('\n');
 2681                }
 2682            }
 2683
 2684            if !text.is_empty() {
 2685                cx.write_to_primary(ClipboardItem::new_string(text));
 2686            }
 2687        }
 2688
 2689        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
 2690            self.buffer.update(cx, |buffer, cx| {
 2691                buffer.set_active_selections(
 2692                    &self.selections.disjoint_anchors(),
 2693                    self.selections.line_mode,
 2694                    self.cursor_shape,
 2695                    cx,
 2696                )
 2697            });
 2698        }
 2699        let display_map = self
 2700            .display_map
 2701            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2702        let buffer = &display_map.buffer_snapshot;
 2703        self.add_selections_state = None;
 2704        self.select_next_state = None;
 2705        self.select_prev_state = None;
 2706        self.select_larger_syntax_node_stack.clear();
 2707        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2708        self.snippet_stack
 2709            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2710        self.take_rename(false, cx);
 2711
 2712        let new_cursor_position = self.selections.newest_anchor().head();
 2713
 2714        self.push_to_nav_history(
 2715            *old_cursor_position,
 2716            Some(new_cursor_position.to_point(buffer)),
 2717            cx,
 2718        );
 2719
 2720        if local {
 2721            let new_cursor_position = self.selections.newest_anchor().head();
 2722            let mut context_menu = self.context_menu.write();
 2723            let completion_menu = match context_menu.as_ref() {
 2724                Some(ContextMenu::Completions(menu)) => Some(menu),
 2725
 2726                _ => {
 2727                    *context_menu = None;
 2728                    None
 2729                }
 2730            };
 2731
 2732            if let Some(completion_menu) = completion_menu {
 2733                let cursor_position = new_cursor_position.to_offset(buffer);
 2734                let (word_range, kind) =
 2735                    buffer.surrounding_word(completion_menu.initial_position, true);
 2736                if kind == Some(CharKind::Word)
 2737                    && word_range.to_inclusive().contains(&cursor_position)
 2738                {
 2739                    let mut completion_menu = completion_menu.clone();
 2740                    drop(context_menu);
 2741
 2742                    let query = Self::completion_query(buffer, cursor_position);
 2743                    cx.spawn(move |this, mut cx| async move {
 2744                        completion_menu
 2745                            .filter(query.as_deref(), cx.background_executor().clone())
 2746                            .await;
 2747
 2748                        this.update(&mut cx, |this, cx| {
 2749                            let mut context_menu = this.context_menu.write();
 2750                            let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
 2751                                return;
 2752                            };
 2753
 2754                            if menu.id > completion_menu.id {
 2755                                return;
 2756                            }
 2757
 2758                            *context_menu = Some(ContextMenu::Completions(completion_menu));
 2759                            drop(context_menu);
 2760                            cx.notify();
 2761                        })
 2762                    })
 2763                    .detach();
 2764
 2765                    if show_completions {
 2766                        self.show_completions(&ShowCompletions { trigger: None }, cx);
 2767                    }
 2768                } else {
 2769                    drop(context_menu);
 2770                    self.hide_context_menu(cx);
 2771                }
 2772            } else {
 2773                drop(context_menu);
 2774            }
 2775
 2776            hide_hover(self, cx);
 2777
 2778            if old_cursor_position.to_display_point(&display_map).row()
 2779                != new_cursor_position.to_display_point(&display_map).row()
 2780            {
 2781                self.available_code_actions.take();
 2782            }
 2783            self.refresh_code_actions(cx);
 2784            self.refresh_document_highlights(cx);
 2785            refresh_matching_bracket_highlights(self, cx);
 2786            self.discard_inline_completion(false, cx);
 2787            linked_editing_ranges::refresh_linked_ranges(self, cx);
 2788            if self.git_blame_inline_enabled {
 2789                self.start_inline_blame_timer(cx);
 2790            }
 2791        }
 2792
 2793        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2794        cx.emit(EditorEvent::SelectionsChanged { local });
 2795
 2796        if self.selections.disjoint_anchors().len() == 1 {
 2797            cx.emit(SearchEvent::ActiveMatchChanged)
 2798        }
 2799        cx.notify();
 2800    }
 2801
 2802    pub fn change_selections<R>(
 2803        &mut self,
 2804        autoscroll: Option<Autoscroll>,
 2805        cx: &mut ViewContext<Self>,
 2806        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2807    ) -> R {
 2808        self.change_selections_inner(autoscroll, true, cx, change)
 2809    }
 2810
 2811    pub fn change_selections_inner<R>(
 2812        &mut self,
 2813        autoscroll: Option<Autoscroll>,
 2814        request_completions: bool,
 2815        cx: &mut ViewContext<Self>,
 2816        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2817    ) -> R {
 2818        let old_cursor_position = self.selections.newest_anchor().head();
 2819        self.push_to_selection_history();
 2820
 2821        let (changed, result) = self.selections.change_with(cx, change);
 2822
 2823        if changed {
 2824            if let Some(autoscroll) = autoscroll {
 2825                self.request_autoscroll(autoscroll, cx);
 2826            }
 2827            self.selections_did_change(true, &old_cursor_position, request_completions, cx);
 2828
 2829            if self.should_open_signature_help_automatically(
 2830                &old_cursor_position,
 2831                self.signature_help_state.backspace_pressed(),
 2832                cx,
 2833            ) {
 2834                self.show_signature_help(&ShowSignatureHelp, cx);
 2835            }
 2836            self.signature_help_state.set_backspace_pressed(false);
 2837        }
 2838
 2839        result
 2840    }
 2841
 2842    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2843    where
 2844        I: IntoIterator<Item = (Range<S>, T)>,
 2845        S: ToOffset,
 2846        T: Into<Arc<str>>,
 2847    {
 2848        if self.read_only(cx) {
 2849            return;
 2850        }
 2851
 2852        self.buffer
 2853            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2854    }
 2855
 2856    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2857    where
 2858        I: IntoIterator<Item = (Range<S>, T)>,
 2859        S: ToOffset,
 2860        T: Into<Arc<str>>,
 2861    {
 2862        if self.read_only(cx) {
 2863            return;
 2864        }
 2865
 2866        self.buffer.update(cx, |buffer, cx| {
 2867            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2868        });
 2869    }
 2870
 2871    pub fn edit_with_block_indent<I, S, T>(
 2872        &mut self,
 2873        edits: I,
 2874        original_indent_columns: Vec<u32>,
 2875        cx: &mut ViewContext<Self>,
 2876    ) where
 2877        I: IntoIterator<Item = (Range<S>, T)>,
 2878        S: ToOffset,
 2879        T: Into<Arc<str>>,
 2880    {
 2881        if self.read_only(cx) {
 2882            return;
 2883        }
 2884
 2885        self.buffer.update(cx, |buffer, cx| {
 2886            buffer.edit(
 2887                edits,
 2888                Some(AutoindentMode::Block {
 2889                    original_indent_columns,
 2890                }),
 2891                cx,
 2892            )
 2893        });
 2894    }
 2895
 2896    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
 2897        self.hide_context_menu(cx);
 2898
 2899        match phase {
 2900            SelectPhase::Begin {
 2901                position,
 2902                add,
 2903                click_count,
 2904            } => self.begin_selection(position, add, click_count, cx),
 2905            SelectPhase::BeginColumnar {
 2906                position,
 2907                goal_column,
 2908                reset,
 2909            } => self.begin_columnar_selection(position, goal_column, reset, cx),
 2910            SelectPhase::Extend {
 2911                position,
 2912                click_count,
 2913            } => self.extend_selection(position, click_count, cx),
 2914            SelectPhase::Update {
 2915                position,
 2916                goal_column,
 2917                scroll_delta,
 2918            } => self.update_selection(position, goal_column, scroll_delta, cx),
 2919            SelectPhase::End => self.end_selection(cx),
 2920        }
 2921    }
 2922
 2923    fn extend_selection(
 2924        &mut self,
 2925        position: DisplayPoint,
 2926        click_count: usize,
 2927        cx: &mut ViewContext<Self>,
 2928    ) {
 2929        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2930        let tail = self.selections.newest::<usize>(cx).tail();
 2931        self.begin_selection(position, false, click_count, cx);
 2932
 2933        let position = position.to_offset(&display_map, Bias::Left);
 2934        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2935
 2936        let mut pending_selection = self
 2937            .selections
 2938            .pending_anchor()
 2939            .expect("extend_selection not called with pending selection");
 2940        if position >= tail {
 2941            pending_selection.start = tail_anchor;
 2942        } else {
 2943            pending_selection.end = tail_anchor;
 2944            pending_selection.reversed = true;
 2945        }
 2946
 2947        let mut pending_mode = self.selections.pending_mode().unwrap();
 2948        match &mut pending_mode {
 2949            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2950            _ => {}
 2951        }
 2952
 2953        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 2954            s.set_pending(pending_selection, pending_mode)
 2955        });
 2956    }
 2957
 2958    fn begin_selection(
 2959        &mut self,
 2960        position: DisplayPoint,
 2961        add: bool,
 2962        click_count: usize,
 2963        cx: &mut ViewContext<Self>,
 2964    ) {
 2965        if !self.focus_handle.is_focused(cx) {
 2966            self.last_focused_descendant = None;
 2967            cx.focus(&self.focus_handle);
 2968        }
 2969
 2970        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2971        let buffer = &display_map.buffer_snapshot;
 2972        let newest_selection = self.selections.newest_anchor().clone();
 2973        let position = display_map.clip_point(position, Bias::Left);
 2974
 2975        let start;
 2976        let end;
 2977        let mode;
 2978        let auto_scroll;
 2979        match click_count {
 2980            1 => {
 2981                start = buffer.anchor_before(position.to_point(&display_map));
 2982                end = start;
 2983                mode = SelectMode::Character;
 2984                auto_scroll = true;
 2985            }
 2986            2 => {
 2987                let range = movement::surrounding_word(&display_map, position);
 2988                start = buffer.anchor_before(range.start.to_point(&display_map));
 2989                end = buffer.anchor_before(range.end.to_point(&display_map));
 2990                mode = SelectMode::Word(start..end);
 2991                auto_scroll = true;
 2992            }
 2993            3 => {
 2994                let position = display_map
 2995                    .clip_point(position, Bias::Left)
 2996                    .to_point(&display_map);
 2997                let line_start = display_map.prev_line_boundary(position).0;
 2998                let next_line_start = buffer.clip_point(
 2999                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 3000                    Bias::Left,
 3001                );
 3002                start = buffer.anchor_before(line_start);
 3003                end = buffer.anchor_before(next_line_start);
 3004                mode = SelectMode::Line(start..end);
 3005                auto_scroll = true;
 3006            }
 3007            _ => {
 3008                start = buffer.anchor_before(0);
 3009                end = buffer.anchor_before(buffer.len());
 3010                mode = SelectMode::All;
 3011                auto_scroll = false;
 3012            }
 3013        }
 3014
 3015        let point_to_delete: Option<usize> = {
 3016            let selected_points: Vec<Selection<Point>> =
 3017                self.selections.disjoint_in_range(start..end, cx);
 3018
 3019            if !add || click_count > 1 {
 3020                None
 3021            } else if !selected_points.is_empty() {
 3022                Some(selected_points[0].id)
 3023            } else {
 3024                let clicked_point_already_selected =
 3025                    self.selections.disjoint.iter().find(|selection| {
 3026                        selection.start.to_point(buffer) == start.to_point(buffer)
 3027                            || selection.end.to_point(buffer) == end.to_point(buffer)
 3028                    });
 3029
 3030                clicked_point_already_selected.map(|selection| selection.id)
 3031            }
 3032        };
 3033
 3034        let selections_count = self.selections.count();
 3035
 3036        self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
 3037            if let Some(point_to_delete) = point_to_delete {
 3038                s.delete(point_to_delete);
 3039
 3040                if selections_count == 1 {
 3041                    s.set_pending_anchor_range(start..end, mode);
 3042                }
 3043            } else {
 3044                if !add {
 3045                    s.clear_disjoint();
 3046                } else if click_count > 1 {
 3047                    s.delete(newest_selection.id)
 3048                }
 3049
 3050                s.set_pending_anchor_range(start..end, mode);
 3051            }
 3052        });
 3053    }
 3054
 3055    fn begin_columnar_selection(
 3056        &mut self,
 3057        position: DisplayPoint,
 3058        goal_column: u32,
 3059        reset: bool,
 3060        cx: &mut ViewContext<Self>,
 3061    ) {
 3062        if !self.focus_handle.is_focused(cx) {
 3063            self.last_focused_descendant = None;
 3064            cx.focus(&self.focus_handle);
 3065        }
 3066
 3067        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 3068
 3069        if reset {
 3070            let pointer_position = display_map
 3071                .buffer_snapshot
 3072                .anchor_before(position.to_point(&display_map));
 3073
 3074            self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 3075                s.clear_disjoint();
 3076                s.set_pending_anchor_range(
 3077                    pointer_position..pointer_position,
 3078                    SelectMode::Character,
 3079                );
 3080            });
 3081        }
 3082
 3083        let tail = self.selections.newest::<Point>(cx).tail();
 3084        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 3085
 3086        if !reset {
 3087            self.select_columns(
 3088                tail.to_display_point(&display_map),
 3089                position,
 3090                goal_column,
 3091                &display_map,
 3092                cx,
 3093            );
 3094        }
 3095    }
 3096
 3097    fn update_selection(
 3098        &mut self,
 3099        position: DisplayPoint,
 3100        goal_column: u32,
 3101        scroll_delta: gpui::Point<f32>,
 3102        cx: &mut ViewContext<Self>,
 3103    ) {
 3104        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 3105
 3106        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 3107            let tail = tail.to_display_point(&display_map);
 3108            self.select_columns(tail, position, goal_column, &display_map, cx);
 3109        } else if let Some(mut pending) = self.selections.pending_anchor() {
 3110            let buffer = self.buffer.read(cx).snapshot(cx);
 3111            let head;
 3112            let tail;
 3113            let mode = self.selections.pending_mode().unwrap();
 3114            match &mode {
 3115                SelectMode::Character => {
 3116                    head = position.to_point(&display_map);
 3117                    tail = pending.tail().to_point(&buffer);
 3118                }
 3119                SelectMode::Word(original_range) => {
 3120                    let original_display_range = original_range.start.to_display_point(&display_map)
 3121                        ..original_range.end.to_display_point(&display_map);
 3122                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 3123                        ..original_display_range.end.to_point(&display_map);
 3124                    if movement::is_inside_word(&display_map, position)
 3125                        || original_display_range.contains(&position)
 3126                    {
 3127                        let word_range = movement::surrounding_word(&display_map, position);
 3128                        if word_range.start < original_display_range.start {
 3129                            head = word_range.start.to_point(&display_map);
 3130                        } else {
 3131                            head = word_range.end.to_point(&display_map);
 3132                        }
 3133                    } else {
 3134                        head = position.to_point(&display_map);
 3135                    }
 3136
 3137                    if head <= original_buffer_range.start {
 3138                        tail = original_buffer_range.end;
 3139                    } else {
 3140                        tail = original_buffer_range.start;
 3141                    }
 3142                }
 3143                SelectMode::Line(original_range) => {
 3144                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 3145
 3146                    let position = display_map
 3147                        .clip_point(position, Bias::Left)
 3148                        .to_point(&display_map);
 3149                    let line_start = display_map.prev_line_boundary(position).0;
 3150                    let next_line_start = buffer.clip_point(
 3151                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 3152                        Bias::Left,
 3153                    );
 3154
 3155                    if line_start < original_range.start {
 3156                        head = line_start
 3157                    } else {
 3158                        head = next_line_start
 3159                    }
 3160
 3161                    if head <= original_range.start {
 3162                        tail = original_range.end;
 3163                    } else {
 3164                        tail = original_range.start;
 3165                    }
 3166                }
 3167                SelectMode::All => {
 3168                    return;
 3169                }
 3170            };
 3171
 3172            if head < tail {
 3173                pending.start = buffer.anchor_before(head);
 3174                pending.end = buffer.anchor_before(tail);
 3175                pending.reversed = true;
 3176            } else {
 3177                pending.start = buffer.anchor_before(tail);
 3178                pending.end = buffer.anchor_before(head);
 3179                pending.reversed = false;
 3180            }
 3181
 3182            self.change_selections(None, cx, |s| {
 3183                s.set_pending(pending, mode);
 3184            });
 3185        } else {
 3186            log::error!("update_selection dispatched with no pending selection");
 3187            return;
 3188        }
 3189
 3190        self.apply_scroll_delta(scroll_delta, cx);
 3191        cx.notify();
 3192    }
 3193
 3194    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 3195        self.columnar_selection_tail.take();
 3196        if self.selections.pending_anchor().is_some() {
 3197            let selections = self.selections.all::<usize>(cx);
 3198            self.change_selections(None, cx, |s| {
 3199                s.select(selections);
 3200                s.clear_pending();
 3201            });
 3202        }
 3203    }
 3204
 3205    fn select_columns(
 3206        &mut self,
 3207        tail: DisplayPoint,
 3208        head: DisplayPoint,
 3209        goal_column: u32,
 3210        display_map: &DisplaySnapshot,
 3211        cx: &mut ViewContext<Self>,
 3212    ) {
 3213        let start_row = cmp::min(tail.row(), head.row());
 3214        let end_row = cmp::max(tail.row(), head.row());
 3215        let start_column = cmp::min(tail.column(), goal_column);
 3216        let end_column = cmp::max(tail.column(), goal_column);
 3217        let reversed = start_column < tail.column();
 3218
 3219        let selection_ranges = (start_row.0..=end_row.0)
 3220            .map(DisplayRow)
 3221            .filter_map(|row| {
 3222                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 3223                    let start = display_map
 3224                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 3225                        .to_point(display_map);
 3226                    let end = display_map
 3227                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 3228                        .to_point(display_map);
 3229                    if reversed {
 3230                        Some(end..start)
 3231                    } else {
 3232                        Some(start..end)
 3233                    }
 3234                } else {
 3235                    None
 3236                }
 3237            })
 3238            .collect::<Vec<_>>();
 3239
 3240        self.change_selections(None, cx, |s| {
 3241            s.select_ranges(selection_ranges);
 3242        });
 3243        cx.notify();
 3244    }
 3245
 3246    pub fn has_pending_nonempty_selection(&self) -> bool {
 3247        let pending_nonempty_selection = match self.selections.pending_anchor() {
 3248            Some(Selection { start, end, .. }) => start != end,
 3249            None => false,
 3250        };
 3251
 3252        pending_nonempty_selection
 3253            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 3254    }
 3255
 3256    pub fn has_pending_selection(&self) -> bool {
 3257        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 3258    }
 3259
 3260    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 3261        if self.clear_expanded_diff_hunks(cx) {
 3262            cx.notify();
 3263            return;
 3264        }
 3265        if self.dismiss_menus_and_popups(true, cx) {
 3266            return;
 3267        }
 3268
 3269        if self.mode == EditorMode::Full
 3270            && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
 3271        {
 3272            return;
 3273        }
 3274
 3275        cx.propagate();
 3276    }
 3277
 3278    pub fn dismiss_menus_and_popups(
 3279        &mut self,
 3280        should_report_inline_completion_event: bool,
 3281        cx: &mut ViewContext<Self>,
 3282    ) -> bool {
 3283        if self.take_rename(false, cx).is_some() {
 3284            return true;
 3285        }
 3286
 3287        if hide_hover(self, cx) {
 3288            return true;
 3289        }
 3290
 3291        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 3292            return true;
 3293        }
 3294
 3295        if self.hide_context_menu(cx).is_some() {
 3296            return true;
 3297        }
 3298
 3299        if self.mouse_context_menu.take().is_some() {
 3300            return true;
 3301        }
 3302
 3303        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 3304            return true;
 3305        }
 3306
 3307        if self.snippet_stack.pop().is_some() {
 3308            return true;
 3309        }
 3310
 3311        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 3312            self.dismiss_diagnostics(cx);
 3313            return true;
 3314        }
 3315
 3316        false
 3317    }
 3318
 3319    fn linked_editing_ranges_for(
 3320        &self,
 3321        selection: Range<text::Anchor>,
 3322        cx: &AppContext,
 3323    ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
 3324        if self.linked_edit_ranges.is_empty() {
 3325            return None;
 3326        }
 3327        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 3328            selection.end.buffer_id.and_then(|end_buffer_id| {
 3329                if selection.start.buffer_id != Some(end_buffer_id) {
 3330                    return None;
 3331                }
 3332                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 3333                let snapshot = buffer.read(cx).snapshot();
 3334                self.linked_edit_ranges
 3335                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 3336                    .map(|ranges| (ranges, snapshot, buffer))
 3337            })?;
 3338        use text::ToOffset as TO;
 3339        // find offset from the start of current range to current cursor position
 3340        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 3341
 3342        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 3343        let start_difference = start_offset - start_byte_offset;
 3344        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 3345        let end_difference = end_offset - start_byte_offset;
 3346        // Current range has associated linked ranges.
 3347        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3348        for range in linked_ranges.iter() {
 3349            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 3350            let end_offset = start_offset + end_difference;
 3351            let start_offset = start_offset + start_difference;
 3352            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 3353                continue;
 3354            }
 3355            if self.selections.disjoint_anchor_ranges().iter().any(|s| {
 3356                if s.start.buffer_id != selection.start.buffer_id
 3357                    || s.end.buffer_id != selection.end.buffer_id
 3358                {
 3359                    return false;
 3360                }
 3361                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 3362                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 3363            }) {
 3364                continue;
 3365            }
 3366            let start = buffer_snapshot.anchor_after(start_offset);
 3367            let end = buffer_snapshot.anchor_after(end_offset);
 3368            linked_edits
 3369                .entry(buffer.clone())
 3370                .or_default()
 3371                .push(start..end);
 3372        }
 3373        Some(linked_edits)
 3374    }
 3375
 3376    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3377        let text: Arc<str> = text.into();
 3378
 3379        if self.read_only(cx) {
 3380            return;
 3381        }
 3382
 3383        let selections = self.selections.all_adjusted(cx);
 3384        let mut bracket_inserted = false;
 3385        let mut edits = Vec::new();
 3386        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3387        let mut new_selections = Vec::with_capacity(selections.len());
 3388        let mut new_autoclose_regions = Vec::new();
 3389        let snapshot = self.buffer.read(cx).read(cx);
 3390
 3391        for (selection, autoclose_region) in
 3392            self.selections_with_autoclose_regions(selections, &snapshot)
 3393        {
 3394            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 3395                // Determine if the inserted text matches the opening or closing
 3396                // bracket of any of this language's bracket pairs.
 3397                let mut bracket_pair = None;
 3398                let mut is_bracket_pair_start = false;
 3399                let mut is_bracket_pair_end = false;
 3400                if !text.is_empty() {
 3401                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 3402                    //  and they are removing the character that triggered IME popup.
 3403                    for (pair, enabled) in scope.brackets() {
 3404                        if !pair.close && !pair.surround {
 3405                            continue;
 3406                        }
 3407
 3408                        if enabled && pair.start.ends_with(text.as_ref()) {
 3409                            let prefix_len = pair.start.len() - text.len();
 3410                            let preceding_text_matches_prefix = prefix_len == 0
 3411                                || (selection.start.column >= (prefix_len as u32)
 3412                                    && snapshot.contains_str_at(
 3413                                        Point::new(
 3414                                            selection.start.row,
 3415                                            selection.start.column - (prefix_len as u32),
 3416                                        ),
 3417                                        &pair.start[..prefix_len],
 3418                                    ));
 3419                            if preceding_text_matches_prefix {
 3420                                bracket_pair = Some(pair.clone());
 3421                                is_bracket_pair_start = true;
 3422                                break;
 3423                            }
 3424                        }
 3425                        if pair.end.as_str() == text.as_ref() {
 3426                            bracket_pair = Some(pair.clone());
 3427                            is_bracket_pair_end = true;
 3428                            break;
 3429                        }
 3430                    }
 3431                }
 3432
 3433                if let Some(bracket_pair) = bracket_pair {
 3434                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 3435                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 3436                    let auto_surround =
 3437                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 3438                    if selection.is_empty() {
 3439                        if is_bracket_pair_start {
 3440                            // If the inserted text is a suffix of an opening bracket and the
 3441                            // selection is preceded by the rest of the opening bracket, then
 3442                            // insert the closing bracket.
 3443                            let following_text_allows_autoclose = snapshot
 3444                                .chars_at(selection.start)
 3445                                .next()
 3446                                .map_or(true, |c| scope.should_autoclose_before(c));
 3447
 3448                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 3449                                && bracket_pair.start.len() == 1
 3450                            {
 3451                                let target = bracket_pair.start.chars().next().unwrap();
 3452                                let current_line_count = snapshot
 3453                                    .reversed_chars_at(selection.start)
 3454                                    .take_while(|&c| c != '\n')
 3455                                    .filter(|&c| c == target)
 3456                                    .count();
 3457                                current_line_count % 2 == 1
 3458                            } else {
 3459                                false
 3460                            };
 3461
 3462                            if autoclose
 3463                                && bracket_pair.close
 3464                                && following_text_allows_autoclose
 3465                                && !is_closing_quote
 3466                            {
 3467                                let anchor = snapshot.anchor_before(selection.end);
 3468                                new_selections.push((selection.map(|_| anchor), text.len()));
 3469                                new_autoclose_regions.push((
 3470                                    anchor,
 3471                                    text.len(),
 3472                                    selection.id,
 3473                                    bracket_pair.clone(),
 3474                                ));
 3475                                edits.push((
 3476                                    selection.range(),
 3477                                    format!("{}{}", text, bracket_pair.end).into(),
 3478                                ));
 3479                                bracket_inserted = true;
 3480                                continue;
 3481                            }
 3482                        }
 3483
 3484                        if let Some(region) = autoclose_region {
 3485                            // If the selection is followed by an auto-inserted closing bracket,
 3486                            // then don't insert that closing bracket again; just move the selection
 3487                            // past the closing bracket.
 3488                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3489                                && text.as_ref() == region.pair.end.as_str();
 3490                            if should_skip {
 3491                                let anchor = snapshot.anchor_after(selection.end);
 3492                                new_selections
 3493                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3494                                continue;
 3495                            }
 3496                        }
 3497
 3498                        let always_treat_brackets_as_autoclosed = snapshot
 3499                            .settings_at(selection.start, cx)
 3500                            .always_treat_brackets_as_autoclosed;
 3501                        if always_treat_brackets_as_autoclosed
 3502                            && is_bracket_pair_end
 3503                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3504                        {
 3505                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3506                            // and the inserted text is a closing bracket and the selection is followed
 3507                            // by the closing bracket then move the selection past the closing bracket.
 3508                            let anchor = snapshot.anchor_after(selection.end);
 3509                            new_selections.push((selection.map(|_| anchor), text.len()));
 3510                            continue;
 3511                        }
 3512                    }
 3513                    // If an opening bracket is 1 character long and is typed while
 3514                    // text is selected, then surround that text with the bracket pair.
 3515                    else if auto_surround
 3516                        && bracket_pair.surround
 3517                        && is_bracket_pair_start
 3518                        && bracket_pair.start.chars().count() == 1
 3519                    {
 3520                        edits.push((selection.start..selection.start, text.clone()));
 3521                        edits.push((
 3522                            selection.end..selection.end,
 3523                            bracket_pair.end.as_str().into(),
 3524                        ));
 3525                        bracket_inserted = true;
 3526                        new_selections.push((
 3527                            Selection {
 3528                                id: selection.id,
 3529                                start: snapshot.anchor_after(selection.start),
 3530                                end: snapshot.anchor_before(selection.end),
 3531                                reversed: selection.reversed,
 3532                                goal: selection.goal,
 3533                            },
 3534                            0,
 3535                        ));
 3536                        continue;
 3537                    }
 3538                }
 3539            }
 3540
 3541            if self.auto_replace_emoji_shortcode
 3542                && selection.is_empty()
 3543                && text.as_ref().ends_with(':')
 3544            {
 3545                if let Some(possible_emoji_short_code) =
 3546                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3547                {
 3548                    if !possible_emoji_short_code.is_empty() {
 3549                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3550                            let emoji_shortcode_start = Point::new(
 3551                                selection.start.row,
 3552                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3553                            );
 3554
 3555                            // Remove shortcode from buffer
 3556                            edits.push((
 3557                                emoji_shortcode_start..selection.start,
 3558                                "".to_string().into(),
 3559                            ));
 3560                            new_selections.push((
 3561                                Selection {
 3562                                    id: selection.id,
 3563                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3564                                    end: snapshot.anchor_before(selection.start),
 3565                                    reversed: selection.reversed,
 3566                                    goal: selection.goal,
 3567                                },
 3568                                0,
 3569                            ));
 3570
 3571                            // Insert emoji
 3572                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3573                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3574                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3575
 3576                            continue;
 3577                        }
 3578                    }
 3579                }
 3580            }
 3581
 3582            // If not handling any auto-close operation, then just replace the selected
 3583            // text with the given input and move the selection to the end of the
 3584            // newly inserted text.
 3585            let anchor = snapshot.anchor_after(selection.end);
 3586            if !self.linked_edit_ranges.is_empty() {
 3587                let start_anchor = snapshot.anchor_before(selection.start);
 3588
 3589                let is_word_char = text.chars().next().map_or(true, |char| {
 3590                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3591                    classifier.is_word(char)
 3592                });
 3593
 3594                if is_word_char {
 3595                    if let Some(ranges) = self
 3596                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3597                    {
 3598                        for (buffer, edits) in ranges {
 3599                            linked_edits
 3600                                .entry(buffer.clone())
 3601                                .or_default()
 3602                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3603                        }
 3604                    }
 3605                }
 3606            }
 3607
 3608            new_selections.push((selection.map(|_| anchor), 0));
 3609            edits.push((selection.start..selection.end, text.clone()));
 3610        }
 3611
 3612        drop(snapshot);
 3613
 3614        self.transact(cx, |this, cx| {
 3615            this.buffer.update(cx, |buffer, cx| {
 3616                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3617            });
 3618            for (buffer, edits) in linked_edits {
 3619                buffer.update(cx, |buffer, cx| {
 3620                    let snapshot = buffer.snapshot();
 3621                    let edits = edits
 3622                        .into_iter()
 3623                        .map(|(range, text)| {
 3624                            use text::ToPoint as TP;
 3625                            let end_point = TP::to_point(&range.end, &snapshot);
 3626                            let start_point = TP::to_point(&range.start, &snapshot);
 3627                            (start_point..end_point, text)
 3628                        })
 3629                        .sorted_by_key(|(range, _)| range.start)
 3630                        .collect::<Vec<_>>();
 3631                    buffer.edit(edits, None, cx);
 3632                })
 3633            }
 3634            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3635            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3636            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3637            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3638                .zip(new_selection_deltas)
 3639                .map(|(selection, delta)| Selection {
 3640                    id: selection.id,
 3641                    start: selection.start + delta,
 3642                    end: selection.end + delta,
 3643                    reversed: selection.reversed,
 3644                    goal: SelectionGoal::None,
 3645                })
 3646                .collect::<Vec<_>>();
 3647
 3648            let mut i = 0;
 3649            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3650                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3651                let start = map.buffer_snapshot.anchor_before(position);
 3652                let end = map.buffer_snapshot.anchor_after(position);
 3653                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3654                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3655                        Ordering::Less => i += 1,
 3656                        Ordering::Greater => break,
 3657                        Ordering::Equal => {
 3658                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3659                                Ordering::Less => i += 1,
 3660                                Ordering::Equal => break,
 3661                                Ordering::Greater => break,
 3662                            }
 3663                        }
 3664                    }
 3665                }
 3666                this.autoclose_regions.insert(
 3667                    i,
 3668                    AutocloseRegion {
 3669                        selection_id,
 3670                        range: start..end,
 3671                        pair,
 3672                    },
 3673                );
 3674            }
 3675
 3676            let had_active_inline_completion = this.has_active_inline_completion(cx);
 3677            this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
 3678                s.select(new_selections)
 3679            });
 3680
 3681            if !bracket_inserted {
 3682                if let Some(on_type_format_task) =
 3683                    this.trigger_on_type_formatting(text.to_string(), cx)
 3684                {
 3685                    on_type_format_task.detach_and_log_err(cx);
 3686                }
 3687            }
 3688
 3689            let editor_settings = EditorSettings::get_global(cx);
 3690            if bracket_inserted
 3691                && (editor_settings.auto_signature_help
 3692                    || editor_settings.show_signature_help_after_edits)
 3693            {
 3694                this.show_signature_help(&ShowSignatureHelp, cx);
 3695            }
 3696
 3697            let trigger_in_words = !had_active_inline_completion;
 3698            this.trigger_completion_on_input(&text, trigger_in_words, cx);
 3699            linked_editing_ranges::refresh_linked_ranges(this, cx);
 3700            this.refresh_inline_completion(true, false, cx);
 3701        });
 3702    }
 3703
 3704    fn find_possible_emoji_shortcode_at_position(
 3705        snapshot: &MultiBufferSnapshot,
 3706        position: Point,
 3707    ) -> Option<String> {
 3708        let mut chars = Vec::new();
 3709        let mut found_colon = false;
 3710        for char in snapshot.reversed_chars_at(position).take(100) {
 3711            // Found a possible emoji shortcode in the middle of the buffer
 3712            if found_colon {
 3713                if char.is_whitespace() {
 3714                    chars.reverse();
 3715                    return Some(chars.iter().collect());
 3716                }
 3717                // If the previous character is not a whitespace, we are in the middle of a word
 3718                // and we only want to complete the shortcode if the word is made up of other emojis
 3719                let mut containing_word = String::new();
 3720                for ch in snapshot
 3721                    .reversed_chars_at(position)
 3722                    .skip(chars.len() + 1)
 3723                    .take(100)
 3724                {
 3725                    if ch.is_whitespace() {
 3726                        break;
 3727                    }
 3728                    containing_word.push(ch);
 3729                }
 3730                let containing_word = containing_word.chars().rev().collect::<String>();
 3731                if util::word_consists_of_emojis(containing_word.as_str()) {
 3732                    chars.reverse();
 3733                    return Some(chars.iter().collect());
 3734                }
 3735            }
 3736
 3737            if char.is_whitespace() || !char.is_ascii() {
 3738                return None;
 3739            }
 3740            if char == ':' {
 3741                found_colon = true;
 3742            } else {
 3743                chars.push(char);
 3744            }
 3745        }
 3746        // Found a possible emoji shortcode at the beginning of the buffer
 3747        chars.reverse();
 3748        Some(chars.iter().collect())
 3749    }
 3750
 3751    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 3752        self.transact(cx, |this, cx| {
 3753            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3754                let selections = this.selections.all::<usize>(cx);
 3755                let multi_buffer = this.buffer.read(cx);
 3756                let buffer = multi_buffer.snapshot(cx);
 3757                selections
 3758                    .iter()
 3759                    .map(|selection| {
 3760                        let start_point = selection.start.to_point(&buffer);
 3761                        let mut indent =
 3762                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3763                        indent.len = cmp::min(indent.len, start_point.column);
 3764                        let start = selection.start;
 3765                        let end = selection.end;
 3766                        let selection_is_empty = start == end;
 3767                        let language_scope = buffer.language_scope_at(start);
 3768                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3769                            &language_scope
 3770                        {
 3771                            let leading_whitespace_len = buffer
 3772                                .reversed_chars_at(start)
 3773                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3774                                .map(|c| c.len_utf8())
 3775                                .sum::<usize>();
 3776
 3777                            let trailing_whitespace_len = buffer
 3778                                .chars_at(end)
 3779                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3780                                .map(|c| c.len_utf8())
 3781                                .sum::<usize>();
 3782
 3783                            let insert_extra_newline =
 3784                                language.brackets().any(|(pair, enabled)| {
 3785                                    let pair_start = pair.start.trim_end();
 3786                                    let pair_end = pair.end.trim_start();
 3787
 3788                                    enabled
 3789                                        && pair.newline
 3790                                        && buffer.contains_str_at(
 3791                                            end + trailing_whitespace_len,
 3792                                            pair_end,
 3793                                        )
 3794                                        && buffer.contains_str_at(
 3795                                            (start - leading_whitespace_len)
 3796                                                .saturating_sub(pair_start.len()),
 3797                                            pair_start,
 3798                                        )
 3799                                });
 3800
 3801                            // Comment extension on newline is allowed only for cursor selections
 3802                            let comment_delimiter = maybe!({
 3803                                if !selection_is_empty {
 3804                                    return None;
 3805                                }
 3806
 3807                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3808                                    return None;
 3809                                }
 3810
 3811                                let delimiters = language.line_comment_prefixes();
 3812                                let max_len_of_delimiter =
 3813                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3814                                let (snapshot, range) =
 3815                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3816
 3817                                let mut index_of_first_non_whitespace = 0;
 3818                                let comment_candidate = snapshot
 3819                                    .chars_for_range(range)
 3820                                    .skip_while(|c| {
 3821                                        let should_skip = c.is_whitespace();
 3822                                        if should_skip {
 3823                                            index_of_first_non_whitespace += 1;
 3824                                        }
 3825                                        should_skip
 3826                                    })
 3827                                    .take(max_len_of_delimiter)
 3828                                    .collect::<String>();
 3829                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3830                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3831                                })?;
 3832                                let cursor_is_placed_after_comment_marker =
 3833                                    index_of_first_non_whitespace + comment_prefix.len()
 3834                                        <= start_point.column as usize;
 3835                                if cursor_is_placed_after_comment_marker {
 3836                                    Some(comment_prefix.clone())
 3837                                } else {
 3838                                    None
 3839                                }
 3840                            });
 3841                            (comment_delimiter, insert_extra_newline)
 3842                        } else {
 3843                            (None, false)
 3844                        };
 3845
 3846                        let capacity_for_delimiter = comment_delimiter
 3847                            .as_deref()
 3848                            .map(str::len)
 3849                            .unwrap_or_default();
 3850                        let mut new_text =
 3851                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3852                        new_text.push('\n');
 3853                        new_text.extend(indent.chars());
 3854                        if let Some(delimiter) = &comment_delimiter {
 3855                            new_text.push_str(delimiter);
 3856                        }
 3857                        if insert_extra_newline {
 3858                            new_text = new_text.repeat(2);
 3859                        }
 3860
 3861                        let anchor = buffer.anchor_after(end);
 3862                        let new_selection = selection.map(|_| anchor);
 3863                        (
 3864                            (start..end, new_text),
 3865                            (insert_extra_newline, new_selection),
 3866                        )
 3867                    })
 3868                    .unzip()
 3869            };
 3870
 3871            this.edit_with_autoindent(edits, cx);
 3872            let buffer = this.buffer.read(cx).snapshot(cx);
 3873            let new_selections = selection_fixup_info
 3874                .into_iter()
 3875                .map(|(extra_newline_inserted, new_selection)| {
 3876                    let mut cursor = new_selection.end.to_point(&buffer);
 3877                    if extra_newline_inserted {
 3878                        cursor.row -= 1;
 3879                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3880                    }
 3881                    new_selection.map(|_| cursor)
 3882                })
 3883                .collect();
 3884
 3885            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3886            this.refresh_inline_completion(true, false, cx);
 3887        });
 3888    }
 3889
 3890    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3891        let buffer = self.buffer.read(cx);
 3892        let snapshot = buffer.snapshot(cx);
 3893
 3894        let mut edits = Vec::new();
 3895        let mut rows = Vec::new();
 3896
 3897        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3898            let cursor = selection.head();
 3899            let row = cursor.row;
 3900
 3901            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3902
 3903            let newline = "\n".to_string();
 3904            edits.push((start_of_line..start_of_line, newline));
 3905
 3906            rows.push(row + rows_inserted as u32);
 3907        }
 3908
 3909        self.transact(cx, |editor, cx| {
 3910            editor.edit(edits, cx);
 3911
 3912            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3913                let mut index = 0;
 3914                s.move_cursors_with(|map, _, _| {
 3915                    let row = rows[index];
 3916                    index += 1;
 3917
 3918                    let point = Point::new(row, 0);
 3919                    let boundary = map.next_line_boundary(point).1;
 3920                    let clipped = map.clip_point(boundary, Bias::Left);
 3921
 3922                    (clipped, SelectionGoal::None)
 3923                });
 3924            });
 3925
 3926            let mut indent_edits = Vec::new();
 3927            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3928            for row in rows {
 3929                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3930                for (row, indent) in indents {
 3931                    if indent.len == 0 {
 3932                        continue;
 3933                    }
 3934
 3935                    let text = match indent.kind {
 3936                        IndentKind::Space => " ".repeat(indent.len as usize),
 3937                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3938                    };
 3939                    let point = Point::new(row.0, 0);
 3940                    indent_edits.push((point..point, text));
 3941                }
 3942            }
 3943            editor.edit(indent_edits, cx);
 3944        });
 3945    }
 3946
 3947    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3948        let buffer = self.buffer.read(cx);
 3949        let snapshot = buffer.snapshot(cx);
 3950
 3951        let mut edits = Vec::new();
 3952        let mut rows = Vec::new();
 3953        let mut rows_inserted = 0;
 3954
 3955        for selection in self.selections.all_adjusted(cx) {
 3956            let cursor = selection.head();
 3957            let row = cursor.row;
 3958
 3959            let point = Point::new(row + 1, 0);
 3960            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3961
 3962            let newline = "\n".to_string();
 3963            edits.push((start_of_line..start_of_line, newline));
 3964
 3965            rows_inserted += 1;
 3966            rows.push(row + rows_inserted);
 3967        }
 3968
 3969        self.transact(cx, |editor, cx| {
 3970            editor.edit(edits, cx);
 3971
 3972            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3973                let mut index = 0;
 3974                s.move_cursors_with(|map, _, _| {
 3975                    let row = rows[index];
 3976                    index += 1;
 3977
 3978                    let point = Point::new(row, 0);
 3979                    let boundary = map.next_line_boundary(point).1;
 3980                    let clipped = map.clip_point(boundary, Bias::Left);
 3981
 3982                    (clipped, SelectionGoal::None)
 3983                });
 3984            });
 3985
 3986            let mut indent_edits = Vec::new();
 3987            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3988            for row in rows {
 3989                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3990                for (row, indent) in indents {
 3991                    if indent.len == 0 {
 3992                        continue;
 3993                    }
 3994
 3995                    let text = match indent.kind {
 3996                        IndentKind::Space => " ".repeat(indent.len as usize),
 3997                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3998                    };
 3999                    let point = Point::new(row.0, 0);
 4000                    indent_edits.push((point..point, text));
 4001                }
 4002            }
 4003            editor.edit(indent_edits, cx);
 4004        });
 4005    }
 4006
 4007    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 4008        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 4009            original_indent_columns: Vec::new(),
 4010        });
 4011        self.insert_with_autoindent_mode(text, autoindent, cx);
 4012    }
 4013
 4014    fn insert_with_autoindent_mode(
 4015        &mut self,
 4016        text: &str,
 4017        autoindent_mode: Option<AutoindentMode>,
 4018        cx: &mut ViewContext<Self>,
 4019    ) {
 4020        if self.read_only(cx) {
 4021            return;
 4022        }
 4023
 4024        let text: Arc<str> = text.into();
 4025        self.transact(cx, |this, cx| {
 4026            let old_selections = this.selections.all_adjusted(cx);
 4027            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 4028                let anchors = {
 4029                    let snapshot = buffer.read(cx);
 4030                    old_selections
 4031                        .iter()
 4032                        .map(|s| {
 4033                            let anchor = snapshot.anchor_after(s.head());
 4034                            s.map(|_| anchor)
 4035                        })
 4036                        .collect::<Vec<_>>()
 4037                };
 4038                buffer.edit(
 4039                    old_selections
 4040                        .iter()
 4041                        .map(|s| (s.start..s.end, text.clone())),
 4042                    autoindent_mode,
 4043                    cx,
 4044                );
 4045                anchors
 4046            });
 4047
 4048            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 4049                s.select_anchors(selection_anchors);
 4050            })
 4051        });
 4052    }
 4053
 4054    fn trigger_completion_on_input(
 4055        &mut self,
 4056        text: &str,
 4057        trigger_in_words: bool,
 4058        cx: &mut ViewContext<Self>,
 4059    ) {
 4060        if self.is_completion_trigger(text, trigger_in_words, cx) {
 4061            self.show_completions(
 4062                &ShowCompletions {
 4063                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 4064                },
 4065                cx,
 4066            );
 4067        } else {
 4068            self.hide_context_menu(cx);
 4069        }
 4070    }
 4071
 4072    fn is_completion_trigger(
 4073        &self,
 4074        text: &str,
 4075        trigger_in_words: bool,
 4076        cx: &mut ViewContext<Self>,
 4077    ) -> bool {
 4078        let position = self.selections.newest_anchor().head();
 4079        let multibuffer = self.buffer.read(cx);
 4080        let Some(buffer) = position
 4081            .buffer_id
 4082            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 4083        else {
 4084            return false;
 4085        };
 4086
 4087        if let Some(completion_provider) = &self.completion_provider {
 4088            completion_provider.is_completion_trigger(
 4089                &buffer,
 4090                position.text_anchor,
 4091                text,
 4092                trigger_in_words,
 4093                cx,
 4094            )
 4095        } else {
 4096            false
 4097        }
 4098    }
 4099
 4100    /// If any empty selections is touching the start of its innermost containing autoclose
 4101    /// region, expand it to select the brackets.
 4102    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 4103        let selections = self.selections.all::<usize>(cx);
 4104        let buffer = self.buffer.read(cx).read(cx);
 4105        let new_selections = self
 4106            .selections_with_autoclose_regions(selections, &buffer)
 4107            .map(|(mut selection, region)| {
 4108                if !selection.is_empty() {
 4109                    return selection;
 4110                }
 4111
 4112                if let Some(region) = region {
 4113                    let mut range = region.range.to_offset(&buffer);
 4114                    if selection.start == range.start && range.start >= region.pair.start.len() {
 4115                        range.start -= region.pair.start.len();
 4116                        if buffer.contains_str_at(range.start, &region.pair.start)
 4117                            && buffer.contains_str_at(range.end, &region.pair.end)
 4118                        {
 4119                            range.end += region.pair.end.len();
 4120                            selection.start = range.start;
 4121                            selection.end = range.end;
 4122
 4123                            return selection;
 4124                        }
 4125                    }
 4126                }
 4127
 4128                let always_treat_brackets_as_autoclosed = buffer
 4129                    .settings_at(selection.start, cx)
 4130                    .always_treat_brackets_as_autoclosed;
 4131
 4132                if !always_treat_brackets_as_autoclosed {
 4133                    return selection;
 4134                }
 4135
 4136                if let Some(scope) = buffer.language_scope_at(selection.start) {
 4137                    for (pair, enabled) in scope.brackets() {
 4138                        if !enabled || !pair.close {
 4139                            continue;
 4140                        }
 4141
 4142                        if buffer.contains_str_at(selection.start, &pair.end) {
 4143                            let pair_start_len = pair.start.len();
 4144                            if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
 4145                            {
 4146                                selection.start -= pair_start_len;
 4147                                selection.end += pair.end.len();
 4148
 4149                                return selection;
 4150                            }
 4151                        }
 4152                    }
 4153                }
 4154
 4155                selection
 4156            })
 4157            .collect();
 4158
 4159        drop(buffer);
 4160        self.change_selections(None, cx, |selections| selections.select(new_selections));
 4161    }
 4162
 4163    /// Iterate the given selections, and for each one, find the smallest surrounding
 4164    /// autoclose region. This uses the ordering of the selections and the autoclose
 4165    /// regions to avoid repeated comparisons.
 4166    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 4167        &'a self,
 4168        selections: impl IntoIterator<Item = Selection<D>>,
 4169        buffer: &'a MultiBufferSnapshot,
 4170    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 4171        let mut i = 0;
 4172        let mut regions = self.autoclose_regions.as_slice();
 4173        selections.into_iter().map(move |selection| {
 4174            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 4175
 4176            let mut enclosing = None;
 4177            while let Some(pair_state) = regions.get(i) {
 4178                if pair_state.range.end.to_offset(buffer) < range.start {
 4179                    regions = &regions[i + 1..];
 4180                    i = 0;
 4181                } else if pair_state.range.start.to_offset(buffer) > range.end {
 4182                    break;
 4183                } else {
 4184                    if pair_state.selection_id == selection.id {
 4185                        enclosing = Some(pair_state);
 4186                    }
 4187                    i += 1;
 4188                }
 4189            }
 4190
 4191            (selection, enclosing)
 4192        })
 4193    }
 4194
 4195    /// Remove any autoclose regions that no longer contain their selection.
 4196    fn invalidate_autoclose_regions(
 4197        &mut self,
 4198        mut selections: &[Selection<Anchor>],
 4199        buffer: &MultiBufferSnapshot,
 4200    ) {
 4201        self.autoclose_regions.retain(|state| {
 4202            let mut i = 0;
 4203            while let Some(selection) = selections.get(i) {
 4204                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 4205                    selections = &selections[1..];
 4206                    continue;
 4207                }
 4208                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 4209                    break;
 4210                }
 4211                if selection.id == state.selection_id {
 4212                    return true;
 4213                } else {
 4214                    i += 1;
 4215                }
 4216            }
 4217            false
 4218        });
 4219    }
 4220
 4221    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 4222        let offset = position.to_offset(buffer);
 4223        let (word_range, kind) = buffer.surrounding_word(offset, true);
 4224        if offset > word_range.start && kind == Some(CharKind::Word) {
 4225            Some(
 4226                buffer
 4227                    .text_for_range(word_range.start..offset)
 4228                    .collect::<String>(),
 4229            )
 4230        } else {
 4231            None
 4232        }
 4233    }
 4234
 4235    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 4236        self.refresh_inlay_hints(
 4237            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 4238            cx,
 4239        );
 4240    }
 4241
 4242    pub fn inlay_hints_enabled(&self) -> bool {
 4243        self.inlay_hint_cache.enabled
 4244    }
 4245
 4246    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 4247        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 4248            return;
 4249        }
 4250
 4251        let reason_description = reason.description();
 4252        let ignore_debounce = matches!(
 4253            reason,
 4254            InlayHintRefreshReason::SettingsChange(_)
 4255                | InlayHintRefreshReason::Toggle(_)
 4256                | InlayHintRefreshReason::ExcerptsRemoved(_)
 4257        );
 4258        let (invalidate_cache, required_languages) = match reason {
 4259            InlayHintRefreshReason::Toggle(enabled) => {
 4260                self.inlay_hint_cache.enabled = enabled;
 4261                if enabled {
 4262                    (InvalidationStrategy::RefreshRequested, None)
 4263                } else {
 4264                    self.inlay_hint_cache.clear();
 4265                    self.splice_inlays(
 4266                        self.visible_inlay_hints(cx)
 4267                            .iter()
 4268                            .map(|inlay| inlay.id)
 4269                            .collect(),
 4270                        Vec::new(),
 4271                        cx,
 4272                    );
 4273                    return;
 4274                }
 4275            }
 4276            InlayHintRefreshReason::SettingsChange(new_settings) => {
 4277                match self.inlay_hint_cache.update_settings(
 4278                    &self.buffer,
 4279                    new_settings,
 4280                    self.visible_inlay_hints(cx),
 4281                    cx,
 4282                ) {
 4283                    ControlFlow::Break(Some(InlaySplice {
 4284                        to_remove,
 4285                        to_insert,
 4286                    })) => {
 4287                        self.splice_inlays(to_remove, to_insert, cx);
 4288                        return;
 4289                    }
 4290                    ControlFlow::Break(None) => return,
 4291                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 4292                }
 4293            }
 4294            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 4295                if let Some(InlaySplice {
 4296                    to_remove,
 4297                    to_insert,
 4298                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 4299                {
 4300                    self.splice_inlays(to_remove, to_insert, cx);
 4301                }
 4302                return;
 4303            }
 4304            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 4305            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 4306                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 4307            }
 4308            InlayHintRefreshReason::RefreshRequested => {
 4309                (InvalidationStrategy::RefreshRequested, None)
 4310            }
 4311        };
 4312
 4313        if let Some(InlaySplice {
 4314            to_remove,
 4315            to_insert,
 4316        }) = self.inlay_hint_cache.spawn_hint_refresh(
 4317            reason_description,
 4318            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 4319            invalidate_cache,
 4320            ignore_debounce,
 4321            cx,
 4322        ) {
 4323            self.splice_inlays(to_remove, to_insert, cx);
 4324        }
 4325    }
 4326
 4327    fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
 4328        self.display_map
 4329            .read(cx)
 4330            .current_inlays()
 4331            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 4332            .cloned()
 4333            .collect()
 4334    }
 4335
 4336    pub fn excerpts_for_inlay_hints_query(
 4337        &self,
 4338        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 4339        cx: &mut ViewContext<Editor>,
 4340    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 4341        let Some(project) = self.project.as_ref() else {
 4342            return HashMap::default();
 4343        };
 4344        let project = project.read(cx);
 4345        let multi_buffer = self.buffer().read(cx);
 4346        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 4347        let multi_buffer_visible_start = self
 4348            .scroll_manager
 4349            .anchor()
 4350            .anchor
 4351            .to_point(&multi_buffer_snapshot);
 4352        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 4353            multi_buffer_visible_start
 4354                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 4355            Bias::Left,
 4356        );
 4357        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 4358        multi_buffer
 4359            .range_to_buffer_ranges(multi_buffer_visible_range, cx)
 4360            .into_iter()
 4361            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 4362            .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
 4363                let buffer = buffer_handle.read(cx);
 4364                let buffer_file = project::File::from_dyn(buffer.file())?;
 4365                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 4366                let worktree_entry = buffer_worktree
 4367                    .read(cx)
 4368                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 4369                if worktree_entry.is_ignored {
 4370                    return None;
 4371                }
 4372
 4373                let language = buffer.language()?;
 4374                if let Some(restrict_to_languages) = restrict_to_languages {
 4375                    if !restrict_to_languages.contains(language) {
 4376                        return None;
 4377                    }
 4378                }
 4379                Some((
 4380                    excerpt_id,
 4381                    (
 4382                        buffer_handle,
 4383                        buffer.version().clone(),
 4384                        excerpt_visible_range,
 4385                    ),
 4386                ))
 4387            })
 4388            .collect()
 4389    }
 4390
 4391    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 4392        TextLayoutDetails {
 4393            text_system: cx.text_system().clone(),
 4394            editor_style: self.style.clone().unwrap(),
 4395            rem_size: cx.rem_size(),
 4396            scroll_anchor: self.scroll_manager.anchor(),
 4397            visible_rows: self.visible_line_count(),
 4398            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 4399        }
 4400    }
 4401
 4402    fn splice_inlays(
 4403        &self,
 4404        to_remove: Vec<InlayId>,
 4405        to_insert: Vec<Inlay>,
 4406        cx: &mut ViewContext<Self>,
 4407    ) {
 4408        self.display_map.update(cx, |display_map, cx| {
 4409            display_map.splice_inlays(to_remove, to_insert, cx);
 4410        });
 4411        cx.notify();
 4412    }
 4413
 4414    fn trigger_on_type_formatting(
 4415        &self,
 4416        input: String,
 4417        cx: &mut ViewContext<Self>,
 4418    ) -> Option<Task<Result<()>>> {
 4419        if input.len() != 1 {
 4420            return None;
 4421        }
 4422
 4423        let project = self.project.as_ref()?;
 4424        let position = self.selections.newest_anchor().head();
 4425        let (buffer, buffer_position) = self
 4426            .buffer
 4427            .read(cx)
 4428            .text_anchor_for_position(position, cx)?;
 4429
 4430        let settings = language_settings::language_settings(
 4431            buffer
 4432                .read(cx)
 4433                .language_at(buffer_position)
 4434                .map(|l| l.name()),
 4435            buffer.read(cx).file(),
 4436            cx,
 4437        );
 4438        if !settings.use_on_type_format {
 4439            return None;
 4440        }
 4441
 4442        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 4443        // hence we do LSP request & edit on host side only — add formats to host's history.
 4444        let push_to_lsp_host_history = true;
 4445        // If this is not the host, append its history with new edits.
 4446        let push_to_client_history = project.read(cx).is_via_collab();
 4447
 4448        let on_type_formatting = project.update(cx, |project, cx| {
 4449            project.on_type_format(
 4450                buffer.clone(),
 4451                buffer_position,
 4452                input,
 4453                push_to_lsp_host_history,
 4454                cx,
 4455            )
 4456        });
 4457        Some(cx.spawn(|editor, mut cx| async move {
 4458            if let Some(transaction) = on_type_formatting.await? {
 4459                if push_to_client_history {
 4460                    buffer
 4461                        .update(&mut cx, |buffer, _| {
 4462                            buffer.push_transaction(transaction, Instant::now());
 4463                        })
 4464                        .ok();
 4465                }
 4466                editor.update(&mut cx, |editor, cx| {
 4467                    editor.refresh_document_highlights(cx);
 4468                })?;
 4469            }
 4470            Ok(())
 4471        }))
 4472    }
 4473
 4474    pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
 4475        if self.pending_rename.is_some() {
 4476            return;
 4477        }
 4478
 4479        let Some(provider) = self.completion_provider.as_ref() else {
 4480            return;
 4481        };
 4482
 4483        if !self.snippet_stack.is_empty() && self.context_menu.read().as_ref().is_some() {
 4484            return;
 4485        }
 4486
 4487        let position = self.selections.newest_anchor().head();
 4488        let (buffer, buffer_position) =
 4489            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4490                output
 4491            } else {
 4492                return;
 4493            };
 4494
 4495        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4496        let is_followup_invoke = {
 4497            let context_menu_state = self.context_menu.read();
 4498            matches!(
 4499                context_menu_state.deref(),
 4500                Some(ContextMenu::Completions(_))
 4501            )
 4502        };
 4503        let trigger_kind = match (&options.trigger, is_followup_invoke) {
 4504            (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
 4505            (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4506                CompletionTriggerKind::TRIGGER_CHARACTER
 4507            }
 4508
 4509            _ => CompletionTriggerKind::INVOKED,
 4510        };
 4511        let completion_context = CompletionContext {
 4512            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 4513                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4514                    Some(String::from(trigger))
 4515                } else {
 4516                    None
 4517                }
 4518            }),
 4519            trigger_kind,
 4520        };
 4521        let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
 4522        let sort_completions = provider.sort_completions();
 4523
 4524        let id = post_inc(&mut self.next_completion_id);
 4525        let task = cx.spawn(|this, mut cx| {
 4526            async move {
 4527                this.update(&mut cx, |this, _| {
 4528                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4529                })?;
 4530                let completions = completions.await.log_err();
 4531                let menu = if let Some(completions) = completions {
 4532                    let mut menu = CompletionsMenu::new(
 4533                        id,
 4534                        sort_completions,
 4535                        position,
 4536                        buffer.clone(),
 4537                        completions.into(),
 4538                    );
 4539                    menu.filter(query.as_deref(), cx.background_executor().clone())
 4540                        .await;
 4541
 4542                    if menu.matches.is_empty() {
 4543                        None
 4544                    } else {
 4545                        this.update(&mut cx, |editor, cx| {
 4546                            let completions = menu.completions.clone();
 4547                            let matches = menu.matches.clone();
 4548
 4549                            let delay_ms = EditorSettings::get_global(cx)
 4550                                .completion_documentation_secondary_query_debounce;
 4551                            let delay = Duration::from_millis(delay_ms);
 4552                            editor
 4553                                .completion_documentation_pre_resolve_debounce
 4554                                .fire_new(delay, cx, |editor, cx| {
 4555                                    CompletionsMenu::pre_resolve_completion_documentation(
 4556                                        buffer,
 4557                                        completions,
 4558                                        matches,
 4559                                        editor,
 4560                                        cx,
 4561                                    )
 4562                                });
 4563                        })
 4564                        .ok();
 4565                        Some(menu)
 4566                    }
 4567                } else {
 4568                    None
 4569                };
 4570
 4571                this.update(&mut cx, |this, cx| {
 4572                    let mut context_menu = this.context_menu.write();
 4573                    match context_menu.as_ref() {
 4574                        None => {}
 4575
 4576                        Some(ContextMenu::Completions(prev_menu)) => {
 4577                            if prev_menu.id > id {
 4578                                return;
 4579                            }
 4580                        }
 4581
 4582                        _ => return,
 4583                    }
 4584
 4585                    if this.focus_handle.is_focused(cx) && menu.is_some() {
 4586                        let menu = menu.unwrap();
 4587                        *context_menu = Some(ContextMenu::Completions(menu));
 4588                        drop(context_menu);
 4589                        this.discard_inline_completion(false, cx);
 4590                        cx.notify();
 4591                    } else if this.completion_tasks.len() <= 1 {
 4592                        // If there are no more completion tasks and the last menu was
 4593                        // empty, we should hide it. If it was already hidden, we should
 4594                        // also show the copilot completion when available.
 4595                        drop(context_menu);
 4596                        if this.hide_context_menu(cx).is_none() {
 4597                            this.update_visible_inline_completion(cx);
 4598                        }
 4599                    }
 4600                })?;
 4601
 4602                Ok::<_, anyhow::Error>(())
 4603            }
 4604            .log_err()
 4605        });
 4606
 4607        self.completion_tasks.push((id, task));
 4608    }
 4609
 4610    pub fn confirm_completion(
 4611        &mut self,
 4612        action: &ConfirmCompletion,
 4613        cx: &mut ViewContext<Self>,
 4614    ) -> Option<Task<Result<()>>> {
 4615        self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
 4616    }
 4617
 4618    pub fn compose_completion(
 4619        &mut self,
 4620        action: &ComposeCompletion,
 4621        cx: &mut ViewContext<Self>,
 4622    ) -> Option<Task<Result<()>>> {
 4623        self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
 4624    }
 4625
 4626    fn do_completion(
 4627        &mut self,
 4628        item_ix: Option<usize>,
 4629        intent: CompletionIntent,
 4630        cx: &mut ViewContext<Editor>,
 4631    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 4632        use language::ToOffset as _;
 4633
 4634        let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 4635            menu
 4636        } else {
 4637            return None;
 4638        };
 4639
 4640        let mat = completions_menu
 4641            .matches
 4642            .get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4643        let buffer_handle = completions_menu.buffer;
 4644        let completions = completions_menu.completions.read();
 4645        let completion = completions.get(mat.candidate_id)?;
 4646        cx.stop_propagation();
 4647
 4648        let snippet;
 4649        let text;
 4650
 4651        if completion.is_snippet() {
 4652            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4653            text = snippet.as_ref().unwrap().text.clone();
 4654        } else {
 4655            snippet = None;
 4656            text = completion.new_text.clone();
 4657        };
 4658        let selections = self.selections.all::<usize>(cx);
 4659        let buffer = buffer_handle.read(cx);
 4660        let old_range = completion.old_range.to_offset(buffer);
 4661        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4662
 4663        let newest_selection = self.selections.newest_anchor();
 4664        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4665            return None;
 4666        }
 4667
 4668        let lookbehind = newest_selection
 4669            .start
 4670            .text_anchor
 4671            .to_offset(buffer)
 4672            .saturating_sub(old_range.start);
 4673        let lookahead = old_range
 4674            .end
 4675            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4676        let mut common_prefix_len = old_text
 4677            .bytes()
 4678            .zip(text.bytes())
 4679            .take_while(|(a, b)| a == b)
 4680            .count();
 4681
 4682        let snapshot = self.buffer.read(cx).snapshot(cx);
 4683        let mut range_to_replace: Option<Range<isize>> = None;
 4684        let mut ranges = Vec::new();
 4685        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4686        for selection in &selections {
 4687            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4688                let start = selection.start.saturating_sub(lookbehind);
 4689                let end = selection.end + lookahead;
 4690                if selection.id == newest_selection.id {
 4691                    range_to_replace = Some(
 4692                        ((start + common_prefix_len) as isize - selection.start as isize)
 4693                            ..(end as isize - selection.start as isize),
 4694                    );
 4695                }
 4696                ranges.push(start + common_prefix_len..end);
 4697            } else {
 4698                common_prefix_len = 0;
 4699                ranges.clear();
 4700                ranges.extend(selections.iter().map(|s| {
 4701                    if s.id == newest_selection.id {
 4702                        range_to_replace = Some(
 4703                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4704                                - selection.start as isize
 4705                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4706                                    - selection.start as isize,
 4707                        );
 4708                        old_range.clone()
 4709                    } else {
 4710                        s.start..s.end
 4711                    }
 4712                }));
 4713                break;
 4714            }
 4715            if !self.linked_edit_ranges.is_empty() {
 4716                let start_anchor = snapshot.anchor_before(selection.head());
 4717                let end_anchor = snapshot.anchor_after(selection.tail());
 4718                if let Some(ranges) = self
 4719                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4720                {
 4721                    for (buffer, edits) in ranges {
 4722                        linked_edits.entry(buffer.clone()).or_default().extend(
 4723                            edits
 4724                                .into_iter()
 4725                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4726                        );
 4727                    }
 4728                }
 4729            }
 4730        }
 4731        let text = &text[common_prefix_len..];
 4732
 4733        cx.emit(EditorEvent::InputHandled {
 4734            utf16_range_to_replace: range_to_replace,
 4735            text: text.into(),
 4736        });
 4737
 4738        self.transact(cx, |this, cx| {
 4739            if let Some(mut snippet) = snippet {
 4740                snippet.text = text.to_string();
 4741                for tabstop in snippet
 4742                    .tabstops
 4743                    .iter_mut()
 4744                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4745                {
 4746                    tabstop.start -= common_prefix_len as isize;
 4747                    tabstop.end -= common_prefix_len as isize;
 4748                }
 4749
 4750                this.insert_snippet(&ranges, snippet, cx).log_err();
 4751            } else {
 4752                this.buffer.update(cx, |buffer, cx| {
 4753                    buffer.edit(
 4754                        ranges.iter().map(|range| (range.clone(), text)),
 4755                        this.autoindent_mode.clone(),
 4756                        cx,
 4757                    );
 4758                });
 4759            }
 4760            for (buffer, edits) in linked_edits {
 4761                buffer.update(cx, |buffer, cx| {
 4762                    let snapshot = buffer.snapshot();
 4763                    let edits = edits
 4764                        .into_iter()
 4765                        .map(|(range, text)| {
 4766                            use text::ToPoint as TP;
 4767                            let end_point = TP::to_point(&range.end, &snapshot);
 4768                            let start_point = TP::to_point(&range.start, &snapshot);
 4769                            (start_point..end_point, text)
 4770                        })
 4771                        .sorted_by_key(|(range, _)| range.start)
 4772                        .collect::<Vec<_>>();
 4773                    buffer.edit(edits, None, cx);
 4774                })
 4775            }
 4776
 4777            this.refresh_inline_completion(true, false, cx);
 4778        });
 4779
 4780        let show_new_completions_on_confirm = completion
 4781            .confirm
 4782            .as_ref()
 4783            .map_or(false, |confirm| confirm(intent, cx));
 4784        if show_new_completions_on_confirm {
 4785            self.show_completions(&ShowCompletions { trigger: None }, cx);
 4786        }
 4787
 4788        let provider = self.completion_provider.as_ref()?;
 4789        let apply_edits = provider.apply_additional_edits_for_completion(
 4790            buffer_handle,
 4791            completion.clone(),
 4792            true,
 4793            cx,
 4794        );
 4795
 4796        let editor_settings = EditorSettings::get_global(cx);
 4797        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4798            // After the code completion is finished, users often want to know what signatures are needed.
 4799            // so we should automatically call signature_help
 4800            self.show_signature_help(&ShowSignatureHelp, cx);
 4801        }
 4802
 4803        Some(cx.foreground_executor().spawn(async move {
 4804            apply_edits.await?;
 4805            Ok(())
 4806        }))
 4807    }
 4808
 4809    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 4810        let mut context_menu = self.context_menu.write();
 4811        if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4812            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4813                // Toggle if we're selecting the same one
 4814                *context_menu = None;
 4815                cx.notify();
 4816                return;
 4817            } else {
 4818                // Otherwise, clear it and start a new one
 4819                *context_menu = None;
 4820                cx.notify();
 4821            }
 4822        }
 4823        drop(context_menu);
 4824        let snapshot = self.snapshot(cx);
 4825        let deployed_from_indicator = action.deployed_from_indicator;
 4826        let mut task = self.code_actions_task.take();
 4827        let action = action.clone();
 4828        cx.spawn(|editor, mut cx| async move {
 4829            while let Some(prev_task) = task {
 4830                prev_task.await.log_err();
 4831                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4832            }
 4833
 4834            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 4835                if editor.focus_handle.is_focused(cx) {
 4836                    let multibuffer_point = action
 4837                        .deployed_from_indicator
 4838                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4839                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4840                    let (buffer, buffer_row) = snapshot
 4841                        .buffer_snapshot
 4842                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4843                        .and_then(|(buffer_snapshot, range)| {
 4844                            editor
 4845                                .buffer
 4846                                .read(cx)
 4847                                .buffer(buffer_snapshot.remote_id())
 4848                                .map(|buffer| (buffer, range.start.row))
 4849                        })?;
 4850                    let (_, code_actions) = editor
 4851                        .available_code_actions
 4852                        .clone()
 4853                        .and_then(|(location, code_actions)| {
 4854                            let snapshot = location.buffer.read(cx).snapshot();
 4855                            let point_range = location.range.to_point(&snapshot);
 4856                            let point_range = point_range.start.row..=point_range.end.row;
 4857                            if point_range.contains(&buffer_row) {
 4858                                Some((location, code_actions))
 4859                            } else {
 4860                                None
 4861                            }
 4862                        })
 4863                        .unzip();
 4864                    let buffer_id = buffer.read(cx).remote_id();
 4865                    let tasks = editor
 4866                        .tasks
 4867                        .get(&(buffer_id, buffer_row))
 4868                        .map(|t| Arc::new(t.to_owned()));
 4869                    if tasks.is_none() && code_actions.is_none() {
 4870                        return None;
 4871                    }
 4872
 4873                    editor.completion_tasks.clear();
 4874                    editor.discard_inline_completion(false, cx);
 4875                    let task_context =
 4876                        tasks
 4877                            .as_ref()
 4878                            .zip(editor.project.clone())
 4879                            .map(|(tasks, project)| {
 4880                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4881                            });
 4882
 4883                    Some(cx.spawn(|editor, mut cx| async move {
 4884                        let task_context = match task_context {
 4885                            Some(task_context) => task_context.await,
 4886                            None => None,
 4887                        };
 4888                        let resolved_tasks =
 4889                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4890                                Arc::new(ResolvedTasks {
 4891                                    templates: tasks.resolve(&task_context).collect(),
 4892                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4893                                        multibuffer_point.row,
 4894                                        tasks.column,
 4895                                    )),
 4896                                })
 4897                            });
 4898                        let spawn_straight_away = resolved_tasks
 4899                            .as_ref()
 4900                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4901                            && code_actions
 4902                                .as_ref()
 4903                                .map_or(true, |actions| actions.is_empty());
 4904                        if let Ok(task) = editor.update(&mut cx, |editor, cx| {
 4905                            *editor.context_menu.write() =
 4906                                Some(ContextMenu::CodeActions(CodeActionsMenu {
 4907                                    buffer,
 4908                                    actions: CodeActionContents {
 4909                                        tasks: resolved_tasks,
 4910                                        actions: code_actions,
 4911                                    },
 4912                                    selected_item: Default::default(),
 4913                                    scroll_handle: UniformListScrollHandle::default(),
 4914                                    deployed_from_indicator,
 4915                                }));
 4916                            if spawn_straight_away {
 4917                                if let Some(task) = editor.confirm_code_action(
 4918                                    &ConfirmCodeAction { item_ix: Some(0) },
 4919                                    cx,
 4920                                ) {
 4921                                    cx.notify();
 4922                                    return task;
 4923                                }
 4924                            }
 4925                            cx.notify();
 4926                            Task::ready(Ok(()))
 4927                        }) {
 4928                            task.await
 4929                        } else {
 4930                            Ok(())
 4931                        }
 4932                    }))
 4933                } else {
 4934                    Some(Task::ready(Ok(())))
 4935                }
 4936            })?;
 4937            if let Some(task) = spawned_test_task {
 4938                task.await?;
 4939            }
 4940
 4941            Ok::<_, anyhow::Error>(())
 4942        })
 4943        .detach_and_log_err(cx);
 4944    }
 4945
 4946    pub fn confirm_code_action(
 4947        &mut self,
 4948        action: &ConfirmCodeAction,
 4949        cx: &mut ViewContext<Self>,
 4950    ) -> Option<Task<Result<()>>> {
 4951        let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4952            menu
 4953        } else {
 4954            return None;
 4955        };
 4956        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4957        let action = actions_menu.actions.get(action_ix)?;
 4958        let title = action.label();
 4959        let buffer = actions_menu.buffer;
 4960        let workspace = self.workspace()?;
 4961
 4962        match action {
 4963            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4964                workspace.update(cx, |workspace, cx| {
 4965                    workspace::tasks::schedule_resolved_task(
 4966                        workspace,
 4967                        task_source_kind,
 4968                        resolved_task,
 4969                        false,
 4970                        cx,
 4971                    );
 4972
 4973                    Some(Task::ready(Ok(())))
 4974                })
 4975            }
 4976            CodeActionsItem::CodeAction {
 4977                excerpt_id,
 4978                action,
 4979                provider,
 4980            } => {
 4981                let apply_code_action =
 4982                    provider.apply_code_action(buffer, action, excerpt_id, true, cx);
 4983                let workspace = workspace.downgrade();
 4984                Some(cx.spawn(|editor, cx| async move {
 4985                    let project_transaction = apply_code_action.await?;
 4986                    Self::open_project_transaction(
 4987                        &editor,
 4988                        workspace,
 4989                        project_transaction,
 4990                        title,
 4991                        cx,
 4992                    )
 4993                    .await
 4994                }))
 4995            }
 4996        }
 4997    }
 4998
 4999    pub async fn open_project_transaction(
 5000        this: &WeakView<Editor>,
 5001        workspace: WeakView<Workspace>,
 5002        transaction: ProjectTransaction,
 5003        title: String,
 5004        mut cx: AsyncWindowContext,
 5005    ) -> Result<()> {
 5006        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 5007        cx.update(|cx| {
 5008            entries.sort_unstable_by_key(|(buffer, _)| {
 5009                buffer.read(cx).file().map(|f| f.path().clone())
 5010            });
 5011        })?;
 5012
 5013        // If the project transaction's edits are all contained within this editor, then
 5014        // avoid opening a new editor to display them.
 5015
 5016        if let Some((buffer, transaction)) = entries.first() {
 5017            if entries.len() == 1 {
 5018                let excerpt = this.update(&mut cx, |editor, cx| {
 5019                    editor
 5020                        .buffer()
 5021                        .read(cx)
 5022                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 5023                })?;
 5024                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 5025                    if excerpted_buffer == *buffer {
 5026                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 5027                            let excerpt_range = excerpt_range.to_offset(buffer);
 5028                            buffer
 5029                                .edited_ranges_for_transaction::<usize>(transaction)
 5030                                .all(|range| {
 5031                                    excerpt_range.start <= range.start
 5032                                        && excerpt_range.end >= range.end
 5033                                })
 5034                        })?;
 5035
 5036                        if all_edits_within_excerpt {
 5037                            return Ok(());
 5038                        }
 5039                    }
 5040                }
 5041            }
 5042        } else {
 5043            return Ok(());
 5044        }
 5045
 5046        let mut ranges_to_highlight = Vec::new();
 5047        let excerpt_buffer = cx.new_model(|cx| {
 5048            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 5049            for (buffer_handle, transaction) in &entries {
 5050                let buffer = buffer_handle.read(cx);
 5051                ranges_to_highlight.extend(
 5052                    multibuffer.push_excerpts_with_context_lines(
 5053                        buffer_handle.clone(),
 5054                        buffer
 5055                            .edited_ranges_for_transaction::<usize>(transaction)
 5056                            .collect(),
 5057                        DEFAULT_MULTIBUFFER_CONTEXT,
 5058                        cx,
 5059                    ),
 5060                );
 5061            }
 5062            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 5063            multibuffer
 5064        })?;
 5065
 5066        workspace.update(&mut cx, |workspace, cx| {
 5067            let project = workspace.project().clone();
 5068            let editor =
 5069                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 5070            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 5071            editor.update(cx, |editor, cx| {
 5072                editor.highlight_background::<Self>(
 5073                    &ranges_to_highlight,
 5074                    |theme| theme.editor_highlighted_line_background,
 5075                    cx,
 5076                );
 5077            });
 5078        })?;
 5079
 5080        Ok(())
 5081    }
 5082
 5083    pub fn clear_code_action_providers(&mut self) {
 5084        self.code_action_providers.clear();
 5085        self.available_code_actions.take();
 5086    }
 5087
 5088    pub fn push_code_action_provider(
 5089        &mut self,
 5090        provider: Arc<dyn CodeActionProvider>,
 5091        cx: &mut ViewContext<Self>,
 5092    ) {
 5093        self.code_action_providers.push(provider);
 5094        self.refresh_code_actions(cx);
 5095    }
 5096
 5097    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 5098        let buffer = self.buffer.read(cx);
 5099        let newest_selection = self.selections.newest_anchor().clone();
 5100        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 5101        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 5102        if start_buffer != end_buffer {
 5103            return None;
 5104        }
 5105
 5106        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 5107            cx.background_executor()
 5108                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 5109                .await;
 5110
 5111            let (providers, tasks) = this.update(&mut cx, |this, cx| {
 5112                let providers = this.code_action_providers.clone();
 5113                let tasks = this
 5114                    .code_action_providers
 5115                    .iter()
 5116                    .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
 5117                    .collect::<Vec<_>>();
 5118                (providers, tasks)
 5119            })?;
 5120
 5121            let mut actions = Vec::new();
 5122            for (provider, provider_actions) in
 5123                providers.into_iter().zip(future::join_all(tasks).await)
 5124            {
 5125                if let Some(provider_actions) = provider_actions.log_err() {
 5126                    actions.extend(provider_actions.into_iter().map(|action| {
 5127                        AvailableCodeAction {
 5128                            excerpt_id: newest_selection.start.excerpt_id,
 5129                            action,
 5130                            provider: provider.clone(),
 5131                        }
 5132                    }));
 5133                }
 5134            }
 5135
 5136            this.update(&mut cx, |this, cx| {
 5137                this.available_code_actions = if actions.is_empty() {
 5138                    None
 5139                } else {
 5140                    Some((
 5141                        Location {
 5142                            buffer: start_buffer,
 5143                            range: start..end,
 5144                        },
 5145                        actions.into(),
 5146                    ))
 5147                };
 5148                cx.notify();
 5149            })
 5150        }));
 5151        None
 5152    }
 5153
 5154    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 5155        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 5156            self.show_git_blame_inline = false;
 5157
 5158            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 5159                cx.background_executor().timer(delay).await;
 5160
 5161                this.update(&mut cx, |this, cx| {
 5162                    this.show_git_blame_inline = true;
 5163                    cx.notify();
 5164                })
 5165                .log_err();
 5166            }));
 5167        }
 5168    }
 5169
 5170    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 5171        if self.pending_rename.is_some() {
 5172            return None;
 5173        }
 5174
 5175        let provider = self.semantics_provider.clone()?;
 5176        let buffer = self.buffer.read(cx);
 5177        let newest_selection = self.selections.newest_anchor().clone();
 5178        let cursor_position = newest_selection.head();
 5179        let (cursor_buffer, cursor_buffer_position) =
 5180            buffer.text_anchor_for_position(cursor_position, cx)?;
 5181        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 5182        if cursor_buffer != tail_buffer {
 5183            return None;
 5184        }
 5185
 5186        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 5187            cx.background_executor()
 5188                .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
 5189                .await;
 5190
 5191            let highlights = if let Some(highlights) = cx
 5192                .update(|cx| {
 5193                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 5194                })
 5195                .ok()
 5196                .flatten()
 5197            {
 5198                highlights.await.log_err()
 5199            } else {
 5200                None
 5201            };
 5202
 5203            if let Some(highlights) = highlights {
 5204                this.update(&mut cx, |this, cx| {
 5205                    if this.pending_rename.is_some() {
 5206                        return;
 5207                    }
 5208
 5209                    let buffer_id = cursor_position.buffer_id;
 5210                    let buffer = this.buffer.read(cx);
 5211                    if !buffer
 5212                        .text_anchor_for_position(cursor_position, cx)
 5213                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 5214                    {
 5215                        return;
 5216                    }
 5217
 5218                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 5219                    let mut write_ranges = Vec::new();
 5220                    let mut read_ranges = Vec::new();
 5221                    for highlight in highlights {
 5222                        for (excerpt_id, excerpt_range) in
 5223                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 5224                        {
 5225                            let start = highlight
 5226                                .range
 5227                                .start
 5228                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 5229                            let end = highlight
 5230                                .range
 5231                                .end
 5232                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 5233                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 5234                                continue;
 5235                            }
 5236
 5237                            let range = Anchor {
 5238                                buffer_id,
 5239                                excerpt_id,
 5240                                text_anchor: start,
 5241                            }..Anchor {
 5242                                buffer_id,
 5243                                excerpt_id,
 5244                                text_anchor: end,
 5245                            };
 5246                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 5247                                write_ranges.push(range);
 5248                            } else {
 5249                                read_ranges.push(range);
 5250                            }
 5251                        }
 5252                    }
 5253
 5254                    this.highlight_background::<DocumentHighlightRead>(
 5255                        &read_ranges,
 5256                        |theme| theme.editor_document_highlight_read_background,
 5257                        cx,
 5258                    );
 5259                    this.highlight_background::<DocumentHighlightWrite>(
 5260                        &write_ranges,
 5261                        |theme| theme.editor_document_highlight_write_background,
 5262                        cx,
 5263                    );
 5264                    cx.notify();
 5265                })
 5266                .log_err();
 5267            }
 5268        }));
 5269        None
 5270    }
 5271
 5272    pub fn refresh_inline_completion(
 5273        &mut self,
 5274        debounce: bool,
 5275        user_requested: bool,
 5276        cx: &mut ViewContext<Self>,
 5277    ) -> Option<()> {
 5278        let provider = self.inline_completion_provider()?;
 5279        let cursor = self.selections.newest_anchor().head();
 5280        let (buffer, cursor_buffer_position) =
 5281            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5282
 5283        if !user_requested
 5284            && (!self.enable_inline_completions
 5285                || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx))
 5286        {
 5287            self.discard_inline_completion(false, cx);
 5288            return None;
 5289        }
 5290
 5291        self.update_visible_inline_completion(cx);
 5292        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 5293        Some(())
 5294    }
 5295
 5296    fn cycle_inline_completion(
 5297        &mut self,
 5298        direction: Direction,
 5299        cx: &mut ViewContext<Self>,
 5300    ) -> Option<()> {
 5301        let provider = self.inline_completion_provider()?;
 5302        let cursor = self.selections.newest_anchor().head();
 5303        let (buffer, cursor_buffer_position) =
 5304            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5305        if !self.enable_inline_completions
 5306            || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 5307        {
 5308            return None;
 5309        }
 5310
 5311        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5312        self.update_visible_inline_completion(cx);
 5313
 5314        Some(())
 5315    }
 5316
 5317    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 5318        if !self.has_active_inline_completion(cx) {
 5319            self.refresh_inline_completion(false, true, cx);
 5320            return;
 5321        }
 5322
 5323        self.update_visible_inline_completion(cx);
 5324    }
 5325
 5326    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 5327        self.show_cursor_names(cx);
 5328    }
 5329
 5330    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 5331        self.show_cursor_names = true;
 5332        cx.notify();
 5333        cx.spawn(|this, mut cx| async move {
 5334            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5335            this.update(&mut cx, |this, cx| {
 5336                this.show_cursor_names = false;
 5337                cx.notify()
 5338            })
 5339            .ok()
 5340        })
 5341        .detach();
 5342    }
 5343
 5344    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 5345        if self.has_active_inline_completion(cx) {
 5346            self.cycle_inline_completion(Direction::Next, cx);
 5347        } else {
 5348            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5349            if is_copilot_disabled {
 5350                cx.propagate();
 5351            }
 5352        }
 5353    }
 5354
 5355    pub fn previous_inline_completion(
 5356        &mut self,
 5357        _: &PreviousInlineCompletion,
 5358        cx: &mut ViewContext<Self>,
 5359    ) {
 5360        if self.has_active_inline_completion(cx) {
 5361            self.cycle_inline_completion(Direction::Prev, cx);
 5362        } else {
 5363            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5364            if is_copilot_disabled {
 5365                cx.propagate();
 5366            }
 5367        }
 5368    }
 5369
 5370    pub fn accept_inline_completion(
 5371        &mut self,
 5372        _: &AcceptInlineCompletion,
 5373        cx: &mut ViewContext<Self>,
 5374    ) {
 5375        let Some(completion) = self.take_active_inline_completion(cx) else {
 5376            return;
 5377        };
 5378        if let Some(provider) = self.inline_completion_provider() {
 5379            provider.accept(cx);
 5380        }
 5381
 5382        cx.emit(EditorEvent::InputHandled {
 5383            utf16_range_to_replace: None,
 5384            text: completion.text.to_string().into(),
 5385        });
 5386
 5387        if let Some(range) = completion.delete_range {
 5388            self.change_selections(None, cx, |s| s.select_ranges([range]))
 5389        }
 5390        self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
 5391        self.refresh_inline_completion(true, true, cx);
 5392        cx.notify();
 5393    }
 5394
 5395    pub fn accept_partial_inline_completion(
 5396        &mut self,
 5397        _: &AcceptPartialInlineCompletion,
 5398        cx: &mut ViewContext<Self>,
 5399    ) {
 5400        if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
 5401            if let Some(completion) = self.take_active_inline_completion(cx) {
 5402                let mut partial_completion = completion
 5403                    .text
 5404                    .chars()
 5405                    .by_ref()
 5406                    .take_while(|c| c.is_alphabetic())
 5407                    .collect::<String>();
 5408                if partial_completion.is_empty() {
 5409                    partial_completion = completion
 5410                        .text
 5411                        .chars()
 5412                        .by_ref()
 5413                        .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5414                        .collect::<String>();
 5415                }
 5416
 5417                cx.emit(EditorEvent::InputHandled {
 5418                    utf16_range_to_replace: None,
 5419                    text: partial_completion.clone().into(),
 5420                });
 5421
 5422                if let Some(range) = completion.delete_range {
 5423                    self.change_selections(None, cx, |s| s.select_ranges([range]))
 5424                }
 5425                self.insert_with_autoindent_mode(&partial_completion, None, cx);
 5426
 5427                self.refresh_inline_completion(true, true, cx);
 5428                cx.notify();
 5429            }
 5430        }
 5431    }
 5432
 5433    fn discard_inline_completion(
 5434        &mut self,
 5435        should_report_inline_completion_event: bool,
 5436        cx: &mut ViewContext<Self>,
 5437    ) -> bool {
 5438        if let Some(provider) = self.inline_completion_provider() {
 5439            provider.discard(should_report_inline_completion_event, cx);
 5440        }
 5441
 5442        self.take_active_inline_completion(cx).is_some()
 5443    }
 5444
 5445    pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
 5446        if let Some(completion) = self.active_inline_completion.as_ref() {
 5447            let buffer = self.buffer.read(cx).read(cx);
 5448            completion.position.is_valid(&buffer)
 5449        } else {
 5450            false
 5451        }
 5452    }
 5453
 5454    fn take_active_inline_completion(
 5455        &mut self,
 5456        cx: &mut ViewContext<Self>,
 5457    ) -> Option<CompletionState> {
 5458        let completion = self.active_inline_completion.take()?;
 5459        let render_inlay_ids = completion.render_inlay_ids.clone();
 5460        self.display_map.update(cx, |map, cx| {
 5461            map.splice_inlays(render_inlay_ids, Default::default(), cx);
 5462        });
 5463        let buffer = self.buffer.read(cx).read(cx);
 5464
 5465        if completion.position.is_valid(&buffer) {
 5466            Some(completion)
 5467        } else {
 5468            None
 5469        }
 5470    }
 5471
 5472    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
 5473        let selection = self.selections.newest_anchor();
 5474        let cursor = selection.head();
 5475
 5476        let excerpt_id = cursor.excerpt_id;
 5477
 5478        if self.context_menu.read().is_none()
 5479            && self.completion_tasks.is_empty()
 5480            && selection.start == selection.end
 5481        {
 5482            if let Some(provider) = self.inline_completion_provider() {
 5483                if let Some((buffer, cursor_buffer_position)) =
 5484                    self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5485                {
 5486                    if let Some(proposal) =
 5487                        provider.active_completion_text(&buffer, cursor_buffer_position, cx)
 5488                    {
 5489                        let mut to_remove = Vec::new();
 5490                        if let Some(completion) = self.active_inline_completion.take() {
 5491                            to_remove.extend(completion.render_inlay_ids.iter());
 5492                        }
 5493
 5494                        let to_add = proposal
 5495                            .inlays
 5496                            .iter()
 5497                            .filter_map(|inlay| {
 5498                                let snapshot = self.buffer.read(cx).snapshot(cx);
 5499                                let id = post_inc(&mut self.next_inlay_id);
 5500                                match inlay {
 5501                                    InlayProposal::Hint(position, hint) => {
 5502                                        let position =
 5503                                            snapshot.anchor_in_excerpt(excerpt_id, *position)?;
 5504                                        Some(Inlay::hint(id, position, hint))
 5505                                    }
 5506                                    InlayProposal::Suggestion(position, text) => {
 5507                                        let position =
 5508                                            snapshot.anchor_in_excerpt(excerpt_id, *position)?;
 5509                                        Some(Inlay::suggestion(id, position, text.clone()))
 5510                                    }
 5511                                }
 5512                            })
 5513                            .collect_vec();
 5514
 5515                        self.active_inline_completion = Some(CompletionState {
 5516                            position: cursor,
 5517                            text: proposal.text,
 5518                            delete_range: proposal.delete_range.and_then(|range| {
 5519                                let snapshot = self.buffer.read(cx).snapshot(cx);
 5520                                let start = snapshot.anchor_in_excerpt(excerpt_id, range.start);
 5521                                let end = snapshot.anchor_in_excerpt(excerpt_id, range.end);
 5522                                Some(start?..end?)
 5523                            }),
 5524                            render_inlay_ids: to_add.iter().map(|i| i.id).collect(),
 5525                        });
 5526
 5527                        self.display_map
 5528                            .update(cx, move |map, cx| map.splice_inlays(to_remove, to_add, cx));
 5529
 5530                        cx.notify();
 5531                        return;
 5532                    }
 5533                }
 5534            }
 5535        }
 5536
 5537        self.discard_inline_completion(false, cx);
 5538    }
 5539
 5540    fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5541        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 5542    }
 5543
 5544    fn render_code_actions_indicator(
 5545        &self,
 5546        _style: &EditorStyle,
 5547        row: DisplayRow,
 5548        is_active: bool,
 5549        cx: &mut ViewContext<Self>,
 5550    ) -> Option<IconButton> {
 5551        if self.available_code_actions.is_some() {
 5552            Some(
 5553                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5554                    .shape(ui::IconButtonShape::Square)
 5555                    .icon_size(IconSize::XSmall)
 5556                    .icon_color(Color::Muted)
 5557                    .selected(is_active)
 5558                    .tooltip({
 5559                        let focus_handle = self.focus_handle.clone();
 5560                        move |cx| {
 5561                            Tooltip::for_action_in(
 5562                                "Toggle Code Actions",
 5563                                &ToggleCodeActions {
 5564                                    deployed_from_indicator: None,
 5565                                },
 5566                                &focus_handle,
 5567                                cx,
 5568                            )
 5569                        }
 5570                    })
 5571                    .on_click(cx.listener(move |editor, _e, cx| {
 5572                        editor.focus(cx);
 5573                        editor.toggle_code_actions(
 5574                            &ToggleCodeActions {
 5575                                deployed_from_indicator: Some(row),
 5576                            },
 5577                            cx,
 5578                        );
 5579                    })),
 5580            )
 5581        } else {
 5582            None
 5583        }
 5584    }
 5585
 5586    fn clear_tasks(&mut self) {
 5587        self.tasks.clear()
 5588    }
 5589
 5590    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5591        if self.tasks.insert(key, value).is_some() {
 5592            // This case should hopefully be rare, but just in case...
 5593            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5594        }
 5595    }
 5596
 5597    fn build_tasks_context(
 5598        project: &Model<Project>,
 5599        buffer: &Model<Buffer>,
 5600        buffer_row: u32,
 5601        tasks: &Arc<RunnableTasks>,
 5602        cx: &mut ViewContext<Self>,
 5603    ) -> Task<Option<task::TaskContext>> {
 5604        let position = Point::new(buffer_row, tasks.column);
 5605        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5606        let location = Location {
 5607            buffer: buffer.clone(),
 5608            range: range_start..range_start,
 5609        };
 5610        // Fill in the environmental variables from the tree-sitter captures
 5611        let mut captured_task_variables = TaskVariables::default();
 5612        for (capture_name, value) in tasks.extra_variables.clone() {
 5613            captured_task_variables.insert(
 5614                task::VariableName::Custom(capture_name.into()),
 5615                value.clone(),
 5616            );
 5617        }
 5618        project.update(cx, |project, cx| {
 5619            project.task_store().update(cx, |task_store, cx| {
 5620                task_store.task_context_for_location(captured_task_variables, location, cx)
 5621            })
 5622        })
 5623    }
 5624
 5625    pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
 5626        let Some((workspace, _)) = self.workspace.clone() else {
 5627            return;
 5628        };
 5629        let Some(project) = self.project.clone() else {
 5630            return;
 5631        };
 5632
 5633        // Try to find a closest, enclosing node using tree-sitter that has a
 5634        // task
 5635        let Some((buffer, buffer_row, tasks)) = self
 5636            .find_enclosing_node_task(cx)
 5637            // Or find the task that's closest in row-distance.
 5638            .or_else(|| self.find_closest_task(cx))
 5639        else {
 5640            return;
 5641        };
 5642
 5643        let reveal_strategy = action.reveal;
 5644        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5645        cx.spawn(|_, mut cx| async move {
 5646            let context = task_context.await?;
 5647            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5648
 5649            let resolved = resolved_task.resolved.as_mut()?;
 5650            resolved.reveal = reveal_strategy;
 5651
 5652            workspace
 5653                .update(&mut cx, |workspace, cx| {
 5654                    workspace::tasks::schedule_resolved_task(
 5655                        workspace,
 5656                        task_source_kind,
 5657                        resolved_task,
 5658                        false,
 5659                        cx,
 5660                    );
 5661                })
 5662                .ok()
 5663        })
 5664        .detach();
 5665    }
 5666
 5667    fn find_closest_task(
 5668        &mut self,
 5669        cx: &mut ViewContext<Self>,
 5670    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5671        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5672
 5673        let ((buffer_id, row), tasks) = self
 5674            .tasks
 5675            .iter()
 5676            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5677
 5678        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5679        let tasks = Arc::new(tasks.to_owned());
 5680        Some((buffer, *row, tasks))
 5681    }
 5682
 5683    fn find_enclosing_node_task(
 5684        &mut self,
 5685        cx: &mut ViewContext<Self>,
 5686    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5687        let snapshot = self.buffer.read(cx).snapshot(cx);
 5688        let offset = self.selections.newest::<usize>(cx).head();
 5689        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5690        let buffer_id = excerpt.buffer().remote_id();
 5691
 5692        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5693        let mut cursor = layer.node().walk();
 5694
 5695        while cursor.goto_first_child_for_byte(offset).is_some() {
 5696            if cursor.node().end_byte() == offset {
 5697                cursor.goto_next_sibling();
 5698            }
 5699        }
 5700
 5701        // Ascend to the smallest ancestor that contains the range and has a task.
 5702        loop {
 5703            let node = cursor.node();
 5704            let node_range = node.byte_range();
 5705            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5706
 5707            // Check if this node contains our offset
 5708            if node_range.start <= offset && node_range.end >= offset {
 5709                // If it contains offset, check for task
 5710                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5711                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5712                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5713                }
 5714            }
 5715
 5716            if !cursor.goto_parent() {
 5717                break;
 5718            }
 5719        }
 5720        None
 5721    }
 5722
 5723    fn render_run_indicator(
 5724        &self,
 5725        _style: &EditorStyle,
 5726        is_active: bool,
 5727        row: DisplayRow,
 5728        cx: &mut ViewContext<Self>,
 5729    ) -> IconButton {
 5730        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5731            .shape(ui::IconButtonShape::Square)
 5732            .icon_size(IconSize::XSmall)
 5733            .icon_color(Color::Muted)
 5734            .selected(is_active)
 5735            .on_click(cx.listener(move |editor, _e, cx| {
 5736                editor.focus(cx);
 5737                editor.toggle_code_actions(
 5738                    &ToggleCodeActions {
 5739                        deployed_from_indicator: Some(row),
 5740                    },
 5741                    cx,
 5742                );
 5743            }))
 5744    }
 5745
 5746    pub fn context_menu_visible(&self) -> bool {
 5747        self.context_menu
 5748            .read()
 5749            .as_ref()
 5750            .map_or(false, |menu| menu.visible())
 5751    }
 5752
 5753    fn render_context_menu(
 5754        &self,
 5755        cursor_position: DisplayPoint,
 5756        style: &EditorStyle,
 5757        max_height: Pixels,
 5758        cx: &mut ViewContext<Editor>,
 5759    ) -> Option<(ContextMenuOrigin, AnyElement)> {
 5760        self.context_menu.read().as_ref().map(|menu| {
 5761            menu.render(
 5762                cursor_position,
 5763                style,
 5764                max_height,
 5765                self.workspace.as_ref().map(|(w, _)| w.clone()),
 5766                cx,
 5767            )
 5768        })
 5769    }
 5770
 5771    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
 5772        cx.notify();
 5773        self.completion_tasks.clear();
 5774        let context_menu = self.context_menu.write().take();
 5775        if context_menu.is_some() {
 5776            self.update_visible_inline_completion(cx);
 5777        }
 5778        context_menu
 5779    }
 5780
 5781    fn show_snippet_choices(
 5782        &mut self,
 5783        choices: &Vec<String>,
 5784        selection: Range<Anchor>,
 5785        cx: &mut ViewContext<Self>,
 5786    ) {
 5787        if selection.start.buffer_id.is_none() {
 5788            return;
 5789        }
 5790        let buffer_id = selection.start.buffer_id.unwrap();
 5791        let buffer = self.buffer().read(cx).buffer(buffer_id);
 5792        let id = post_inc(&mut self.next_completion_id);
 5793
 5794        if let Some(buffer) = buffer {
 5795            *self.context_menu.write() = Some(ContextMenu::Completions(
 5796                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer)
 5797                    .suppress_documentation_resolution(),
 5798            ));
 5799        }
 5800    }
 5801
 5802    pub fn insert_snippet(
 5803        &mut self,
 5804        insertion_ranges: &[Range<usize>],
 5805        snippet: Snippet,
 5806        cx: &mut ViewContext<Self>,
 5807    ) -> Result<()> {
 5808        struct Tabstop<T> {
 5809            is_end_tabstop: bool,
 5810            ranges: Vec<Range<T>>,
 5811            choices: Option<Vec<String>>,
 5812        }
 5813
 5814        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5815            let snippet_text: Arc<str> = snippet.text.clone().into();
 5816            buffer.edit(
 5817                insertion_ranges
 5818                    .iter()
 5819                    .cloned()
 5820                    .map(|range| (range, snippet_text.clone())),
 5821                Some(AutoindentMode::EachLine),
 5822                cx,
 5823            );
 5824
 5825            let snapshot = &*buffer.read(cx);
 5826            let snippet = &snippet;
 5827            snippet
 5828                .tabstops
 5829                .iter()
 5830                .map(|tabstop| {
 5831                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 5832                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5833                    });
 5834                    let mut tabstop_ranges = tabstop
 5835                        .ranges
 5836                        .iter()
 5837                        .flat_map(|tabstop_range| {
 5838                            let mut delta = 0_isize;
 5839                            insertion_ranges.iter().map(move |insertion_range| {
 5840                                let insertion_start = insertion_range.start as isize + delta;
 5841                                delta +=
 5842                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5843
 5844                                let start = ((insertion_start + tabstop_range.start) as usize)
 5845                                    .min(snapshot.len());
 5846                                let end = ((insertion_start + tabstop_range.end) as usize)
 5847                                    .min(snapshot.len());
 5848                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5849                            })
 5850                        })
 5851                        .collect::<Vec<_>>();
 5852                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5853
 5854                    Tabstop {
 5855                        is_end_tabstop,
 5856                        ranges: tabstop_ranges,
 5857                        choices: tabstop.choices.clone(),
 5858                    }
 5859                })
 5860                .collect::<Vec<_>>()
 5861        });
 5862        if let Some(tabstop) = tabstops.first() {
 5863            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5864                s.select_ranges(tabstop.ranges.iter().cloned());
 5865            });
 5866
 5867            if let Some(choices) = &tabstop.choices {
 5868                if let Some(selection) = tabstop.ranges.first() {
 5869                    self.show_snippet_choices(choices, selection.clone(), cx)
 5870                }
 5871            }
 5872
 5873            // If we're already at the last tabstop and it's at the end of the snippet,
 5874            // we're done, we don't need to keep the state around.
 5875            if !tabstop.is_end_tabstop {
 5876                let choices = tabstops
 5877                    .iter()
 5878                    .map(|tabstop| tabstop.choices.clone())
 5879                    .collect();
 5880
 5881                let ranges = tabstops
 5882                    .into_iter()
 5883                    .map(|tabstop| tabstop.ranges)
 5884                    .collect::<Vec<_>>();
 5885
 5886                self.snippet_stack.push(SnippetState {
 5887                    active_index: 0,
 5888                    ranges,
 5889                    choices,
 5890                });
 5891            }
 5892
 5893            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5894            if self.autoclose_regions.is_empty() {
 5895                let snapshot = self.buffer.read(cx).snapshot(cx);
 5896                for selection in &mut self.selections.all::<Point>(cx) {
 5897                    let selection_head = selection.head();
 5898                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5899                        continue;
 5900                    };
 5901
 5902                    let mut bracket_pair = None;
 5903                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5904                    let prev_chars = snapshot
 5905                        .reversed_chars_at(selection_head)
 5906                        .collect::<String>();
 5907                    for (pair, enabled) in scope.brackets() {
 5908                        if enabled
 5909                            && pair.close
 5910                            && prev_chars.starts_with(pair.start.as_str())
 5911                            && next_chars.starts_with(pair.end.as_str())
 5912                        {
 5913                            bracket_pair = Some(pair.clone());
 5914                            break;
 5915                        }
 5916                    }
 5917                    if let Some(pair) = bracket_pair {
 5918                        let start = snapshot.anchor_after(selection_head);
 5919                        let end = snapshot.anchor_after(selection_head);
 5920                        self.autoclose_regions.push(AutocloseRegion {
 5921                            selection_id: selection.id,
 5922                            range: start..end,
 5923                            pair,
 5924                        });
 5925                    }
 5926                }
 5927            }
 5928        }
 5929        Ok(())
 5930    }
 5931
 5932    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5933        self.move_to_snippet_tabstop(Bias::Right, cx)
 5934    }
 5935
 5936    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5937        self.move_to_snippet_tabstop(Bias::Left, cx)
 5938    }
 5939
 5940    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5941        if let Some(mut snippet) = self.snippet_stack.pop() {
 5942            match bias {
 5943                Bias::Left => {
 5944                    if snippet.active_index > 0 {
 5945                        snippet.active_index -= 1;
 5946                    } else {
 5947                        self.snippet_stack.push(snippet);
 5948                        return false;
 5949                    }
 5950                }
 5951                Bias::Right => {
 5952                    if snippet.active_index + 1 < snippet.ranges.len() {
 5953                        snippet.active_index += 1;
 5954                    } else {
 5955                        self.snippet_stack.push(snippet);
 5956                        return false;
 5957                    }
 5958                }
 5959            }
 5960            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5961                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5962                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5963                });
 5964
 5965                if let Some(choices) = &snippet.choices[snippet.active_index] {
 5966                    if let Some(selection) = current_ranges.first() {
 5967                        self.show_snippet_choices(&choices, selection.clone(), cx);
 5968                    }
 5969                }
 5970
 5971                // If snippet state is not at the last tabstop, push it back on the stack
 5972                if snippet.active_index + 1 < snippet.ranges.len() {
 5973                    self.snippet_stack.push(snippet);
 5974                }
 5975                return true;
 5976            }
 5977        }
 5978
 5979        false
 5980    }
 5981
 5982    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 5983        self.transact(cx, |this, cx| {
 5984            this.select_all(&SelectAll, cx);
 5985            this.insert("", cx);
 5986        });
 5987    }
 5988
 5989    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 5990        self.transact(cx, |this, cx| {
 5991            this.select_autoclose_pair(cx);
 5992            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5993            if !this.linked_edit_ranges.is_empty() {
 5994                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5995                let snapshot = this.buffer.read(cx).snapshot(cx);
 5996
 5997                for selection in selections.iter() {
 5998                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5999                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 6000                    if selection_start.buffer_id != selection_end.buffer_id {
 6001                        continue;
 6002                    }
 6003                    if let Some(ranges) =
 6004                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 6005                    {
 6006                        for (buffer, entries) in ranges {
 6007                            linked_ranges.entry(buffer).or_default().extend(entries);
 6008                        }
 6009                    }
 6010                }
 6011            }
 6012
 6013            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 6014            if !this.selections.line_mode {
 6015                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 6016                for selection in &mut selections {
 6017                    if selection.is_empty() {
 6018                        let old_head = selection.head();
 6019                        let mut new_head =
 6020                            movement::left(&display_map, old_head.to_display_point(&display_map))
 6021                                .to_point(&display_map);
 6022                        if let Some((buffer, line_buffer_range)) = display_map
 6023                            .buffer_snapshot
 6024                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 6025                        {
 6026                            let indent_size =
 6027                                buffer.indent_size_for_line(line_buffer_range.start.row);
 6028                            let indent_len = match indent_size.kind {
 6029                                IndentKind::Space => {
 6030                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 6031                                }
 6032                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 6033                            };
 6034                            if old_head.column <= indent_size.len && old_head.column > 0 {
 6035                                let indent_len = indent_len.get();
 6036                                new_head = cmp::min(
 6037                                    new_head,
 6038                                    MultiBufferPoint::new(
 6039                                        old_head.row,
 6040                                        ((old_head.column - 1) / indent_len) * indent_len,
 6041                                    ),
 6042                                );
 6043                            }
 6044                        }
 6045
 6046                        selection.set_head(new_head, SelectionGoal::None);
 6047                    }
 6048                }
 6049            }
 6050
 6051            this.signature_help_state.set_backspace_pressed(true);
 6052            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6053            this.insert("", cx);
 6054            let empty_str: Arc<str> = Arc::from("");
 6055            for (buffer, edits) in linked_ranges {
 6056                let snapshot = buffer.read(cx).snapshot();
 6057                use text::ToPoint as TP;
 6058
 6059                let edits = edits
 6060                    .into_iter()
 6061                    .map(|range| {
 6062                        let end_point = TP::to_point(&range.end, &snapshot);
 6063                        let mut start_point = TP::to_point(&range.start, &snapshot);
 6064
 6065                        if end_point == start_point {
 6066                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 6067                                .saturating_sub(1);
 6068                            start_point = TP::to_point(&offset, &snapshot);
 6069                        };
 6070
 6071                        (start_point..end_point, empty_str.clone())
 6072                    })
 6073                    .sorted_by_key(|(range, _)| range.start)
 6074                    .collect::<Vec<_>>();
 6075                buffer.update(cx, |this, cx| {
 6076                    this.edit(edits, None, cx);
 6077                })
 6078            }
 6079            this.refresh_inline_completion(true, false, cx);
 6080            linked_editing_ranges::refresh_linked_ranges(this, cx);
 6081        });
 6082    }
 6083
 6084    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 6085        self.transact(cx, |this, cx| {
 6086            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6087                let line_mode = s.line_mode;
 6088                s.move_with(|map, selection| {
 6089                    if selection.is_empty() && !line_mode {
 6090                        let cursor = movement::right(map, selection.head());
 6091                        selection.end = cursor;
 6092                        selection.reversed = true;
 6093                        selection.goal = SelectionGoal::None;
 6094                    }
 6095                })
 6096            });
 6097            this.insert("", cx);
 6098            this.refresh_inline_completion(true, false, cx);
 6099        });
 6100    }
 6101
 6102    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 6103        if self.move_to_prev_snippet_tabstop(cx) {
 6104            return;
 6105        }
 6106
 6107        self.outdent(&Outdent, cx);
 6108    }
 6109
 6110    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 6111        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 6112            return;
 6113        }
 6114
 6115        let mut selections = self.selections.all_adjusted(cx);
 6116        let buffer = self.buffer.read(cx);
 6117        let snapshot = buffer.snapshot(cx);
 6118        let rows_iter = selections.iter().map(|s| s.head().row);
 6119        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 6120
 6121        let mut edits = Vec::new();
 6122        let mut prev_edited_row = 0;
 6123        let mut row_delta = 0;
 6124        for selection in &mut selections {
 6125            if selection.start.row != prev_edited_row {
 6126                row_delta = 0;
 6127            }
 6128            prev_edited_row = selection.end.row;
 6129
 6130            // If the selection is non-empty, then increase the indentation of the selected lines.
 6131            if !selection.is_empty() {
 6132                row_delta =
 6133                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6134                continue;
 6135            }
 6136
 6137            // If the selection is empty and the cursor is in the leading whitespace before the
 6138            // suggested indentation, then auto-indent the line.
 6139            let cursor = selection.head();
 6140            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 6141            if let Some(suggested_indent) =
 6142                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 6143            {
 6144                if cursor.column < suggested_indent.len
 6145                    && cursor.column <= current_indent.len
 6146                    && current_indent.len <= suggested_indent.len
 6147                {
 6148                    selection.start = Point::new(cursor.row, suggested_indent.len);
 6149                    selection.end = selection.start;
 6150                    if row_delta == 0 {
 6151                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 6152                            cursor.row,
 6153                            current_indent,
 6154                            suggested_indent,
 6155                        ));
 6156                        row_delta = suggested_indent.len - current_indent.len;
 6157                    }
 6158                    continue;
 6159                }
 6160            }
 6161
 6162            // Otherwise, insert a hard or soft tab.
 6163            let settings = buffer.settings_at(cursor, cx);
 6164            let tab_size = if settings.hard_tabs {
 6165                IndentSize::tab()
 6166            } else {
 6167                let tab_size = settings.tab_size.get();
 6168                let char_column = snapshot
 6169                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 6170                    .flat_map(str::chars)
 6171                    .count()
 6172                    + row_delta as usize;
 6173                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 6174                IndentSize::spaces(chars_to_next_tab_stop)
 6175            };
 6176            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 6177            selection.end = selection.start;
 6178            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 6179            row_delta += tab_size.len;
 6180        }
 6181
 6182        self.transact(cx, |this, cx| {
 6183            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6184            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6185            this.refresh_inline_completion(true, false, cx);
 6186        });
 6187    }
 6188
 6189    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 6190        if self.read_only(cx) {
 6191            return;
 6192        }
 6193        let mut selections = self.selections.all::<Point>(cx);
 6194        let mut prev_edited_row = 0;
 6195        let mut row_delta = 0;
 6196        let mut edits = Vec::new();
 6197        let buffer = self.buffer.read(cx);
 6198        let snapshot = buffer.snapshot(cx);
 6199        for selection in &mut selections {
 6200            if selection.start.row != prev_edited_row {
 6201                row_delta = 0;
 6202            }
 6203            prev_edited_row = selection.end.row;
 6204
 6205            row_delta =
 6206                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6207        }
 6208
 6209        self.transact(cx, |this, cx| {
 6210            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6211            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6212        });
 6213    }
 6214
 6215    fn indent_selection(
 6216        buffer: &MultiBuffer,
 6217        snapshot: &MultiBufferSnapshot,
 6218        selection: &mut Selection<Point>,
 6219        edits: &mut Vec<(Range<Point>, String)>,
 6220        delta_for_start_row: u32,
 6221        cx: &AppContext,
 6222    ) -> u32 {
 6223        let settings = buffer.settings_at(selection.start, cx);
 6224        let tab_size = settings.tab_size.get();
 6225        let indent_kind = if settings.hard_tabs {
 6226            IndentKind::Tab
 6227        } else {
 6228            IndentKind::Space
 6229        };
 6230        let mut start_row = selection.start.row;
 6231        let mut end_row = selection.end.row + 1;
 6232
 6233        // If a selection ends at the beginning of a line, don't indent
 6234        // that last line.
 6235        if selection.end.column == 0 && selection.end.row > selection.start.row {
 6236            end_row -= 1;
 6237        }
 6238
 6239        // Avoid re-indenting a row that has already been indented by a
 6240        // previous selection, but still update this selection's column
 6241        // to reflect that indentation.
 6242        if delta_for_start_row > 0 {
 6243            start_row += 1;
 6244            selection.start.column += delta_for_start_row;
 6245            if selection.end.row == selection.start.row {
 6246                selection.end.column += delta_for_start_row;
 6247            }
 6248        }
 6249
 6250        let mut delta_for_end_row = 0;
 6251        let has_multiple_rows = start_row + 1 != end_row;
 6252        for row in start_row..end_row {
 6253            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 6254            let indent_delta = match (current_indent.kind, indent_kind) {
 6255                (IndentKind::Space, IndentKind::Space) => {
 6256                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 6257                    IndentSize::spaces(columns_to_next_tab_stop)
 6258                }
 6259                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 6260                (_, IndentKind::Tab) => IndentSize::tab(),
 6261            };
 6262
 6263            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 6264                0
 6265            } else {
 6266                selection.start.column
 6267            };
 6268            let row_start = Point::new(row, start);
 6269            edits.push((
 6270                row_start..row_start,
 6271                indent_delta.chars().collect::<String>(),
 6272            ));
 6273
 6274            // Update this selection's endpoints to reflect the indentation.
 6275            if row == selection.start.row {
 6276                selection.start.column += indent_delta.len;
 6277            }
 6278            if row == selection.end.row {
 6279                selection.end.column += indent_delta.len;
 6280                delta_for_end_row = indent_delta.len;
 6281            }
 6282        }
 6283
 6284        if selection.start.row == selection.end.row {
 6285            delta_for_start_row + delta_for_end_row
 6286        } else {
 6287            delta_for_end_row
 6288        }
 6289    }
 6290
 6291    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 6292        if self.read_only(cx) {
 6293            return;
 6294        }
 6295        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6296        let selections = self.selections.all::<Point>(cx);
 6297        let mut deletion_ranges = Vec::new();
 6298        let mut last_outdent = None;
 6299        {
 6300            let buffer = self.buffer.read(cx);
 6301            let snapshot = buffer.snapshot(cx);
 6302            for selection in &selections {
 6303                let settings = buffer.settings_at(selection.start, cx);
 6304                let tab_size = settings.tab_size.get();
 6305                let mut rows = selection.spanned_rows(false, &display_map);
 6306
 6307                // Avoid re-outdenting a row that has already been outdented by a
 6308                // previous selection.
 6309                if let Some(last_row) = last_outdent {
 6310                    if last_row == rows.start {
 6311                        rows.start = rows.start.next_row();
 6312                    }
 6313                }
 6314                let has_multiple_rows = rows.len() > 1;
 6315                for row in rows.iter_rows() {
 6316                    let indent_size = snapshot.indent_size_for_line(row);
 6317                    if indent_size.len > 0 {
 6318                        let deletion_len = match indent_size.kind {
 6319                            IndentKind::Space => {
 6320                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 6321                                if columns_to_prev_tab_stop == 0 {
 6322                                    tab_size
 6323                                } else {
 6324                                    columns_to_prev_tab_stop
 6325                                }
 6326                            }
 6327                            IndentKind::Tab => 1,
 6328                        };
 6329                        let start = if has_multiple_rows
 6330                            || deletion_len > selection.start.column
 6331                            || indent_size.len < selection.start.column
 6332                        {
 6333                            0
 6334                        } else {
 6335                            selection.start.column - deletion_len
 6336                        };
 6337                        deletion_ranges.push(
 6338                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 6339                        );
 6340                        last_outdent = Some(row);
 6341                    }
 6342                }
 6343            }
 6344        }
 6345
 6346        self.transact(cx, |this, cx| {
 6347            this.buffer.update(cx, |buffer, cx| {
 6348                let empty_str: Arc<str> = Arc::default();
 6349                buffer.edit(
 6350                    deletion_ranges
 6351                        .into_iter()
 6352                        .map(|range| (range, empty_str.clone())),
 6353                    None,
 6354                    cx,
 6355                );
 6356            });
 6357            let selections = this.selections.all::<usize>(cx);
 6358            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6359        });
 6360    }
 6361
 6362    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 6363        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6364        let selections = self.selections.all::<Point>(cx);
 6365
 6366        let mut new_cursors = Vec::new();
 6367        let mut edit_ranges = Vec::new();
 6368        let mut selections = selections.iter().peekable();
 6369        while let Some(selection) = selections.next() {
 6370            let mut rows = selection.spanned_rows(false, &display_map);
 6371            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6372
 6373            // Accumulate contiguous regions of rows that we want to delete.
 6374            while let Some(next_selection) = selections.peek() {
 6375                let next_rows = next_selection.spanned_rows(false, &display_map);
 6376                if next_rows.start <= rows.end {
 6377                    rows.end = next_rows.end;
 6378                    selections.next().unwrap();
 6379                } else {
 6380                    break;
 6381                }
 6382            }
 6383
 6384            let buffer = &display_map.buffer_snapshot;
 6385            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6386            let edit_end;
 6387            let cursor_buffer_row;
 6388            if buffer.max_point().row >= rows.end.0 {
 6389                // If there's a line after the range, delete the \n from the end of the row range
 6390                // and position the cursor on the next line.
 6391                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6392                cursor_buffer_row = rows.end;
 6393            } else {
 6394                // If there isn't a line after the range, delete the \n from the line before the
 6395                // start of the row range and position the cursor there.
 6396                edit_start = edit_start.saturating_sub(1);
 6397                edit_end = buffer.len();
 6398                cursor_buffer_row = rows.start.previous_row();
 6399            }
 6400
 6401            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6402            *cursor.column_mut() =
 6403                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6404
 6405            new_cursors.push((
 6406                selection.id,
 6407                buffer.anchor_after(cursor.to_point(&display_map)),
 6408            ));
 6409            edit_ranges.push(edit_start..edit_end);
 6410        }
 6411
 6412        self.transact(cx, |this, cx| {
 6413            let buffer = this.buffer.update(cx, |buffer, cx| {
 6414                let empty_str: Arc<str> = Arc::default();
 6415                buffer.edit(
 6416                    edit_ranges
 6417                        .into_iter()
 6418                        .map(|range| (range, empty_str.clone())),
 6419                    None,
 6420                    cx,
 6421                );
 6422                buffer.snapshot(cx)
 6423            });
 6424            let new_selections = new_cursors
 6425                .into_iter()
 6426                .map(|(id, cursor)| {
 6427                    let cursor = cursor.to_point(&buffer);
 6428                    Selection {
 6429                        id,
 6430                        start: cursor,
 6431                        end: cursor,
 6432                        reversed: false,
 6433                        goal: SelectionGoal::None,
 6434                    }
 6435                })
 6436                .collect();
 6437
 6438            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6439                s.select(new_selections);
 6440            });
 6441        });
 6442    }
 6443
 6444    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 6445        if self.read_only(cx) {
 6446            return;
 6447        }
 6448        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6449        for selection in self.selections.all::<Point>(cx) {
 6450            let start = MultiBufferRow(selection.start.row);
 6451            // Treat single line selections as if they include the next line. Otherwise this action
 6452            // would do nothing for single line selections individual cursors.
 6453            let end = if selection.start.row == selection.end.row {
 6454                MultiBufferRow(selection.start.row + 1)
 6455            } else {
 6456                MultiBufferRow(selection.end.row)
 6457            };
 6458
 6459            if let Some(last_row_range) = row_ranges.last_mut() {
 6460                if start <= last_row_range.end {
 6461                    last_row_range.end = end;
 6462                    continue;
 6463                }
 6464            }
 6465            row_ranges.push(start..end);
 6466        }
 6467
 6468        let snapshot = self.buffer.read(cx).snapshot(cx);
 6469        let mut cursor_positions = Vec::new();
 6470        for row_range in &row_ranges {
 6471            let anchor = snapshot.anchor_before(Point::new(
 6472                row_range.end.previous_row().0,
 6473                snapshot.line_len(row_range.end.previous_row()),
 6474            ));
 6475            cursor_positions.push(anchor..anchor);
 6476        }
 6477
 6478        self.transact(cx, |this, cx| {
 6479            for row_range in row_ranges.into_iter().rev() {
 6480                for row in row_range.iter_rows().rev() {
 6481                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6482                    let next_line_row = row.next_row();
 6483                    let indent = snapshot.indent_size_for_line(next_line_row);
 6484                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 6485
 6486                    let replace = if snapshot.line_len(next_line_row) > indent.len {
 6487                        " "
 6488                    } else {
 6489                        ""
 6490                    };
 6491
 6492                    this.buffer.update(cx, |buffer, cx| {
 6493                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6494                    });
 6495                }
 6496            }
 6497
 6498            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6499                s.select_anchor_ranges(cursor_positions)
 6500            });
 6501        });
 6502    }
 6503
 6504    pub fn sort_lines_case_sensitive(
 6505        &mut self,
 6506        _: &SortLinesCaseSensitive,
 6507        cx: &mut ViewContext<Self>,
 6508    ) {
 6509        self.manipulate_lines(cx, |lines| lines.sort())
 6510    }
 6511
 6512    pub fn sort_lines_case_insensitive(
 6513        &mut self,
 6514        _: &SortLinesCaseInsensitive,
 6515        cx: &mut ViewContext<Self>,
 6516    ) {
 6517        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 6518    }
 6519
 6520    pub fn unique_lines_case_insensitive(
 6521        &mut self,
 6522        _: &UniqueLinesCaseInsensitive,
 6523        cx: &mut ViewContext<Self>,
 6524    ) {
 6525        self.manipulate_lines(cx, |lines| {
 6526            let mut seen = HashSet::default();
 6527            lines.retain(|line| seen.insert(line.to_lowercase()));
 6528        })
 6529    }
 6530
 6531    pub fn unique_lines_case_sensitive(
 6532        &mut self,
 6533        _: &UniqueLinesCaseSensitive,
 6534        cx: &mut ViewContext<Self>,
 6535    ) {
 6536        self.manipulate_lines(cx, |lines| {
 6537            let mut seen = HashSet::default();
 6538            lines.retain(|line| seen.insert(*line));
 6539        })
 6540    }
 6541
 6542    pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
 6543        let mut revert_changes = HashMap::default();
 6544        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 6545        for hunk in hunks_for_rows(
 6546            Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
 6547            &multi_buffer_snapshot,
 6548        ) {
 6549            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 6550        }
 6551        if !revert_changes.is_empty() {
 6552            self.transact(cx, |editor, cx| {
 6553                editor.revert(revert_changes, cx);
 6554            });
 6555        }
 6556    }
 6557
 6558    pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
 6559        let Some(project) = self.project.clone() else {
 6560            return;
 6561        };
 6562        self.reload(project, cx).detach_and_notify_err(cx);
 6563    }
 6564
 6565    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 6566        let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
 6567        if !revert_changes.is_empty() {
 6568            self.transact(cx, |editor, cx| {
 6569                editor.revert(revert_changes, cx);
 6570            });
 6571        }
 6572    }
 6573
 6574    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 6575        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6576            let project_path = buffer.read(cx).project_path(cx)?;
 6577            let project = self.project.as_ref()?.read(cx);
 6578            let entry = project.entry_for_path(&project_path, cx)?;
 6579            let parent = match &entry.canonical_path {
 6580                Some(canonical_path) => canonical_path.to_path_buf(),
 6581                None => project.absolute_path(&project_path, cx)?,
 6582            }
 6583            .parent()?
 6584            .to_path_buf();
 6585            Some(parent)
 6586        }) {
 6587            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 6588        }
 6589    }
 6590
 6591    fn gather_revert_changes(
 6592        &mut self,
 6593        selections: &[Selection<Anchor>],
 6594        cx: &mut ViewContext<'_, Editor>,
 6595    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 6596        let mut revert_changes = HashMap::default();
 6597        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 6598        for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
 6599            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 6600        }
 6601        revert_changes
 6602    }
 6603
 6604    pub fn prepare_revert_change(
 6605        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6606        multi_buffer: &Model<MultiBuffer>,
 6607        hunk: &MultiBufferDiffHunk,
 6608        cx: &AppContext,
 6609    ) -> Option<()> {
 6610        let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
 6611        let buffer = buffer.read(cx);
 6612        let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
 6613        let buffer_snapshot = buffer.snapshot();
 6614        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6615        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6616            probe
 6617                .0
 6618                .start
 6619                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6620                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6621        }) {
 6622            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6623            Some(())
 6624        } else {
 6625            None
 6626        }
 6627    }
 6628
 6629    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 6630        self.manipulate_lines(cx, |lines| lines.reverse())
 6631    }
 6632
 6633    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 6634        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 6635    }
 6636
 6637    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6638    where
 6639        Fn: FnMut(&mut Vec<&str>),
 6640    {
 6641        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6642        let buffer = self.buffer.read(cx).snapshot(cx);
 6643
 6644        let mut edits = Vec::new();
 6645
 6646        let selections = self.selections.all::<Point>(cx);
 6647        let mut selections = selections.iter().peekable();
 6648        let mut contiguous_row_selections = Vec::new();
 6649        let mut new_selections = Vec::new();
 6650        let mut added_lines = 0;
 6651        let mut removed_lines = 0;
 6652
 6653        while let Some(selection) = selections.next() {
 6654            let (start_row, end_row) = consume_contiguous_rows(
 6655                &mut contiguous_row_selections,
 6656                selection,
 6657                &display_map,
 6658                &mut selections,
 6659            );
 6660
 6661            let start_point = Point::new(start_row.0, 0);
 6662            let end_point = Point::new(
 6663                end_row.previous_row().0,
 6664                buffer.line_len(end_row.previous_row()),
 6665            );
 6666            let text = buffer
 6667                .text_for_range(start_point..end_point)
 6668                .collect::<String>();
 6669
 6670            let mut lines = text.split('\n').collect_vec();
 6671
 6672            let lines_before = lines.len();
 6673            callback(&mut lines);
 6674            let lines_after = lines.len();
 6675
 6676            edits.push((start_point..end_point, lines.join("\n")));
 6677
 6678            // Selections must change based on added and removed line count
 6679            let start_row =
 6680                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6681            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6682            new_selections.push(Selection {
 6683                id: selection.id,
 6684                start: start_row,
 6685                end: end_row,
 6686                goal: SelectionGoal::None,
 6687                reversed: selection.reversed,
 6688            });
 6689
 6690            if lines_after > lines_before {
 6691                added_lines += lines_after - lines_before;
 6692            } else if lines_before > lines_after {
 6693                removed_lines += lines_before - lines_after;
 6694            }
 6695        }
 6696
 6697        self.transact(cx, |this, cx| {
 6698            let buffer = this.buffer.update(cx, |buffer, cx| {
 6699                buffer.edit(edits, None, cx);
 6700                buffer.snapshot(cx)
 6701            });
 6702
 6703            // Recalculate offsets on newly edited buffer
 6704            let new_selections = new_selections
 6705                .iter()
 6706                .map(|s| {
 6707                    let start_point = Point::new(s.start.0, 0);
 6708                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6709                    Selection {
 6710                        id: s.id,
 6711                        start: buffer.point_to_offset(start_point),
 6712                        end: buffer.point_to_offset(end_point),
 6713                        goal: s.goal,
 6714                        reversed: s.reversed,
 6715                    }
 6716                })
 6717                .collect();
 6718
 6719            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6720                s.select(new_selections);
 6721            });
 6722
 6723            this.request_autoscroll(Autoscroll::fit(), cx);
 6724        });
 6725    }
 6726
 6727    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 6728        self.manipulate_text(cx, |text| text.to_uppercase())
 6729    }
 6730
 6731    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 6732        self.manipulate_text(cx, |text| text.to_lowercase())
 6733    }
 6734
 6735    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 6736        self.manipulate_text(cx, |text| {
 6737            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6738            // https://github.com/rutrum/convert-case/issues/16
 6739            text.split('\n')
 6740                .map(|line| line.to_case(Case::Title))
 6741                .join("\n")
 6742        })
 6743    }
 6744
 6745    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6746        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6747    }
 6748
 6749    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6750        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6751    }
 6752
 6753    pub fn convert_to_upper_camel_case(
 6754        &mut self,
 6755        _: &ConvertToUpperCamelCase,
 6756        cx: &mut ViewContext<Self>,
 6757    ) {
 6758        self.manipulate_text(cx, |text| {
 6759            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6760            // https://github.com/rutrum/convert-case/issues/16
 6761            text.split('\n')
 6762                .map(|line| line.to_case(Case::UpperCamel))
 6763                .join("\n")
 6764        })
 6765    }
 6766
 6767    pub fn convert_to_lower_camel_case(
 6768        &mut self,
 6769        _: &ConvertToLowerCamelCase,
 6770        cx: &mut ViewContext<Self>,
 6771    ) {
 6772        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6773    }
 6774
 6775    pub fn convert_to_opposite_case(
 6776        &mut self,
 6777        _: &ConvertToOppositeCase,
 6778        cx: &mut ViewContext<Self>,
 6779    ) {
 6780        self.manipulate_text(cx, |text| {
 6781            text.chars()
 6782                .fold(String::with_capacity(text.len()), |mut t, c| {
 6783                    if c.is_uppercase() {
 6784                        t.extend(c.to_lowercase());
 6785                    } else {
 6786                        t.extend(c.to_uppercase());
 6787                    }
 6788                    t
 6789                })
 6790        })
 6791    }
 6792
 6793    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6794    where
 6795        Fn: FnMut(&str) -> String,
 6796    {
 6797        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6798        let buffer = self.buffer.read(cx).snapshot(cx);
 6799
 6800        let mut new_selections = Vec::new();
 6801        let mut edits = Vec::new();
 6802        let mut selection_adjustment = 0i32;
 6803
 6804        for selection in self.selections.all::<usize>(cx) {
 6805            let selection_is_empty = selection.is_empty();
 6806
 6807            let (start, end) = if selection_is_empty {
 6808                let word_range = movement::surrounding_word(
 6809                    &display_map,
 6810                    selection.start.to_display_point(&display_map),
 6811                );
 6812                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6813                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6814                (start, end)
 6815            } else {
 6816                (selection.start, selection.end)
 6817            };
 6818
 6819            let text = buffer.text_for_range(start..end).collect::<String>();
 6820            let old_length = text.len() as i32;
 6821            let text = callback(&text);
 6822
 6823            new_selections.push(Selection {
 6824                start: (start as i32 - selection_adjustment) as usize,
 6825                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6826                goal: SelectionGoal::None,
 6827                ..selection
 6828            });
 6829
 6830            selection_adjustment += old_length - text.len() as i32;
 6831
 6832            edits.push((start..end, text));
 6833        }
 6834
 6835        self.transact(cx, |this, cx| {
 6836            this.buffer.update(cx, |buffer, cx| {
 6837                buffer.edit(edits, None, cx);
 6838            });
 6839
 6840            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6841                s.select(new_selections);
 6842            });
 6843
 6844            this.request_autoscroll(Autoscroll::fit(), cx);
 6845        });
 6846    }
 6847
 6848    pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
 6849        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6850        let buffer = &display_map.buffer_snapshot;
 6851        let selections = self.selections.all::<Point>(cx);
 6852
 6853        let mut edits = Vec::new();
 6854        let mut selections_iter = selections.iter().peekable();
 6855        while let Some(selection) = selections_iter.next() {
 6856            // Avoid duplicating the same lines twice.
 6857            let mut rows = selection.spanned_rows(false, &display_map);
 6858
 6859            while let Some(next_selection) = selections_iter.peek() {
 6860                let next_rows = next_selection.spanned_rows(false, &display_map);
 6861                if next_rows.start < rows.end {
 6862                    rows.end = next_rows.end;
 6863                    selections_iter.next().unwrap();
 6864                } else {
 6865                    break;
 6866                }
 6867            }
 6868
 6869            // Copy the text from the selected row region and splice it either at the start
 6870            // or end of the region.
 6871            let start = Point::new(rows.start.0, 0);
 6872            let end = Point::new(
 6873                rows.end.previous_row().0,
 6874                buffer.line_len(rows.end.previous_row()),
 6875            );
 6876            let text = buffer
 6877                .text_for_range(start..end)
 6878                .chain(Some("\n"))
 6879                .collect::<String>();
 6880            let insert_location = if upwards {
 6881                Point::new(rows.end.0, 0)
 6882            } else {
 6883                start
 6884            };
 6885            edits.push((insert_location..insert_location, text));
 6886        }
 6887
 6888        self.transact(cx, |this, cx| {
 6889            this.buffer.update(cx, |buffer, cx| {
 6890                buffer.edit(edits, None, cx);
 6891            });
 6892
 6893            this.request_autoscroll(Autoscroll::fit(), cx);
 6894        });
 6895    }
 6896
 6897    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6898        self.duplicate_line(true, cx);
 6899    }
 6900
 6901    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6902        self.duplicate_line(false, cx);
 6903    }
 6904
 6905    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6906        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6907        let buffer = self.buffer.read(cx).snapshot(cx);
 6908
 6909        let mut edits = Vec::new();
 6910        let mut unfold_ranges = Vec::new();
 6911        let mut refold_creases = Vec::new();
 6912
 6913        let selections = self.selections.all::<Point>(cx);
 6914        let mut selections = selections.iter().peekable();
 6915        let mut contiguous_row_selections = Vec::new();
 6916        let mut new_selections = Vec::new();
 6917
 6918        while let Some(selection) = selections.next() {
 6919            // Find all the selections that span a contiguous row range
 6920            let (start_row, end_row) = consume_contiguous_rows(
 6921                &mut contiguous_row_selections,
 6922                selection,
 6923                &display_map,
 6924                &mut selections,
 6925            );
 6926
 6927            // Move the text spanned by the row range to be before the line preceding the row range
 6928            if start_row.0 > 0 {
 6929                let range_to_move = Point::new(
 6930                    start_row.previous_row().0,
 6931                    buffer.line_len(start_row.previous_row()),
 6932                )
 6933                    ..Point::new(
 6934                        end_row.previous_row().0,
 6935                        buffer.line_len(end_row.previous_row()),
 6936                    );
 6937                let insertion_point = display_map
 6938                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6939                    .0;
 6940
 6941                // Don't move lines across excerpts
 6942                if buffer
 6943                    .excerpt_boundaries_in_range((
 6944                        Bound::Excluded(insertion_point),
 6945                        Bound::Included(range_to_move.end),
 6946                    ))
 6947                    .next()
 6948                    .is_none()
 6949                {
 6950                    let text = buffer
 6951                        .text_for_range(range_to_move.clone())
 6952                        .flat_map(|s| s.chars())
 6953                        .skip(1)
 6954                        .chain(['\n'])
 6955                        .collect::<String>();
 6956
 6957                    edits.push((
 6958                        buffer.anchor_after(range_to_move.start)
 6959                            ..buffer.anchor_before(range_to_move.end),
 6960                        String::new(),
 6961                    ));
 6962                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6963                    edits.push((insertion_anchor..insertion_anchor, text));
 6964
 6965                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6966
 6967                    // Move selections up
 6968                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6969                        |mut selection| {
 6970                            selection.start.row -= row_delta;
 6971                            selection.end.row -= row_delta;
 6972                            selection
 6973                        },
 6974                    ));
 6975
 6976                    // Move folds up
 6977                    unfold_ranges.push(range_to_move.clone());
 6978                    for fold in display_map.folds_in_range(
 6979                        buffer.anchor_before(range_to_move.start)
 6980                            ..buffer.anchor_after(range_to_move.end),
 6981                    ) {
 6982                        let mut start = fold.range.start.to_point(&buffer);
 6983                        let mut end = fold.range.end.to_point(&buffer);
 6984                        start.row -= row_delta;
 6985                        end.row -= row_delta;
 6986                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6987                    }
 6988                }
 6989            }
 6990
 6991            // If we didn't move line(s), preserve the existing selections
 6992            new_selections.append(&mut contiguous_row_selections);
 6993        }
 6994
 6995        self.transact(cx, |this, cx| {
 6996            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6997            this.buffer.update(cx, |buffer, cx| {
 6998                for (range, text) in edits {
 6999                    buffer.edit([(range, text)], None, cx);
 7000                }
 7001            });
 7002            this.fold_creases(refold_creases, true, cx);
 7003            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7004                s.select(new_selections);
 7005            })
 7006        });
 7007    }
 7008
 7009    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 7010        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7011        let buffer = self.buffer.read(cx).snapshot(cx);
 7012
 7013        let mut edits = Vec::new();
 7014        let mut unfold_ranges = Vec::new();
 7015        let mut refold_creases = Vec::new();
 7016
 7017        let selections = self.selections.all::<Point>(cx);
 7018        let mut selections = selections.iter().peekable();
 7019        let mut contiguous_row_selections = Vec::new();
 7020        let mut new_selections = Vec::new();
 7021
 7022        while let Some(selection) = selections.next() {
 7023            // Find all the selections that span a contiguous row range
 7024            let (start_row, end_row) = consume_contiguous_rows(
 7025                &mut contiguous_row_selections,
 7026                selection,
 7027                &display_map,
 7028                &mut selections,
 7029            );
 7030
 7031            // Move the text spanned by the row range to be after the last line of the row range
 7032            if end_row.0 <= buffer.max_point().row {
 7033                let range_to_move =
 7034                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 7035                let insertion_point = display_map
 7036                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 7037                    .0;
 7038
 7039                // Don't move lines across excerpt boundaries
 7040                if buffer
 7041                    .excerpt_boundaries_in_range((
 7042                        Bound::Excluded(range_to_move.start),
 7043                        Bound::Included(insertion_point),
 7044                    ))
 7045                    .next()
 7046                    .is_none()
 7047                {
 7048                    let mut text = String::from("\n");
 7049                    text.extend(buffer.text_for_range(range_to_move.clone()));
 7050                    text.pop(); // Drop trailing newline
 7051                    edits.push((
 7052                        buffer.anchor_after(range_to_move.start)
 7053                            ..buffer.anchor_before(range_to_move.end),
 7054                        String::new(),
 7055                    ));
 7056                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7057                    edits.push((insertion_anchor..insertion_anchor, text));
 7058
 7059                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 7060
 7061                    // Move selections down
 7062                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7063                        |mut selection| {
 7064                            selection.start.row += row_delta;
 7065                            selection.end.row += row_delta;
 7066                            selection
 7067                        },
 7068                    ));
 7069
 7070                    // Move folds down
 7071                    unfold_ranges.push(range_to_move.clone());
 7072                    for fold in display_map.folds_in_range(
 7073                        buffer.anchor_before(range_to_move.start)
 7074                            ..buffer.anchor_after(range_to_move.end),
 7075                    ) {
 7076                        let mut start = fold.range.start.to_point(&buffer);
 7077                        let mut end = fold.range.end.to_point(&buffer);
 7078                        start.row += row_delta;
 7079                        end.row += row_delta;
 7080                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7081                    }
 7082                }
 7083            }
 7084
 7085            // If we didn't move line(s), preserve the existing selections
 7086            new_selections.append(&mut contiguous_row_selections);
 7087        }
 7088
 7089        self.transact(cx, |this, cx| {
 7090            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7091            this.buffer.update(cx, |buffer, cx| {
 7092                for (range, text) in edits {
 7093                    buffer.edit([(range, text)], None, cx);
 7094                }
 7095            });
 7096            this.fold_creases(refold_creases, true, cx);
 7097            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 7098        });
 7099    }
 7100
 7101    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 7102        let text_layout_details = &self.text_layout_details(cx);
 7103        self.transact(cx, |this, cx| {
 7104            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7105                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 7106                let line_mode = s.line_mode;
 7107                s.move_with(|display_map, selection| {
 7108                    if !selection.is_empty() || line_mode {
 7109                        return;
 7110                    }
 7111
 7112                    let mut head = selection.head();
 7113                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 7114                    if head.column() == display_map.line_len(head.row()) {
 7115                        transpose_offset = display_map
 7116                            .buffer_snapshot
 7117                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7118                    }
 7119
 7120                    if transpose_offset == 0 {
 7121                        return;
 7122                    }
 7123
 7124                    *head.column_mut() += 1;
 7125                    head = display_map.clip_point(head, Bias::Right);
 7126                    let goal = SelectionGoal::HorizontalPosition(
 7127                        display_map
 7128                            .x_for_display_point(head, text_layout_details)
 7129                            .into(),
 7130                    );
 7131                    selection.collapse_to(head, goal);
 7132
 7133                    let transpose_start = display_map
 7134                        .buffer_snapshot
 7135                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7136                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 7137                        let transpose_end = display_map
 7138                            .buffer_snapshot
 7139                            .clip_offset(transpose_offset + 1, Bias::Right);
 7140                        if let Some(ch) =
 7141                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 7142                        {
 7143                            edits.push((transpose_start..transpose_offset, String::new()));
 7144                            edits.push((transpose_end..transpose_end, ch.to_string()));
 7145                        }
 7146                    }
 7147                });
 7148                edits
 7149            });
 7150            this.buffer
 7151                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7152            let selections = this.selections.all::<usize>(cx);
 7153            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7154                s.select(selections);
 7155            });
 7156        });
 7157    }
 7158
 7159    pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
 7160        self.rewrap_impl(IsVimMode::No, cx)
 7161    }
 7162
 7163    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
 7164        let buffer = self.buffer.read(cx).snapshot(cx);
 7165        let selections = self.selections.all::<Point>(cx);
 7166        let mut selections = selections.iter().peekable();
 7167
 7168        let mut edits = Vec::new();
 7169        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 7170
 7171        while let Some(selection) = selections.next() {
 7172            let mut start_row = selection.start.row;
 7173            let mut end_row = selection.end.row;
 7174
 7175            // Skip selections that overlap with a range that has already been rewrapped.
 7176            let selection_range = start_row..end_row;
 7177            if rewrapped_row_ranges
 7178                .iter()
 7179                .any(|range| range.overlaps(&selection_range))
 7180            {
 7181                continue;
 7182            }
 7183
 7184            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 7185
 7186            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 7187                match language_scope.language_name().0.as_ref() {
 7188                    "Markdown" | "Plain Text" => {
 7189                        should_rewrap = true;
 7190                    }
 7191                    _ => {}
 7192                }
 7193            }
 7194
 7195            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 7196
 7197            // Since not all lines in the selection may be at the same indent
 7198            // level, choose the indent size that is the most common between all
 7199            // of the lines.
 7200            //
 7201            // If there is a tie, we use the deepest indent.
 7202            let (indent_size, indent_end) = {
 7203                let mut indent_size_occurrences = HashMap::default();
 7204                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 7205
 7206                for row in start_row..=end_row {
 7207                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 7208                    rows_by_indent_size.entry(indent).or_default().push(row);
 7209                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 7210                }
 7211
 7212                let indent_size = indent_size_occurrences
 7213                    .into_iter()
 7214                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 7215                    .map(|(indent, _)| indent)
 7216                    .unwrap_or_default();
 7217                let row = rows_by_indent_size[&indent_size][0];
 7218                let indent_end = Point::new(row, indent_size.len);
 7219
 7220                (indent_size, indent_end)
 7221            };
 7222
 7223            let mut line_prefix = indent_size.chars().collect::<String>();
 7224
 7225            if let Some(comment_prefix) =
 7226                buffer
 7227                    .language_scope_at(selection.head())
 7228                    .and_then(|language| {
 7229                        language
 7230                            .line_comment_prefixes()
 7231                            .iter()
 7232                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 7233                            .cloned()
 7234                    })
 7235            {
 7236                line_prefix.push_str(&comment_prefix);
 7237                should_rewrap = true;
 7238            }
 7239
 7240            if !should_rewrap {
 7241                continue;
 7242            }
 7243
 7244            if selection.is_empty() {
 7245                'expand_upwards: while start_row > 0 {
 7246                    let prev_row = start_row - 1;
 7247                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 7248                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 7249                    {
 7250                        start_row = prev_row;
 7251                    } else {
 7252                        break 'expand_upwards;
 7253                    }
 7254                }
 7255
 7256                'expand_downwards: while end_row < buffer.max_point().row {
 7257                    let next_row = end_row + 1;
 7258                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 7259                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 7260                    {
 7261                        end_row = next_row;
 7262                    } else {
 7263                        break 'expand_downwards;
 7264                    }
 7265                }
 7266            }
 7267
 7268            let start = Point::new(start_row, 0);
 7269            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 7270            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 7271            let Some(lines_without_prefixes) = selection_text
 7272                .lines()
 7273                .map(|line| {
 7274                    line.strip_prefix(&line_prefix)
 7275                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 7276                        .ok_or_else(|| {
 7277                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 7278                        })
 7279                })
 7280                .collect::<Result<Vec<_>, _>>()
 7281                .log_err()
 7282            else {
 7283                continue;
 7284            };
 7285
 7286            let wrap_column = buffer
 7287                .settings_at(Point::new(start_row, 0), cx)
 7288                .preferred_line_length as usize;
 7289            let wrapped_text = wrap_with_prefix(
 7290                line_prefix,
 7291                lines_without_prefixes.join(" "),
 7292                wrap_column,
 7293                tab_size,
 7294            );
 7295
 7296            // TODO: should always use char-based diff while still supporting cursor behavior that
 7297            // matches vim.
 7298            let diff = match is_vim_mode {
 7299                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 7300                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 7301            };
 7302            let mut offset = start.to_offset(&buffer);
 7303            let mut moved_since_edit = true;
 7304
 7305            for change in diff.iter_all_changes() {
 7306                let value = change.value();
 7307                match change.tag() {
 7308                    ChangeTag::Equal => {
 7309                        offset += value.len();
 7310                        moved_since_edit = true;
 7311                    }
 7312                    ChangeTag::Delete => {
 7313                        let start = buffer.anchor_after(offset);
 7314                        let end = buffer.anchor_before(offset + value.len());
 7315
 7316                        if moved_since_edit {
 7317                            edits.push((start..end, String::new()));
 7318                        } else {
 7319                            edits.last_mut().unwrap().0.end = end;
 7320                        }
 7321
 7322                        offset += value.len();
 7323                        moved_since_edit = false;
 7324                    }
 7325                    ChangeTag::Insert => {
 7326                        if moved_since_edit {
 7327                            let anchor = buffer.anchor_after(offset);
 7328                            edits.push((anchor..anchor, value.to_string()));
 7329                        } else {
 7330                            edits.last_mut().unwrap().1.push_str(value);
 7331                        }
 7332
 7333                        moved_since_edit = false;
 7334                    }
 7335                }
 7336            }
 7337
 7338            rewrapped_row_ranges.push(start_row..=end_row);
 7339        }
 7340
 7341        self.buffer
 7342            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7343    }
 7344
 7345    pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
 7346        let mut text = String::new();
 7347        let buffer = self.buffer.read(cx).snapshot(cx);
 7348        let mut selections = self.selections.all::<Point>(cx);
 7349        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7350        {
 7351            let max_point = buffer.max_point();
 7352            let mut is_first = true;
 7353            for selection in &mut selections {
 7354                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7355                if is_entire_line {
 7356                    selection.start = Point::new(selection.start.row, 0);
 7357                    if !selection.is_empty() && selection.end.column == 0 {
 7358                        selection.end = cmp::min(max_point, selection.end);
 7359                    } else {
 7360                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7361                    }
 7362                    selection.goal = SelectionGoal::None;
 7363                }
 7364                if is_first {
 7365                    is_first = false;
 7366                } else {
 7367                    text += "\n";
 7368                }
 7369                let mut len = 0;
 7370                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7371                    text.push_str(chunk);
 7372                    len += chunk.len();
 7373                }
 7374                clipboard_selections.push(ClipboardSelection {
 7375                    len,
 7376                    is_entire_line,
 7377                    first_line_indent: buffer
 7378                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7379                        .len,
 7380                });
 7381            }
 7382        }
 7383
 7384        self.transact(cx, |this, cx| {
 7385            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7386                s.select(selections);
 7387            });
 7388            this.insert("", cx);
 7389        });
 7390        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 7391    }
 7392
 7393    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 7394        let item = self.cut_common(cx);
 7395        cx.write_to_clipboard(item);
 7396    }
 7397
 7398    pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
 7399        self.change_selections(None, cx, |s| {
 7400            s.move_with(|snapshot, sel| {
 7401                if sel.is_empty() {
 7402                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 7403                }
 7404            });
 7405        });
 7406        let item = self.cut_common(cx);
 7407        cx.set_global(KillRing(item))
 7408    }
 7409
 7410    pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
 7411        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 7412            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 7413                (kill_ring.text().to_string(), kill_ring.metadata_json())
 7414            } else {
 7415                return;
 7416            }
 7417        } else {
 7418            return;
 7419        };
 7420        self.do_paste(&text, metadata, false, cx);
 7421    }
 7422
 7423    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 7424        let selections = self.selections.all::<Point>(cx);
 7425        let buffer = self.buffer.read(cx).read(cx);
 7426        let mut text = String::new();
 7427
 7428        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7429        {
 7430            let max_point = buffer.max_point();
 7431            let mut is_first = true;
 7432            for selection in selections.iter() {
 7433                let mut start = selection.start;
 7434                let mut end = selection.end;
 7435                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7436                if is_entire_line {
 7437                    start = Point::new(start.row, 0);
 7438                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 7439                }
 7440                if is_first {
 7441                    is_first = false;
 7442                } else {
 7443                    text += "\n";
 7444                }
 7445                let mut len = 0;
 7446                for chunk in buffer.text_for_range(start..end) {
 7447                    text.push_str(chunk);
 7448                    len += chunk.len();
 7449                }
 7450                clipboard_selections.push(ClipboardSelection {
 7451                    len,
 7452                    is_entire_line,
 7453                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 7454                });
 7455            }
 7456        }
 7457
 7458        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7459            text,
 7460            clipboard_selections,
 7461        ));
 7462    }
 7463
 7464    pub fn do_paste(
 7465        &mut self,
 7466        text: &String,
 7467        clipboard_selections: Option<Vec<ClipboardSelection>>,
 7468        handle_entire_lines: bool,
 7469        cx: &mut ViewContext<Self>,
 7470    ) {
 7471        if self.read_only(cx) {
 7472            return;
 7473        }
 7474
 7475        let clipboard_text = Cow::Borrowed(text);
 7476
 7477        self.transact(cx, |this, cx| {
 7478            if let Some(mut clipboard_selections) = clipboard_selections {
 7479                let old_selections = this.selections.all::<usize>(cx);
 7480                let all_selections_were_entire_line =
 7481                    clipboard_selections.iter().all(|s| s.is_entire_line);
 7482                let first_selection_indent_column =
 7483                    clipboard_selections.first().map(|s| s.first_line_indent);
 7484                if clipboard_selections.len() != old_selections.len() {
 7485                    clipboard_selections.drain(..);
 7486                }
 7487                let cursor_offset = this.selections.last::<usize>(cx).head();
 7488                let mut auto_indent_on_paste = true;
 7489
 7490                this.buffer.update(cx, |buffer, cx| {
 7491                    let snapshot = buffer.read(cx);
 7492                    auto_indent_on_paste =
 7493                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 7494
 7495                    let mut start_offset = 0;
 7496                    let mut edits = Vec::new();
 7497                    let mut original_indent_columns = Vec::new();
 7498                    for (ix, selection) in old_selections.iter().enumerate() {
 7499                        let to_insert;
 7500                        let entire_line;
 7501                        let original_indent_column;
 7502                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 7503                            let end_offset = start_offset + clipboard_selection.len;
 7504                            to_insert = &clipboard_text[start_offset..end_offset];
 7505                            entire_line = clipboard_selection.is_entire_line;
 7506                            start_offset = end_offset + 1;
 7507                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7508                        } else {
 7509                            to_insert = clipboard_text.as_str();
 7510                            entire_line = all_selections_were_entire_line;
 7511                            original_indent_column = first_selection_indent_column
 7512                        }
 7513
 7514                        // If the corresponding selection was empty when this slice of the
 7515                        // clipboard text was written, then the entire line containing the
 7516                        // selection was copied. If this selection is also currently empty,
 7517                        // then paste the line before the current line of the buffer.
 7518                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7519                            let column = selection.start.to_point(&snapshot).column as usize;
 7520                            let line_start = selection.start - column;
 7521                            line_start..line_start
 7522                        } else {
 7523                            selection.range()
 7524                        };
 7525
 7526                        edits.push((range, to_insert));
 7527                        original_indent_columns.extend(original_indent_column);
 7528                    }
 7529                    drop(snapshot);
 7530
 7531                    buffer.edit(
 7532                        edits,
 7533                        if auto_indent_on_paste {
 7534                            Some(AutoindentMode::Block {
 7535                                original_indent_columns,
 7536                            })
 7537                        } else {
 7538                            None
 7539                        },
 7540                        cx,
 7541                    );
 7542                });
 7543
 7544                let selections = this.selections.all::<usize>(cx);
 7545                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 7546            } else {
 7547                this.insert(&clipboard_text, cx);
 7548            }
 7549        });
 7550    }
 7551
 7552    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 7553        if let Some(item) = cx.read_from_clipboard() {
 7554            let entries = item.entries();
 7555
 7556            match entries.first() {
 7557                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7558                // of all the pasted entries.
 7559                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7560                    .do_paste(
 7561                        clipboard_string.text(),
 7562                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7563                        true,
 7564                        cx,
 7565                    ),
 7566                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
 7567            }
 7568        }
 7569    }
 7570
 7571    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 7572        if self.read_only(cx) {
 7573            return;
 7574        }
 7575
 7576        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7577            if let Some((selections, _)) =
 7578                self.selection_history.transaction(transaction_id).cloned()
 7579            {
 7580                self.change_selections(None, cx, |s| {
 7581                    s.select_anchors(selections.to_vec());
 7582                });
 7583            }
 7584            self.request_autoscroll(Autoscroll::fit(), cx);
 7585            self.unmark_text(cx);
 7586            self.refresh_inline_completion(true, false, cx);
 7587            cx.emit(EditorEvent::Edited { transaction_id });
 7588            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7589        }
 7590    }
 7591
 7592    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 7593        if self.read_only(cx) {
 7594            return;
 7595        }
 7596
 7597        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7598            if let Some((_, Some(selections))) =
 7599                self.selection_history.transaction(transaction_id).cloned()
 7600            {
 7601                self.change_selections(None, cx, |s| {
 7602                    s.select_anchors(selections.to_vec());
 7603                });
 7604            }
 7605            self.request_autoscroll(Autoscroll::fit(), cx);
 7606            self.unmark_text(cx);
 7607            self.refresh_inline_completion(true, false, cx);
 7608            cx.emit(EditorEvent::Edited { transaction_id });
 7609        }
 7610    }
 7611
 7612    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 7613        self.buffer
 7614            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7615    }
 7616
 7617    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 7618        self.buffer
 7619            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7620    }
 7621
 7622    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 7623        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7624            let line_mode = s.line_mode;
 7625            s.move_with(|map, selection| {
 7626                let cursor = if selection.is_empty() && !line_mode {
 7627                    movement::left(map, selection.start)
 7628                } else {
 7629                    selection.start
 7630                };
 7631                selection.collapse_to(cursor, SelectionGoal::None);
 7632            });
 7633        })
 7634    }
 7635
 7636    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 7637        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7638            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7639        })
 7640    }
 7641
 7642    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 7643        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7644            let line_mode = s.line_mode;
 7645            s.move_with(|map, selection| {
 7646                let cursor = if selection.is_empty() && !line_mode {
 7647                    movement::right(map, selection.end)
 7648                } else {
 7649                    selection.end
 7650                };
 7651                selection.collapse_to(cursor, SelectionGoal::None)
 7652            });
 7653        })
 7654    }
 7655
 7656    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 7657        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7658            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7659        })
 7660    }
 7661
 7662    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 7663        if self.take_rename(true, cx).is_some() {
 7664            return;
 7665        }
 7666
 7667        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7668            cx.propagate();
 7669            return;
 7670        }
 7671
 7672        let text_layout_details = &self.text_layout_details(cx);
 7673        let selection_count = self.selections.count();
 7674        let first_selection = self.selections.first_anchor();
 7675
 7676        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7677            let line_mode = s.line_mode;
 7678            s.move_with(|map, selection| {
 7679                if !selection.is_empty() && !line_mode {
 7680                    selection.goal = SelectionGoal::None;
 7681                }
 7682                let (cursor, goal) = movement::up(
 7683                    map,
 7684                    selection.start,
 7685                    selection.goal,
 7686                    false,
 7687                    text_layout_details,
 7688                );
 7689                selection.collapse_to(cursor, goal);
 7690            });
 7691        });
 7692
 7693        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7694        {
 7695            cx.propagate();
 7696        }
 7697    }
 7698
 7699    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 7700        if self.take_rename(true, cx).is_some() {
 7701            return;
 7702        }
 7703
 7704        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7705            cx.propagate();
 7706            return;
 7707        }
 7708
 7709        let text_layout_details = &self.text_layout_details(cx);
 7710
 7711        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7712            let line_mode = s.line_mode;
 7713            s.move_with(|map, selection| {
 7714                if !selection.is_empty() && !line_mode {
 7715                    selection.goal = SelectionGoal::None;
 7716                }
 7717                let (cursor, goal) = movement::up_by_rows(
 7718                    map,
 7719                    selection.start,
 7720                    action.lines,
 7721                    selection.goal,
 7722                    false,
 7723                    text_layout_details,
 7724                );
 7725                selection.collapse_to(cursor, goal);
 7726            });
 7727        })
 7728    }
 7729
 7730    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 7731        if self.take_rename(true, cx).is_some() {
 7732            return;
 7733        }
 7734
 7735        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7736            cx.propagate();
 7737            return;
 7738        }
 7739
 7740        let text_layout_details = &self.text_layout_details(cx);
 7741
 7742        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7743            let line_mode = s.line_mode;
 7744            s.move_with(|map, selection| {
 7745                if !selection.is_empty() && !line_mode {
 7746                    selection.goal = SelectionGoal::None;
 7747                }
 7748                let (cursor, goal) = movement::down_by_rows(
 7749                    map,
 7750                    selection.start,
 7751                    action.lines,
 7752                    selection.goal,
 7753                    false,
 7754                    text_layout_details,
 7755                );
 7756                selection.collapse_to(cursor, goal);
 7757            });
 7758        })
 7759    }
 7760
 7761    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 7762        let text_layout_details = &self.text_layout_details(cx);
 7763        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7764            s.move_heads_with(|map, head, goal| {
 7765                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7766            })
 7767        })
 7768    }
 7769
 7770    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 7771        let text_layout_details = &self.text_layout_details(cx);
 7772        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7773            s.move_heads_with(|map, head, goal| {
 7774                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7775            })
 7776        })
 7777    }
 7778
 7779    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 7780        let Some(row_count) = self.visible_row_count() else {
 7781            return;
 7782        };
 7783
 7784        let text_layout_details = &self.text_layout_details(cx);
 7785
 7786        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7787            s.move_heads_with(|map, head, goal| {
 7788                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7789            })
 7790        })
 7791    }
 7792
 7793    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 7794        if self.take_rename(true, cx).is_some() {
 7795            return;
 7796        }
 7797
 7798        if self
 7799            .context_menu
 7800            .write()
 7801            .as_mut()
 7802            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 7803            .unwrap_or(false)
 7804        {
 7805            return;
 7806        }
 7807
 7808        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7809            cx.propagate();
 7810            return;
 7811        }
 7812
 7813        let Some(row_count) = self.visible_row_count() else {
 7814            return;
 7815        };
 7816
 7817        let autoscroll = if action.center_cursor {
 7818            Autoscroll::center()
 7819        } else {
 7820            Autoscroll::fit()
 7821        };
 7822
 7823        let text_layout_details = &self.text_layout_details(cx);
 7824
 7825        self.change_selections(Some(autoscroll), cx, |s| {
 7826            let line_mode = s.line_mode;
 7827            s.move_with(|map, selection| {
 7828                if !selection.is_empty() && !line_mode {
 7829                    selection.goal = SelectionGoal::None;
 7830                }
 7831                let (cursor, goal) = movement::up_by_rows(
 7832                    map,
 7833                    selection.end,
 7834                    row_count,
 7835                    selection.goal,
 7836                    false,
 7837                    text_layout_details,
 7838                );
 7839                selection.collapse_to(cursor, goal);
 7840            });
 7841        });
 7842    }
 7843
 7844    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 7845        let text_layout_details = &self.text_layout_details(cx);
 7846        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7847            s.move_heads_with(|map, head, goal| {
 7848                movement::up(map, head, goal, false, text_layout_details)
 7849            })
 7850        })
 7851    }
 7852
 7853    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 7854        self.take_rename(true, cx);
 7855
 7856        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7857            cx.propagate();
 7858            return;
 7859        }
 7860
 7861        let text_layout_details = &self.text_layout_details(cx);
 7862        let selection_count = self.selections.count();
 7863        let first_selection = self.selections.first_anchor();
 7864
 7865        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7866            let line_mode = s.line_mode;
 7867            s.move_with(|map, selection| {
 7868                if !selection.is_empty() && !line_mode {
 7869                    selection.goal = SelectionGoal::None;
 7870                }
 7871                let (cursor, goal) = movement::down(
 7872                    map,
 7873                    selection.end,
 7874                    selection.goal,
 7875                    false,
 7876                    text_layout_details,
 7877                );
 7878                selection.collapse_to(cursor, goal);
 7879            });
 7880        });
 7881
 7882        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7883        {
 7884            cx.propagate();
 7885        }
 7886    }
 7887
 7888    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 7889        let Some(row_count) = self.visible_row_count() else {
 7890            return;
 7891        };
 7892
 7893        let text_layout_details = &self.text_layout_details(cx);
 7894
 7895        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7896            s.move_heads_with(|map, head, goal| {
 7897                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 7898            })
 7899        })
 7900    }
 7901
 7902    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 7903        if self.take_rename(true, cx).is_some() {
 7904            return;
 7905        }
 7906
 7907        if self
 7908            .context_menu
 7909            .write()
 7910            .as_mut()
 7911            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 7912            .unwrap_or(false)
 7913        {
 7914            return;
 7915        }
 7916
 7917        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7918            cx.propagate();
 7919            return;
 7920        }
 7921
 7922        let Some(row_count) = self.visible_row_count() else {
 7923            return;
 7924        };
 7925
 7926        let autoscroll = if action.center_cursor {
 7927            Autoscroll::center()
 7928        } else {
 7929            Autoscroll::fit()
 7930        };
 7931
 7932        let text_layout_details = &self.text_layout_details(cx);
 7933        self.change_selections(Some(autoscroll), cx, |s| {
 7934            let line_mode = s.line_mode;
 7935            s.move_with(|map, selection| {
 7936                if !selection.is_empty() && !line_mode {
 7937                    selection.goal = SelectionGoal::None;
 7938                }
 7939                let (cursor, goal) = movement::down_by_rows(
 7940                    map,
 7941                    selection.end,
 7942                    row_count,
 7943                    selection.goal,
 7944                    false,
 7945                    text_layout_details,
 7946                );
 7947                selection.collapse_to(cursor, goal);
 7948            });
 7949        });
 7950    }
 7951
 7952    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 7953        let text_layout_details = &self.text_layout_details(cx);
 7954        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7955            s.move_heads_with(|map, head, goal| {
 7956                movement::down(map, head, goal, false, text_layout_details)
 7957            })
 7958        });
 7959    }
 7960
 7961    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 7962        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7963            context_menu.select_first(self.completion_provider.as_deref(), cx);
 7964        }
 7965    }
 7966
 7967    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 7968        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7969            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 7970        }
 7971    }
 7972
 7973    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7974        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7975            context_menu.select_next(self.completion_provider.as_deref(), cx);
 7976        }
 7977    }
 7978
 7979    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 7980        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7981            context_menu.select_last(self.completion_provider.as_deref(), cx);
 7982        }
 7983    }
 7984
 7985    pub fn move_to_previous_word_start(
 7986        &mut self,
 7987        _: &MoveToPreviousWordStart,
 7988        cx: &mut ViewContext<Self>,
 7989    ) {
 7990        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7991            s.move_cursors_with(|map, head, _| {
 7992                (
 7993                    movement::previous_word_start(map, head),
 7994                    SelectionGoal::None,
 7995                )
 7996            });
 7997        })
 7998    }
 7999
 8000    pub fn move_to_previous_subword_start(
 8001        &mut self,
 8002        _: &MoveToPreviousSubwordStart,
 8003        cx: &mut ViewContext<Self>,
 8004    ) {
 8005        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8006            s.move_cursors_with(|map, head, _| {
 8007                (
 8008                    movement::previous_subword_start(map, head),
 8009                    SelectionGoal::None,
 8010                )
 8011            });
 8012        })
 8013    }
 8014
 8015    pub fn select_to_previous_word_start(
 8016        &mut self,
 8017        _: &SelectToPreviousWordStart,
 8018        cx: &mut ViewContext<Self>,
 8019    ) {
 8020        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8021            s.move_heads_with(|map, head, _| {
 8022                (
 8023                    movement::previous_word_start(map, head),
 8024                    SelectionGoal::None,
 8025                )
 8026            });
 8027        })
 8028    }
 8029
 8030    pub fn select_to_previous_subword_start(
 8031        &mut self,
 8032        _: &SelectToPreviousSubwordStart,
 8033        cx: &mut ViewContext<Self>,
 8034    ) {
 8035        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8036            s.move_heads_with(|map, head, _| {
 8037                (
 8038                    movement::previous_subword_start(map, head),
 8039                    SelectionGoal::None,
 8040                )
 8041            });
 8042        })
 8043    }
 8044
 8045    pub fn delete_to_previous_word_start(
 8046        &mut self,
 8047        action: &DeleteToPreviousWordStart,
 8048        cx: &mut ViewContext<Self>,
 8049    ) {
 8050        self.transact(cx, |this, cx| {
 8051            this.select_autoclose_pair(cx);
 8052            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8053                let line_mode = s.line_mode;
 8054                s.move_with(|map, selection| {
 8055                    if selection.is_empty() && !line_mode {
 8056                        let cursor = if action.ignore_newlines {
 8057                            movement::previous_word_start(map, selection.head())
 8058                        } else {
 8059                            movement::previous_word_start_or_newline(map, selection.head())
 8060                        };
 8061                        selection.set_head(cursor, SelectionGoal::None);
 8062                    }
 8063                });
 8064            });
 8065            this.insert("", cx);
 8066        });
 8067    }
 8068
 8069    pub fn delete_to_previous_subword_start(
 8070        &mut self,
 8071        _: &DeleteToPreviousSubwordStart,
 8072        cx: &mut ViewContext<Self>,
 8073    ) {
 8074        self.transact(cx, |this, cx| {
 8075            this.select_autoclose_pair(cx);
 8076            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8077                let line_mode = s.line_mode;
 8078                s.move_with(|map, selection| {
 8079                    if selection.is_empty() && !line_mode {
 8080                        let cursor = movement::previous_subword_start(map, selection.head());
 8081                        selection.set_head(cursor, SelectionGoal::None);
 8082                    }
 8083                });
 8084            });
 8085            this.insert("", cx);
 8086        });
 8087    }
 8088
 8089    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 8090        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8091            s.move_cursors_with(|map, head, _| {
 8092                (movement::next_word_end(map, head), SelectionGoal::None)
 8093            });
 8094        })
 8095    }
 8096
 8097    pub fn move_to_next_subword_end(
 8098        &mut self,
 8099        _: &MoveToNextSubwordEnd,
 8100        cx: &mut ViewContext<Self>,
 8101    ) {
 8102        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8103            s.move_cursors_with(|map, head, _| {
 8104                (movement::next_subword_end(map, head), SelectionGoal::None)
 8105            });
 8106        })
 8107    }
 8108
 8109    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 8110        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8111            s.move_heads_with(|map, head, _| {
 8112                (movement::next_word_end(map, head), SelectionGoal::None)
 8113            });
 8114        })
 8115    }
 8116
 8117    pub fn select_to_next_subword_end(
 8118        &mut self,
 8119        _: &SelectToNextSubwordEnd,
 8120        cx: &mut ViewContext<Self>,
 8121    ) {
 8122        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8123            s.move_heads_with(|map, head, _| {
 8124                (movement::next_subword_end(map, head), SelectionGoal::None)
 8125            });
 8126        })
 8127    }
 8128
 8129    pub fn delete_to_next_word_end(
 8130        &mut self,
 8131        action: &DeleteToNextWordEnd,
 8132        cx: &mut ViewContext<Self>,
 8133    ) {
 8134        self.transact(cx, |this, cx| {
 8135            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8136                let line_mode = s.line_mode;
 8137                s.move_with(|map, selection| {
 8138                    if selection.is_empty() && !line_mode {
 8139                        let cursor = if action.ignore_newlines {
 8140                            movement::next_word_end(map, selection.head())
 8141                        } else {
 8142                            movement::next_word_end_or_newline(map, selection.head())
 8143                        };
 8144                        selection.set_head(cursor, SelectionGoal::None);
 8145                    }
 8146                });
 8147            });
 8148            this.insert("", cx);
 8149        });
 8150    }
 8151
 8152    pub fn delete_to_next_subword_end(
 8153        &mut self,
 8154        _: &DeleteToNextSubwordEnd,
 8155        cx: &mut ViewContext<Self>,
 8156    ) {
 8157        self.transact(cx, |this, cx| {
 8158            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8159                s.move_with(|map, selection| {
 8160                    if selection.is_empty() {
 8161                        let cursor = movement::next_subword_end(map, selection.head());
 8162                        selection.set_head(cursor, SelectionGoal::None);
 8163                    }
 8164                });
 8165            });
 8166            this.insert("", cx);
 8167        });
 8168    }
 8169
 8170    pub fn move_to_beginning_of_line(
 8171        &mut self,
 8172        action: &MoveToBeginningOfLine,
 8173        cx: &mut ViewContext<Self>,
 8174    ) {
 8175        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8176            s.move_cursors_with(|map, head, _| {
 8177                (
 8178                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8179                    SelectionGoal::None,
 8180                )
 8181            });
 8182        })
 8183    }
 8184
 8185    pub fn select_to_beginning_of_line(
 8186        &mut self,
 8187        action: &SelectToBeginningOfLine,
 8188        cx: &mut ViewContext<Self>,
 8189    ) {
 8190        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8191            s.move_heads_with(|map, head, _| {
 8192                (
 8193                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8194                    SelectionGoal::None,
 8195                )
 8196            });
 8197        });
 8198    }
 8199
 8200    pub fn delete_to_beginning_of_line(
 8201        &mut self,
 8202        _: &DeleteToBeginningOfLine,
 8203        cx: &mut ViewContext<Self>,
 8204    ) {
 8205        self.transact(cx, |this, cx| {
 8206            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8207                s.move_with(|_, selection| {
 8208                    selection.reversed = true;
 8209                });
 8210            });
 8211
 8212            this.select_to_beginning_of_line(
 8213                &SelectToBeginningOfLine {
 8214                    stop_at_soft_wraps: false,
 8215                },
 8216                cx,
 8217            );
 8218            this.backspace(&Backspace, cx);
 8219        });
 8220    }
 8221
 8222    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 8223        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8224            s.move_cursors_with(|map, head, _| {
 8225                (
 8226                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8227                    SelectionGoal::None,
 8228                )
 8229            });
 8230        })
 8231    }
 8232
 8233    pub fn select_to_end_of_line(
 8234        &mut self,
 8235        action: &SelectToEndOfLine,
 8236        cx: &mut ViewContext<Self>,
 8237    ) {
 8238        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8239            s.move_heads_with(|map, head, _| {
 8240                (
 8241                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8242                    SelectionGoal::None,
 8243                )
 8244            });
 8245        })
 8246    }
 8247
 8248    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 8249        self.transact(cx, |this, cx| {
 8250            this.select_to_end_of_line(
 8251                &SelectToEndOfLine {
 8252                    stop_at_soft_wraps: false,
 8253                },
 8254                cx,
 8255            );
 8256            this.delete(&Delete, cx);
 8257        });
 8258    }
 8259
 8260    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 8261        self.transact(cx, |this, cx| {
 8262            this.select_to_end_of_line(
 8263                &SelectToEndOfLine {
 8264                    stop_at_soft_wraps: false,
 8265                },
 8266                cx,
 8267            );
 8268            this.cut(&Cut, cx);
 8269        });
 8270    }
 8271
 8272    pub fn move_to_start_of_paragraph(
 8273        &mut self,
 8274        _: &MoveToStartOfParagraph,
 8275        cx: &mut ViewContext<Self>,
 8276    ) {
 8277        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8278            cx.propagate();
 8279            return;
 8280        }
 8281
 8282        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8283            s.move_with(|map, selection| {
 8284                selection.collapse_to(
 8285                    movement::start_of_paragraph(map, selection.head(), 1),
 8286                    SelectionGoal::None,
 8287                )
 8288            });
 8289        })
 8290    }
 8291
 8292    pub fn move_to_end_of_paragraph(
 8293        &mut self,
 8294        _: &MoveToEndOfParagraph,
 8295        cx: &mut ViewContext<Self>,
 8296    ) {
 8297        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8298            cx.propagate();
 8299            return;
 8300        }
 8301
 8302        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8303            s.move_with(|map, selection| {
 8304                selection.collapse_to(
 8305                    movement::end_of_paragraph(map, selection.head(), 1),
 8306                    SelectionGoal::None,
 8307                )
 8308            });
 8309        })
 8310    }
 8311
 8312    pub fn select_to_start_of_paragraph(
 8313        &mut self,
 8314        _: &SelectToStartOfParagraph,
 8315        cx: &mut ViewContext<Self>,
 8316    ) {
 8317        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8318            cx.propagate();
 8319            return;
 8320        }
 8321
 8322        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8323            s.move_heads_with(|map, head, _| {
 8324                (
 8325                    movement::start_of_paragraph(map, head, 1),
 8326                    SelectionGoal::None,
 8327                )
 8328            });
 8329        })
 8330    }
 8331
 8332    pub fn select_to_end_of_paragraph(
 8333        &mut self,
 8334        _: &SelectToEndOfParagraph,
 8335        cx: &mut ViewContext<Self>,
 8336    ) {
 8337        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8338            cx.propagate();
 8339            return;
 8340        }
 8341
 8342        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8343            s.move_heads_with(|map, head, _| {
 8344                (
 8345                    movement::end_of_paragraph(map, head, 1),
 8346                    SelectionGoal::None,
 8347                )
 8348            });
 8349        })
 8350    }
 8351
 8352    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 8353        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8354            cx.propagate();
 8355            return;
 8356        }
 8357
 8358        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8359            s.select_ranges(vec![0..0]);
 8360        });
 8361    }
 8362
 8363    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 8364        let mut selection = self.selections.last::<Point>(cx);
 8365        selection.set_head(Point::zero(), SelectionGoal::None);
 8366
 8367        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8368            s.select(vec![selection]);
 8369        });
 8370    }
 8371
 8372    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 8373        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8374            cx.propagate();
 8375            return;
 8376        }
 8377
 8378        let cursor = self.buffer.read(cx).read(cx).len();
 8379        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8380            s.select_ranges(vec![cursor..cursor])
 8381        });
 8382    }
 8383
 8384    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 8385        self.nav_history = nav_history;
 8386    }
 8387
 8388    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 8389        self.nav_history.as_ref()
 8390    }
 8391
 8392    fn push_to_nav_history(
 8393        &mut self,
 8394        cursor_anchor: Anchor,
 8395        new_position: Option<Point>,
 8396        cx: &mut ViewContext<Self>,
 8397    ) {
 8398        if let Some(nav_history) = self.nav_history.as_mut() {
 8399            let buffer = self.buffer.read(cx).read(cx);
 8400            let cursor_position = cursor_anchor.to_point(&buffer);
 8401            let scroll_state = self.scroll_manager.anchor();
 8402            let scroll_top_row = scroll_state.top_row(&buffer);
 8403            drop(buffer);
 8404
 8405            if let Some(new_position) = new_position {
 8406                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 8407                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 8408                    return;
 8409                }
 8410            }
 8411
 8412            nav_history.push(
 8413                Some(NavigationData {
 8414                    cursor_anchor,
 8415                    cursor_position,
 8416                    scroll_anchor: scroll_state,
 8417                    scroll_top_row,
 8418                }),
 8419                cx,
 8420            );
 8421        }
 8422    }
 8423
 8424    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 8425        let buffer = self.buffer.read(cx).snapshot(cx);
 8426        let mut selection = self.selections.first::<usize>(cx);
 8427        selection.set_head(buffer.len(), SelectionGoal::None);
 8428        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8429            s.select(vec![selection]);
 8430        });
 8431    }
 8432
 8433    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 8434        let end = self.buffer.read(cx).read(cx).len();
 8435        self.change_selections(None, cx, |s| {
 8436            s.select_ranges(vec![0..end]);
 8437        });
 8438    }
 8439
 8440    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 8441        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8442        let mut selections = self.selections.all::<Point>(cx);
 8443        let max_point = display_map.buffer_snapshot.max_point();
 8444        for selection in &mut selections {
 8445            let rows = selection.spanned_rows(true, &display_map);
 8446            selection.start = Point::new(rows.start.0, 0);
 8447            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 8448            selection.reversed = false;
 8449        }
 8450        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8451            s.select(selections);
 8452        });
 8453    }
 8454
 8455    pub fn split_selection_into_lines(
 8456        &mut self,
 8457        _: &SplitSelectionIntoLines,
 8458        cx: &mut ViewContext<Self>,
 8459    ) {
 8460        let mut to_unfold = Vec::new();
 8461        let mut new_selection_ranges = Vec::new();
 8462        {
 8463            let selections = self.selections.all::<Point>(cx);
 8464            let buffer = self.buffer.read(cx).read(cx);
 8465            for selection in selections {
 8466                for row in selection.start.row..selection.end.row {
 8467                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 8468                    new_selection_ranges.push(cursor..cursor);
 8469                }
 8470                new_selection_ranges.push(selection.end..selection.end);
 8471                to_unfold.push(selection.start..selection.end);
 8472            }
 8473        }
 8474        self.unfold_ranges(&to_unfold, true, true, cx);
 8475        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8476            s.select_ranges(new_selection_ranges);
 8477        });
 8478    }
 8479
 8480    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 8481        self.add_selection(true, cx);
 8482    }
 8483
 8484    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 8485        self.add_selection(false, cx);
 8486    }
 8487
 8488    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 8489        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8490        let mut selections = self.selections.all::<Point>(cx);
 8491        let text_layout_details = self.text_layout_details(cx);
 8492        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 8493            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 8494            let range = oldest_selection.display_range(&display_map).sorted();
 8495
 8496            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 8497            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 8498            let positions = start_x.min(end_x)..start_x.max(end_x);
 8499
 8500            selections.clear();
 8501            let mut stack = Vec::new();
 8502            for row in range.start.row().0..=range.end.row().0 {
 8503                if let Some(selection) = self.selections.build_columnar_selection(
 8504                    &display_map,
 8505                    DisplayRow(row),
 8506                    &positions,
 8507                    oldest_selection.reversed,
 8508                    &text_layout_details,
 8509                ) {
 8510                    stack.push(selection.id);
 8511                    selections.push(selection);
 8512                }
 8513            }
 8514
 8515            if above {
 8516                stack.reverse();
 8517            }
 8518
 8519            AddSelectionsState { above, stack }
 8520        });
 8521
 8522        let last_added_selection = *state.stack.last().unwrap();
 8523        let mut new_selections = Vec::new();
 8524        if above == state.above {
 8525            let end_row = if above {
 8526                DisplayRow(0)
 8527            } else {
 8528                display_map.max_point().row()
 8529            };
 8530
 8531            'outer: for selection in selections {
 8532                if selection.id == last_added_selection {
 8533                    let range = selection.display_range(&display_map).sorted();
 8534                    debug_assert_eq!(range.start.row(), range.end.row());
 8535                    let mut row = range.start.row();
 8536                    let positions =
 8537                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 8538                            px(start)..px(end)
 8539                        } else {
 8540                            let start_x =
 8541                                display_map.x_for_display_point(range.start, &text_layout_details);
 8542                            let end_x =
 8543                                display_map.x_for_display_point(range.end, &text_layout_details);
 8544                            start_x.min(end_x)..start_x.max(end_x)
 8545                        };
 8546
 8547                    while row != end_row {
 8548                        if above {
 8549                            row.0 -= 1;
 8550                        } else {
 8551                            row.0 += 1;
 8552                        }
 8553
 8554                        if let Some(new_selection) = self.selections.build_columnar_selection(
 8555                            &display_map,
 8556                            row,
 8557                            &positions,
 8558                            selection.reversed,
 8559                            &text_layout_details,
 8560                        ) {
 8561                            state.stack.push(new_selection.id);
 8562                            if above {
 8563                                new_selections.push(new_selection);
 8564                                new_selections.push(selection);
 8565                            } else {
 8566                                new_selections.push(selection);
 8567                                new_selections.push(new_selection);
 8568                            }
 8569
 8570                            continue 'outer;
 8571                        }
 8572                    }
 8573                }
 8574
 8575                new_selections.push(selection);
 8576            }
 8577        } else {
 8578            new_selections = selections;
 8579            new_selections.retain(|s| s.id != last_added_selection);
 8580            state.stack.pop();
 8581        }
 8582
 8583        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8584            s.select(new_selections);
 8585        });
 8586        if state.stack.len() > 1 {
 8587            self.add_selections_state = Some(state);
 8588        }
 8589    }
 8590
 8591    pub fn select_next_match_internal(
 8592        &mut self,
 8593        display_map: &DisplaySnapshot,
 8594        replace_newest: bool,
 8595        autoscroll: Option<Autoscroll>,
 8596        cx: &mut ViewContext<Self>,
 8597    ) -> Result<()> {
 8598        fn select_next_match_ranges(
 8599            this: &mut Editor,
 8600            range: Range<usize>,
 8601            replace_newest: bool,
 8602            auto_scroll: Option<Autoscroll>,
 8603            cx: &mut ViewContext<Editor>,
 8604        ) {
 8605            this.unfold_ranges(&[range.clone()], false, true, cx);
 8606            this.change_selections(auto_scroll, cx, |s| {
 8607                if replace_newest {
 8608                    s.delete(s.newest_anchor().id);
 8609                }
 8610                s.insert_range(range.clone());
 8611            });
 8612        }
 8613
 8614        let buffer = &display_map.buffer_snapshot;
 8615        let mut selections = self.selections.all::<usize>(cx);
 8616        if let Some(mut select_next_state) = self.select_next_state.take() {
 8617            let query = &select_next_state.query;
 8618            if !select_next_state.done {
 8619                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8620                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8621                let mut next_selected_range = None;
 8622
 8623                let bytes_after_last_selection =
 8624                    buffer.bytes_in_range(last_selection.end..buffer.len());
 8625                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 8626                let query_matches = query
 8627                    .stream_find_iter(bytes_after_last_selection)
 8628                    .map(|result| (last_selection.end, result))
 8629                    .chain(
 8630                        query
 8631                            .stream_find_iter(bytes_before_first_selection)
 8632                            .map(|result| (0, result)),
 8633                    );
 8634
 8635                for (start_offset, query_match) in query_matches {
 8636                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8637                    let offset_range =
 8638                        start_offset + query_match.start()..start_offset + query_match.end();
 8639                    let display_range = offset_range.start.to_display_point(display_map)
 8640                        ..offset_range.end.to_display_point(display_map);
 8641
 8642                    if !select_next_state.wordwise
 8643                        || (!movement::is_inside_word(display_map, display_range.start)
 8644                            && !movement::is_inside_word(display_map, display_range.end))
 8645                    {
 8646                        // TODO: This is n^2, because we might check all the selections
 8647                        if !selections
 8648                            .iter()
 8649                            .any(|selection| selection.range().overlaps(&offset_range))
 8650                        {
 8651                            next_selected_range = Some(offset_range);
 8652                            break;
 8653                        }
 8654                    }
 8655                }
 8656
 8657                if let Some(next_selected_range) = next_selected_range {
 8658                    select_next_match_ranges(
 8659                        self,
 8660                        next_selected_range,
 8661                        replace_newest,
 8662                        autoscroll,
 8663                        cx,
 8664                    );
 8665                } else {
 8666                    select_next_state.done = true;
 8667                }
 8668            }
 8669
 8670            self.select_next_state = Some(select_next_state);
 8671        } else {
 8672            let mut only_carets = true;
 8673            let mut same_text_selected = true;
 8674            let mut selected_text = None;
 8675
 8676            let mut selections_iter = selections.iter().peekable();
 8677            while let Some(selection) = selections_iter.next() {
 8678                if selection.start != selection.end {
 8679                    only_carets = false;
 8680                }
 8681
 8682                if same_text_selected {
 8683                    if selected_text.is_none() {
 8684                        selected_text =
 8685                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8686                    }
 8687
 8688                    if let Some(next_selection) = selections_iter.peek() {
 8689                        if next_selection.range().len() == selection.range().len() {
 8690                            let next_selected_text = buffer
 8691                                .text_for_range(next_selection.range())
 8692                                .collect::<String>();
 8693                            if Some(next_selected_text) != selected_text {
 8694                                same_text_selected = false;
 8695                                selected_text = None;
 8696                            }
 8697                        } else {
 8698                            same_text_selected = false;
 8699                            selected_text = None;
 8700                        }
 8701                    }
 8702                }
 8703            }
 8704
 8705            if only_carets {
 8706                for selection in &mut selections {
 8707                    let word_range = movement::surrounding_word(
 8708                        display_map,
 8709                        selection.start.to_display_point(display_map),
 8710                    );
 8711                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 8712                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 8713                    selection.goal = SelectionGoal::None;
 8714                    selection.reversed = false;
 8715                    select_next_match_ranges(
 8716                        self,
 8717                        selection.start..selection.end,
 8718                        replace_newest,
 8719                        autoscroll,
 8720                        cx,
 8721                    );
 8722                }
 8723
 8724                if selections.len() == 1 {
 8725                    let selection = selections
 8726                        .last()
 8727                        .expect("ensured that there's only one selection");
 8728                    let query = buffer
 8729                        .text_for_range(selection.start..selection.end)
 8730                        .collect::<String>();
 8731                    let is_empty = query.is_empty();
 8732                    let select_state = SelectNextState {
 8733                        query: AhoCorasick::new(&[query])?,
 8734                        wordwise: true,
 8735                        done: is_empty,
 8736                    };
 8737                    self.select_next_state = Some(select_state);
 8738                } else {
 8739                    self.select_next_state = None;
 8740                }
 8741            } else if let Some(selected_text) = selected_text {
 8742                self.select_next_state = Some(SelectNextState {
 8743                    query: AhoCorasick::new(&[selected_text])?,
 8744                    wordwise: false,
 8745                    done: false,
 8746                });
 8747                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 8748            }
 8749        }
 8750        Ok(())
 8751    }
 8752
 8753    pub fn select_all_matches(
 8754        &mut self,
 8755        _action: &SelectAllMatches,
 8756        cx: &mut ViewContext<Self>,
 8757    ) -> Result<()> {
 8758        self.push_to_selection_history();
 8759        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8760
 8761        self.select_next_match_internal(&display_map, false, None, cx)?;
 8762        let Some(select_next_state) = self.select_next_state.as_mut() else {
 8763            return Ok(());
 8764        };
 8765        if select_next_state.done {
 8766            return Ok(());
 8767        }
 8768
 8769        let mut new_selections = self.selections.all::<usize>(cx);
 8770
 8771        let buffer = &display_map.buffer_snapshot;
 8772        let query_matches = select_next_state
 8773            .query
 8774            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 8775
 8776        for query_match in query_matches {
 8777            let query_match = query_match.unwrap(); // can only fail due to I/O
 8778            let offset_range = query_match.start()..query_match.end();
 8779            let display_range = offset_range.start.to_display_point(&display_map)
 8780                ..offset_range.end.to_display_point(&display_map);
 8781
 8782            if !select_next_state.wordwise
 8783                || (!movement::is_inside_word(&display_map, display_range.start)
 8784                    && !movement::is_inside_word(&display_map, display_range.end))
 8785            {
 8786                self.selections.change_with(cx, |selections| {
 8787                    new_selections.push(Selection {
 8788                        id: selections.new_selection_id(),
 8789                        start: offset_range.start,
 8790                        end: offset_range.end,
 8791                        reversed: false,
 8792                        goal: SelectionGoal::None,
 8793                    });
 8794                });
 8795            }
 8796        }
 8797
 8798        new_selections.sort_by_key(|selection| selection.start);
 8799        let mut ix = 0;
 8800        while ix + 1 < new_selections.len() {
 8801            let current_selection = &new_selections[ix];
 8802            let next_selection = &new_selections[ix + 1];
 8803            if current_selection.range().overlaps(&next_selection.range()) {
 8804                if current_selection.id < next_selection.id {
 8805                    new_selections.remove(ix + 1);
 8806                } else {
 8807                    new_selections.remove(ix);
 8808                }
 8809            } else {
 8810                ix += 1;
 8811            }
 8812        }
 8813
 8814        select_next_state.done = true;
 8815        self.unfold_ranges(
 8816            &new_selections
 8817                .iter()
 8818                .map(|selection| selection.range())
 8819                .collect::<Vec<_>>(),
 8820            false,
 8821            false,
 8822            cx,
 8823        );
 8824        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 8825            selections.select(new_selections)
 8826        });
 8827
 8828        Ok(())
 8829    }
 8830
 8831    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 8832        self.push_to_selection_history();
 8833        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8834        self.select_next_match_internal(
 8835            &display_map,
 8836            action.replace_newest,
 8837            Some(Autoscroll::newest()),
 8838            cx,
 8839        )?;
 8840        Ok(())
 8841    }
 8842
 8843    pub fn select_previous(
 8844        &mut self,
 8845        action: &SelectPrevious,
 8846        cx: &mut ViewContext<Self>,
 8847    ) -> Result<()> {
 8848        self.push_to_selection_history();
 8849        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8850        let buffer = &display_map.buffer_snapshot;
 8851        let mut selections = self.selections.all::<usize>(cx);
 8852        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8853            let query = &select_prev_state.query;
 8854            if !select_prev_state.done {
 8855                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8856                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8857                let mut next_selected_range = None;
 8858                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8859                let bytes_before_last_selection =
 8860                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8861                let bytes_after_first_selection =
 8862                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8863                let query_matches = query
 8864                    .stream_find_iter(bytes_before_last_selection)
 8865                    .map(|result| (last_selection.start, result))
 8866                    .chain(
 8867                        query
 8868                            .stream_find_iter(bytes_after_first_selection)
 8869                            .map(|result| (buffer.len(), result)),
 8870                    );
 8871                for (end_offset, query_match) in query_matches {
 8872                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8873                    let offset_range =
 8874                        end_offset - query_match.end()..end_offset - query_match.start();
 8875                    let display_range = offset_range.start.to_display_point(&display_map)
 8876                        ..offset_range.end.to_display_point(&display_map);
 8877
 8878                    if !select_prev_state.wordwise
 8879                        || (!movement::is_inside_word(&display_map, display_range.start)
 8880                            && !movement::is_inside_word(&display_map, display_range.end))
 8881                    {
 8882                        next_selected_range = Some(offset_range);
 8883                        break;
 8884                    }
 8885                }
 8886
 8887                if let Some(next_selected_range) = next_selected_range {
 8888                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 8889                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8890                        if action.replace_newest {
 8891                            s.delete(s.newest_anchor().id);
 8892                        }
 8893                        s.insert_range(next_selected_range);
 8894                    });
 8895                } else {
 8896                    select_prev_state.done = true;
 8897                }
 8898            }
 8899
 8900            self.select_prev_state = Some(select_prev_state);
 8901        } else {
 8902            let mut only_carets = true;
 8903            let mut same_text_selected = true;
 8904            let mut selected_text = None;
 8905
 8906            let mut selections_iter = selections.iter().peekable();
 8907            while let Some(selection) = selections_iter.next() {
 8908                if selection.start != selection.end {
 8909                    only_carets = false;
 8910                }
 8911
 8912                if same_text_selected {
 8913                    if selected_text.is_none() {
 8914                        selected_text =
 8915                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8916                    }
 8917
 8918                    if let Some(next_selection) = selections_iter.peek() {
 8919                        if next_selection.range().len() == selection.range().len() {
 8920                            let next_selected_text = buffer
 8921                                .text_for_range(next_selection.range())
 8922                                .collect::<String>();
 8923                            if Some(next_selected_text) != selected_text {
 8924                                same_text_selected = false;
 8925                                selected_text = None;
 8926                            }
 8927                        } else {
 8928                            same_text_selected = false;
 8929                            selected_text = None;
 8930                        }
 8931                    }
 8932                }
 8933            }
 8934
 8935            if only_carets {
 8936                for selection in &mut selections {
 8937                    let word_range = movement::surrounding_word(
 8938                        &display_map,
 8939                        selection.start.to_display_point(&display_map),
 8940                    );
 8941                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8942                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8943                    selection.goal = SelectionGoal::None;
 8944                    selection.reversed = false;
 8945                }
 8946                if selections.len() == 1 {
 8947                    let selection = selections
 8948                        .last()
 8949                        .expect("ensured that there's only one selection");
 8950                    let query = buffer
 8951                        .text_for_range(selection.start..selection.end)
 8952                        .collect::<String>();
 8953                    let is_empty = query.is_empty();
 8954                    let select_state = SelectNextState {
 8955                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8956                        wordwise: true,
 8957                        done: is_empty,
 8958                    };
 8959                    self.select_prev_state = Some(select_state);
 8960                } else {
 8961                    self.select_prev_state = None;
 8962                }
 8963
 8964                self.unfold_ranges(
 8965                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8966                    false,
 8967                    true,
 8968                    cx,
 8969                );
 8970                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8971                    s.select(selections);
 8972                });
 8973            } else if let Some(selected_text) = selected_text {
 8974                self.select_prev_state = Some(SelectNextState {
 8975                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8976                    wordwise: false,
 8977                    done: false,
 8978                });
 8979                self.select_previous(action, cx)?;
 8980            }
 8981        }
 8982        Ok(())
 8983    }
 8984
 8985    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 8986        if self.read_only(cx) {
 8987            return;
 8988        }
 8989        let text_layout_details = &self.text_layout_details(cx);
 8990        self.transact(cx, |this, cx| {
 8991            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8992            let mut edits = Vec::new();
 8993            let mut selection_edit_ranges = Vec::new();
 8994            let mut last_toggled_row = None;
 8995            let snapshot = this.buffer.read(cx).read(cx);
 8996            let empty_str: Arc<str> = Arc::default();
 8997            let mut suffixes_inserted = Vec::new();
 8998            let ignore_indent = action.ignore_indent;
 8999
 9000            fn comment_prefix_range(
 9001                snapshot: &MultiBufferSnapshot,
 9002                row: MultiBufferRow,
 9003                comment_prefix: &str,
 9004                comment_prefix_whitespace: &str,
 9005                ignore_indent: bool,
 9006            ) -> Range<Point> {
 9007                let indent_size = if ignore_indent {
 9008                    0
 9009                } else {
 9010                    snapshot.indent_size_for_line(row).len
 9011                };
 9012
 9013                let start = Point::new(row.0, indent_size);
 9014
 9015                let mut line_bytes = snapshot
 9016                    .bytes_in_range(start..snapshot.max_point())
 9017                    .flatten()
 9018                    .copied();
 9019
 9020                // If this line currently begins with the line comment prefix, then record
 9021                // the range containing the prefix.
 9022                if line_bytes
 9023                    .by_ref()
 9024                    .take(comment_prefix.len())
 9025                    .eq(comment_prefix.bytes())
 9026                {
 9027                    // Include any whitespace that matches the comment prefix.
 9028                    let matching_whitespace_len = line_bytes
 9029                        .zip(comment_prefix_whitespace.bytes())
 9030                        .take_while(|(a, b)| a == b)
 9031                        .count() as u32;
 9032                    let end = Point::new(
 9033                        start.row,
 9034                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 9035                    );
 9036                    start..end
 9037                } else {
 9038                    start..start
 9039                }
 9040            }
 9041
 9042            fn comment_suffix_range(
 9043                snapshot: &MultiBufferSnapshot,
 9044                row: MultiBufferRow,
 9045                comment_suffix: &str,
 9046                comment_suffix_has_leading_space: bool,
 9047            ) -> Range<Point> {
 9048                let end = Point::new(row.0, snapshot.line_len(row));
 9049                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 9050
 9051                let mut line_end_bytes = snapshot
 9052                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 9053                    .flatten()
 9054                    .copied();
 9055
 9056                let leading_space_len = if suffix_start_column > 0
 9057                    && line_end_bytes.next() == Some(b' ')
 9058                    && comment_suffix_has_leading_space
 9059                {
 9060                    1
 9061                } else {
 9062                    0
 9063                };
 9064
 9065                // If this line currently begins with the line comment prefix, then record
 9066                // the range containing the prefix.
 9067                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 9068                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 9069                    start..end
 9070                } else {
 9071                    end..end
 9072                }
 9073            }
 9074
 9075            // TODO: Handle selections that cross excerpts
 9076            for selection in &mut selections {
 9077                let start_column = snapshot
 9078                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 9079                    .len;
 9080                let language = if let Some(language) =
 9081                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 9082                {
 9083                    language
 9084                } else {
 9085                    continue;
 9086                };
 9087
 9088                selection_edit_ranges.clear();
 9089
 9090                // If multiple selections contain a given row, avoid processing that
 9091                // row more than once.
 9092                let mut start_row = MultiBufferRow(selection.start.row);
 9093                if last_toggled_row == Some(start_row) {
 9094                    start_row = start_row.next_row();
 9095                }
 9096                let end_row =
 9097                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 9098                        MultiBufferRow(selection.end.row - 1)
 9099                    } else {
 9100                        MultiBufferRow(selection.end.row)
 9101                    };
 9102                last_toggled_row = Some(end_row);
 9103
 9104                if start_row > end_row {
 9105                    continue;
 9106                }
 9107
 9108                // If the language has line comments, toggle those.
 9109                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 9110
 9111                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 9112                if ignore_indent {
 9113                    full_comment_prefixes = full_comment_prefixes
 9114                        .into_iter()
 9115                        .map(|s| Arc::from(s.trim_end()))
 9116                        .collect();
 9117                }
 9118
 9119                if !full_comment_prefixes.is_empty() {
 9120                    let first_prefix = full_comment_prefixes
 9121                        .first()
 9122                        .expect("prefixes is non-empty");
 9123                    let prefix_trimmed_lengths = full_comment_prefixes
 9124                        .iter()
 9125                        .map(|p| p.trim_end_matches(' ').len())
 9126                        .collect::<SmallVec<[usize; 4]>>();
 9127
 9128                    let mut all_selection_lines_are_comments = true;
 9129
 9130                    for row in start_row.0..=end_row.0 {
 9131                        let row = MultiBufferRow(row);
 9132                        if start_row < end_row && snapshot.is_line_blank(row) {
 9133                            continue;
 9134                        }
 9135
 9136                        let prefix_range = full_comment_prefixes
 9137                            .iter()
 9138                            .zip(prefix_trimmed_lengths.iter().copied())
 9139                            .map(|(prefix, trimmed_prefix_len)| {
 9140                                comment_prefix_range(
 9141                                    snapshot.deref(),
 9142                                    row,
 9143                                    &prefix[..trimmed_prefix_len],
 9144                                    &prefix[trimmed_prefix_len..],
 9145                                    ignore_indent,
 9146                                )
 9147                            })
 9148                            .max_by_key(|range| range.end.column - range.start.column)
 9149                            .expect("prefixes is non-empty");
 9150
 9151                        if prefix_range.is_empty() {
 9152                            all_selection_lines_are_comments = false;
 9153                        }
 9154
 9155                        selection_edit_ranges.push(prefix_range);
 9156                    }
 9157
 9158                    if all_selection_lines_are_comments {
 9159                        edits.extend(
 9160                            selection_edit_ranges
 9161                                .iter()
 9162                                .cloned()
 9163                                .map(|range| (range, empty_str.clone())),
 9164                        );
 9165                    } else {
 9166                        let min_column = selection_edit_ranges
 9167                            .iter()
 9168                            .map(|range| range.start.column)
 9169                            .min()
 9170                            .unwrap_or(0);
 9171                        edits.extend(selection_edit_ranges.iter().map(|range| {
 9172                            let position = Point::new(range.start.row, min_column);
 9173                            (position..position, first_prefix.clone())
 9174                        }));
 9175                    }
 9176                } else if let Some((full_comment_prefix, comment_suffix)) =
 9177                    language.block_comment_delimiters()
 9178                {
 9179                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 9180                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 9181                    let prefix_range = comment_prefix_range(
 9182                        snapshot.deref(),
 9183                        start_row,
 9184                        comment_prefix,
 9185                        comment_prefix_whitespace,
 9186                        ignore_indent,
 9187                    );
 9188                    let suffix_range = comment_suffix_range(
 9189                        snapshot.deref(),
 9190                        end_row,
 9191                        comment_suffix.trim_start_matches(' '),
 9192                        comment_suffix.starts_with(' '),
 9193                    );
 9194
 9195                    if prefix_range.is_empty() || suffix_range.is_empty() {
 9196                        edits.push((
 9197                            prefix_range.start..prefix_range.start,
 9198                            full_comment_prefix.clone(),
 9199                        ));
 9200                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 9201                        suffixes_inserted.push((end_row, comment_suffix.len()));
 9202                    } else {
 9203                        edits.push((prefix_range, empty_str.clone()));
 9204                        edits.push((suffix_range, empty_str.clone()));
 9205                    }
 9206                } else {
 9207                    continue;
 9208                }
 9209            }
 9210
 9211            drop(snapshot);
 9212            this.buffer.update(cx, |buffer, cx| {
 9213                buffer.edit(edits, None, cx);
 9214            });
 9215
 9216            // Adjust selections so that they end before any comment suffixes that
 9217            // were inserted.
 9218            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 9219            let mut selections = this.selections.all::<Point>(cx);
 9220            let snapshot = this.buffer.read(cx).read(cx);
 9221            for selection in &mut selections {
 9222                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 9223                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 9224                        Ordering::Less => {
 9225                            suffixes_inserted.next();
 9226                            continue;
 9227                        }
 9228                        Ordering::Greater => break,
 9229                        Ordering::Equal => {
 9230                            if selection.end.column == snapshot.line_len(row) {
 9231                                if selection.is_empty() {
 9232                                    selection.start.column -= suffix_len as u32;
 9233                                }
 9234                                selection.end.column -= suffix_len as u32;
 9235                            }
 9236                            break;
 9237                        }
 9238                    }
 9239                }
 9240            }
 9241
 9242            drop(snapshot);
 9243            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 9244
 9245            let selections = this.selections.all::<Point>(cx);
 9246            let selections_on_single_row = selections.windows(2).all(|selections| {
 9247                selections[0].start.row == selections[1].start.row
 9248                    && selections[0].end.row == selections[1].end.row
 9249                    && selections[0].start.row == selections[0].end.row
 9250            });
 9251            let selections_selecting = selections
 9252                .iter()
 9253                .any(|selection| selection.start != selection.end);
 9254            let advance_downwards = action.advance_downwards
 9255                && selections_on_single_row
 9256                && !selections_selecting
 9257                && !matches!(this.mode, EditorMode::SingleLine { .. });
 9258
 9259            if advance_downwards {
 9260                let snapshot = this.buffer.read(cx).snapshot(cx);
 9261
 9262                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9263                    s.move_cursors_with(|display_snapshot, display_point, _| {
 9264                        let mut point = display_point.to_point(display_snapshot);
 9265                        point.row += 1;
 9266                        point = snapshot.clip_point(point, Bias::Left);
 9267                        let display_point = point.to_display_point(display_snapshot);
 9268                        let goal = SelectionGoal::HorizontalPosition(
 9269                            display_snapshot
 9270                                .x_for_display_point(display_point, text_layout_details)
 9271                                .into(),
 9272                        );
 9273                        (display_point, goal)
 9274                    })
 9275                });
 9276            }
 9277        });
 9278    }
 9279
 9280    pub fn select_enclosing_symbol(
 9281        &mut self,
 9282        _: &SelectEnclosingSymbol,
 9283        cx: &mut ViewContext<Self>,
 9284    ) {
 9285        let buffer = self.buffer.read(cx).snapshot(cx);
 9286        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9287
 9288        fn update_selection(
 9289            selection: &Selection<usize>,
 9290            buffer_snap: &MultiBufferSnapshot,
 9291        ) -> Option<Selection<usize>> {
 9292            let cursor = selection.head();
 9293            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 9294            for symbol in symbols.iter().rev() {
 9295                let start = symbol.range.start.to_offset(buffer_snap);
 9296                let end = symbol.range.end.to_offset(buffer_snap);
 9297                let new_range = start..end;
 9298                if start < selection.start || end > selection.end {
 9299                    return Some(Selection {
 9300                        id: selection.id,
 9301                        start: new_range.start,
 9302                        end: new_range.end,
 9303                        goal: SelectionGoal::None,
 9304                        reversed: selection.reversed,
 9305                    });
 9306                }
 9307            }
 9308            None
 9309        }
 9310
 9311        let mut selected_larger_symbol = false;
 9312        let new_selections = old_selections
 9313            .iter()
 9314            .map(|selection| match update_selection(selection, &buffer) {
 9315                Some(new_selection) => {
 9316                    if new_selection.range() != selection.range() {
 9317                        selected_larger_symbol = true;
 9318                    }
 9319                    new_selection
 9320                }
 9321                None => selection.clone(),
 9322            })
 9323            .collect::<Vec<_>>();
 9324
 9325        if selected_larger_symbol {
 9326            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9327                s.select(new_selections);
 9328            });
 9329        }
 9330    }
 9331
 9332    pub fn select_larger_syntax_node(
 9333        &mut self,
 9334        _: &SelectLargerSyntaxNode,
 9335        cx: &mut ViewContext<Self>,
 9336    ) {
 9337        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9338        let buffer = self.buffer.read(cx).snapshot(cx);
 9339        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9340
 9341        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9342        let mut selected_larger_node = false;
 9343        let new_selections = old_selections
 9344            .iter()
 9345            .map(|selection| {
 9346                let old_range = selection.start..selection.end;
 9347                let mut new_range = old_range.clone();
 9348                while let Some(containing_range) =
 9349                    buffer.range_for_syntax_ancestor(new_range.clone())
 9350                {
 9351                    new_range = containing_range;
 9352                    if !display_map.intersects_fold(new_range.start)
 9353                        && !display_map.intersects_fold(new_range.end)
 9354                    {
 9355                        break;
 9356                    }
 9357                }
 9358
 9359                selected_larger_node |= new_range != old_range;
 9360                Selection {
 9361                    id: selection.id,
 9362                    start: new_range.start,
 9363                    end: new_range.end,
 9364                    goal: SelectionGoal::None,
 9365                    reversed: selection.reversed,
 9366                }
 9367            })
 9368            .collect::<Vec<_>>();
 9369
 9370        if selected_larger_node {
 9371            stack.push(old_selections);
 9372            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9373                s.select(new_selections);
 9374            });
 9375        }
 9376        self.select_larger_syntax_node_stack = stack;
 9377    }
 9378
 9379    pub fn select_smaller_syntax_node(
 9380        &mut self,
 9381        _: &SelectSmallerSyntaxNode,
 9382        cx: &mut ViewContext<Self>,
 9383    ) {
 9384        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9385        if let Some(selections) = stack.pop() {
 9386            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9387                s.select(selections.to_vec());
 9388            });
 9389        }
 9390        self.select_larger_syntax_node_stack = stack;
 9391    }
 9392
 9393    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 9394        if !EditorSettings::get_global(cx).gutter.runnables {
 9395            self.clear_tasks();
 9396            return Task::ready(());
 9397        }
 9398        let project = self.project.as_ref().map(Model::downgrade);
 9399        cx.spawn(|this, mut cx| async move {
 9400            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
 9401            let Some(project) = project.and_then(|p| p.upgrade()) else {
 9402                return;
 9403            };
 9404            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 9405                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 9406            }) else {
 9407                return;
 9408            };
 9409
 9410            let hide_runnables = project
 9411                .update(&mut cx, |project, cx| {
 9412                    // Do not display any test indicators in non-dev server remote projects.
 9413                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 9414                })
 9415                .unwrap_or(true);
 9416            if hide_runnables {
 9417                return;
 9418            }
 9419            let new_rows =
 9420                cx.background_executor()
 9421                    .spawn({
 9422                        let snapshot = display_snapshot.clone();
 9423                        async move {
 9424                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 9425                        }
 9426                    })
 9427                    .await;
 9428            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 9429
 9430            this.update(&mut cx, |this, _| {
 9431                this.clear_tasks();
 9432                for (key, value) in rows {
 9433                    this.insert_tasks(key, value);
 9434                }
 9435            })
 9436            .ok();
 9437        })
 9438    }
 9439    fn fetch_runnable_ranges(
 9440        snapshot: &DisplaySnapshot,
 9441        range: Range<Anchor>,
 9442    ) -> Vec<language::RunnableRange> {
 9443        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 9444    }
 9445
 9446    fn runnable_rows(
 9447        project: Model<Project>,
 9448        snapshot: DisplaySnapshot,
 9449        runnable_ranges: Vec<RunnableRange>,
 9450        mut cx: AsyncWindowContext,
 9451    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 9452        runnable_ranges
 9453            .into_iter()
 9454            .filter_map(|mut runnable| {
 9455                let tasks = cx
 9456                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 9457                    .ok()?;
 9458                if tasks.is_empty() {
 9459                    return None;
 9460                }
 9461
 9462                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 9463
 9464                let row = snapshot
 9465                    .buffer_snapshot
 9466                    .buffer_line_for_row(MultiBufferRow(point.row))?
 9467                    .1
 9468                    .start
 9469                    .row;
 9470
 9471                let context_range =
 9472                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 9473                Some((
 9474                    (runnable.buffer_id, row),
 9475                    RunnableTasks {
 9476                        templates: tasks,
 9477                        offset: MultiBufferOffset(runnable.run_range.start),
 9478                        context_range,
 9479                        column: point.column,
 9480                        extra_variables: runnable.extra_captures,
 9481                    },
 9482                ))
 9483            })
 9484            .collect()
 9485    }
 9486
 9487    fn templates_with_tags(
 9488        project: &Model<Project>,
 9489        runnable: &mut Runnable,
 9490        cx: &WindowContext<'_>,
 9491    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 9492        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 9493            let (worktree_id, file) = project
 9494                .buffer_for_id(runnable.buffer, cx)
 9495                .and_then(|buffer| buffer.read(cx).file())
 9496                .map(|file| (file.worktree_id(cx), file.clone()))
 9497                .unzip();
 9498
 9499            (
 9500                project.task_store().read(cx).task_inventory().cloned(),
 9501                worktree_id,
 9502                file,
 9503            )
 9504        });
 9505
 9506        let tags = mem::take(&mut runnable.tags);
 9507        let mut tags: Vec<_> = tags
 9508            .into_iter()
 9509            .flat_map(|tag| {
 9510                let tag = tag.0.clone();
 9511                inventory
 9512                    .as_ref()
 9513                    .into_iter()
 9514                    .flat_map(|inventory| {
 9515                        inventory.read(cx).list_tasks(
 9516                            file.clone(),
 9517                            Some(runnable.language.clone()),
 9518                            worktree_id,
 9519                            cx,
 9520                        )
 9521                    })
 9522                    .filter(move |(_, template)| {
 9523                        template.tags.iter().any(|source_tag| source_tag == &tag)
 9524                    })
 9525            })
 9526            .sorted_by_key(|(kind, _)| kind.to_owned())
 9527            .collect();
 9528        if let Some((leading_tag_source, _)) = tags.first() {
 9529            // Strongest source wins; if we have worktree tag binding, prefer that to
 9530            // global and language bindings;
 9531            // if we have a global binding, prefer that to language binding.
 9532            let first_mismatch = tags
 9533                .iter()
 9534                .position(|(tag_source, _)| tag_source != leading_tag_source);
 9535            if let Some(index) = first_mismatch {
 9536                tags.truncate(index);
 9537            }
 9538        }
 9539
 9540        tags
 9541    }
 9542
 9543    pub fn move_to_enclosing_bracket(
 9544        &mut self,
 9545        _: &MoveToEnclosingBracket,
 9546        cx: &mut ViewContext<Self>,
 9547    ) {
 9548        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9549            s.move_offsets_with(|snapshot, selection| {
 9550                let Some(enclosing_bracket_ranges) =
 9551                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 9552                else {
 9553                    return;
 9554                };
 9555
 9556                let mut best_length = usize::MAX;
 9557                let mut best_inside = false;
 9558                let mut best_in_bracket_range = false;
 9559                let mut best_destination = None;
 9560                for (open, close) in enclosing_bracket_ranges {
 9561                    let close = close.to_inclusive();
 9562                    let length = close.end() - open.start;
 9563                    let inside = selection.start >= open.end && selection.end <= *close.start();
 9564                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 9565                        || close.contains(&selection.head());
 9566
 9567                    // If best is next to a bracket and current isn't, skip
 9568                    if !in_bracket_range && best_in_bracket_range {
 9569                        continue;
 9570                    }
 9571
 9572                    // Prefer smaller lengths unless best is inside and current isn't
 9573                    if length > best_length && (best_inside || !inside) {
 9574                        continue;
 9575                    }
 9576
 9577                    best_length = length;
 9578                    best_inside = inside;
 9579                    best_in_bracket_range = in_bracket_range;
 9580                    best_destination = Some(
 9581                        if close.contains(&selection.start) && close.contains(&selection.end) {
 9582                            if inside {
 9583                                open.end
 9584                            } else {
 9585                                open.start
 9586                            }
 9587                        } else if inside {
 9588                            *close.start()
 9589                        } else {
 9590                            *close.end()
 9591                        },
 9592                    );
 9593                }
 9594
 9595                if let Some(destination) = best_destination {
 9596                    selection.collapse_to(destination, SelectionGoal::None);
 9597                }
 9598            })
 9599        });
 9600    }
 9601
 9602    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 9603        self.end_selection(cx);
 9604        self.selection_history.mode = SelectionHistoryMode::Undoing;
 9605        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 9606            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9607            self.select_next_state = entry.select_next_state;
 9608            self.select_prev_state = entry.select_prev_state;
 9609            self.add_selections_state = entry.add_selections_state;
 9610            self.request_autoscroll(Autoscroll::newest(), cx);
 9611        }
 9612        self.selection_history.mode = SelectionHistoryMode::Normal;
 9613    }
 9614
 9615    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 9616        self.end_selection(cx);
 9617        self.selection_history.mode = SelectionHistoryMode::Redoing;
 9618        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 9619            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9620            self.select_next_state = entry.select_next_state;
 9621            self.select_prev_state = entry.select_prev_state;
 9622            self.add_selections_state = entry.add_selections_state;
 9623            self.request_autoscroll(Autoscroll::newest(), cx);
 9624        }
 9625        self.selection_history.mode = SelectionHistoryMode::Normal;
 9626    }
 9627
 9628    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 9629        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 9630    }
 9631
 9632    pub fn expand_excerpts_down(
 9633        &mut self,
 9634        action: &ExpandExcerptsDown,
 9635        cx: &mut ViewContext<Self>,
 9636    ) {
 9637        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 9638    }
 9639
 9640    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 9641        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 9642    }
 9643
 9644    pub fn expand_excerpts_for_direction(
 9645        &mut self,
 9646        lines: u32,
 9647        direction: ExpandExcerptDirection,
 9648        cx: &mut ViewContext<Self>,
 9649    ) {
 9650        let selections = self.selections.disjoint_anchors();
 9651
 9652        let lines = if lines == 0 {
 9653            EditorSettings::get_global(cx).expand_excerpt_lines
 9654        } else {
 9655            lines
 9656        };
 9657
 9658        self.buffer.update(cx, |buffer, cx| {
 9659            buffer.expand_excerpts(
 9660                selections
 9661                    .iter()
 9662                    .map(|selection| selection.head().excerpt_id)
 9663                    .dedup(),
 9664                lines,
 9665                direction,
 9666                cx,
 9667            )
 9668        })
 9669    }
 9670
 9671    pub fn expand_excerpt(
 9672        &mut self,
 9673        excerpt: ExcerptId,
 9674        direction: ExpandExcerptDirection,
 9675        cx: &mut ViewContext<Self>,
 9676    ) {
 9677        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 9678        self.buffer.update(cx, |buffer, cx| {
 9679            buffer.expand_excerpts([excerpt], lines, direction, cx)
 9680        })
 9681    }
 9682
 9683    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 9684        self.go_to_diagnostic_impl(Direction::Next, cx)
 9685    }
 9686
 9687    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 9688        self.go_to_diagnostic_impl(Direction::Prev, cx)
 9689    }
 9690
 9691    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 9692        let buffer = self.buffer.read(cx).snapshot(cx);
 9693        let selection = self.selections.newest::<usize>(cx);
 9694
 9695        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 9696        if direction == Direction::Next {
 9697            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 9698                let (group_id, jump_to) = popover.activation_info();
 9699                if self.activate_diagnostics(group_id, cx) {
 9700                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9701                        let mut new_selection = s.newest_anchor().clone();
 9702                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 9703                        s.select_anchors(vec![new_selection.clone()]);
 9704                    });
 9705                }
 9706                return;
 9707            }
 9708        }
 9709
 9710        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 9711            active_diagnostics
 9712                .primary_range
 9713                .to_offset(&buffer)
 9714                .to_inclusive()
 9715        });
 9716        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 9717            if active_primary_range.contains(&selection.head()) {
 9718                *active_primary_range.start()
 9719            } else {
 9720                selection.head()
 9721            }
 9722        } else {
 9723            selection.head()
 9724        };
 9725        let snapshot = self.snapshot(cx);
 9726        loop {
 9727            let diagnostics = if direction == Direction::Prev {
 9728                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 9729            } else {
 9730                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 9731            }
 9732            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 9733            let group = diagnostics
 9734                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 9735                // be sorted in a stable way
 9736                // skip until we are at current active diagnostic, if it exists
 9737                .skip_while(|entry| {
 9738                    (match direction {
 9739                        Direction::Prev => entry.range.start >= search_start,
 9740                        Direction::Next => entry.range.start <= search_start,
 9741                    }) && self
 9742                        .active_diagnostics
 9743                        .as_ref()
 9744                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 9745                })
 9746                .find_map(|entry| {
 9747                    if entry.diagnostic.is_primary
 9748                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 9749                        && !entry.range.is_empty()
 9750                        // if we match with the active diagnostic, skip it
 9751                        && Some(entry.diagnostic.group_id)
 9752                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 9753                    {
 9754                        Some((entry.range, entry.diagnostic.group_id))
 9755                    } else {
 9756                        None
 9757                    }
 9758                });
 9759
 9760            if let Some((primary_range, group_id)) = group {
 9761                if self.activate_diagnostics(group_id, cx) {
 9762                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9763                        s.select(vec![Selection {
 9764                            id: selection.id,
 9765                            start: primary_range.start,
 9766                            end: primary_range.start,
 9767                            reversed: false,
 9768                            goal: SelectionGoal::None,
 9769                        }]);
 9770                    });
 9771                }
 9772                break;
 9773            } else {
 9774                // Cycle around to the start of the buffer, potentially moving back to the start of
 9775                // the currently active diagnostic.
 9776                active_primary_range.take();
 9777                if direction == Direction::Prev {
 9778                    if search_start == buffer.len() {
 9779                        break;
 9780                    } else {
 9781                        search_start = buffer.len();
 9782                    }
 9783                } else if search_start == 0 {
 9784                    break;
 9785                } else {
 9786                    search_start = 0;
 9787                }
 9788            }
 9789        }
 9790    }
 9791
 9792    fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 9793        let snapshot = self
 9794            .display_map
 9795            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9796        let selection = self.selections.newest::<Point>(cx);
 9797        self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
 9798    }
 9799
 9800    fn go_to_hunk_after_position(
 9801        &mut self,
 9802        snapshot: &DisplaySnapshot,
 9803        position: Point,
 9804        cx: &mut ViewContext<'_, Editor>,
 9805    ) -> Option<MultiBufferDiffHunk> {
 9806        if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9807            snapshot,
 9808            position,
 9809            false,
 9810            snapshot
 9811                .buffer_snapshot
 9812                .git_diff_hunks_in_range(MultiBufferRow(position.row + 1)..MultiBufferRow::MAX),
 9813            cx,
 9814        ) {
 9815            return Some(hunk);
 9816        }
 9817
 9818        let wrapped_point = Point::zero();
 9819        self.go_to_next_hunk_in_direction(
 9820            snapshot,
 9821            wrapped_point,
 9822            true,
 9823            snapshot.buffer_snapshot.git_diff_hunks_in_range(
 9824                MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
 9825            ),
 9826            cx,
 9827        )
 9828    }
 9829
 9830    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 9831        let snapshot = self
 9832            .display_map
 9833            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9834        let selection = self.selections.newest::<Point>(cx);
 9835
 9836        self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
 9837    }
 9838
 9839    fn go_to_hunk_before_position(
 9840        &mut self,
 9841        snapshot: &DisplaySnapshot,
 9842        position: Point,
 9843        cx: &mut ViewContext<'_, Editor>,
 9844    ) -> Option<MultiBufferDiffHunk> {
 9845        if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9846            snapshot,
 9847            position,
 9848            false,
 9849            snapshot
 9850                .buffer_snapshot
 9851                .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(position.row)),
 9852            cx,
 9853        ) {
 9854            return Some(hunk);
 9855        }
 9856
 9857        let wrapped_point = snapshot.buffer_snapshot.max_point();
 9858        self.go_to_next_hunk_in_direction(
 9859            snapshot,
 9860            wrapped_point,
 9861            true,
 9862            snapshot
 9863                .buffer_snapshot
 9864                .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(wrapped_point.row)),
 9865            cx,
 9866        )
 9867    }
 9868
 9869    fn go_to_next_hunk_in_direction(
 9870        &mut self,
 9871        snapshot: &DisplaySnapshot,
 9872        initial_point: Point,
 9873        is_wrapped: bool,
 9874        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
 9875        cx: &mut ViewContext<Editor>,
 9876    ) -> Option<MultiBufferDiffHunk> {
 9877        let display_point = initial_point.to_display_point(snapshot);
 9878        let mut hunks = hunks
 9879            .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
 9880            .filter(|(display_hunk, _)| {
 9881                is_wrapped || !display_hunk.contains_display_row(display_point.row())
 9882            })
 9883            .dedup();
 9884
 9885        if let Some((display_hunk, hunk)) = hunks.next() {
 9886            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9887                let row = display_hunk.start_display_row();
 9888                let point = DisplayPoint::new(row, 0);
 9889                s.select_display_ranges([point..point]);
 9890            });
 9891
 9892            Some(hunk)
 9893        } else {
 9894            None
 9895        }
 9896    }
 9897
 9898    pub fn go_to_definition(
 9899        &mut self,
 9900        _: &GoToDefinition,
 9901        cx: &mut ViewContext<Self>,
 9902    ) -> Task<Result<Navigated>> {
 9903        let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
 9904        cx.spawn(|editor, mut cx| async move {
 9905            if definition.await? == Navigated::Yes {
 9906                return Ok(Navigated::Yes);
 9907            }
 9908            match editor.update(&mut cx, |editor, cx| {
 9909                editor.find_all_references(&FindAllReferences, cx)
 9910            })? {
 9911                Some(references) => references.await,
 9912                None => Ok(Navigated::No),
 9913            }
 9914        })
 9915    }
 9916
 9917    pub fn go_to_declaration(
 9918        &mut self,
 9919        _: &GoToDeclaration,
 9920        cx: &mut ViewContext<Self>,
 9921    ) -> Task<Result<Navigated>> {
 9922        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
 9923    }
 9924
 9925    pub fn go_to_declaration_split(
 9926        &mut self,
 9927        _: &GoToDeclaration,
 9928        cx: &mut ViewContext<Self>,
 9929    ) -> Task<Result<Navigated>> {
 9930        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
 9931    }
 9932
 9933    pub fn go_to_implementation(
 9934        &mut self,
 9935        _: &GoToImplementation,
 9936        cx: &mut ViewContext<Self>,
 9937    ) -> Task<Result<Navigated>> {
 9938        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 9939    }
 9940
 9941    pub fn go_to_implementation_split(
 9942        &mut self,
 9943        _: &GoToImplementationSplit,
 9944        cx: &mut ViewContext<Self>,
 9945    ) -> Task<Result<Navigated>> {
 9946        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 9947    }
 9948
 9949    pub fn go_to_type_definition(
 9950        &mut self,
 9951        _: &GoToTypeDefinition,
 9952        cx: &mut ViewContext<Self>,
 9953    ) -> Task<Result<Navigated>> {
 9954        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 9955    }
 9956
 9957    pub fn go_to_definition_split(
 9958        &mut self,
 9959        _: &GoToDefinitionSplit,
 9960        cx: &mut ViewContext<Self>,
 9961    ) -> Task<Result<Navigated>> {
 9962        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 9963    }
 9964
 9965    pub fn go_to_type_definition_split(
 9966        &mut self,
 9967        _: &GoToTypeDefinitionSplit,
 9968        cx: &mut ViewContext<Self>,
 9969    ) -> Task<Result<Navigated>> {
 9970        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 9971    }
 9972
 9973    fn go_to_definition_of_kind(
 9974        &mut self,
 9975        kind: GotoDefinitionKind,
 9976        split: bool,
 9977        cx: &mut ViewContext<Self>,
 9978    ) -> Task<Result<Navigated>> {
 9979        let Some(provider) = self.semantics_provider.clone() else {
 9980            return Task::ready(Ok(Navigated::No));
 9981        };
 9982        let head = self.selections.newest::<usize>(cx).head();
 9983        let buffer = self.buffer.read(cx);
 9984        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 9985            text_anchor
 9986        } else {
 9987            return Task::ready(Ok(Navigated::No));
 9988        };
 9989
 9990        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
 9991            return Task::ready(Ok(Navigated::No));
 9992        };
 9993
 9994        cx.spawn(|editor, mut cx| async move {
 9995            let definitions = definitions.await?;
 9996            let navigated = editor
 9997                .update(&mut cx, |editor, cx| {
 9998                    editor.navigate_to_hover_links(
 9999                        Some(kind),
10000                        definitions
10001                            .into_iter()
10002                            .filter(|location| {
10003                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10004                            })
10005                            .map(HoverLink::Text)
10006                            .collect::<Vec<_>>(),
10007                        split,
10008                        cx,
10009                    )
10010                })?
10011                .await?;
10012            anyhow::Ok(navigated)
10013        })
10014    }
10015
10016    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
10017        let position = self.selections.newest_anchor().head();
10018        let Some((buffer, buffer_position)) =
10019            self.buffer.read(cx).text_anchor_for_position(position, cx)
10020        else {
10021            return;
10022        };
10023
10024        cx.spawn(|editor, mut cx| async move {
10025            if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
10026                editor.update(&mut cx, |_, cx| {
10027                    cx.open_url(&url);
10028                })
10029            } else {
10030                Ok(())
10031            }
10032        })
10033        .detach();
10034    }
10035
10036    pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
10037        let Some(workspace) = self.workspace() else {
10038            return;
10039        };
10040
10041        let position = self.selections.newest_anchor().head();
10042
10043        let Some((buffer, buffer_position)) =
10044            self.buffer.read(cx).text_anchor_for_position(position, cx)
10045        else {
10046            return;
10047        };
10048
10049        let project = self.project.clone();
10050
10051        cx.spawn(|_, mut cx| async move {
10052            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10053
10054            if let Some((_, path)) = result {
10055                workspace
10056                    .update(&mut cx, |workspace, cx| {
10057                        workspace.open_resolved_path(path, cx)
10058                    })?
10059                    .await?;
10060            }
10061            anyhow::Ok(())
10062        })
10063        .detach();
10064    }
10065
10066    pub(crate) fn navigate_to_hover_links(
10067        &mut self,
10068        kind: Option<GotoDefinitionKind>,
10069        mut definitions: Vec<HoverLink>,
10070        split: bool,
10071        cx: &mut ViewContext<Editor>,
10072    ) -> Task<Result<Navigated>> {
10073        // If there is one definition, just open it directly
10074        if definitions.len() == 1 {
10075            let definition = definitions.pop().unwrap();
10076
10077            enum TargetTaskResult {
10078                Location(Option<Location>),
10079                AlreadyNavigated,
10080            }
10081
10082            let target_task = match definition {
10083                HoverLink::Text(link) => {
10084                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10085                }
10086                HoverLink::InlayHint(lsp_location, server_id) => {
10087                    let computation = self.compute_target_location(lsp_location, server_id, cx);
10088                    cx.background_executor().spawn(async move {
10089                        let location = computation.await?;
10090                        Ok(TargetTaskResult::Location(location))
10091                    })
10092                }
10093                HoverLink::Url(url) => {
10094                    cx.open_url(&url);
10095                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10096                }
10097                HoverLink::File(path) => {
10098                    if let Some(workspace) = self.workspace() {
10099                        cx.spawn(|_, mut cx| async move {
10100                            workspace
10101                                .update(&mut cx, |workspace, cx| {
10102                                    workspace.open_resolved_path(path, cx)
10103                                })?
10104                                .await
10105                                .map(|_| TargetTaskResult::AlreadyNavigated)
10106                        })
10107                    } else {
10108                        Task::ready(Ok(TargetTaskResult::Location(None)))
10109                    }
10110                }
10111            };
10112            cx.spawn(|editor, mut cx| async move {
10113                let target = match target_task.await.context("target resolution task")? {
10114                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10115                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
10116                    TargetTaskResult::Location(Some(target)) => target,
10117                };
10118
10119                editor.update(&mut cx, |editor, cx| {
10120                    let Some(workspace) = editor.workspace() else {
10121                        return Navigated::No;
10122                    };
10123                    let pane = workspace.read(cx).active_pane().clone();
10124
10125                    let range = target.range.to_offset(target.buffer.read(cx));
10126                    let range = editor.range_for_match(&range);
10127
10128                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10129                        let buffer = target.buffer.read(cx);
10130                        let range = check_multiline_range(buffer, range);
10131                        editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10132                            s.select_ranges([range]);
10133                        });
10134                    } else {
10135                        cx.window_context().defer(move |cx| {
10136                            let target_editor: View<Self> =
10137                                workspace.update(cx, |workspace, cx| {
10138                                    let pane = if split {
10139                                        workspace.adjacent_pane(cx)
10140                                    } else {
10141                                        workspace.active_pane().clone()
10142                                    };
10143
10144                                    workspace.open_project_item(
10145                                        pane,
10146                                        target.buffer.clone(),
10147                                        true,
10148                                        true,
10149                                        cx,
10150                                    )
10151                                });
10152                            target_editor.update(cx, |target_editor, cx| {
10153                                // When selecting a definition in a different buffer, disable the nav history
10154                                // to avoid creating a history entry at the previous cursor location.
10155                                pane.update(cx, |pane, _| pane.disable_history());
10156                                let buffer = target.buffer.read(cx);
10157                                let range = check_multiline_range(buffer, range);
10158                                target_editor.change_selections(
10159                                    Some(Autoscroll::focused()),
10160                                    cx,
10161                                    |s| {
10162                                        s.select_ranges([range]);
10163                                    },
10164                                );
10165                                pane.update(cx, |pane, _| pane.enable_history());
10166                            });
10167                        });
10168                    }
10169                    Navigated::Yes
10170                })
10171            })
10172        } else if !definitions.is_empty() {
10173            cx.spawn(|editor, mut cx| async move {
10174                let (title, location_tasks, workspace) = editor
10175                    .update(&mut cx, |editor, cx| {
10176                        let tab_kind = match kind {
10177                            Some(GotoDefinitionKind::Implementation) => "Implementations",
10178                            _ => "Definitions",
10179                        };
10180                        let title = definitions
10181                            .iter()
10182                            .find_map(|definition| match definition {
10183                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10184                                    let buffer = origin.buffer.read(cx);
10185                                    format!(
10186                                        "{} for {}",
10187                                        tab_kind,
10188                                        buffer
10189                                            .text_for_range(origin.range.clone())
10190                                            .collect::<String>()
10191                                    )
10192                                }),
10193                                HoverLink::InlayHint(_, _) => None,
10194                                HoverLink::Url(_) => None,
10195                                HoverLink::File(_) => None,
10196                            })
10197                            .unwrap_or(tab_kind.to_string());
10198                        let location_tasks = definitions
10199                            .into_iter()
10200                            .map(|definition| match definition {
10201                                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
10202                                HoverLink::InlayHint(lsp_location, server_id) => {
10203                                    editor.compute_target_location(lsp_location, server_id, cx)
10204                                }
10205                                HoverLink::Url(_) => Task::ready(Ok(None)),
10206                                HoverLink::File(_) => Task::ready(Ok(None)),
10207                            })
10208                            .collect::<Vec<_>>();
10209                        (title, location_tasks, editor.workspace().clone())
10210                    })
10211                    .context("location tasks preparation")?;
10212
10213                let locations = future::join_all(location_tasks)
10214                    .await
10215                    .into_iter()
10216                    .filter_map(|location| location.transpose())
10217                    .collect::<Result<_>>()
10218                    .context("location tasks")?;
10219
10220                let Some(workspace) = workspace else {
10221                    return Ok(Navigated::No);
10222                };
10223                let opened = workspace
10224                    .update(&mut cx, |workspace, cx| {
10225                        Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
10226                    })
10227                    .ok();
10228
10229                anyhow::Ok(Navigated::from_bool(opened.is_some()))
10230            })
10231        } else {
10232            Task::ready(Ok(Navigated::No))
10233        }
10234    }
10235
10236    fn compute_target_location(
10237        &self,
10238        lsp_location: lsp::Location,
10239        server_id: LanguageServerId,
10240        cx: &mut ViewContext<Self>,
10241    ) -> Task<anyhow::Result<Option<Location>>> {
10242        let Some(project) = self.project.clone() else {
10243            return Task::Ready(Some(Ok(None)));
10244        };
10245
10246        cx.spawn(move |editor, mut cx| async move {
10247            let location_task = editor.update(&mut cx, |_, cx| {
10248                project.update(cx, |project, cx| {
10249                    let language_server_name = project
10250                        .language_server_statuses(cx)
10251                        .find(|(id, _)| server_id == *id)
10252                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10253                    language_server_name.map(|language_server_name| {
10254                        project.open_local_buffer_via_lsp(
10255                            lsp_location.uri.clone(),
10256                            server_id,
10257                            language_server_name,
10258                            cx,
10259                        )
10260                    })
10261                })
10262            })?;
10263            let location = match location_task {
10264                Some(task) => Some({
10265                    let target_buffer_handle = task.await.context("open local buffer")?;
10266                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10267                        let target_start = target_buffer
10268                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10269                        let target_end = target_buffer
10270                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10271                        target_buffer.anchor_after(target_start)
10272                            ..target_buffer.anchor_before(target_end)
10273                    })?;
10274                    Location {
10275                        buffer: target_buffer_handle,
10276                        range,
10277                    }
10278                }),
10279                None => None,
10280            };
10281            Ok(location)
10282        })
10283    }
10284
10285    pub fn find_all_references(
10286        &mut self,
10287        _: &FindAllReferences,
10288        cx: &mut ViewContext<Self>,
10289    ) -> Option<Task<Result<Navigated>>> {
10290        let selection = self.selections.newest::<usize>(cx);
10291        let multi_buffer = self.buffer.read(cx);
10292        let head = selection.head();
10293
10294        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10295        let head_anchor = multi_buffer_snapshot.anchor_at(
10296            head,
10297            if head < selection.tail() {
10298                Bias::Right
10299            } else {
10300                Bias::Left
10301            },
10302        );
10303
10304        match self
10305            .find_all_references_task_sources
10306            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10307        {
10308            Ok(_) => {
10309                log::info!(
10310                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
10311                );
10312                return None;
10313            }
10314            Err(i) => {
10315                self.find_all_references_task_sources.insert(i, head_anchor);
10316            }
10317        }
10318
10319        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10320        let workspace = self.workspace()?;
10321        let project = workspace.read(cx).project().clone();
10322        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10323        Some(cx.spawn(|editor, mut cx| async move {
10324            let _cleanup = defer({
10325                let mut cx = cx.clone();
10326                move || {
10327                    let _ = editor.update(&mut cx, |editor, _| {
10328                        if let Ok(i) =
10329                            editor
10330                                .find_all_references_task_sources
10331                                .binary_search_by(|anchor| {
10332                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10333                                })
10334                        {
10335                            editor.find_all_references_task_sources.remove(i);
10336                        }
10337                    });
10338                }
10339            });
10340
10341            let locations = references.await?;
10342            if locations.is_empty() {
10343                return anyhow::Ok(Navigated::No);
10344            }
10345
10346            workspace.update(&mut cx, |workspace, cx| {
10347                let title = locations
10348                    .first()
10349                    .as_ref()
10350                    .map(|location| {
10351                        let buffer = location.buffer.read(cx);
10352                        format!(
10353                            "References to `{}`",
10354                            buffer
10355                                .text_for_range(location.range.clone())
10356                                .collect::<String>()
10357                        )
10358                    })
10359                    .unwrap();
10360                Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
10361                Navigated::Yes
10362            })
10363        }))
10364    }
10365
10366    /// Opens a multibuffer with the given project locations in it
10367    pub fn open_locations_in_multibuffer(
10368        workspace: &mut Workspace,
10369        mut locations: Vec<Location>,
10370        title: String,
10371        split: bool,
10372        cx: &mut ViewContext<Workspace>,
10373    ) {
10374        // If there are multiple definitions, open them in a multibuffer
10375        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10376        let mut locations = locations.into_iter().peekable();
10377        let mut ranges_to_highlight = Vec::new();
10378        let capability = workspace.project().read(cx).capability();
10379
10380        let excerpt_buffer = cx.new_model(|cx| {
10381            let mut multibuffer = MultiBuffer::new(capability);
10382            while let Some(location) = locations.next() {
10383                let buffer = location.buffer.read(cx);
10384                let mut ranges_for_buffer = Vec::new();
10385                let range = location.range.to_offset(buffer);
10386                ranges_for_buffer.push(range.clone());
10387
10388                while let Some(next_location) = locations.peek() {
10389                    if next_location.buffer == location.buffer {
10390                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
10391                        locations.next();
10392                    } else {
10393                        break;
10394                    }
10395                }
10396
10397                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10398                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
10399                    location.buffer.clone(),
10400                    ranges_for_buffer,
10401                    DEFAULT_MULTIBUFFER_CONTEXT,
10402                    cx,
10403                ))
10404            }
10405
10406            multibuffer.with_title(title)
10407        });
10408
10409        let editor = cx.new_view(|cx| {
10410            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
10411        });
10412        editor.update(cx, |editor, cx| {
10413            if let Some(first_range) = ranges_to_highlight.first() {
10414                editor.change_selections(None, cx, |selections| {
10415                    selections.clear_disjoint();
10416                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10417                });
10418            }
10419            editor.highlight_background::<Self>(
10420                &ranges_to_highlight,
10421                |theme| theme.editor_highlighted_line_background,
10422                cx,
10423            );
10424        });
10425
10426        let item = Box::new(editor);
10427        let item_id = item.item_id();
10428
10429        if split {
10430            workspace.split_item(SplitDirection::Right, item.clone(), cx);
10431        } else {
10432            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10433                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10434                    pane.close_current_preview_item(cx)
10435                } else {
10436                    None
10437                }
10438            });
10439            workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
10440        }
10441        workspace.active_pane().update(cx, |pane, cx| {
10442            pane.set_preview_item_id(Some(item_id), cx);
10443        });
10444    }
10445
10446    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10447        use language::ToOffset as _;
10448
10449        let provider = self.semantics_provider.clone()?;
10450        let selection = self.selections.newest_anchor().clone();
10451        let (cursor_buffer, cursor_buffer_position) = self
10452            .buffer
10453            .read(cx)
10454            .text_anchor_for_position(selection.head(), cx)?;
10455        let (tail_buffer, cursor_buffer_position_end) = self
10456            .buffer
10457            .read(cx)
10458            .text_anchor_for_position(selection.tail(), cx)?;
10459        if tail_buffer != cursor_buffer {
10460            return None;
10461        }
10462
10463        let snapshot = cursor_buffer.read(cx).snapshot();
10464        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10465        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10466        let prepare_rename = provider
10467            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10468            .unwrap_or_else(|| Task::ready(Ok(None)));
10469        drop(snapshot);
10470
10471        Some(cx.spawn(|this, mut cx| async move {
10472            let rename_range = if let Some(range) = prepare_rename.await? {
10473                Some(range)
10474            } else {
10475                this.update(&mut cx, |this, cx| {
10476                    let buffer = this.buffer.read(cx).snapshot(cx);
10477                    let mut buffer_highlights = this
10478                        .document_highlights_for_position(selection.head(), &buffer)
10479                        .filter(|highlight| {
10480                            highlight.start.excerpt_id == selection.head().excerpt_id
10481                                && highlight.end.excerpt_id == selection.head().excerpt_id
10482                        });
10483                    buffer_highlights
10484                        .next()
10485                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10486                })?
10487            };
10488            if let Some(rename_range) = rename_range {
10489                this.update(&mut cx, |this, cx| {
10490                    let snapshot = cursor_buffer.read(cx).snapshot();
10491                    let rename_buffer_range = rename_range.to_offset(&snapshot);
10492                    let cursor_offset_in_rename_range =
10493                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10494                    let cursor_offset_in_rename_range_end =
10495                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10496
10497                    this.take_rename(false, cx);
10498                    let buffer = this.buffer.read(cx).read(cx);
10499                    let cursor_offset = selection.head().to_offset(&buffer);
10500                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10501                    let rename_end = rename_start + rename_buffer_range.len();
10502                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10503                    let mut old_highlight_id = None;
10504                    let old_name: Arc<str> = buffer
10505                        .chunks(rename_start..rename_end, true)
10506                        .map(|chunk| {
10507                            if old_highlight_id.is_none() {
10508                                old_highlight_id = chunk.syntax_highlight_id;
10509                            }
10510                            chunk.text
10511                        })
10512                        .collect::<String>()
10513                        .into();
10514
10515                    drop(buffer);
10516
10517                    // Position the selection in the rename editor so that it matches the current selection.
10518                    this.show_local_selections = false;
10519                    let rename_editor = cx.new_view(|cx| {
10520                        let mut editor = Editor::single_line(cx);
10521                        editor.buffer.update(cx, |buffer, cx| {
10522                            buffer.edit([(0..0, old_name.clone())], None, cx)
10523                        });
10524                        let rename_selection_range = match cursor_offset_in_rename_range
10525                            .cmp(&cursor_offset_in_rename_range_end)
10526                        {
10527                            Ordering::Equal => {
10528                                editor.select_all(&SelectAll, cx);
10529                                return editor;
10530                            }
10531                            Ordering::Less => {
10532                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10533                            }
10534                            Ordering::Greater => {
10535                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10536                            }
10537                        };
10538                        if rename_selection_range.end > old_name.len() {
10539                            editor.select_all(&SelectAll, cx);
10540                        } else {
10541                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10542                                s.select_ranges([rename_selection_range]);
10543                            });
10544                        }
10545                        editor
10546                    });
10547                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10548                        if e == &EditorEvent::Focused {
10549                            cx.emit(EditorEvent::FocusedIn)
10550                        }
10551                    })
10552                    .detach();
10553
10554                    let write_highlights =
10555                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10556                    let read_highlights =
10557                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
10558                    let ranges = write_highlights
10559                        .iter()
10560                        .flat_map(|(_, ranges)| ranges.iter())
10561                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10562                        .cloned()
10563                        .collect();
10564
10565                    this.highlight_text::<Rename>(
10566                        ranges,
10567                        HighlightStyle {
10568                            fade_out: Some(0.6),
10569                            ..Default::default()
10570                        },
10571                        cx,
10572                    );
10573                    let rename_focus_handle = rename_editor.focus_handle(cx);
10574                    cx.focus(&rename_focus_handle);
10575                    let block_id = this.insert_blocks(
10576                        [BlockProperties {
10577                            style: BlockStyle::Flex,
10578                            placement: BlockPlacement::Below(range.start),
10579                            height: 1,
10580                            render: Arc::new({
10581                                let rename_editor = rename_editor.clone();
10582                                move |cx: &mut BlockContext| {
10583                                    let mut text_style = cx.editor_style.text.clone();
10584                                    if let Some(highlight_style) = old_highlight_id
10585                                        .and_then(|h| h.style(&cx.editor_style.syntax))
10586                                    {
10587                                        text_style = text_style.highlight(highlight_style);
10588                                    }
10589                                    div()
10590                                        .block_mouse_down()
10591                                        .pl(cx.anchor_x)
10592                                        .child(EditorElement::new(
10593                                            &rename_editor,
10594                                            EditorStyle {
10595                                                background: cx.theme().system().transparent,
10596                                                local_player: cx.editor_style.local_player,
10597                                                text: text_style,
10598                                                scrollbar_width: cx.editor_style.scrollbar_width,
10599                                                syntax: cx.editor_style.syntax.clone(),
10600                                                status: cx.editor_style.status.clone(),
10601                                                inlay_hints_style: HighlightStyle {
10602                                                    font_weight: Some(FontWeight::BOLD),
10603                                                    ..make_inlay_hints_style(cx)
10604                                                },
10605                                                suggestions_style: HighlightStyle {
10606                                                    color: Some(cx.theme().status().predictive),
10607                                                    ..HighlightStyle::default()
10608                                                },
10609                                                ..EditorStyle::default()
10610                                            },
10611                                        ))
10612                                        .into_any_element()
10613                                }
10614                            }),
10615                            priority: 0,
10616                        }],
10617                        Some(Autoscroll::fit()),
10618                        cx,
10619                    )[0];
10620                    this.pending_rename = Some(RenameState {
10621                        range,
10622                        old_name,
10623                        editor: rename_editor,
10624                        block_id,
10625                    });
10626                })?;
10627            }
10628
10629            Ok(())
10630        }))
10631    }
10632
10633    pub fn confirm_rename(
10634        &mut self,
10635        _: &ConfirmRename,
10636        cx: &mut ViewContext<Self>,
10637    ) -> Option<Task<Result<()>>> {
10638        let rename = self.take_rename(false, cx)?;
10639        let workspace = self.workspace()?.downgrade();
10640        let (buffer, start) = self
10641            .buffer
10642            .read(cx)
10643            .text_anchor_for_position(rename.range.start, cx)?;
10644        let (end_buffer, _) = self
10645            .buffer
10646            .read(cx)
10647            .text_anchor_for_position(rename.range.end, cx)?;
10648        if buffer != end_buffer {
10649            return None;
10650        }
10651
10652        let old_name = rename.old_name;
10653        let new_name = rename.editor.read(cx).text(cx);
10654
10655        let rename = self.semantics_provider.as_ref()?.perform_rename(
10656            &buffer,
10657            start,
10658            new_name.clone(),
10659            cx,
10660        )?;
10661
10662        Some(cx.spawn(|editor, mut cx| async move {
10663            let project_transaction = rename.await?;
10664            Self::open_project_transaction(
10665                &editor,
10666                workspace,
10667                project_transaction,
10668                format!("Rename: {}{}", old_name, new_name),
10669                cx.clone(),
10670            )
10671            .await?;
10672
10673            editor.update(&mut cx, |editor, cx| {
10674                editor.refresh_document_highlights(cx);
10675            })?;
10676            Ok(())
10677        }))
10678    }
10679
10680    fn take_rename(
10681        &mut self,
10682        moving_cursor: bool,
10683        cx: &mut ViewContext<Self>,
10684    ) -> Option<RenameState> {
10685        let rename = self.pending_rename.take()?;
10686        if rename.editor.focus_handle(cx).is_focused(cx) {
10687            cx.focus(&self.focus_handle);
10688        }
10689
10690        self.remove_blocks(
10691            [rename.block_id].into_iter().collect(),
10692            Some(Autoscroll::fit()),
10693            cx,
10694        );
10695        self.clear_highlights::<Rename>(cx);
10696        self.show_local_selections = true;
10697
10698        if moving_cursor {
10699            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10700                editor.selections.newest::<usize>(cx).head()
10701            });
10702
10703            // Update the selection to match the position of the selection inside
10704            // the rename editor.
10705            let snapshot = self.buffer.read(cx).read(cx);
10706            let rename_range = rename.range.to_offset(&snapshot);
10707            let cursor_in_editor = snapshot
10708                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10709                .min(rename_range.end);
10710            drop(snapshot);
10711
10712            self.change_selections(None, cx, |s| {
10713                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10714            });
10715        } else {
10716            self.refresh_document_highlights(cx);
10717        }
10718
10719        Some(rename)
10720    }
10721
10722    pub fn pending_rename(&self) -> Option<&RenameState> {
10723        self.pending_rename.as_ref()
10724    }
10725
10726    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10727        let project = match &self.project {
10728            Some(project) => project.clone(),
10729            None => return None,
10730        };
10731
10732        Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10733    }
10734
10735    fn format_selections(
10736        &mut self,
10737        _: &FormatSelections,
10738        cx: &mut ViewContext<Self>,
10739    ) -> Option<Task<Result<()>>> {
10740        let project = match &self.project {
10741            Some(project) => project.clone(),
10742            None => return None,
10743        };
10744
10745        let selections = self
10746            .selections
10747            .all_adjusted(cx)
10748            .into_iter()
10749            .filter(|s| !s.is_empty())
10750            .collect_vec();
10751
10752        Some(self.perform_format(
10753            project,
10754            FormatTrigger::Manual,
10755            FormatTarget::Ranges(selections),
10756            cx,
10757        ))
10758    }
10759
10760    fn perform_format(
10761        &mut self,
10762        project: Model<Project>,
10763        trigger: FormatTrigger,
10764        target: FormatTarget,
10765        cx: &mut ViewContext<Self>,
10766    ) -> Task<Result<()>> {
10767        let buffer = self.buffer().clone();
10768        let mut buffers = buffer.read(cx).all_buffers();
10769        if trigger == FormatTrigger::Save {
10770            buffers.retain(|buffer| buffer.read(cx).is_dirty());
10771        }
10772
10773        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10774        let format = project.update(cx, |project, cx| {
10775            project.format(buffers, true, trigger, target, cx)
10776        });
10777
10778        cx.spawn(|_, mut cx| async move {
10779            let transaction = futures::select_biased! {
10780                () = timeout => {
10781                    log::warn!("timed out waiting for formatting");
10782                    None
10783                }
10784                transaction = format.log_err().fuse() => transaction,
10785            };
10786
10787            buffer
10788                .update(&mut cx, |buffer, cx| {
10789                    if let Some(transaction) = transaction {
10790                        if !buffer.is_singleton() {
10791                            buffer.push_transaction(&transaction.0, cx);
10792                        }
10793                    }
10794
10795                    cx.notify();
10796                })
10797                .ok();
10798
10799            Ok(())
10800        })
10801    }
10802
10803    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10804        if let Some(project) = self.project.clone() {
10805            self.buffer.update(cx, |multi_buffer, cx| {
10806                project.update(cx, |project, cx| {
10807                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10808                });
10809            })
10810        }
10811    }
10812
10813    fn cancel_language_server_work(
10814        &mut self,
10815        _: &actions::CancelLanguageServerWork,
10816        cx: &mut ViewContext<Self>,
10817    ) {
10818        if let Some(project) = self.project.clone() {
10819            self.buffer.update(cx, |multi_buffer, cx| {
10820                project.update(cx, |project, cx| {
10821                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10822                });
10823            })
10824        }
10825    }
10826
10827    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10828        cx.show_character_palette();
10829    }
10830
10831    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10832        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10833            let buffer = self.buffer.read(cx).snapshot(cx);
10834            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10835            let is_valid = buffer
10836                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10837                .any(|entry| {
10838                    entry.diagnostic.is_primary
10839                        && !entry.range.is_empty()
10840                        && entry.range.start == primary_range_start
10841                        && entry.diagnostic.message == active_diagnostics.primary_message
10842                });
10843
10844            if is_valid != active_diagnostics.is_valid {
10845                active_diagnostics.is_valid = is_valid;
10846                let mut new_styles = HashMap::default();
10847                for (block_id, diagnostic) in &active_diagnostics.blocks {
10848                    new_styles.insert(
10849                        *block_id,
10850                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10851                    );
10852                }
10853                self.display_map.update(cx, |display_map, _cx| {
10854                    display_map.replace_blocks(new_styles)
10855                });
10856            }
10857        }
10858    }
10859
10860    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10861        self.dismiss_diagnostics(cx);
10862        let snapshot = self.snapshot(cx);
10863        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10864            let buffer = self.buffer.read(cx).snapshot(cx);
10865
10866            let mut primary_range = None;
10867            let mut primary_message = None;
10868            let mut group_end = Point::zero();
10869            let diagnostic_group = buffer
10870                .diagnostic_group::<MultiBufferPoint>(group_id)
10871                .filter_map(|entry| {
10872                    if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10873                        && (entry.range.start.row == entry.range.end.row
10874                            || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10875                    {
10876                        return None;
10877                    }
10878                    if entry.range.end > group_end {
10879                        group_end = entry.range.end;
10880                    }
10881                    if entry.diagnostic.is_primary {
10882                        primary_range = Some(entry.range.clone());
10883                        primary_message = Some(entry.diagnostic.message.clone());
10884                    }
10885                    Some(entry)
10886                })
10887                .collect::<Vec<_>>();
10888            let primary_range = primary_range?;
10889            let primary_message = primary_message?;
10890            let primary_range =
10891                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10892
10893            let blocks = display_map
10894                .insert_blocks(
10895                    diagnostic_group.iter().map(|entry| {
10896                        let diagnostic = entry.diagnostic.clone();
10897                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10898                        BlockProperties {
10899                            style: BlockStyle::Fixed,
10900                            placement: BlockPlacement::Below(
10901                                buffer.anchor_after(entry.range.start),
10902                            ),
10903                            height: message_height,
10904                            render: diagnostic_block_renderer(diagnostic, None, true, true),
10905                            priority: 0,
10906                        }
10907                    }),
10908                    cx,
10909                )
10910                .into_iter()
10911                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10912                .collect();
10913
10914            Some(ActiveDiagnosticGroup {
10915                primary_range,
10916                primary_message,
10917                group_id,
10918                blocks,
10919                is_valid: true,
10920            })
10921        });
10922        self.active_diagnostics.is_some()
10923    }
10924
10925    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10926        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10927            self.display_map.update(cx, |display_map, cx| {
10928                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10929            });
10930            cx.notify();
10931        }
10932    }
10933
10934    pub fn set_selections_from_remote(
10935        &mut self,
10936        selections: Vec<Selection<Anchor>>,
10937        pending_selection: Option<Selection<Anchor>>,
10938        cx: &mut ViewContext<Self>,
10939    ) {
10940        let old_cursor_position = self.selections.newest_anchor().head();
10941        self.selections.change_with(cx, |s| {
10942            s.select_anchors(selections);
10943            if let Some(pending_selection) = pending_selection {
10944                s.set_pending(pending_selection, SelectMode::Character);
10945            } else {
10946                s.clear_pending();
10947            }
10948        });
10949        self.selections_did_change(false, &old_cursor_position, true, cx);
10950    }
10951
10952    fn push_to_selection_history(&mut self) {
10953        self.selection_history.push(SelectionHistoryEntry {
10954            selections: self.selections.disjoint_anchors(),
10955            select_next_state: self.select_next_state.clone(),
10956            select_prev_state: self.select_prev_state.clone(),
10957            add_selections_state: self.add_selections_state.clone(),
10958        });
10959    }
10960
10961    pub fn transact(
10962        &mut self,
10963        cx: &mut ViewContext<Self>,
10964        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10965    ) -> Option<TransactionId> {
10966        self.start_transaction_at(Instant::now(), cx);
10967        update(self, cx);
10968        self.end_transaction_at(Instant::now(), cx)
10969    }
10970
10971    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10972        self.end_selection(cx);
10973        if let Some(tx_id) = self
10974            .buffer
10975            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10976        {
10977            self.selection_history
10978                .insert_transaction(tx_id, self.selections.disjoint_anchors());
10979            cx.emit(EditorEvent::TransactionBegun {
10980                transaction_id: tx_id,
10981            })
10982        }
10983    }
10984
10985    fn end_transaction_at(
10986        &mut self,
10987        now: Instant,
10988        cx: &mut ViewContext<Self>,
10989    ) -> Option<TransactionId> {
10990        if let Some(transaction_id) = self
10991            .buffer
10992            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10993        {
10994            if let Some((_, end_selections)) =
10995                self.selection_history.transaction_mut(transaction_id)
10996            {
10997                *end_selections = Some(self.selections.disjoint_anchors());
10998            } else {
10999                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11000            }
11001
11002            cx.emit(EditorEvent::Edited { transaction_id });
11003            Some(transaction_id)
11004        } else {
11005            None
11006        }
11007    }
11008
11009    pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
11010        let selection = self.selections.newest::<Point>(cx);
11011
11012        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11013        let range = if selection.is_empty() {
11014            let point = selection.head().to_display_point(&display_map);
11015            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11016            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11017                .to_point(&display_map);
11018            start..end
11019        } else {
11020            selection.range()
11021        };
11022        if display_map.folds_in_range(range).next().is_some() {
11023            self.unfold_lines(&Default::default(), cx)
11024        } else {
11025            self.fold(&Default::default(), cx)
11026        }
11027    }
11028
11029    pub fn toggle_fold_recursive(
11030        &mut self,
11031        _: &actions::ToggleFoldRecursive,
11032        cx: &mut ViewContext<Self>,
11033    ) {
11034        let selection = self.selections.newest::<Point>(cx);
11035
11036        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11037        let range = if selection.is_empty() {
11038            let point = selection.head().to_display_point(&display_map);
11039            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11040            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11041                .to_point(&display_map);
11042            start..end
11043        } else {
11044            selection.range()
11045        };
11046        if display_map.folds_in_range(range).next().is_some() {
11047            self.unfold_recursive(&Default::default(), cx)
11048        } else {
11049            self.fold_recursive(&Default::default(), cx)
11050        }
11051    }
11052
11053    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
11054        let mut to_fold = Vec::new();
11055        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11056        let selections = self.selections.all_adjusted(cx);
11057
11058        for selection in selections {
11059            let range = selection.range().sorted();
11060            let buffer_start_row = range.start.row;
11061
11062            if range.start.row != range.end.row {
11063                let mut found = false;
11064                let mut row = range.start.row;
11065                while row <= range.end.row {
11066                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11067                        found = true;
11068                        row = crease.range().end.row + 1;
11069                        to_fold.push(crease);
11070                    } else {
11071                        row += 1
11072                    }
11073                }
11074                if found {
11075                    continue;
11076                }
11077            }
11078
11079            for row in (0..=range.start.row).rev() {
11080                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11081                    if crease.range().end.row >= buffer_start_row {
11082                        to_fold.push(crease);
11083                        if row <= range.start.row {
11084                            break;
11085                        }
11086                    }
11087                }
11088            }
11089        }
11090
11091        self.fold_creases(to_fold, true, cx);
11092    }
11093
11094    fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
11095        let fold_at_level = fold_at.level;
11096        let snapshot = self.buffer.read(cx).snapshot(cx);
11097        let mut to_fold = Vec::new();
11098        let mut stack = vec![(0, snapshot.max_buffer_row().0, 1)];
11099
11100        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
11101            while start_row < end_row {
11102                match self
11103                    .snapshot(cx)
11104                    .crease_for_buffer_row(MultiBufferRow(start_row))
11105                {
11106                    Some(crease) => {
11107                        let nested_start_row = crease.range().start.row + 1;
11108                        let nested_end_row = crease.range().end.row;
11109
11110                        if current_level < fold_at_level {
11111                            stack.push((nested_start_row, nested_end_row, current_level + 1));
11112                        } else if current_level == fold_at_level {
11113                            to_fold.push(crease);
11114                        }
11115
11116                        start_row = nested_end_row + 1;
11117                    }
11118                    None => start_row += 1,
11119                }
11120            }
11121        }
11122
11123        self.fold_creases(to_fold, true, cx);
11124    }
11125
11126    pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
11127        let mut fold_ranges = Vec::new();
11128        let snapshot = self.buffer.read(cx).snapshot(cx);
11129
11130        for row in 0..snapshot.max_buffer_row().0 {
11131            if let Some(foldable_range) =
11132                self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
11133            {
11134                fold_ranges.push(foldable_range);
11135            }
11136        }
11137
11138        self.fold_creases(fold_ranges, true, cx);
11139    }
11140
11141    pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
11142        let mut to_fold = Vec::new();
11143        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11144        let selections = self.selections.all_adjusted(cx);
11145
11146        for selection in selections {
11147            let range = selection.range().sorted();
11148            let buffer_start_row = range.start.row;
11149
11150            if range.start.row != range.end.row {
11151                let mut found = false;
11152                for row in range.start.row..=range.end.row {
11153                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11154                        found = true;
11155                        to_fold.push(crease);
11156                    }
11157                }
11158                if found {
11159                    continue;
11160                }
11161            }
11162
11163            for row in (0..=range.start.row).rev() {
11164                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11165                    if crease.range().end.row >= buffer_start_row {
11166                        to_fold.push(crease);
11167                    } else {
11168                        break;
11169                    }
11170                }
11171            }
11172        }
11173
11174        self.fold_creases(to_fold, true, cx);
11175    }
11176
11177    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
11178        let buffer_row = fold_at.buffer_row;
11179        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11180
11181        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
11182            let autoscroll = self
11183                .selections
11184                .all::<Point>(cx)
11185                .iter()
11186                .any(|selection| crease.range().overlaps(&selection.range()));
11187
11188            self.fold_creases(vec![crease], autoscroll, cx);
11189        }
11190    }
11191
11192    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
11193        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11194        let buffer = &display_map.buffer_snapshot;
11195        let selections = self.selections.all::<Point>(cx);
11196        let ranges = selections
11197            .iter()
11198            .map(|s| {
11199                let range = s.display_range(&display_map).sorted();
11200                let mut start = range.start.to_point(&display_map);
11201                let mut end = range.end.to_point(&display_map);
11202                start.column = 0;
11203                end.column = buffer.line_len(MultiBufferRow(end.row));
11204                start..end
11205            })
11206            .collect::<Vec<_>>();
11207
11208        self.unfold_ranges(&ranges, true, true, cx);
11209    }
11210
11211    pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
11212        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11213        let selections = self.selections.all::<Point>(cx);
11214        let ranges = selections
11215            .iter()
11216            .map(|s| {
11217                let mut range = s.display_range(&display_map).sorted();
11218                *range.start.column_mut() = 0;
11219                *range.end.column_mut() = display_map.line_len(range.end.row());
11220                let start = range.start.to_point(&display_map);
11221                let end = range.end.to_point(&display_map);
11222                start..end
11223            })
11224            .collect::<Vec<_>>();
11225
11226        self.unfold_ranges(&ranges, true, true, cx);
11227    }
11228
11229    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
11230        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11231
11232        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
11233            ..Point::new(
11234                unfold_at.buffer_row.0,
11235                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
11236            );
11237
11238        let autoscroll = self
11239            .selections
11240            .all::<Point>(cx)
11241            .iter()
11242            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
11243
11244        self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
11245    }
11246
11247    pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
11248        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11249        self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
11250    }
11251
11252    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
11253        let selections = self.selections.all::<Point>(cx);
11254        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11255        let line_mode = self.selections.line_mode;
11256        let ranges = selections
11257            .into_iter()
11258            .map(|s| {
11259                if line_mode {
11260                    let start = Point::new(s.start.row, 0);
11261                    let end = Point::new(
11262                        s.end.row,
11263                        display_map
11264                            .buffer_snapshot
11265                            .line_len(MultiBufferRow(s.end.row)),
11266                    );
11267                    Crease::simple(start..end, display_map.fold_placeholder.clone())
11268                } else {
11269                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
11270                }
11271            })
11272            .collect::<Vec<_>>();
11273        self.fold_creases(ranges, true, cx);
11274    }
11275
11276    pub fn fold_creases<T: ToOffset + Clone>(
11277        &mut self,
11278        creases: Vec<Crease<T>>,
11279        auto_scroll: bool,
11280        cx: &mut ViewContext<Self>,
11281    ) {
11282        if creases.is_empty() {
11283            return;
11284        }
11285
11286        let mut buffers_affected = HashMap::default();
11287        let multi_buffer = self.buffer().read(cx);
11288        for crease in &creases {
11289            if let Some((_, buffer, _)) =
11290                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
11291            {
11292                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
11293            };
11294        }
11295
11296        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
11297
11298        if auto_scroll {
11299            self.request_autoscroll(Autoscroll::fit(), cx);
11300        }
11301
11302        for buffer in buffers_affected.into_values() {
11303            self.sync_expanded_diff_hunks(buffer, cx);
11304        }
11305
11306        cx.notify();
11307
11308        if let Some(active_diagnostics) = self.active_diagnostics.take() {
11309            // Clear diagnostics block when folding a range that contains it.
11310            let snapshot = self.snapshot(cx);
11311            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
11312                drop(snapshot);
11313                self.active_diagnostics = Some(active_diagnostics);
11314                self.dismiss_diagnostics(cx);
11315            } else {
11316                self.active_diagnostics = Some(active_diagnostics);
11317            }
11318        }
11319
11320        self.scrollbar_marker_state.dirty = true;
11321    }
11322
11323    /// Removes any folds whose ranges intersect any of the given ranges.
11324    pub fn unfold_ranges<T: ToOffset + Clone>(
11325        &mut self,
11326        ranges: &[Range<T>],
11327        inclusive: bool,
11328        auto_scroll: bool,
11329        cx: &mut ViewContext<Self>,
11330    ) {
11331        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11332            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
11333        });
11334    }
11335
11336    /// Removes any folds with the given ranges.
11337    pub fn remove_folds_with_type<T: ToOffset + Clone>(
11338        &mut self,
11339        ranges: &[Range<T>],
11340        type_id: TypeId,
11341        auto_scroll: bool,
11342        cx: &mut ViewContext<Self>,
11343    ) {
11344        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11345            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
11346        });
11347    }
11348
11349    fn remove_folds_with<T: ToOffset + Clone>(
11350        &mut self,
11351        ranges: &[Range<T>],
11352        auto_scroll: bool,
11353        cx: &mut ViewContext<Self>,
11354        update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
11355    ) {
11356        if ranges.is_empty() {
11357            return;
11358        }
11359
11360        let mut buffers_affected = HashMap::default();
11361        let multi_buffer = self.buffer().read(cx);
11362        for range in ranges {
11363            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11364                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
11365            };
11366        }
11367
11368        self.display_map.update(cx, update);
11369
11370        if auto_scroll {
11371            self.request_autoscroll(Autoscroll::fit(), cx);
11372        }
11373
11374        for buffer in buffers_affected.into_values() {
11375            self.sync_expanded_diff_hunks(buffer, cx);
11376        }
11377
11378        cx.notify();
11379        self.scrollbar_marker_state.dirty = true;
11380        self.active_indent_guides_state.dirty = true;
11381    }
11382
11383    pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
11384        self.display_map.read(cx).fold_placeholder.clone()
11385    }
11386
11387    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11388        if hovered != self.gutter_hovered {
11389            self.gutter_hovered = hovered;
11390            cx.notify();
11391        }
11392    }
11393
11394    pub fn insert_blocks(
11395        &mut self,
11396        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11397        autoscroll: Option<Autoscroll>,
11398        cx: &mut ViewContext<Self>,
11399    ) -> Vec<CustomBlockId> {
11400        let blocks = self
11401            .display_map
11402            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11403        if let Some(autoscroll) = autoscroll {
11404            self.request_autoscroll(autoscroll, cx);
11405        }
11406        cx.notify();
11407        blocks
11408    }
11409
11410    pub fn resize_blocks(
11411        &mut self,
11412        heights: HashMap<CustomBlockId, u32>,
11413        autoscroll: Option<Autoscroll>,
11414        cx: &mut ViewContext<Self>,
11415    ) {
11416        self.display_map
11417            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11418        if let Some(autoscroll) = autoscroll {
11419            self.request_autoscroll(autoscroll, cx);
11420        }
11421        cx.notify();
11422    }
11423
11424    pub fn replace_blocks(
11425        &mut self,
11426        renderers: HashMap<CustomBlockId, RenderBlock>,
11427        autoscroll: Option<Autoscroll>,
11428        cx: &mut ViewContext<Self>,
11429    ) {
11430        self.display_map
11431            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11432        if let Some(autoscroll) = autoscroll {
11433            self.request_autoscroll(autoscroll, cx);
11434        }
11435        cx.notify();
11436    }
11437
11438    pub fn remove_blocks(
11439        &mut self,
11440        block_ids: HashSet<CustomBlockId>,
11441        autoscroll: Option<Autoscroll>,
11442        cx: &mut ViewContext<Self>,
11443    ) {
11444        self.display_map.update(cx, |display_map, cx| {
11445            display_map.remove_blocks(block_ids, cx)
11446        });
11447        if let Some(autoscroll) = autoscroll {
11448            self.request_autoscroll(autoscroll, cx);
11449        }
11450        cx.notify();
11451    }
11452
11453    pub fn row_for_block(
11454        &self,
11455        block_id: CustomBlockId,
11456        cx: &mut ViewContext<Self>,
11457    ) -> Option<DisplayRow> {
11458        self.display_map
11459            .update(cx, |map, cx| map.row_for_block(block_id, cx))
11460    }
11461
11462    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11463        self.focused_block = Some(focused_block);
11464    }
11465
11466    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11467        self.focused_block.take()
11468    }
11469
11470    pub fn insert_creases(
11471        &mut self,
11472        creases: impl IntoIterator<Item = Crease<Anchor>>,
11473        cx: &mut ViewContext<Self>,
11474    ) -> Vec<CreaseId> {
11475        self.display_map
11476            .update(cx, |map, cx| map.insert_creases(creases, cx))
11477    }
11478
11479    pub fn remove_creases(
11480        &mut self,
11481        ids: impl IntoIterator<Item = CreaseId>,
11482        cx: &mut ViewContext<Self>,
11483    ) {
11484        self.display_map
11485            .update(cx, |map, cx| map.remove_creases(ids, cx));
11486    }
11487
11488    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11489        self.display_map
11490            .update(cx, |map, cx| map.snapshot(cx))
11491            .longest_row()
11492    }
11493
11494    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11495        self.display_map
11496            .update(cx, |map, cx| map.snapshot(cx))
11497            .max_point()
11498    }
11499
11500    pub fn text(&self, cx: &AppContext) -> String {
11501        self.buffer.read(cx).read(cx).text()
11502    }
11503
11504    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11505        let text = self.text(cx);
11506        let text = text.trim();
11507
11508        if text.is_empty() {
11509            return None;
11510        }
11511
11512        Some(text.to_string())
11513    }
11514
11515    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11516        self.transact(cx, |this, cx| {
11517            this.buffer
11518                .read(cx)
11519                .as_singleton()
11520                .expect("you can only call set_text on editors for singleton buffers")
11521                .update(cx, |buffer, cx| buffer.set_text(text, cx));
11522        });
11523    }
11524
11525    pub fn display_text(&self, cx: &mut AppContext) -> String {
11526        self.display_map
11527            .update(cx, |map, cx| map.snapshot(cx))
11528            .text()
11529    }
11530
11531    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11532        let mut wrap_guides = smallvec::smallvec![];
11533
11534        if self.show_wrap_guides == Some(false) {
11535            return wrap_guides;
11536        }
11537
11538        let settings = self.buffer.read(cx).settings_at(0, cx);
11539        if settings.show_wrap_guides {
11540            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11541                wrap_guides.push((soft_wrap as usize, true));
11542            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11543                wrap_guides.push((soft_wrap as usize, true));
11544            }
11545            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11546        }
11547
11548        wrap_guides
11549    }
11550
11551    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11552        let settings = self.buffer.read(cx).settings_at(0, cx);
11553        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11554        match mode {
11555            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11556                SoftWrap::None
11557            }
11558            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11559            language_settings::SoftWrap::PreferredLineLength => {
11560                SoftWrap::Column(settings.preferred_line_length)
11561            }
11562            language_settings::SoftWrap::Bounded => {
11563                SoftWrap::Bounded(settings.preferred_line_length)
11564            }
11565        }
11566    }
11567
11568    pub fn set_soft_wrap_mode(
11569        &mut self,
11570        mode: language_settings::SoftWrap,
11571        cx: &mut ViewContext<Self>,
11572    ) {
11573        self.soft_wrap_mode_override = Some(mode);
11574        cx.notify();
11575    }
11576
11577    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11578        self.text_style_refinement = Some(style);
11579    }
11580
11581    /// called by the Element so we know what style we were most recently rendered with.
11582    pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11583        let rem_size = cx.rem_size();
11584        self.display_map.update(cx, |map, cx| {
11585            map.set_font(
11586                style.text.font(),
11587                style.text.font_size.to_pixels(rem_size),
11588                cx,
11589            )
11590        });
11591        self.style = Some(style);
11592    }
11593
11594    pub fn style(&self) -> Option<&EditorStyle> {
11595        self.style.as_ref()
11596    }
11597
11598    // Called by the element. This method is not designed to be called outside of the editor
11599    // element's layout code because it does not notify when rewrapping is computed synchronously.
11600    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11601        self.display_map
11602            .update(cx, |map, cx| map.set_wrap_width(width, cx))
11603    }
11604
11605    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11606        if self.soft_wrap_mode_override.is_some() {
11607            self.soft_wrap_mode_override.take();
11608        } else {
11609            let soft_wrap = match self.soft_wrap_mode(cx) {
11610                SoftWrap::GitDiff => return,
11611                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11612                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11613                    language_settings::SoftWrap::None
11614                }
11615            };
11616            self.soft_wrap_mode_override = Some(soft_wrap);
11617        }
11618        cx.notify();
11619    }
11620
11621    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11622        let Some(workspace) = self.workspace() else {
11623            return;
11624        };
11625        let fs = workspace.read(cx).app_state().fs.clone();
11626        let current_show = TabBarSettings::get_global(cx).show;
11627        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11628            setting.show = Some(!current_show);
11629        });
11630    }
11631
11632    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11633        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11634            self.buffer
11635                .read(cx)
11636                .settings_at(0, cx)
11637                .indent_guides
11638                .enabled
11639        });
11640        self.show_indent_guides = Some(!currently_enabled);
11641        cx.notify();
11642    }
11643
11644    fn should_show_indent_guides(&self) -> Option<bool> {
11645        self.show_indent_guides
11646    }
11647
11648    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11649        let mut editor_settings = EditorSettings::get_global(cx).clone();
11650        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11651        EditorSettings::override_global(editor_settings, cx);
11652    }
11653
11654    pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11655        self.use_relative_line_numbers
11656            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11657    }
11658
11659    pub fn toggle_relative_line_numbers(
11660        &mut self,
11661        _: &ToggleRelativeLineNumbers,
11662        cx: &mut ViewContext<Self>,
11663    ) {
11664        let is_relative = self.should_use_relative_line_numbers(cx);
11665        self.set_relative_line_number(Some(!is_relative), cx)
11666    }
11667
11668    pub fn set_relative_line_number(
11669        &mut self,
11670        is_relative: Option<bool>,
11671        cx: &mut ViewContext<Self>,
11672    ) {
11673        self.use_relative_line_numbers = is_relative;
11674        cx.notify();
11675    }
11676
11677    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11678        self.show_gutter = show_gutter;
11679        cx.notify();
11680    }
11681
11682    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11683        self.show_line_numbers = Some(show_line_numbers);
11684        cx.notify();
11685    }
11686
11687    pub fn set_show_git_diff_gutter(
11688        &mut self,
11689        show_git_diff_gutter: bool,
11690        cx: &mut ViewContext<Self>,
11691    ) {
11692        self.show_git_diff_gutter = Some(show_git_diff_gutter);
11693        cx.notify();
11694    }
11695
11696    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11697        self.show_code_actions = Some(show_code_actions);
11698        cx.notify();
11699    }
11700
11701    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11702        self.show_runnables = Some(show_runnables);
11703        cx.notify();
11704    }
11705
11706    pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11707        if self.display_map.read(cx).masked != masked {
11708            self.display_map.update(cx, |map, _| map.masked = masked);
11709        }
11710        cx.notify()
11711    }
11712
11713    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11714        self.show_wrap_guides = Some(show_wrap_guides);
11715        cx.notify();
11716    }
11717
11718    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11719        self.show_indent_guides = Some(show_indent_guides);
11720        cx.notify();
11721    }
11722
11723    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11724        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11725            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11726                if let Some(dir) = file.abs_path(cx).parent() {
11727                    return Some(dir.to_owned());
11728                }
11729            }
11730
11731            if let Some(project_path) = buffer.read(cx).project_path(cx) {
11732                return Some(project_path.path.to_path_buf());
11733            }
11734        }
11735
11736        None
11737    }
11738
11739    fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11740        self.active_excerpt(cx)?
11741            .1
11742            .read(cx)
11743            .file()
11744            .and_then(|f| f.as_local())
11745    }
11746
11747    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11748        if let Some(target) = self.target_file(cx) {
11749            cx.reveal_path(&target.abs_path(cx));
11750        }
11751    }
11752
11753    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11754        if let Some(file) = self.target_file(cx) {
11755            if let Some(path) = file.abs_path(cx).to_str() {
11756                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11757            }
11758        }
11759    }
11760
11761    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11762        if let Some(file) = self.target_file(cx) {
11763            if let Some(path) = file.path().to_str() {
11764                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11765            }
11766        }
11767    }
11768
11769    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11770        self.show_git_blame_gutter = !self.show_git_blame_gutter;
11771
11772        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11773            self.start_git_blame(true, cx);
11774        }
11775
11776        cx.notify();
11777    }
11778
11779    pub fn toggle_git_blame_inline(
11780        &mut self,
11781        _: &ToggleGitBlameInline,
11782        cx: &mut ViewContext<Self>,
11783    ) {
11784        self.toggle_git_blame_inline_internal(true, cx);
11785        cx.notify();
11786    }
11787
11788    pub fn git_blame_inline_enabled(&self) -> bool {
11789        self.git_blame_inline_enabled
11790    }
11791
11792    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11793        self.show_selection_menu = self
11794            .show_selection_menu
11795            .map(|show_selections_menu| !show_selections_menu)
11796            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11797
11798        cx.notify();
11799    }
11800
11801    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11802        self.show_selection_menu
11803            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11804    }
11805
11806    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11807        if let Some(project) = self.project.as_ref() {
11808            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11809                return;
11810            };
11811
11812            if buffer.read(cx).file().is_none() {
11813                return;
11814            }
11815
11816            let focused = self.focus_handle(cx).contains_focused(cx);
11817
11818            let project = project.clone();
11819            let blame =
11820                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11821            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11822            self.blame = Some(blame);
11823        }
11824    }
11825
11826    fn toggle_git_blame_inline_internal(
11827        &mut self,
11828        user_triggered: bool,
11829        cx: &mut ViewContext<Self>,
11830    ) {
11831        if self.git_blame_inline_enabled {
11832            self.git_blame_inline_enabled = false;
11833            self.show_git_blame_inline = false;
11834            self.show_git_blame_inline_delay_task.take();
11835        } else {
11836            self.git_blame_inline_enabled = true;
11837            self.start_git_blame_inline(user_triggered, cx);
11838        }
11839
11840        cx.notify();
11841    }
11842
11843    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11844        self.start_git_blame(user_triggered, cx);
11845
11846        if ProjectSettings::get_global(cx)
11847            .git
11848            .inline_blame_delay()
11849            .is_some()
11850        {
11851            self.start_inline_blame_timer(cx);
11852        } else {
11853            self.show_git_blame_inline = true
11854        }
11855    }
11856
11857    pub fn blame(&self) -> Option<&Model<GitBlame>> {
11858        self.blame.as_ref()
11859    }
11860
11861    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11862        self.show_git_blame_gutter && self.has_blame_entries(cx)
11863    }
11864
11865    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11866        self.show_git_blame_inline
11867            && self.focus_handle.is_focused(cx)
11868            && !self.newest_selection_head_on_empty_line(cx)
11869            && self.has_blame_entries(cx)
11870    }
11871
11872    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11873        self.blame()
11874            .map_or(false, |blame| blame.read(cx).has_generated_entries())
11875    }
11876
11877    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11878        let cursor_anchor = self.selections.newest_anchor().head();
11879
11880        let snapshot = self.buffer.read(cx).snapshot(cx);
11881        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11882
11883        snapshot.line_len(buffer_row) == 0
11884    }
11885
11886    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11887        let buffer_and_selection = maybe!({
11888            let selection = self.selections.newest::<Point>(cx);
11889            let selection_range = selection.range();
11890
11891            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11892                (buffer, selection_range.start.row..selection_range.end.row)
11893            } else {
11894                let buffer_ranges = self
11895                    .buffer()
11896                    .read(cx)
11897                    .range_to_buffer_ranges(selection_range, cx);
11898
11899                let (buffer, range, _) = if selection.reversed {
11900                    buffer_ranges.first()
11901                } else {
11902                    buffer_ranges.last()
11903                }?;
11904
11905                let snapshot = buffer.read(cx).snapshot();
11906                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11907                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
11908                (buffer.clone(), selection)
11909            };
11910
11911            Some((buffer, selection))
11912        });
11913
11914        let Some((buffer, selection)) = buffer_and_selection else {
11915            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11916        };
11917
11918        let Some(project) = self.project.as_ref() else {
11919            return Task::ready(Err(anyhow!("editor does not have project")));
11920        };
11921
11922        project.update(cx, |project, cx| {
11923            project.get_permalink_to_line(&buffer, selection, cx)
11924        })
11925    }
11926
11927    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11928        let permalink_task = self.get_permalink_to_line(cx);
11929        let workspace = self.workspace();
11930
11931        cx.spawn(|_, mut cx| async move {
11932            match permalink_task.await {
11933                Ok(permalink) => {
11934                    cx.update(|cx| {
11935                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11936                    })
11937                    .ok();
11938                }
11939                Err(err) => {
11940                    let message = format!("Failed to copy permalink: {err}");
11941
11942                    Err::<(), anyhow::Error>(err).log_err();
11943
11944                    if let Some(workspace) = workspace {
11945                        workspace
11946                            .update(&mut cx, |workspace, cx| {
11947                                struct CopyPermalinkToLine;
11948
11949                                workspace.show_toast(
11950                                    Toast::new(
11951                                        NotificationId::unique::<CopyPermalinkToLine>(),
11952                                        message,
11953                                    ),
11954                                    cx,
11955                                )
11956                            })
11957                            .ok();
11958                    }
11959                }
11960            }
11961        })
11962        .detach();
11963    }
11964
11965    pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11966        let selection = self.selections.newest::<Point>(cx).start.row + 1;
11967        if let Some(file) = self.target_file(cx) {
11968            if let Some(path) = file.path().to_str() {
11969                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11970            }
11971        }
11972    }
11973
11974    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11975        let permalink_task = self.get_permalink_to_line(cx);
11976        let workspace = self.workspace();
11977
11978        cx.spawn(|_, mut cx| async move {
11979            match permalink_task.await {
11980                Ok(permalink) => {
11981                    cx.update(|cx| {
11982                        cx.open_url(permalink.as_ref());
11983                    })
11984                    .ok();
11985                }
11986                Err(err) => {
11987                    let message = format!("Failed to open permalink: {err}");
11988
11989                    Err::<(), anyhow::Error>(err).log_err();
11990
11991                    if let Some(workspace) = workspace {
11992                        workspace
11993                            .update(&mut cx, |workspace, cx| {
11994                                struct OpenPermalinkToLine;
11995
11996                                workspace.show_toast(
11997                                    Toast::new(
11998                                        NotificationId::unique::<OpenPermalinkToLine>(),
11999                                        message,
12000                                    ),
12001                                    cx,
12002                                )
12003                            })
12004                            .ok();
12005                    }
12006                }
12007            }
12008        })
12009        .detach();
12010    }
12011
12012    /// Adds a row highlight for the given range. If a row has multiple highlights, the
12013    /// last highlight added will be used.
12014    ///
12015    /// If the range ends at the beginning of a line, then that line will not be highlighted.
12016    pub fn highlight_rows<T: 'static>(
12017        &mut self,
12018        range: Range<Anchor>,
12019        color: Hsla,
12020        should_autoscroll: bool,
12021        cx: &mut ViewContext<Self>,
12022    ) {
12023        let snapshot = self.buffer().read(cx).snapshot(cx);
12024        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
12025        let ix = row_highlights.binary_search_by(|highlight| {
12026            Ordering::Equal
12027                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
12028                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
12029        });
12030
12031        if let Err(mut ix) = ix {
12032            let index = post_inc(&mut self.highlight_order);
12033
12034            // If this range intersects with the preceding highlight, then merge it with
12035            // the preceding highlight. Otherwise insert a new highlight.
12036            let mut merged = false;
12037            if ix > 0 {
12038                let prev_highlight = &mut row_highlights[ix - 1];
12039                if prev_highlight
12040                    .range
12041                    .end
12042                    .cmp(&range.start, &snapshot)
12043                    .is_ge()
12044                {
12045                    ix -= 1;
12046                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
12047                        prev_highlight.range.end = range.end;
12048                    }
12049                    merged = true;
12050                    prev_highlight.index = index;
12051                    prev_highlight.color = color;
12052                    prev_highlight.should_autoscroll = should_autoscroll;
12053                }
12054            }
12055
12056            if !merged {
12057                row_highlights.insert(
12058                    ix,
12059                    RowHighlight {
12060                        range: range.clone(),
12061                        index,
12062                        color,
12063                        should_autoscroll,
12064                    },
12065                );
12066            }
12067
12068            // If any of the following highlights intersect with this one, merge them.
12069            while let Some(next_highlight) = row_highlights.get(ix + 1) {
12070                let highlight = &row_highlights[ix];
12071                if next_highlight
12072                    .range
12073                    .start
12074                    .cmp(&highlight.range.end, &snapshot)
12075                    .is_le()
12076                {
12077                    if next_highlight
12078                        .range
12079                        .end
12080                        .cmp(&highlight.range.end, &snapshot)
12081                        .is_gt()
12082                    {
12083                        row_highlights[ix].range.end = next_highlight.range.end;
12084                    }
12085                    row_highlights.remove(ix + 1);
12086                } else {
12087                    break;
12088                }
12089            }
12090        }
12091    }
12092
12093    /// Remove any highlighted row ranges of the given type that intersect the
12094    /// given ranges.
12095    pub fn remove_highlighted_rows<T: 'static>(
12096        &mut self,
12097        ranges_to_remove: Vec<Range<Anchor>>,
12098        cx: &mut ViewContext<Self>,
12099    ) {
12100        let snapshot = self.buffer().read(cx).snapshot(cx);
12101        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
12102        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
12103        row_highlights.retain(|highlight| {
12104            while let Some(range_to_remove) = ranges_to_remove.peek() {
12105                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
12106                    Ordering::Less | Ordering::Equal => {
12107                        ranges_to_remove.next();
12108                    }
12109                    Ordering::Greater => {
12110                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
12111                            Ordering::Less | Ordering::Equal => {
12112                                return false;
12113                            }
12114                            Ordering::Greater => break,
12115                        }
12116                    }
12117                }
12118            }
12119
12120            true
12121        })
12122    }
12123
12124    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
12125    pub fn clear_row_highlights<T: 'static>(&mut self) {
12126        self.highlighted_rows.remove(&TypeId::of::<T>());
12127    }
12128
12129    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
12130    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
12131        self.highlighted_rows
12132            .get(&TypeId::of::<T>())
12133            .map_or(&[] as &[_], |vec| vec.as_slice())
12134            .iter()
12135            .map(|highlight| (highlight.range.clone(), highlight.color))
12136    }
12137
12138    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
12139    /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
12140    /// Allows to ignore certain kinds of highlights.
12141    pub fn highlighted_display_rows(
12142        &mut self,
12143        cx: &mut WindowContext,
12144    ) -> BTreeMap<DisplayRow, Hsla> {
12145        let snapshot = self.snapshot(cx);
12146        let mut used_highlight_orders = HashMap::default();
12147        self.highlighted_rows
12148            .iter()
12149            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
12150            .fold(
12151                BTreeMap::<DisplayRow, Hsla>::new(),
12152                |mut unique_rows, highlight| {
12153                    let start = highlight.range.start.to_display_point(&snapshot);
12154                    let end = highlight.range.end.to_display_point(&snapshot);
12155                    let start_row = start.row().0;
12156                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
12157                        && end.column() == 0
12158                    {
12159                        end.row().0.saturating_sub(1)
12160                    } else {
12161                        end.row().0
12162                    };
12163                    for row in start_row..=end_row {
12164                        let used_index =
12165                            used_highlight_orders.entry(row).or_insert(highlight.index);
12166                        if highlight.index >= *used_index {
12167                            *used_index = highlight.index;
12168                            unique_rows.insert(DisplayRow(row), highlight.color);
12169                        }
12170                    }
12171                    unique_rows
12172                },
12173            )
12174    }
12175
12176    pub fn highlighted_display_row_for_autoscroll(
12177        &self,
12178        snapshot: &DisplaySnapshot,
12179    ) -> Option<DisplayRow> {
12180        self.highlighted_rows
12181            .values()
12182            .flat_map(|highlighted_rows| highlighted_rows.iter())
12183            .filter_map(|highlight| {
12184                if highlight.should_autoscroll {
12185                    Some(highlight.range.start.to_display_point(snapshot).row())
12186                } else {
12187                    None
12188                }
12189            })
12190            .min()
12191    }
12192
12193    pub fn set_search_within_ranges(
12194        &mut self,
12195        ranges: &[Range<Anchor>],
12196        cx: &mut ViewContext<Self>,
12197    ) {
12198        self.highlight_background::<SearchWithinRange>(
12199            ranges,
12200            |colors| colors.editor_document_highlight_read_background,
12201            cx,
12202        )
12203    }
12204
12205    pub fn set_breadcrumb_header(&mut self, new_header: String) {
12206        self.breadcrumb_header = Some(new_header);
12207    }
12208
12209    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
12210        self.clear_background_highlights::<SearchWithinRange>(cx);
12211    }
12212
12213    pub fn highlight_background<T: 'static>(
12214        &mut self,
12215        ranges: &[Range<Anchor>],
12216        color_fetcher: fn(&ThemeColors) -> Hsla,
12217        cx: &mut ViewContext<Self>,
12218    ) {
12219        self.background_highlights
12220            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12221        self.scrollbar_marker_state.dirty = true;
12222        cx.notify();
12223    }
12224
12225    pub fn clear_background_highlights<T: 'static>(
12226        &mut self,
12227        cx: &mut ViewContext<Self>,
12228    ) -> Option<BackgroundHighlight> {
12229        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
12230        if !text_highlights.1.is_empty() {
12231            self.scrollbar_marker_state.dirty = true;
12232            cx.notify();
12233        }
12234        Some(text_highlights)
12235    }
12236
12237    pub fn highlight_gutter<T: 'static>(
12238        &mut self,
12239        ranges: &[Range<Anchor>],
12240        color_fetcher: fn(&AppContext) -> Hsla,
12241        cx: &mut ViewContext<Self>,
12242    ) {
12243        self.gutter_highlights
12244            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12245        cx.notify();
12246    }
12247
12248    pub fn clear_gutter_highlights<T: 'static>(
12249        &mut self,
12250        cx: &mut ViewContext<Self>,
12251    ) -> Option<GutterHighlight> {
12252        cx.notify();
12253        self.gutter_highlights.remove(&TypeId::of::<T>())
12254    }
12255
12256    #[cfg(feature = "test-support")]
12257    pub fn all_text_background_highlights(
12258        &mut self,
12259        cx: &mut ViewContext<Self>,
12260    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12261        let snapshot = self.snapshot(cx);
12262        let buffer = &snapshot.buffer_snapshot;
12263        let start = buffer.anchor_before(0);
12264        let end = buffer.anchor_after(buffer.len());
12265        let theme = cx.theme().colors();
12266        self.background_highlights_in_range(start..end, &snapshot, theme)
12267    }
12268
12269    #[cfg(feature = "test-support")]
12270    pub fn search_background_highlights(
12271        &mut self,
12272        cx: &mut ViewContext<Self>,
12273    ) -> Vec<Range<Point>> {
12274        let snapshot = self.buffer().read(cx).snapshot(cx);
12275
12276        let highlights = self
12277            .background_highlights
12278            .get(&TypeId::of::<items::BufferSearchHighlights>());
12279
12280        if let Some((_color, ranges)) = highlights {
12281            ranges
12282                .iter()
12283                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
12284                .collect_vec()
12285        } else {
12286            vec![]
12287        }
12288    }
12289
12290    fn document_highlights_for_position<'a>(
12291        &'a self,
12292        position: Anchor,
12293        buffer: &'a MultiBufferSnapshot,
12294    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
12295        let read_highlights = self
12296            .background_highlights
12297            .get(&TypeId::of::<DocumentHighlightRead>())
12298            .map(|h| &h.1);
12299        let write_highlights = self
12300            .background_highlights
12301            .get(&TypeId::of::<DocumentHighlightWrite>())
12302            .map(|h| &h.1);
12303        let left_position = position.bias_left(buffer);
12304        let right_position = position.bias_right(buffer);
12305        read_highlights
12306            .into_iter()
12307            .chain(write_highlights)
12308            .flat_map(move |ranges| {
12309                let start_ix = match ranges.binary_search_by(|probe| {
12310                    let cmp = probe.end.cmp(&left_position, buffer);
12311                    if cmp.is_ge() {
12312                        Ordering::Greater
12313                    } else {
12314                        Ordering::Less
12315                    }
12316                }) {
12317                    Ok(i) | Err(i) => i,
12318                };
12319
12320                ranges[start_ix..]
12321                    .iter()
12322                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
12323            })
12324    }
12325
12326    pub fn has_background_highlights<T: 'static>(&self) -> bool {
12327        self.background_highlights
12328            .get(&TypeId::of::<T>())
12329            .map_or(false, |(_, highlights)| !highlights.is_empty())
12330    }
12331
12332    pub fn background_highlights_in_range(
12333        &self,
12334        search_range: Range<Anchor>,
12335        display_snapshot: &DisplaySnapshot,
12336        theme: &ThemeColors,
12337    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12338        let mut results = Vec::new();
12339        for (color_fetcher, ranges) in self.background_highlights.values() {
12340            let color = color_fetcher(theme);
12341            let start_ix = match ranges.binary_search_by(|probe| {
12342                let cmp = probe
12343                    .end
12344                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12345                if cmp.is_gt() {
12346                    Ordering::Greater
12347                } else {
12348                    Ordering::Less
12349                }
12350            }) {
12351                Ok(i) | Err(i) => i,
12352            };
12353            for range in &ranges[start_ix..] {
12354                if range
12355                    .start
12356                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12357                    .is_ge()
12358                {
12359                    break;
12360                }
12361
12362                let start = range.start.to_display_point(display_snapshot);
12363                let end = range.end.to_display_point(display_snapshot);
12364                results.push((start..end, color))
12365            }
12366        }
12367        results
12368    }
12369
12370    pub fn background_highlight_row_ranges<T: 'static>(
12371        &self,
12372        search_range: Range<Anchor>,
12373        display_snapshot: &DisplaySnapshot,
12374        count: usize,
12375    ) -> Vec<RangeInclusive<DisplayPoint>> {
12376        let mut results = Vec::new();
12377        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12378            return vec![];
12379        };
12380
12381        let start_ix = match ranges.binary_search_by(|probe| {
12382            let cmp = probe
12383                .end
12384                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12385            if cmp.is_gt() {
12386                Ordering::Greater
12387            } else {
12388                Ordering::Less
12389            }
12390        }) {
12391            Ok(i) | Err(i) => i,
12392        };
12393        let mut push_region = |start: Option<Point>, end: Option<Point>| {
12394            if let (Some(start_display), Some(end_display)) = (start, end) {
12395                results.push(
12396                    start_display.to_display_point(display_snapshot)
12397                        ..=end_display.to_display_point(display_snapshot),
12398                );
12399            }
12400        };
12401        let mut start_row: Option<Point> = None;
12402        let mut end_row: Option<Point> = None;
12403        if ranges.len() > count {
12404            return Vec::new();
12405        }
12406        for range in &ranges[start_ix..] {
12407            if range
12408                .start
12409                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12410                .is_ge()
12411            {
12412                break;
12413            }
12414            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12415            if let Some(current_row) = &end_row {
12416                if end.row == current_row.row {
12417                    continue;
12418                }
12419            }
12420            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12421            if start_row.is_none() {
12422                assert_eq!(end_row, None);
12423                start_row = Some(start);
12424                end_row = Some(end);
12425                continue;
12426            }
12427            if let Some(current_end) = end_row.as_mut() {
12428                if start.row > current_end.row + 1 {
12429                    push_region(start_row, end_row);
12430                    start_row = Some(start);
12431                    end_row = Some(end);
12432                } else {
12433                    // Merge two hunks.
12434                    *current_end = end;
12435                }
12436            } else {
12437                unreachable!();
12438            }
12439        }
12440        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12441        push_region(start_row, end_row);
12442        results
12443    }
12444
12445    pub fn gutter_highlights_in_range(
12446        &self,
12447        search_range: Range<Anchor>,
12448        display_snapshot: &DisplaySnapshot,
12449        cx: &AppContext,
12450    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12451        let mut results = Vec::new();
12452        for (color_fetcher, ranges) in self.gutter_highlights.values() {
12453            let color = color_fetcher(cx);
12454            let start_ix = match ranges.binary_search_by(|probe| {
12455                let cmp = probe
12456                    .end
12457                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12458                if cmp.is_gt() {
12459                    Ordering::Greater
12460                } else {
12461                    Ordering::Less
12462                }
12463            }) {
12464                Ok(i) | Err(i) => i,
12465            };
12466            for range in &ranges[start_ix..] {
12467                if range
12468                    .start
12469                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12470                    .is_ge()
12471                {
12472                    break;
12473                }
12474
12475                let start = range.start.to_display_point(display_snapshot);
12476                let end = range.end.to_display_point(display_snapshot);
12477                results.push((start..end, color))
12478            }
12479        }
12480        results
12481    }
12482
12483    /// Get the text ranges corresponding to the redaction query
12484    pub fn redacted_ranges(
12485        &self,
12486        search_range: Range<Anchor>,
12487        display_snapshot: &DisplaySnapshot,
12488        cx: &WindowContext,
12489    ) -> Vec<Range<DisplayPoint>> {
12490        display_snapshot
12491            .buffer_snapshot
12492            .redacted_ranges(search_range, |file| {
12493                if let Some(file) = file {
12494                    file.is_private()
12495                        && EditorSettings::get(
12496                            Some(SettingsLocation {
12497                                worktree_id: file.worktree_id(cx),
12498                                path: file.path().as_ref(),
12499                            }),
12500                            cx,
12501                        )
12502                        .redact_private_values
12503                } else {
12504                    false
12505                }
12506            })
12507            .map(|range| {
12508                range.start.to_display_point(display_snapshot)
12509                    ..range.end.to_display_point(display_snapshot)
12510            })
12511            .collect()
12512    }
12513
12514    pub fn highlight_text<T: 'static>(
12515        &mut self,
12516        ranges: Vec<Range<Anchor>>,
12517        style: HighlightStyle,
12518        cx: &mut ViewContext<Self>,
12519    ) {
12520        self.display_map.update(cx, |map, _| {
12521            map.highlight_text(TypeId::of::<T>(), ranges, style)
12522        });
12523        cx.notify();
12524    }
12525
12526    pub(crate) fn highlight_inlays<T: 'static>(
12527        &mut self,
12528        highlights: Vec<InlayHighlight>,
12529        style: HighlightStyle,
12530        cx: &mut ViewContext<Self>,
12531    ) {
12532        self.display_map.update(cx, |map, _| {
12533            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12534        });
12535        cx.notify();
12536    }
12537
12538    pub fn text_highlights<'a, T: 'static>(
12539        &'a self,
12540        cx: &'a AppContext,
12541    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12542        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12543    }
12544
12545    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12546        let cleared = self
12547            .display_map
12548            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12549        if cleared {
12550            cx.notify();
12551        }
12552    }
12553
12554    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12555        (self.read_only(cx) || self.blink_manager.read(cx).visible())
12556            && self.focus_handle.is_focused(cx)
12557    }
12558
12559    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12560        self.show_cursor_when_unfocused = is_enabled;
12561        cx.notify();
12562    }
12563
12564    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12565        cx.notify();
12566    }
12567
12568    fn on_buffer_event(
12569        &mut self,
12570        multibuffer: Model<MultiBuffer>,
12571        event: &multi_buffer::Event,
12572        cx: &mut ViewContext<Self>,
12573    ) {
12574        match event {
12575            multi_buffer::Event::Edited {
12576                singleton_buffer_edited,
12577            } => {
12578                self.scrollbar_marker_state.dirty = true;
12579                self.active_indent_guides_state.dirty = true;
12580                self.refresh_active_diagnostics(cx);
12581                self.refresh_code_actions(cx);
12582                if self.has_active_inline_completion(cx) {
12583                    self.update_visible_inline_completion(cx);
12584                }
12585                cx.emit(EditorEvent::BufferEdited);
12586                cx.emit(SearchEvent::MatchesInvalidated);
12587                if *singleton_buffer_edited {
12588                    if let Some(project) = &self.project {
12589                        let project = project.read(cx);
12590                        #[allow(clippy::mutable_key_type)]
12591                        let languages_affected = multibuffer
12592                            .read(cx)
12593                            .all_buffers()
12594                            .into_iter()
12595                            .filter_map(|buffer| {
12596                                let buffer = buffer.read(cx);
12597                                let language = buffer.language()?;
12598                                if project.is_local()
12599                                    && project.language_servers_for_buffer(buffer, cx).count() == 0
12600                                {
12601                                    None
12602                                } else {
12603                                    Some(language)
12604                                }
12605                            })
12606                            .cloned()
12607                            .collect::<HashSet<_>>();
12608                        if !languages_affected.is_empty() {
12609                            self.refresh_inlay_hints(
12610                                InlayHintRefreshReason::BufferEdited(languages_affected),
12611                                cx,
12612                            );
12613                        }
12614                    }
12615                }
12616
12617                let Some(project) = &self.project else { return };
12618                let (telemetry, is_via_ssh) = {
12619                    let project = project.read(cx);
12620                    let telemetry = project.client().telemetry().clone();
12621                    let is_via_ssh = project.is_via_ssh();
12622                    (telemetry, is_via_ssh)
12623                };
12624                refresh_linked_ranges(self, cx);
12625                telemetry.log_edit_event("editor", is_via_ssh);
12626            }
12627            multi_buffer::Event::ExcerptsAdded {
12628                buffer,
12629                predecessor,
12630                excerpts,
12631            } => {
12632                self.tasks_update_task = Some(self.refresh_runnables(cx));
12633                cx.emit(EditorEvent::ExcerptsAdded {
12634                    buffer: buffer.clone(),
12635                    predecessor: *predecessor,
12636                    excerpts: excerpts.clone(),
12637                });
12638                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12639            }
12640            multi_buffer::Event::ExcerptsRemoved { ids } => {
12641                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12642                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12643            }
12644            multi_buffer::Event::ExcerptsEdited { ids } => {
12645                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12646            }
12647            multi_buffer::Event::ExcerptsExpanded { ids } => {
12648                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12649            }
12650            multi_buffer::Event::Reparsed(buffer_id) => {
12651                self.tasks_update_task = Some(self.refresh_runnables(cx));
12652
12653                cx.emit(EditorEvent::Reparsed(*buffer_id));
12654            }
12655            multi_buffer::Event::LanguageChanged(buffer_id) => {
12656                linked_editing_ranges::refresh_linked_ranges(self, cx);
12657                cx.emit(EditorEvent::Reparsed(*buffer_id));
12658                cx.notify();
12659            }
12660            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12661            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12662            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12663                cx.emit(EditorEvent::TitleChanged)
12664            }
12665            multi_buffer::Event::DiffBaseChanged => {
12666                self.scrollbar_marker_state.dirty = true;
12667                cx.emit(EditorEvent::DiffBaseChanged);
12668                cx.notify();
12669            }
12670            multi_buffer::Event::DiffUpdated { buffer } => {
12671                self.sync_expanded_diff_hunks(buffer.clone(), cx);
12672                cx.notify();
12673            }
12674            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12675            multi_buffer::Event::DiagnosticsUpdated => {
12676                self.refresh_active_diagnostics(cx);
12677                self.scrollbar_marker_state.dirty = true;
12678                cx.notify();
12679            }
12680            _ => {}
12681        };
12682    }
12683
12684    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12685        cx.notify();
12686    }
12687
12688    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12689        self.tasks_update_task = Some(self.refresh_runnables(cx));
12690        self.refresh_inline_completion(true, false, cx);
12691        self.refresh_inlay_hints(
12692            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12693                self.selections.newest_anchor().head(),
12694                &self.buffer.read(cx).snapshot(cx),
12695                cx,
12696            )),
12697            cx,
12698        );
12699
12700        let old_cursor_shape = self.cursor_shape;
12701
12702        {
12703            let editor_settings = EditorSettings::get_global(cx);
12704            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12705            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12706            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12707        }
12708
12709        if old_cursor_shape != self.cursor_shape {
12710            cx.emit(EditorEvent::CursorShapeChanged);
12711        }
12712
12713        let project_settings = ProjectSettings::get_global(cx);
12714        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12715
12716        if self.mode == EditorMode::Full {
12717            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12718            if self.git_blame_inline_enabled != inline_blame_enabled {
12719                self.toggle_git_blame_inline_internal(false, cx);
12720            }
12721        }
12722
12723        cx.notify();
12724    }
12725
12726    pub fn set_searchable(&mut self, searchable: bool) {
12727        self.searchable = searchable;
12728    }
12729
12730    pub fn searchable(&self) -> bool {
12731        self.searchable
12732    }
12733
12734    fn open_proposed_changes_editor(
12735        &mut self,
12736        _: &OpenProposedChangesEditor,
12737        cx: &mut ViewContext<Self>,
12738    ) {
12739        let Some(workspace) = self.workspace() else {
12740            cx.propagate();
12741            return;
12742        };
12743
12744        let selections = self.selections.all::<usize>(cx);
12745        let buffer = self.buffer.read(cx);
12746        let mut new_selections_by_buffer = HashMap::default();
12747        for selection in selections {
12748            for (buffer, range, _) in
12749                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12750            {
12751                let mut range = range.to_point(buffer.read(cx));
12752                range.start.column = 0;
12753                range.end.column = buffer.read(cx).line_len(range.end.row);
12754                new_selections_by_buffer
12755                    .entry(buffer)
12756                    .or_insert(Vec::new())
12757                    .push(range)
12758            }
12759        }
12760
12761        let proposed_changes_buffers = new_selections_by_buffer
12762            .into_iter()
12763            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12764            .collect::<Vec<_>>();
12765        let proposed_changes_editor = cx.new_view(|cx| {
12766            ProposedChangesEditor::new(
12767                "Proposed changes",
12768                proposed_changes_buffers,
12769                self.project.clone(),
12770                cx,
12771            )
12772        });
12773
12774        cx.window_context().defer(move |cx| {
12775            workspace.update(cx, |workspace, cx| {
12776                workspace.active_pane().update(cx, |pane, cx| {
12777                    pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12778                });
12779            });
12780        });
12781    }
12782
12783    pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12784        self.open_excerpts_common(None, true, cx)
12785    }
12786
12787    pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12788        self.open_excerpts_common(None, false, cx)
12789    }
12790
12791    fn open_excerpts_common(
12792        &mut self,
12793        jump_data: Option<JumpData>,
12794        split: bool,
12795        cx: &mut ViewContext<Self>,
12796    ) {
12797        let Some(workspace) = self.workspace() else {
12798            cx.propagate();
12799            return;
12800        };
12801
12802        if self.buffer.read(cx).is_singleton() {
12803            cx.propagate();
12804            return;
12805        }
12806
12807        let mut new_selections_by_buffer = HashMap::default();
12808        match &jump_data {
12809            Some(jump_data) => {
12810                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12811                if let Some(buffer) = multi_buffer_snapshot
12812                    .buffer_id_for_excerpt(jump_data.excerpt_id)
12813                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12814                {
12815                    let buffer_snapshot = buffer.read(cx).snapshot();
12816                    let jump_to_point = if buffer_snapshot.can_resolve(&jump_data.anchor) {
12817                        language::ToPoint::to_point(&jump_data.anchor, &buffer_snapshot)
12818                    } else {
12819                        buffer_snapshot.clip_point(jump_data.position, Bias::Left)
12820                    };
12821                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12822                    new_selections_by_buffer.insert(
12823                        buffer,
12824                        (
12825                            vec![jump_to_offset..jump_to_offset],
12826                            Some(jump_data.line_offset_from_top),
12827                        ),
12828                    );
12829                }
12830            }
12831            None => {
12832                let selections = self.selections.all::<usize>(cx);
12833                let buffer = self.buffer.read(cx);
12834                for selection in selections {
12835                    for (mut buffer_handle, mut range, _) in
12836                        buffer.range_to_buffer_ranges(selection.range(), cx)
12837                    {
12838                        // When editing branch buffers, jump to the corresponding location
12839                        // in their base buffer.
12840                        let buffer = buffer_handle.read(cx);
12841                        if let Some(base_buffer) = buffer.diff_base_buffer() {
12842                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12843                            buffer_handle = base_buffer;
12844                        }
12845
12846                        if selection.reversed {
12847                            mem::swap(&mut range.start, &mut range.end);
12848                        }
12849                        new_selections_by_buffer
12850                            .entry(buffer_handle)
12851                            .or_insert((Vec::new(), None))
12852                            .0
12853                            .push(range)
12854                    }
12855                }
12856            }
12857        }
12858
12859        if new_selections_by_buffer.is_empty() {
12860            return;
12861        }
12862
12863        // We defer the pane interaction because we ourselves are a workspace item
12864        // and activating a new item causes the pane to call a method on us reentrantly,
12865        // which panics if we're on the stack.
12866        cx.window_context().defer(move |cx| {
12867            workspace.update(cx, |workspace, cx| {
12868                let pane = if split {
12869                    workspace.adjacent_pane(cx)
12870                } else {
12871                    workspace.active_pane().clone()
12872                };
12873
12874                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12875                    let editor =
12876                        workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
12877                    editor.update(cx, |editor, cx| {
12878                        let autoscroll = match scroll_offset {
12879                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12880                            None => Autoscroll::newest(),
12881                        };
12882                        let nav_history = editor.nav_history.take();
12883                        editor.change_selections(Some(autoscroll), cx, |s| {
12884                            s.select_ranges(ranges);
12885                        });
12886                        editor.nav_history = nav_history;
12887                    });
12888                }
12889            })
12890        });
12891    }
12892
12893    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12894        let snapshot = self.buffer.read(cx).read(cx);
12895        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12896        Some(
12897            ranges
12898                .iter()
12899                .map(move |range| {
12900                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12901                })
12902                .collect(),
12903        )
12904    }
12905
12906    fn selection_replacement_ranges(
12907        &self,
12908        range: Range<OffsetUtf16>,
12909        cx: &mut AppContext,
12910    ) -> Vec<Range<OffsetUtf16>> {
12911        let selections = self.selections.all::<OffsetUtf16>(cx);
12912        let newest_selection = selections
12913            .iter()
12914            .max_by_key(|selection| selection.id)
12915            .unwrap();
12916        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12917        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12918        let snapshot = self.buffer.read(cx).read(cx);
12919        selections
12920            .into_iter()
12921            .map(|mut selection| {
12922                selection.start.0 =
12923                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
12924                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12925                snapshot.clip_offset_utf16(selection.start, Bias::Left)
12926                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12927            })
12928            .collect()
12929    }
12930
12931    fn report_editor_event(
12932        &self,
12933        operation: &'static str,
12934        file_extension: Option<String>,
12935        cx: &AppContext,
12936    ) {
12937        if cfg!(any(test, feature = "test-support")) {
12938            return;
12939        }
12940
12941        let Some(project) = &self.project else { return };
12942
12943        // If None, we are in a file without an extension
12944        let file = self
12945            .buffer
12946            .read(cx)
12947            .as_singleton()
12948            .and_then(|b| b.read(cx).file());
12949        let file_extension = file_extension.or(file
12950            .as_ref()
12951            .and_then(|file| Path::new(file.file_name(cx)).extension())
12952            .and_then(|e| e.to_str())
12953            .map(|a| a.to_string()));
12954
12955        let vim_mode = cx
12956            .global::<SettingsStore>()
12957            .raw_user_settings()
12958            .get("vim_mode")
12959            == Some(&serde_json::Value::Bool(true));
12960
12961        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12962            == language::language_settings::InlineCompletionProvider::Copilot;
12963        let copilot_enabled_for_language = self
12964            .buffer
12965            .read(cx)
12966            .settings_at(0, cx)
12967            .show_inline_completions;
12968
12969        let project = project.read(cx);
12970        let telemetry = project.client().telemetry().clone();
12971        telemetry.report_editor_event(
12972            file_extension,
12973            vim_mode,
12974            operation,
12975            copilot_enabled,
12976            copilot_enabled_for_language,
12977            project.is_via_ssh(),
12978        )
12979    }
12980
12981    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12982    /// with each line being an array of {text, highlight} objects.
12983    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12984        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12985            return;
12986        };
12987
12988        #[derive(Serialize)]
12989        struct Chunk<'a> {
12990            text: String,
12991            highlight: Option<&'a str>,
12992        }
12993
12994        let snapshot = buffer.read(cx).snapshot();
12995        let range = self
12996            .selected_text_range(false, cx)
12997            .and_then(|selection| {
12998                if selection.range.is_empty() {
12999                    None
13000                } else {
13001                    Some(selection.range)
13002                }
13003            })
13004            .unwrap_or_else(|| 0..snapshot.len());
13005
13006        let chunks = snapshot.chunks(range, true);
13007        let mut lines = Vec::new();
13008        let mut line: VecDeque<Chunk> = VecDeque::new();
13009
13010        let Some(style) = self.style.as_ref() else {
13011            return;
13012        };
13013
13014        for chunk in chunks {
13015            let highlight = chunk
13016                .syntax_highlight_id
13017                .and_then(|id| id.name(&style.syntax));
13018            let mut chunk_lines = chunk.text.split('\n').peekable();
13019            while let Some(text) = chunk_lines.next() {
13020                let mut merged_with_last_token = false;
13021                if let Some(last_token) = line.back_mut() {
13022                    if last_token.highlight == highlight {
13023                        last_token.text.push_str(text);
13024                        merged_with_last_token = true;
13025                    }
13026                }
13027
13028                if !merged_with_last_token {
13029                    line.push_back(Chunk {
13030                        text: text.into(),
13031                        highlight,
13032                    });
13033                }
13034
13035                if chunk_lines.peek().is_some() {
13036                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
13037                        line.pop_front();
13038                    }
13039                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
13040                        line.pop_back();
13041                    }
13042
13043                    lines.push(mem::take(&mut line));
13044                }
13045            }
13046        }
13047
13048        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
13049            return;
13050        };
13051        cx.write_to_clipboard(ClipboardItem::new_string(lines));
13052    }
13053
13054    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
13055        &self.inlay_hint_cache
13056    }
13057
13058    pub fn replay_insert_event(
13059        &mut self,
13060        text: &str,
13061        relative_utf16_range: Option<Range<isize>>,
13062        cx: &mut ViewContext<Self>,
13063    ) {
13064        if !self.input_enabled {
13065            cx.emit(EditorEvent::InputIgnored { text: text.into() });
13066            return;
13067        }
13068        if let Some(relative_utf16_range) = relative_utf16_range {
13069            let selections = self.selections.all::<OffsetUtf16>(cx);
13070            self.change_selections(None, cx, |s| {
13071                let new_ranges = selections.into_iter().map(|range| {
13072                    let start = OffsetUtf16(
13073                        range
13074                            .head()
13075                            .0
13076                            .saturating_add_signed(relative_utf16_range.start),
13077                    );
13078                    let end = OffsetUtf16(
13079                        range
13080                            .head()
13081                            .0
13082                            .saturating_add_signed(relative_utf16_range.end),
13083                    );
13084                    start..end
13085                });
13086                s.select_ranges(new_ranges);
13087            });
13088        }
13089
13090        self.handle_input(text, cx);
13091    }
13092
13093    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
13094        let Some(provider) = self.semantics_provider.as_ref() else {
13095            return false;
13096        };
13097
13098        let mut supports = false;
13099        self.buffer().read(cx).for_each_buffer(|buffer| {
13100            supports |= provider.supports_inlay_hints(buffer, cx);
13101        });
13102        supports
13103    }
13104
13105    pub fn focus(&self, cx: &mut WindowContext) {
13106        cx.focus(&self.focus_handle)
13107    }
13108
13109    pub fn is_focused(&self, cx: &WindowContext) -> bool {
13110        self.focus_handle.is_focused(cx)
13111    }
13112
13113    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
13114        cx.emit(EditorEvent::Focused);
13115
13116        if let Some(descendant) = self
13117            .last_focused_descendant
13118            .take()
13119            .and_then(|descendant| descendant.upgrade())
13120        {
13121            cx.focus(&descendant);
13122        } else {
13123            if let Some(blame) = self.blame.as_ref() {
13124                blame.update(cx, GitBlame::focus)
13125            }
13126
13127            self.blink_manager.update(cx, BlinkManager::enable);
13128            self.show_cursor_names(cx);
13129            self.buffer.update(cx, |buffer, cx| {
13130                buffer.finalize_last_transaction(cx);
13131                if self.leader_peer_id.is_none() {
13132                    buffer.set_active_selections(
13133                        &self.selections.disjoint_anchors(),
13134                        self.selections.line_mode,
13135                        self.cursor_shape,
13136                        cx,
13137                    );
13138                }
13139            });
13140        }
13141    }
13142
13143    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
13144        cx.emit(EditorEvent::FocusedIn)
13145    }
13146
13147    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
13148        if event.blurred != self.focus_handle {
13149            self.last_focused_descendant = Some(event.blurred);
13150        }
13151    }
13152
13153    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
13154        self.blink_manager.update(cx, BlinkManager::disable);
13155        self.buffer
13156            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
13157
13158        if let Some(blame) = self.blame.as_ref() {
13159            blame.update(cx, GitBlame::blur)
13160        }
13161        if !self.hover_state.focused(cx) {
13162            hide_hover(self, cx);
13163        }
13164
13165        self.hide_context_menu(cx);
13166        cx.emit(EditorEvent::Blurred);
13167        cx.notify();
13168    }
13169
13170    pub fn register_action<A: Action>(
13171        &mut self,
13172        listener: impl Fn(&A, &mut WindowContext) + 'static,
13173    ) -> Subscription {
13174        let id = self.next_editor_action_id.post_inc();
13175        let listener = Arc::new(listener);
13176        self.editor_actions.borrow_mut().insert(
13177            id,
13178            Box::new(move |cx| {
13179                let cx = cx.window_context();
13180                let listener = listener.clone();
13181                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
13182                    let action = action.downcast_ref().unwrap();
13183                    if phase == DispatchPhase::Bubble {
13184                        listener(action, cx)
13185                    }
13186                })
13187            }),
13188        );
13189
13190        let editor_actions = self.editor_actions.clone();
13191        Subscription::new(move || {
13192            editor_actions.borrow_mut().remove(&id);
13193        })
13194    }
13195
13196    pub fn file_header_size(&self) -> u32 {
13197        FILE_HEADER_HEIGHT
13198    }
13199
13200    pub fn revert(
13201        &mut self,
13202        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
13203        cx: &mut ViewContext<Self>,
13204    ) {
13205        self.buffer().update(cx, |multi_buffer, cx| {
13206            for (buffer_id, changes) in revert_changes {
13207                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13208                    buffer.update(cx, |buffer, cx| {
13209                        buffer.edit(
13210                            changes.into_iter().map(|(range, text)| {
13211                                (range, text.to_string().map(Arc::<str>::from))
13212                            }),
13213                            None,
13214                            cx,
13215                        );
13216                    });
13217                }
13218            }
13219        });
13220        self.change_selections(None, cx, |selections| selections.refresh());
13221    }
13222
13223    pub fn to_pixel_point(
13224        &mut self,
13225        source: multi_buffer::Anchor,
13226        editor_snapshot: &EditorSnapshot,
13227        cx: &mut ViewContext<Self>,
13228    ) -> Option<gpui::Point<Pixels>> {
13229        let source_point = source.to_display_point(editor_snapshot);
13230        self.display_to_pixel_point(source_point, editor_snapshot, cx)
13231    }
13232
13233    pub fn display_to_pixel_point(
13234        &mut self,
13235        source: DisplayPoint,
13236        editor_snapshot: &EditorSnapshot,
13237        cx: &mut ViewContext<Self>,
13238    ) -> Option<gpui::Point<Pixels>> {
13239        let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
13240        let text_layout_details = self.text_layout_details(cx);
13241        let scroll_top = text_layout_details
13242            .scroll_anchor
13243            .scroll_position(editor_snapshot)
13244            .y;
13245
13246        if source.row().as_f32() < scroll_top.floor() {
13247            return None;
13248        }
13249        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
13250        let source_y = line_height * (source.row().as_f32() - scroll_top);
13251        Some(gpui::Point::new(source_x, source_y))
13252    }
13253
13254    pub fn has_active_completions_menu(&self) -> bool {
13255        self.context_menu.read().as_ref().map_or(false, |menu| {
13256            menu.visible() && matches!(menu, ContextMenu::Completions(_))
13257        })
13258    }
13259
13260    pub fn register_addon<T: Addon>(&mut self, instance: T) {
13261        self.addons
13262            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
13263    }
13264
13265    pub fn unregister_addon<T: Addon>(&mut self) {
13266        self.addons.remove(&std::any::TypeId::of::<T>());
13267    }
13268
13269    pub fn addon<T: Addon>(&self) -> Option<&T> {
13270        let type_id = std::any::TypeId::of::<T>();
13271        self.addons
13272            .get(&type_id)
13273            .and_then(|item| item.to_any().downcast_ref::<T>())
13274    }
13275}
13276
13277fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13278    let tab_size = tab_size.get() as usize;
13279    let mut width = offset;
13280
13281    for ch in text.chars() {
13282        width += if ch == '\t' {
13283            tab_size - (width % tab_size)
13284        } else {
13285            1
13286        };
13287    }
13288
13289    width - offset
13290}
13291
13292#[cfg(test)]
13293mod tests {
13294    use super::*;
13295
13296    #[test]
13297    fn test_string_size_with_expanded_tabs() {
13298        let nz = |val| NonZeroU32::new(val).unwrap();
13299        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13300        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13301        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13302        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13303        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13304        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13305        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13306        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13307    }
13308}
13309
13310/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13311struct WordBreakingTokenizer<'a> {
13312    input: &'a str,
13313}
13314
13315impl<'a> WordBreakingTokenizer<'a> {
13316    fn new(input: &'a str) -> Self {
13317        Self { input }
13318    }
13319}
13320
13321fn is_char_ideographic(ch: char) -> bool {
13322    use unicode_script::Script::*;
13323    use unicode_script::UnicodeScript;
13324    matches!(ch.script(), Han | Tangut | Yi)
13325}
13326
13327fn is_grapheme_ideographic(text: &str) -> bool {
13328    text.chars().any(is_char_ideographic)
13329}
13330
13331fn is_grapheme_whitespace(text: &str) -> bool {
13332    text.chars().any(|x| x.is_whitespace())
13333}
13334
13335fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13336    text.chars().next().map_or(false, |ch| {
13337        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13338    })
13339}
13340
13341#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13342struct WordBreakToken<'a> {
13343    token: &'a str,
13344    grapheme_len: usize,
13345    is_whitespace: bool,
13346}
13347
13348impl<'a> Iterator for WordBreakingTokenizer<'a> {
13349    /// Yields a span, the count of graphemes in the token, and whether it was
13350    /// whitespace. Note that it also breaks at word boundaries.
13351    type Item = WordBreakToken<'a>;
13352
13353    fn next(&mut self) -> Option<Self::Item> {
13354        use unicode_segmentation::UnicodeSegmentation;
13355        if self.input.is_empty() {
13356            return None;
13357        }
13358
13359        let mut iter = self.input.graphemes(true).peekable();
13360        let mut offset = 0;
13361        let mut graphemes = 0;
13362        if let Some(first_grapheme) = iter.next() {
13363            let is_whitespace = is_grapheme_whitespace(first_grapheme);
13364            offset += first_grapheme.len();
13365            graphemes += 1;
13366            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13367                if let Some(grapheme) = iter.peek().copied() {
13368                    if should_stay_with_preceding_ideograph(grapheme) {
13369                        offset += grapheme.len();
13370                        graphemes += 1;
13371                    }
13372                }
13373            } else {
13374                let mut words = self.input[offset..].split_word_bound_indices().peekable();
13375                let mut next_word_bound = words.peek().copied();
13376                if next_word_bound.map_or(false, |(i, _)| i == 0) {
13377                    next_word_bound = words.next();
13378                }
13379                while let Some(grapheme) = iter.peek().copied() {
13380                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
13381                        break;
13382                    };
13383                    if is_grapheme_whitespace(grapheme) != is_whitespace {
13384                        break;
13385                    };
13386                    offset += grapheme.len();
13387                    graphemes += 1;
13388                    iter.next();
13389                }
13390            }
13391            let token = &self.input[..offset];
13392            self.input = &self.input[offset..];
13393            if is_whitespace {
13394                Some(WordBreakToken {
13395                    token: " ",
13396                    grapheme_len: 1,
13397                    is_whitespace: true,
13398                })
13399            } else {
13400                Some(WordBreakToken {
13401                    token,
13402                    grapheme_len: graphemes,
13403                    is_whitespace: false,
13404                })
13405            }
13406        } else {
13407            None
13408        }
13409    }
13410}
13411
13412#[test]
13413fn test_word_breaking_tokenizer() {
13414    let tests: &[(&str, &[(&str, usize, bool)])] = &[
13415        ("", &[]),
13416        ("  ", &[(" ", 1, true)]),
13417        ("Ʒ", &[("Ʒ", 1, false)]),
13418        ("Ǽ", &[("Ǽ", 1, false)]),
13419        ("", &[("", 1, false)]),
13420        ("⋑⋑", &[("⋑⋑", 2, false)]),
13421        (
13422            "原理,进而",
13423            &[
13424                ("", 1, false),
13425                ("理,", 2, false),
13426                ("", 1, false),
13427                ("", 1, false),
13428            ],
13429        ),
13430        (
13431            "hello world",
13432            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13433        ),
13434        (
13435            "hello, world",
13436            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13437        ),
13438        (
13439            "  hello world",
13440            &[
13441                (" ", 1, true),
13442                ("hello", 5, false),
13443                (" ", 1, true),
13444                ("world", 5, false),
13445            ],
13446        ),
13447        (
13448            "这是什么 \n 钢笔",
13449            &[
13450                ("", 1, false),
13451                ("", 1, false),
13452                ("", 1, false),
13453                ("", 1, false),
13454                (" ", 1, true),
13455                ("", 1, false),
13456                ("", 1, false),
13457            ],
13458        ),
13459        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13460    ];
13461
13462    for (input, result) in tests {
13463        assert_eq!(
13464            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13465            result
13466                .iter()
13467                .copied()
13468                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13469                    token,
13470                    grapheme_len,
13471                    is_whitespace,
13472                })
13473                .collect::<Vec<_>>()
13474        );
13475    }
13476}
13477
13478fn wrap_with_prefix(
13479    line_prefix: String,
13480    unwrapped_text: String,
13481    wrap_column: usize,
13482    tab_size: NonZeroU32,
13483) -> String {
13484    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13485    let mut wrapped_text = String::new();
13486    let mut current_line = line_prefix.clone();
13487
13488    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13489    let mut current_line_len = line_prefix_len;
13490    for WordBreakToken {
13491        token,
13492        grapheme_len,
13493        is_whitespace,
13494    } in tokenizer
13495    {
13496        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13497            wrapped_text.push_str(current_line.trim_end());
13498            wrapped_text.push('\n');
13499            current_line.truncate(line_prefix.len());
13500            current_line_len = line_prefix_len;
13501            if !is_whitespace {
13502                current_line.push_str(token);
13503                current_line_len += grapheme_len;
13504            }
13505        } else if !is_whitespace {
13506            current_line.push_str(token);
13507            current_line_len += grapheme_len;
13508        } else if current_line_len != line_prefix_len {
13509            current_line.push(' ');
13510            current_line_len += 1;
13511        }
13512    }
13513
13514    if !current_line.is_empty() {
13515        wrapped_text.push_str(&current_line);
13516    }
13517    wrapped_text
13518}
13519
13520#[test]
13521fn test_wrap_with_prefix() {
13522    assert_eq!(
13523        wrap_with_prefix(
13524            "# ".to_string(),
13525            "abcdefg".to_string(),
13526            4,
13527            NonZeroU32::new(4).unwrap()
13528        ),
13529        "# abcdefg"
13530    );
13531    assert_eq!(
13532        wrap_with_prefix(
13533            "".to_string(),
13534            "\thello world".to_string(),
13535            8,
13536            NonZeroU32::new(4).unwrap()
13537        ),
13538        "hello\nworld"
13539    );
13540    assert_eq!(
13541        wrap_with_prefix(
13542            "// ".to_string(),
13543            "xx \nyy zz aa bb cc".to_string(),
13544            12,
13545            NonZeroU32::new(4).unwrap()
13546        ),
13547        "// xx yy zz\n// aa bb cc"
13548    );
13549    assert_eq!(
13550        wrap_with_prefix(
13551            String::new(),
13552            "这是什么 \n 钢笔".to_string(),
13553            3,
13554            NonZeroU32::new(4).unwrap()
13555        ),
13556        "这是什\n么 钢\n"
13557    );
13558}
13559
13560fn is_hunk_selected(hunk: &MultiBufferDiffHunk, selections: &[Selection<Point>]) -> bool {
13561    let mut buffer_rows_for_selections = selections.iter().map(|selection| {
13562        let start = MultiBufferRow(selection.start.row);
13563        let end = MultiBufferRow(selection.end.row);
13564        start..end
13565    });
13566
13567    buffer_rows_for_selections.any(|range| does_selection_touch_hunk(&range, hunk))
13568}
13569
13570fn hunks_for_selections(
13571    multi_buffer_snapshot: &MultiBufferSnapshot,
13572    selections: &[Selection<Anchor>],
13573) -> Vec<MultiBufferDiffHunk> {
13574    let buffer_rows_for_selections = selections.iter().map(|selection| {
13575        let start = MultiBufferRow(selection.start.to_point(multi_buffer_snapshot).row);
13576        let end = MultiBufferRow(selection.end.to_point(multi_buffer_snapshot).row);
13577        start..end
13578    });
13579
13580    hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
13581}
13582
13583pub fn hunks_for_rows(
13584    rows: impl Iterator<Item = Range<MultiBufferRow>>,
13585    multi_buffer_snapshot: &MultiBufferSnapshot,
13586) -> Vec<MultiBufferDiffHunk> {
13587    let mut hunks = Vec::new();
13588    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13589        HashMap::default();
13590    for selected_multi_buffer_rows in rows {
13591        let query_rows =
13592            selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
13593        for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
13594            let related_to_selection =
13595                does_selection_touch_hunk(&selected_multi_buffer_rows, &hunk);
13596            if related_to_selection {
13597                if !processed_buffer_rows
13598                    .entry(hunk.buffer_id)
13599                    .or_default()
13600                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13601                {
13602                    continue;
13603                }
13604                hunks.push(hunk);
13605            }
13606        }
13607    }
13608
13609    hunks
13610}
13611
13612fn does_selection_touch_hunk(
13613    selected_multi_buffer_rows: &Range<MultiBufferRow>,
13614    hunk: &MultiBufferDiffHunk,
13615) -> bool {
13616    let query_rows = selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
13617    // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13618    // when the caret is just above or just below the deleted hunk.
13619    let allow_adjacent = hunk_status(hunk) == DiffHunkStatus::Removed;
13620    if allow_adjacent {
13621        hunk.row_range.overlaps(&query_rows)
13622            || hunk.row_range.start == query_rows.end
13623            || hunk.row_range.end == query_rows.start
13624    } else {
13625        // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
13626        // `hunk.row_range` is exclusive (e.g. [2..3] means 2nd row is selected)
13627        hunk.row_range.overlaps(selected_multi_buffer_rows)
13628            || selected_multi_buffer_rows.end == hunk.row_range.start
13629    }
13630}
13631
13632pub trait CollaborationHub {
13633    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13634    fn user_participant_indices<'a>(
13635        &self,
13636        cx: &'a AppContext,
13637    ) -> &'a HashMap<u64, ParticipantIndex>;
13638    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13639}
13640
13641impl CollaborationHub for Model<Project> {
13642    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13643        self.read(cx).collaborators()
13644    }
13645
13646    fn user_participant_indices<'a>(
13647        &self,
13648        cx: &'a AppContext,
13649    ) -> &'a HashMap<u64, ParticipantIndex> {
13650        self.read(cx).user_store().read(cx).participant_indices()
13651    }
13652
13653    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13654        let this = self.read(cx);
13655        let user_ids = this.collaborators().values().map(|c| c.user_id);
13656        this.user_store().read_with(cx, |user_store, cx| {
13657            user_store.participant_names(user_ids, cx)
13658        })
13659    }
13660}
13661
13662pub trait SemanticsProvider {
13663    fn hover(
13664        &self,
13665        buffer: &Model<Buffer>,
13666        position: text::Anchor,
13667        cx: &mut AppContext,
13668    ) -> Option<Task<Vec<project::Hover>>>;
13669
13670    fn inlay_hints(
13671        &self,
13672        buffer_handle: Model<Buffer>,
13673        range: Range<text::Anchor>,
13674        cx: &mut AppContext,
13675    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13676
13677    fn resolve_inlay_hint(
13678        &self,
13679        hint: InlayHint,
13680        buffer_handle: Model<Buffer>,
13681        server_id: LanguageServerId,
13682        cx: &mut AppContext,
13683    ) -> Option<Task<anyhow::Result<InlayHint>>>;
13684
13685    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13686
13687    fn document_highlights(
13688        &self,
13689        buffer: &Model<Buffer>,
13690        position: text::Anchor,
13691        cx: &mut AppContext,
13692    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13693
13694    fn definitions(
13695        &self,
13696        buffer: &Model<Buffer>,
13697        position: text::Anchor,
13698        kind: GotoDefinitionKind,
13699        cx: &mut AppContext,
13700    ) -> Option<Task<Result<Vec<LocationLink>>>>;
13701
13702    fn range_for_rename(
13703        &self,
13704        buffer: &Model<Buffer>,
13705        position: text::Anchor,
13706        cx: &mut AppContext,
13707    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13708
13709    fn perform_rename(
13710        &self,
13711        buffer: &Model<Buffer>,
13712        position: text::Anchor,
13713        new_name: String,
13714        cx: &mut AppContext,
13715    ) -> Option<Task<Result<ProjectTransaction>>>;
13716}
13717
13718pub trait CompletionProvider {
13719    fn completions(
13720        &self,
13721        buffer: &Model<Buffer>,
13722        buffer_position: text::Anchor,
13723        trigger: CompletionContext,
13724        cx: &mut ViewContext<Editor>,
13725    ) -> Task<Result<Vec<Completion>>>;
13726
13727    fn resolve_completions(
13728        &self,
13729        buffer: Model<Buffer>,
13730        completion_indices: Vec<usize>,
13731        completions: Arc<RwLock<Box<[Completion]>>>,
13732        cx: &mut ViewContext<Editor>,
13733    ) -> Task<Result<bool>>;
13734
13735    fn apply_additional_edits_for_completion(
13736        &self,
13737        buffer: Model<Buffer>,
13738        completion: Completion,
13739        push_to_history: bool,
13740        cx: &mut ViewContext<Editor>,
13741    ) -> Task<Result<Option<language::Transaction>>>;
13742
13743    fn is_completion_trigger(
13744        &self,
13745        buffer: &Model<Buffer>,
13746        position: language::Anchor,
13747        text: &str,
13748        trigger_in_words: bool,
13749        cx: &mut ViewContext<Editor>,
13750    ) -> bool;
13751
13752    fn sort_completions(&self) -> bool {
13753        true
13754    }
13755}
13756
13757pub trait CodeActionProvider {
13758    fn code_actions(
13759        &self,
13760        buffer: &Model<Buffer>,
13761        range: Range<text::Anchor>,
13762        cx: &mut WindowContext,
13763    ) -> Task<Result<Vec<CodeAction>>>;
13764
13765    fn apply_code_action(
13766        &self,
13767        buffer_handle: Model<Buffer>,
13768        action: CodeAction,
13769        excerpt_id: ExcerptId,
13770        push_to_history: bool,
13771        cx: &mut WindowContext,
13772    ) -> Task<Result<ProjectTransaction>>;
13773}
13774
13775impl CodeActionProvider for Model<Project> {
13776    fn code_actions(
13777        &self,
13778        buffer: &Model<Buffer>,
13779        range: Range<text::Anchor>,
13780        cx: &mut WindowContext,
13781    ) -> Task<Result<Vec<CodeAction>>> {
13782        self.update(cx, |project, cx| {
13783            project.code_actions(buffer, range, None, cx)
13784        })
13785    }
13786
13787    fn apply_code_action(
13788        &self,
13789        buffer_handle: Model<Buffer>,
13790        action: CodeAction,
13791        _excerpt_id: ExcerptId,
13792        push_to_history: bool,
13793        cx: &mut WindowContext,
13794    ) -> Task<Result<ProjectTransaction>> {
13795        self.update(cx, |project, cx| {
13796            project.apply_code_action(buffer_handle, action, push_to_history, cx)
13797        })
13798    }
13799}
13800
13801fn snippet_completions(
13802    project: &Project,
13803    buffer: &Model<Buffer>,
13804    buffer_position: text::Anchor,
13805    cx: &mut AppContext,
13806) -> Vec<Completion> {
13807    let language = buffer.read(cx).language_at(buffer_position);
13808    let language_name = language.as_ref().map(|language| language.lsp_id());
13809    let snippet_store = project.snippets().read(cx);
13810    let snippets = snippet_store.snippets_for(language_name, cx);
13811
13812    if snippets.is_empty() {
13813        return vec![];
13814    }
13815    let snapshot = buffer.read(cx).text_snapshot();
13816    let chars = snapshot.reversed_chars_for_range(text::Anchor::MIN..buffer_position);
13817
13818    let scope = language.map(|language| language.default_scope());
13819    let classifier = CharClassifier::new(scope).for_completion(true);
13820    let mut last_word = chars
13821        .take_while(|c| classifier.is_word(*c))
13822        .collect::<String>();
13823    last_word = last_word.chars().rev().collect();
13824    let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13825    let to_lsp = |point: &text::Anchor| {
13826        let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13827        point_to_lsp(end)
13828    };
13829    let lsp_end = to_lsp(&buffer_position);
13830    snippets
13831        .into_iter()
13832        .filter_map(|snippet| {
13833            let matching_prefix = snippet
13834                .prefix
13835                .iter()
13836                .find(|prefix| prefix.starts_with(&last_word))?;
13837            let start = as_offset - last_word.len();
13838            let start = snapshot.anchor_before(start);
13839            let range = start..buffer_position;
13840            let lsp_start = to_lsp(&start);
13841            let lsp_range = lsp::Range {
13842                start: lsp_start,
13843                end: lsp_end,
13844            };
13845            Some(Completion {
13846                old_range: range,
13847                new_text: snippet.body.clone(),
13848                label: CodeLabel {
13849                    text: matching_prefix.clone(),
13850                    runs: vec![],
13851                    filter_range: 0..matching_prefix.len(),
13852                },
13853                server_id: LanguageServerId(usize::MAX),
13854                documentation: snippet.description.clone().map(Documentation::SingleLine),
13855                lsp_completion: lsp::CompletionItem {
13856                    label: snippet.prefix.first().unwrap().clone(),
13857                    kind: Some(CompletionItemKind::SNIPPET),
13858                    label_details: snippet.description.as_ref().map(|description| {
13859                        lsp::CompletionItemLabelDetails {
13860                            detail: Some(description.clone()),
13861                            description: None,
13862                        }
13863                    }),
13864                    insert_text_format: Some(InsertTextFormat::SNIPPET),
13865                    text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13866                        lsp::InsertReplaceEdit {
13867                            new_text: snippet.body.clone(),
13868                            insert: lsp_range,
13869                            replace: lsp_range,
13870                        },
13871                    )),
13872                    filter_text: Some(snippet.body.clone()),
13873                    sort_text: Some(char::MAX.to_string()),
13874                    ..Default::default()
13875                },
13876                confirm: None,
13877            })
13878        })
13879        .collect()
13880}
13881
13882impl CompletionProvider for Model<Project> {
13883    fn completions(
13884        &self,
13885        buffer: &Model<Buffer>,
13886        buffer_position: text::Anchor,
13887        options: CompletionContext,
13888        cx: &mut ViewContext<Editor>,
13889    ) -> Task<Result<Vec<Completion>>> {
13890        self.update(cx, |project, cx| {
13891            let snippets = snippet_completions(project, buffer, buffer_position, cx);
13892            let project_completions = project.completions(buffer, buffer_position, options, cx);
13893            cx.background_executor().spawn(async move {
13894                let mut completions = project_completions.await?;
13895                //let snippets = snippets.into_iter().;
13896                completions.extend(snippets);
13897                Ok(completions)
13898            })
13899        })
13900    }
13901
13902    fn resolve_completions(
13903        &self,
13904        buffer: Model<Buffer>,
13905        completion_indices: Vec<usize>,
13906        completions: Arc<RwLock<Box<[Completion]>>>,
13907        cx: &mut ViewContext<Editor>,
13908    ) -> Task<Result<bool>> {
13909        self.update(cx, |project, cx| {
13910            project.resolve_completions(buffer, completion_indices, completions, cx)
13911        })
13912    }
13913
13914    fn apply_additional_edits_for_completion(
13915        &self,
13916        buffer: Model<Buffer>,
13917        completion: Completion,
13918        push_to_history: bool,
13919        cx: &mut ViewContext<Editor>,
13920    ) -> Task<Result<Option<language::Transaction>>> {
13921        self.update(cx, |project, cx| {
13922            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13923        })
13924    }
13925
13926    fn is_completion_trigger(
13927        &self,
13928        buffer: &Model<Buffer>,
13929        position: language::Anchor,
13930        text: &str,
13931        trigger_in_words: bool,
13932        cx: &mut ViewContext<Editor>,
13933    ) -> bool {
13934        if !EditorSettings::get_global(cx).show_completions_on_input {
13935            return false;
13936        }
13937
13938        let mut chars = text.chars();
13939        let char = if let Some(char) = chars.next() {
13940            char
13941        } else {
13942            return false;
13943        };
13944        if chars.next().is_some() {
13945            return false;
13946        }
13947
13948        let buffer = buffer.read(cx);
13949        let classifier = buffer
13950            .snapshot()
13951            .char_classifier_at(position)
13952            .for_completion(true);
13953        if trigger_in_words && classifier.is_word(char) {
13954            return true;
13955        }
13956
13957        buffer.completion_triggers().contains(text)
13958    }
13959}
13960
13961impl SemanticsProvider for Model<Project> {
13962    fn hover(
13963        &self,
13964        buffer: &Model<Buffer>,
13965        position: text::Anchor,
13966        cx: &mut AppContext,
13967    ) -> Option<Task<Vec<project::Hover>>> {
13968        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13969    }
13970
13971    fn document_highlights(
13972        &self,
13973        buffer: &Model<Buffer>,
13974        position: text::Anchor,
13975        cx: &mut AppContext,
13976    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13977        Some(self.update(cx, |project, cx| {
13978            project.document_highlights(buffer, position, cx)
13979        }))
13980    }
13981
13982    fn definitions(
13983        &self,
13984        buffer: &Model<Buffer>,
13985        position: text::Anchor,
13986        kind: GotoDefinitionKind,
13987        cx: &mut AppContext,
13988    ) -> Option<Task<Result<Vec<LocationLink>>>> {
13989        Some(self.update(cx, |project, cx| match kind {
13990            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13991            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13992            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13993            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13994        }))
13995    }
13996
13997    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13998        // TODO: make this work for remote projects
13999        self.read(cx)
14000            .language_servers_for_buffer(buffer.read(cx), cx)
14001            .any(
14002                |(_, server)| match server.capabilities().inlay_hint_provider {
14003                    Some(lsp::OneOf::Left(enabled)) => enabled,
14004                    Some(lsp::OneOf::Right(_)) => true,
14005                    None => false,
14006                },
14007            )
14008    }
14009
14010    fn inlay_hints(
14011        &self,
14012        buffer_handle: Model<Buffer>,
14013        range: Range<text::Anchor>,
14014        cx: &mut AppContext,
14015    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
14016        Some(self.update(cx, |project, cx| {
14017            project.inlay_hints(buffer_handle, range, cx)
14018        }))
14019    }
14020
14021    fn resolve_inlay_hint(
14022        &self,
14023        hint: InlayHint,
14024        buffer_handle: Model<Buffer>,
14025        server_id: LanguageServerId,
14026        cx: &mut AppContext,
14027    ) -> Option<Task<anyhow::Result<InlayHint>>> {
14028        Some(self.update(cx, |project, cx| {
14029            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
14030        }))
14031    }
14032
14033    fn range_for_rename(
14034        &self,
14035        buffer: &Model<Buffer>,
14036        position: text::Anchor,
14037        cx: &mut AppContext,
14038    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
14039        Some(self.update(cx, |project, cx| {
14040            project.prepare_rename(buffer.clone(), position, cx)
14041        }))
14042    }
14043
14044    fn perform_rename(
14045        &self,
14046        buffer: &Model<Buffer>,
14047        position: text::Anchor,
14048        new_name: String,
14049        cx: &mut AppContext,
14050    ) -> Option<Task<Result<ProjectTransaction>>> {
14051        Some(self.update(cx, |project, cx| {
14052            project.perform_rename(buffer.clone(), position, new_name, cx)
14053        }))
14054    }
14055}
14056
14057fn inlay_hint_settings(
14058    location: Anchor,
14059    snapshot: &MultiBufferSnapshot,
14060    cx: &mut ViewContext<'_, Editor>,
14061) -> InlayHintSettings {
14062    let file = snapshot.file_at(location);
14063    let language = snapshot.language_at(location).map(|l| l.name());
14064    language_settings(language, file, cx).inlay_hints
14065}
14066
14067fn consume_contiguous_rows(
14068    contiguous_row_selections: &mut Vec<Selection<Point>>,
14069    selection: &Selection<Point>,
14070    display_map: &DisplaySnapshot,
14071    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
14072) -> (MultiBufferRow, MultiBufferRow) {
14073    contiguous_row_selections.push(selection.clone());
14074    let start_row = MultiBufferRow(selection.start.row);
14075    let mut end_row = ending_row(selection, display_map);
14076
14077    while let Some(next_selection) = selections.peek() {
14078        if next_selection.start.row <= end_row.0 {
14079            end_row = ending_row(next_selection, display_map);
14080            contiguous_row_selections.push(selections.next().unwrap().clone());
14081        } else {
14082            break;
14083        }
14084    }
14085    (start_row, end_row)
14086}
14087
14088fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
14089    if next_selection.end.column > 0 || next_selection.is_empty() {
14090        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
14091    } else {
14092        MultiBufferRow(next_selection.end.row)
14093    }
14094}
14095
14096impl EditorSnapshot {
14097    pub fn remote_selections_in_range<'a>(
14098        &'a self,
14099        range: &'a Range<Anchor>,
14100        collaboration_hub: &dyn CollaborationHub,
14101        cx: &'a AppContext,
14102    ) -> impl 'a + Iterator<Item = RemoteSelection> {
14103        let participant_names = collaboration_hub.user_names(cx);
14104        let participant_indices = collaboration_hub.user_participant_indices(cx);
14105        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
14106        let collaborators_by_replica_id = collaborators_by_peer_id
14107            .iter()
14108            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
14109            .collect::<HashMap<_, _>>();
14110        self.buffer_snapshot
14111            .selections_in_range(range, false)
14112            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
14113                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
14114                let participant_index = participant_indices.get(&collaborator.user_id).copied();
14115                let user_name = participant_names.get(&collaborator.user_id).cloned();
14116                Some(RemoteSelection {
14117                    replica_id,
14118                    selection,
14119                    cursor_shape,
14120                    line_mode,
14121                    participant_index,
14122                    peer_id: collaborator.peer_id,
14123                    user_name,
14124                })
14125            })
14126    }
14127
14128    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
14129        self.display_snapshot.buffer_snapshot.language_at(position)
14130    }
14131
14132    pub fn is_focused(&self) -> bool {
14133        self.is_focused
14134    }
14135
14136    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
14137        self.placeholder_text.as_ref()
14138    }
14139
14140    pub fn scroll_position(&self) -> gpui::Point<f32> {
14141        self.scroll_anchor.scroll_position(&self.display_snapshot)
14142    }
14143
14144    fn gutter_dimensions(
14145        &self,
14146        font_id: FontId,
14147        font_size: Pixels,
14148        em_width: Pixels,
14149        em_advance: Pixels,
14150        max_line_number_width: Pixels,
14151        cx: &AppContext,
14152    ) -> GutterDimensions {
14153        if !self.show_gutter {
14154            return GutterDimensions::default();
14155        }
14156        let descent = cx.text_system().descent(font_id, font_size);
14157
14158        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
14159            matches!(
14160                ProjectSettings::get_global(cx).git.git_gutter,
14161                Some(GitGutterSetting::TrackedFiles)
14162            )
14163        });
14164        let gutter_settings = EditorSettings::get_global(cx).gutter;
14165        let show_line_numbers = self
14166            .show_line_numbers
14167            .unwrap_or(gutter_settings.line_numbers);
14168        let line_gutter_width = if show_line_numbers {
14169            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
14170            let min_width_for_number_on_gutter = em_advance * 4.0;
14171            max_line_number_width.max(min_width_for_number_on_gutter)
14172        } else {
14173            0.0.into()
14174        };
14175
14176        let show_code_actions = self
14177            .show_code_actions
14178            .unwrap_or(gutter_settings.code_actions);
14179
14180        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
14181
14182        let git_blame_entries_width =
14183            self.git_blame_gutter_max_author_length
14184                .map(|max_author_length| {
14185                    // Length of the author name, but also space for the commit hash,
14186                    // the spacing and the timestamp.
14187                    let max_char_count = max_author_length
14188                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
14189                        + 7 // length of commit sha
14190                        + 14 // length of max relative timestamp ("60 minutes ago")
14191                        + 4; // gaps and margins
14192
14193                    em_advance * max_char_count
14194                });
14195
14196        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
14197        left_padding += if show_code_actions || show_runnables {
14198            em_width * 3.0
14199        } else if show_git_gutter && show_line_numbers {
14200            em_width * 2.0
14201        } else if show_git_gutter || show_line_numbers {
14202            em_width
14203        } else {
14204            px(0.)
14205        };
14206
14207        let right_padding = if gutter_settings.folds && show_line_numbers {
14208            em_width * 4.0
14209        } else if gutter_settings.folds {
14210            em_width * 3.0
14211        } else if show_line_numbers {
14212            em_width
14213        } else {
14214            px(0.)
14215        };
14216
14217        GutterDimensions {
14218            left_padding,
14219            right_padding,
14220            width: line_gutter_width + left_padding + right_padding,
14221            margin: -descent,
14222            git_blame_entries_width,
14223        }
14224    }
14225
14226    pub fn render_crease_toggle(
14227        &self,
14228        buffer_row: MultiBufferRow,
14229        row_contains_cursor: bool,
14230        editor: View<Editor>,
14231        cx: &mut WindowContext,
14232    ) -> Option<AnyElement> {
14233        let folded = self.is_line_folded(buffer_row);
14234        let mut is_foldable = false;
14235
14236        if let Some(crease) = self
14237            .crease_snapshot
14238            .query_row(buffer_row, &self.buffer_snapshot)
14239        {
14240            is_foldable = true;
14241            match crease {
14242                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
14243                    if let Some(render_toggle) = render_toggle {
14244                        let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14245                            if folded {
14246                                editor.update(cx, |editor, cx| {
14247                                    editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14248                                });
14249                            } else {
14250                                editor.update(cx, |editor, cx| {
14251                                    editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14252                                });
14253                            }
14254                        });
14255                        return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
14256                    }
14257                }
14258            }
14259        }
14260
14261        is_foldable |= self.starts_indent(buffer_row);
14262
14263        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
14264            Some(
14265                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
14266                    .selected(folded)
14267                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14268                        if folded {
14269                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
14270                        } else {
14271                            this.fold_at(&FoldAt { buffer_row }, cx);
14272                        }
14273                    }))
14274                    .into_any_element(),
14275            )
14276        } else {
14277            None
14278        }
14279    }
14280
14281    pub fn render_crease_trailer(
14282        &self,
14283        buffer_row: MultiBufferRow,
14284        cx: &mut WindowContext,
14285    ) -> Option<AnyElement> {
14286        let folded = self.is_line_folded(buffer_row);
14287        if let Crease::Inline { render_trailer, .. } = self
14288            .crease_snapshot
14289            .query_row(buffer_row, &self.buffer_snapshot)?
14290        {
14291            let render_trailer = render_trailer.as_ref()?;
14292            Some(render_trailer(buffer_row, folded, cx))
14293        } else {
14294            None
14295        }
14296    }
14297}
14298
14299impl Deref for EditorSnapshot {
14300    type Target = DisplaySnapshot;
14301
14302    fn deref(&self) -> &Self::Target {
14303        &self.display_snapshot
14304    }
14305}
14306
14307#[derive(Clone, Debug, PartialEq, Eq)]
14308pub enum EditorEvent {
14309    InputIgnored {
14310        text: Arc<str>,
14311    },
14312    InputHandled {
14313        utf16_range_to_replace: Option<Range<isize>>,
14314        text: Arc<str>,
14315    },
14316    ExcerptsAdded {
14317        buffer: Model<Buffer>,
14318        predecessor: ExcerptId,
14319        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14320    },
14321    ExcerptsRemoved {
14322        ids: Vec<ExcerptId>,
14323    },
14324    ExcerptsEdited {
14325        ids: Vec<ExcerptId>,
14326    },
14327    ExcerptsExpanded {
14328        ids: Vec<ExcerptId>,
14329    },
14330    BufferEdited,
14331    Edited {
14332        transaction_id: clock::Lamport,
14333    },
14334    Reparsed(BufferId),
14335    Focused,
14336    FocusedIn,
14337    Blurred,
14338    DirtyChanged,
14339    Saved,
14340    TitleChanged,
14341    DiffBaseChanged,
14342    SelectionsChanged {
14343        local: bool,
14344    },
14345    ScrollPositionChanged {
14346        local: bool,
14347        autoscroll: bool,
14348    },
14349    Closed,
14350    TransactionUndone {
14351        transaction_id: clock::Lamport,
14352    },
14353    TransactionBegun {
14354        transaction_id: clock::Lamport,
14355    },
14356    Reloaded,
14357    CursorShapeChanged,
14358}
14359
14360impl EventEmitter<EditorEvent> for Editor {}
14361
14362impl FocusableView for Editor {
14363    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14364        self.focus_handle.clone()
14365    }
14366}
14367
14368impl Render for Editor {
14369    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14370        let settings = ThemeSettings::get_global(cx);
14371
14372        let mut text_style = match self.mode {
14373            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14374                color: cx.theme().colors().editor_foreground,
14375                font_family: settings.ui_font.family.clone(),
14376                font_features: settings.ui_font.features.clone(),
14377                font_fallbacks: settings.ui_font.fallbacks.clone(),
14378                font_size: rems(0.875).into(),
14379                font_weight: settings.ui_font.weight,
14380                line_height: relative(settings.buffer_line_height.value()),
14381                ..Default::default()
14382            },
14383            EditorMode::Full => TextStyle {
14384                color: cx.theme().colors().editor_foreground,
14385                font_family: settings.buffer_font.family.clone(),
14386                font_features: settings.buffer_font.features.clone(),
14387                font_fallbacks: settings.buffer_font.fallbacks.clone(),
14388                font_size: settings.buffer_font_size(cx).into(),
14389                font_weight: settings.buffer_font.weight,
14390                line_height: relative(settings.buffer_line_height.value()),
14391                ..Default::default()
14392            },
14393        };
14394        if let Some(text_style_refinement) = &self.text_style_refinement {
14395            text_style.refine(text_style_refinement)
14396        }
14397
14398        let background = match self.mode {
14399            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14400            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14401            EditorMode::Full => cx.theme().colors().editor_background,
14402        };
14403
14404        EditorElement::new(
14405            cx.view(),
14406            EditorStyle {
14407                background,
14408                local_player: cx.theme().players().local(),
14409                text: text_style,
14410                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14411                syntax: cx.theme().syntax().clone(),
14412                status: cx.theme().status().clone(),
14413                inlay_hints_style: make_inlay_hints_style(cx),
14414                suggestions_style: HighlightStyle {
14415                    color: Some(cx.theme().status().predictive),
14416                    ..HighlightStyle::default()
14417                },
14418                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14419            },
14420        )
14421    }
14422}
14423
14424impl ViewInputHandler for Editor {
14425    fn text_for_range(
14426        &mut self,
14427        range_utf16: Range<usize>,
14428        adjusted_range: &mut Option<Range<usize>>,
14429        cx: &mut ViewContext<Self>,
14430    ) -> Option<String> {
14431        let snapshot = self.buffer.read(cx).read(cx);
14432        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
14433        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
14434        if (start.0..end.0) != range_utf16 {
14435            adjusted_range.replace(start.0..end.0);
14436        }
14437        Some(snapshot.text_for_range(start..end).collect())
14438    }
14439
14440    fn selected_text_range(
14441        &mut self,
14442        ignore_disabled_input: bool,
14443        cx: &mut ViewContext<Self>,
14444    ) -> Option<UTF16Selection> {
14445        // Prevent the IME menu from appearing when holding down an alphabetic key
14446        // while input is disabled.
14447        if !ignore_disabled_input && !self.input_enabled {
14448            return None;
14449        }
14450
14451        let selection = self.selections.newest::<OffsetUtf16>(cx);
14452        let range = selection.range();
14453
14454        Some(UTF16Selection {
14455            range: range.start.0..range.end.0,
14456            reversed: selection.reversed,
14457        })
14458    }
14459
14460    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14461        let snapshot = self.buffer.read(cx).read(cx);
14462        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14463        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14464    }
14465
14466    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14467        self.clear_highlights::<InputComposition>(cx);
14468        self.ime_transaction.take();
14469    }
14470
14471    fn replace_text_in_range(
14472        &mut self,
14473        range_utf16: Option<Range<usize>>,
14474        text: &str,
14475        cx: &mut ViewContext<Self>,
14476    ) {
14477        if !self.input_enabled {
14478            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14479            return;
14480        }
14481
14482        self.transact(cx, |this, cx| {
14483            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14484                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14485                Some(this.selection_replacement_ranges(range_utf16, cx))
14486            } else {
14487                this.marked_text_ranges(cx)
14488            };
14489
14490            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14491                let newest_selection_id = this.selections.newest_anchor().id;
14492                this.selections
14493                    .all::<OffsetUtf16>(cx)
14494                    .iter()
14495                    .zip(ranges_to_replace.iter())
14496                    .find_map(|(selection, range)| {
14497                        if selection.id == newest_selection_id {
14498                            Some(
14499                                (range.start.0 as isize - selection.head().0 as isize)
14500                                    ..(range.end.0 as isize - selection.head().0 as isize),
14501                            )
14502                        } else {
14503                            None
14504                        }
14505                    })
14506            });
14507
14508            cx.emit(EditorEvent::InputHandled {
14509                utf16_range_to_replace: range_to_replace,
14510                text: text.into(),
14511            });
14512
14513            if let Some(new_selected_ranges) = new_selected_ranges {
14514                this.change_selections(None, cx, |selections| {
14515                    selections.select_ranges(new_selected_ranges)
14516                });
14517                this.backspace(&Default::default(), cx);
14518            }
14519
14520            this.handle_input(text, cx);
14521        });
14522
14523        if let Some(transaction) = self.ime_transaction {
14524            self.buffer.update(cx, |buffer, cx| {
14525                buffer.group_until_transaction(transaction, cx);
14526            });
14527        }
14528
14529        self.unmark_text(cx);
14530    }
14531
14532    fn replace_and_mark_text_in_range(
14533        &mut self,
14534        range_utf16: Option<Range<usize>>,
14535        text: &str,
14536        new_selected_range_utf16: Option<Range<usize>>,
14537        cx: &mut ViewContext<Self>,
14538    ) {
14539        if !self.input_enabled {
14540            return;
14541        }
14542
14543        let transaction = self.transact(cx, |this, cx| {
14544            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14545                let snapshot = this.buffer.read(cx).read(cx);
14546                if let Some(relative_range_utf16) = range_utf16.as_ref() {
14547                    for marked_range in &mut marked_ranges {
14548                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14549                        marked_range.start.0 += relative_range_utf16.start;
14550                        marked_range.start =
14551                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14552                        marked_range.end =
14553                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14554                    }
14555                }
14556                Some(marked_ranges)
14557            } else if let Some(range_utf16) = range_utf16 {
14558                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14559                Some(this.selection_replacement_ranges(range_utf16, cx))
14560            } else {
14561                None
14562            };
14563
14564            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14565                let newest_selection_id = this.selections.newest_anchor().id;
14566                this.selections
14567                    .all::<OffsetUtf16>(cx)
14568                    .iter()
14569                    .zip(ranges_to_replace.iter())
14570                    .find_map(|(selection, range)| {
14571                        if selection.id == newest_selection_id {
14572                            Some(
14573                                (range.start.0 as isize - selection.head().0 as isize)
14574                                    ..(range.end.0 as isize - selection.head().0 as isize),
14575                            )
14576                        } else {
14577                            None
14578                        }
14579                    })
14580            });
14581
14582            cx.emit(EditorEvent::InputHandled {
14583                utf16_range_to_replace: range_to_replace,
14584                text: text.into(),
14585            });
14586
14587            if let Some(ranges) = ranges_to_replace {
14588                this.change_selections(None, cx, |s| s.select_ranges(ranges));
14589            }
14590
14591            let marked_ranges = {
14592                let snapshot = this.buffer.read(cx).read(cx);
14593                this.selections
14594                    .disjoint_anchors()
14595                    .iter()
14596                    .map(|selection| {
14597                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14598                    })
14599                    .collect::<Vec<_>>()
14600            };
14601
14602            if text.is_empty() {
14603                this.unmark_text(cx);
14604            } else {
14605                this.highlight_text::<InputComposition>(
14606                    marked_ranges.clone(),
14607                    HighlightStyle {
14608                        underline: Some(UnderlineStyle {
14609                            thickness: px(1.),
14610                            color: None,
14611                            wavy: false,
14612                        }),
14613                        ..Default::default()
14614                    },
14615                    cx,
14616                );
14617            }
14618
14619            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14620            let use_autoclose = this.use_autoclose;
14621            let use_auto_surround = this.use_auto_surround;
14622            this.set_use_autoclose(false);
14623            this.set_use_auto_surround(false);
14624            this.handle_input(text, cx);
14625            this.set_use_autoclose(use_autoclose);
14626            this.set_use_auto_surround(use_auto_surround);
14627
14628            if let Some(new_selected_range) = new_selected_range_utf16 {
14629                let snapshot = this.buffer.read(cx).read(cx);
14630                let new_selected_ranges = marked_ranges
14631                    .into_iter()
14632                    .map(|marked_range| {
14633                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14634                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14635                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14636                        snapshot.clip_offset_utf16(new_start, Bias::Left)
14637                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14638                    })
14639                    .collect::<Vec<_>>();
14640
14641                drop(snapshot);
14642                this.change_selections(None, cx, |selections| {
14643                    selections.select_ranges(new_selected_ranges)
14644                });
14645            }
14646        });
14647
14648        self.ime_transaction = self.ime_transaction.or(transaction);
14649        if let Some(transaction) = self.ime_transaction {
14650            self.buffer.update(cx, |buffer, cx| {
14651                buffer.group_until_transaction(transaction, cx);
14652            });
14653        }
14654
14655        if self.text_highlights::<InputComposition>(cx).is_none() {
14656            self.ime_transaction.take();
14657        }
14658    }
14659
14660    fn bounds_for_range(
14661        &mut self,
14662        range_utf16: Range<usize>,
14663        element_bounds: gpui::Bounds<Pixels>,
14664        cx: &mut ViewContext<Self>,
14665    ) -> Option<gpui::Bounds<Pixels>> {
14666        let text_layout_details = self.text_layout_details(cx);
14667        let style = &text_layout_details.editor_style;
14668        let font_id = cx.text_system().resolve_font(&style.text.font());
14669        let font_size = style.text.font_size.to_pixels(cx.rem_size());
14670        let line_height = style.text.line_height_in_pixels(cx.rem_size());
14671
14672        let em_width = cx
14673            .text_system()
14674            .typographic_bounds(font_id, font_size, 'm')
14675            .unwrap()
14676            .size
14677            .width;
14678
14679        let snapshot = self.snapshot(cx);
14680        let scroll_position = snapshot.scroll_position();
14681        let scroll_left = scroll_position.x * em_width;
14682
14683        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14684        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14685            + self.gutter_dimensions.width;
14686        let y = line_height * (start.row().as_f32() - scroll_position.y);
14687
14688        Some(Bounds {
14689            origin: element_bounds.origin + point(x, y),
14690            size: size(em_width, line_height),
14691        })
14692    }
14693}
14694
14695trait SelectionExt {
14696    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14697    fn spanned_rows(
14698        &self,
14699        include_end_if_at_line_start: bool,
14700        map: &DisplaySnapshot,
14701    ) -> Range<MultiBufferRow>;
14702}
14703
14704impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14705    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14706        let start = self
14707            .start
14708            .to_point(&map.buffer_snapshot)
14709            .to_display_point(map);
14710        let end = self
14711            .end
14712            .to_point(&map.buffer_snapshot)
14713            .to_display_point(map);
14714        if self.reversed {
14715            end..start
14716        } else {
14717            start..end
14718        }
14719    }
14720
14721    fn spanned_rows(
14722        &self,
14723        include_end_if_at_line_start: bool,
14724        map: &DisplaySnapshot,
14725    ) -> Range<MultiBufferRow> {
14726        let start = self.start.to_point(&map.buffer_snapshot);
14727        let mut end = self.end.to_point(&map.buffer_snapshot);
14728        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14729            end.row -= 1;
14730        }
14731
14732        let buffer_start = map.prev_line_boundary(start).0;
14733        let buffer_end = map.next_line_boundary(end).0;
14734        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14735    }
14736}
14737
14738impl<T: InvalidationRegion> InvalidationStack<T> {
14739    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14740    where
14741        S: Clone + ToOffset,
14742    {
14743        while let Some(region) = self.last() {
14744            let all_selections_inside_invalidation_ranges =
14745                if selections.len() == region.ranges().len() {
14746                    selections
14747                        .iter()
14748                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14749                        .all(|(selection, invalidation_range)| {
14750                            let head = selection.head().to_offset(buffer);
14751                            invalidation_range.start <= head && invalidation_range.end >= head
14752                        })
14753                } else {
14754                    false
14755                };
14756
14757            if all_selections_inside_invalidation_ranges {
14758                break;
14759            } else {
14760                self.pop();
14761            }
14762        }
14763    }
14764}
14765
14766impl<T> Default for InvalidationStack<T> {
14767    fn default() -> Self {
14768        Self(Default::default())
14769    }
14770}
14771
14772impl<T> Deref for InvalidationStack<T> {
14773    type Target = Vec<T>;
14774
14775    fn deref(&self) -> &Self::Target {
14776        &self.0
14777    }
14778}
14779
14780impl<T> DerefMut for InvalidationStack<T> {
14781    fn deref_mut(&mut self) -> &mut Self::Target {
14782        &mut self.0
14783    }
14784}
14785
14786impl InvalidationRegion for SnippetState {
14787    fn ranges(&self) -> &[Range<Anchor>] {
14788        &self.ranges[self.active_index]
14789    }
14790}
14791
14792pub fn diagnostic_block_renderer(
14793    diagnostic: Diagnostic,
14794    max_message_rows: Option<u8>,
14795    allow_closing: bool,
14796    _is_valid: bool,
14797) -> RenderBlock {
14798    let (text_without_backticks, code_ranges) =
14799        highlight_diagnostic_message(&diagnostic, max_message_rows);
14800
14801    Arc::new(move |cx: &mut BlockContext| {
14802        let group_id: SharedString = cx.block_id.to_string().into();
14803
14804        let mut text_style = cx.text_style().clone();
14805        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14806        let theme_settings = ThemeSettings::get_global(cx);
14807        text_style.font_family = theme_settings.buffer_font.family.clone();
14808        text_style.font_style = theme_settings.buffer_font.style;
14809        text_style.font_features = theme_settings.buffer_font.features.clone();
14810        text_style.font_weight = theme_settings.buffer_font.weight;
14811
14812        let multi_line_diagnostic = diagnostic.message.contains('\n');
14813
14814        let buttons = |diagnostic: &Diagnostic| {
14815            if multi_line_diagnostic {
14816                v_flex()
14817            } else {
14818                h_flex()
14819            }
14820            .when(allow_closing, |div| {
14821                div.children(diagnostic.is_primary.then(|| {
14822                    IconButton::new("close-block", IconName::XCircle)
14823                        .icon_color(Color::Muted)
14824                        .size(ButtonSize::Compact)
14825                        .style(ButtonStyle::Transparent)
14826                        .visible_on_hover(group_id.clone())
14827                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14828                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14829                }))
14830            })
14831            .child(
14832                IconButton::new("copy-block", IconName::Copy)
14833                    .icon_color(Color::Muted)
14834                    .size(ButtonSize::Compact)
14835                    .style(ButtonStyle::Transparent)
14836                    .visible_on_hover(group_id.clone())
14837                    .on_click({
14838                        let message = diagnostic.message.clone();
14839                        move |_click, cx| {
14840                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14841                        }
14842                    })
14843                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14844            )
14845        };
14846
14847        let icon_size = buttons(&diagnostic)
14848            .into_any_element()
14849            .layout_as_root(AvailableSpace::min_size(), cx);
14850
14851        h_flex()
14852            .id(cx.block_id)
14853            .group(group_id.clone())
14854            .relative()
14855            .size_full()
14856            .block_mouse_down()
14857            .pl(cx.gutter_dimensions.width)
14858            .w(cx.max_width - cx.gutter_dimensions.full_width())
14859            .child(
14860                div()
14861                    .flex()
14862                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14863                    .flex_shrink(),
14864            )
14865            .child(buttons(&diagnostic))
14866            .child(div().flex().flex_shrink_0().child(
14867                StyledText::new(text_without_backticks.clone()).with_highlights(
14868                    &text_style,
14869                    code_ranges.iter().map(|range| {
14870                        (
14871                            range.clone(),
14872                            HighlightStyle {
14873                                font_weight: Some(FontWeight::BOLD),
14874                                ..Default::default()
14875                            },
14876                        )
14877                    }),
14878                ),
14879            ))
14880            .into_any_element()
14881    })
14882}
14883
14884pub fn highlight_diagnostic_message(
14885    diagnostic: &Diagnostic,
14886    mut max_message_rows: Option<u8>,
14887) -> (SharedString, Vec<Range<usize>>) {
14888    let mut text_without_backticks = String::new();
14889    let mut code_ranges = Vec::new();
14890
14891    if let Some(source) = &diagnostic.source {
14892        text_without_backticks.push_str(source);
14893        code_ranges.push(0..source.len());
14894        text_without_backticks.push_str(": ");
14895    }
14896
14897    let mut prev_offset = 0;
14898    let mut in_code_block = false;
14899    let has_row_limit = max_message_rows.is_some();
14900    let mut newline_indices = diagnostic
14901        .message
14902        .match_indices('\n')
14903        .filter(|_| has_row_limit)
14904        .map(|(ix, _)| ix)
14905        .fuse()
14906        .peekable();
14907
14908    for (quote_ix, _) in diagnostic
14909        .message
14910        .match_indices('`')
14911        .chain([(diagnostic.message.len(), "")])
14912    {
14913        let mut first_newline_ix = None;
14914        let mut last_newline_ix = None;
14915        while let Some(newline_ix) = newline_indices.peek() {
14916            if *newline_ix < quote_ix {
14917                if first_newline_ix.is_none() {
14918                    first_newline_ix = Some(*newline_ix);
14919                }
14920                last_newline_ix = Some(*newline_ix);
14921
14922                if let Some(rows_left) = &mut max_message_rows {
14923                    if *rows_left == 0 {
14924                        break;
14925                    } else {
14926                        *rows_left -= 1;
14927                    }
14928                }
14929                let _ = newline_indices.next();
14930            } else {
14931                break;
14932            }
14933        }
14934        let prev_len = text_without_backticks.len();
14935        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14936        text_without_backticks.push_str(new_text);
14937        if in_code_block {
14938            code_ranges.push(prev_len..text_without_backticks.len());
14939        }
14940        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14941        in_code_block = !in_code_block;
14942        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14943            text_without_backticks.push_str("...");
14944            break;
14945        }
14946    }
14947
14948    (text_without_backticks.into(), code_ranges)
14949}
14950
14951fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14952    match severity {
14953        DiagnosticSeverity::ERROR => colors.error,
14954        DiagnosticSeverity::WARNING => colors.warning,
14955        DiagnosticSeverity::INFORMATION => colors.info,
14956        DiagnosticSeverity::HINT => colors.info,
14957        _ => colors.ignored,
14958    }
14959}
14960
14961pub fn styled_runs_for_code_label<'a>(
14962    label: &'a CodeLabel,
14963    syntax_theme: &'a theme::SyntaxTheme,
14964) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14965    let fade_out = HighlightStyle {
14966        fade_out: Some(0.35),
14967        ..Default::default()
14968    };
14969
14970    let mut prev_end = label.filter_range.end;
14971    label
14972        .runs
14973        .iter()
14974        .enumerate()
14975        .flat_map(move |(ix, (range, highlight_id))| {
14976            let style = if let Some(style) = highlight_id.style(syntax_theme) {
14977                style
14978            } else {
14979                return Default::default();
14980            };
14981            let mut muted_style = style;
14982            muted_style.highlight(fade_out);
14983
14984            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14985            if range.start >= label.filter_range.end {
14986                if range.start > prev_end {
14987                    runs.push((prev_end..range.start, fade_out));
14988                }
14989                runs.push((range.clone(), muted_style));
14990            } else if range.end <= label.filter_range.end {
14991                runs.push((range.clone(), style));
14992            } else {
14993                runs.push((range.start..label.filter_range.end, style));
14994                runs.push((label.filter_range.end..range.end, muted_style));
14995            }
14996            prev_end = cmp::max(prev_end, range.end);
14997
14998            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14999                runs.push((prev_end..label.text.len(), fade_out));
15000            }
15001
15002            runs
15003        })
15004}
15005
15006pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
15007    let mut prev_index = 0;
15008    let mut prev_codepoint: Option<char> = None;
15009    text.char_indices()
15010        .chain([(text.len(), '\0')])
15011        .filter_map(move |(index, codepoint)| {
15012            let prev_codepoint = prev_codepoint.replace(codepoint)?;
15013            let is_boundary = index == text.len()
15014                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
15015                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
15016            if is_boundary {
15017                let chunk = &text[prev_index..index];
15018                prev_index = index;
15019                Some(chunk)
15020            } else {
15021                None
15022            }
15023        })
15024}
15025
15026pub trait RangeToAnchorExt: Sized {
15027    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
15028
15029    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
15030        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
15031        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
15032    }
15033}
15034
15035impl<T: ToOffset> RangeToAnchorExt for Range<T> {
15036    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
15037        let start_offset = self.start.to_offset(snapshot);
15038        let end_offset = self.end.to_offset(snapshot);
15039        if start_offset == end_offset {
15040            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
15041        } else {
15042            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
15043        }
15044    }
15045}
15046
15047pub trait RowExt {
15048    fn as_f32(&self) -> f32;
15049
15050    fn next_row(&self) -> Self;
15051
15052    fn previous_row(&self) -> Self;
15053
15054    fn minus(&self, other: Self) -> u32;
15055}
15056
15057impl RowExt for DisplayRow {
15058    fn as_f32(&self) -> f32 {
15059        self.0 as f32
15060    }
15061
15062    fn next_row(&self) -> Self {
15063        Self(self.0 + 1)
15064    }
15065
15066    fn previous_row(&self) -> Self {
15067        Self(self.0.saturating_sub(1))
15068    }
15069
15070    fn minus(&self, other: Self) -> u32 {
15071        self.0 - other.0
15072    }
15073}
15074
15075impl RowExt for MultiBufferRow {
15076    fn as_f32(&self) -> f32 {
15077        self.0 as f32
15078    }
15079
15080    fn next_row(&self) -> Self {
15081        Self(self.0 + 1)
15082    }
15083
15084    fn previous_row(&self) -> Self {
15085        Self(self.0.saturating_sub(1))
15086    }
15087
15088    fn minus(&self, other: Self) -> u32 {
15089        self.0 - other.0
15090    }
15091}
15092
15093trait RowRangeExt {
15094    type Row;
15095
15096    fn len(&self) -> usize;
15097
15098    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
15099}
15100
15101impl RowRangeExt for Range<MultiBufferRow> {
15102    type Row = MultiBufferRow;
15103
15104    fn len(&self) -> usize {
15105        (self.end.0 - self.start.0) as usize
15106    }
15107
15108    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
15109        (self.start.0..self.end.0).map(MultiBufferRow)
15110    }
15111}
15112
15113impl RowRangeExt for Range<DisplayRow> {
15114    type Row = DisplayRow;
15115
15116    fn len(&self) -> usize {
15117        (self.end.0 - self.start.0) as usize
15118    }
15119
15120    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
15121        (self.start.0..self.end.0).map(DisplayRow)
15122    }
15123}
15124
15125fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
15126    if hunk.diff_base_byte_range.is_empty() {
15127        DiffHunkStatus::Added
15128    } else if hunk.row_range.is_empty() {
15129        DiffHunkStatus::Removed
15130    } else {
15131        DiffHunkStatus::Modified
15132    }
15133}
15134
15135/// If select range has more than one line, we
15136/// just point the cursor to range.start.
15137fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
15138    if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
15139        range
15140    } else {
15141        range.start..range.start
15142    }
15143}
15144
15145pub struct KillRing(ClipboardItem);
15146impl Global for KillRing {}
15147
15148const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);