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 debounced_delay;
   19pub mod display_map;
   20mod editor_settings;
   21mod editor_settings_controls;
   22mod element;
   23mod git;
   24mod highlight_matching_bracket;
   25mod hover_links;
   26mod hover_popover;
   27mod hunk_diff;
   28mod indent_guides;
   29mod inlay_hint_cache;
   30mod inline_completion_provider;
   31pub mod items;
   32mod linked_editing_ranges;
   33mod mouse_context_menu;
   34pub mod movement;
   35mod persistence;
   36mod rust_analyzer_ext;
   37pub mod scroll;
   38mod selections_collection;
   39pub mod tasks;
   40
   41#[cfg(test)]
   42mod editor_tests;
   43mod signature_help;
   44#[cfg(any(test, feature = "test-support"))]
   45pub mod test;
   46
   47use ::git::diff::{DiffHunk, DiffHunkStatus};
   48use ::git::{parse_git_remote_url, BuildPermalinkParams, GitHostingProviderRegistry};
   49pub(crate) use actions::*;
   50use aho_corasick::AhoCorasick;
   51use anyhow::{anyhow, Context as _, Result};
   52use blink_manager::BlinkManager;
   53use client::{Collaborator, ParticipantIndex};
   54use clock::ReplicaId;
   55use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
   56use convert_case::{Case, Casing};
   57use debounced_delay::DebouncedDelay;
   58use display_map::*;
   59pub use display_map::{DisplayPoint, FoldPlaceholder};
   60pub use editor_settings::{CurrentLineHighlight, EditorSettings};
   61pub use editor_settings_controls::*;
   62use element::LineWithInvisibles;
   63pub use element::{
   64    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   65};
   66use futures::FutureExt;
   67use fuzzy::{StringMatch, StringMatchCandidate};
   68use git::blame::GitBlame;
   69use git::diff_hunk_to_display;
   70use gpui::{
   71    div, impl_actions, point, prelude::*, px, relative, size, uniform_list, Action, AnyElement,
   72    AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds, ClipboardItem,
   73    Context, DispatchPhase, ElementId, EntityId, EventEmitter, FocusHandle, FocusOutEvent,
   74    FocusableView, FontId, FontWeight, HighlightStyle, Hsla, InteractiveText, KeyContext,
   75    ListSizingBehavior, Model, MouseButton, PaintQuad, ParentElement, Pixels, Render, SharedString,
   76    Size, StrikethroughStyle, Styled, StyledText, Subscription, Task, TextStyle, UnderlineStyle,
   77    UniformListScrollHandle, View, ViewContext, ViewInputHandler, VisualContext, WeakFocusHandle,
   78    WeakView, WindowContext,
   79};
   80use highlight_matching_bracket::refresh_matching_bracket_highlights;
   81use hover_popover::{hide_hover, HoverState};
   82use hunk_diff::ExpandedHunks;
   83pub(crate) use hunk_diff::HoveredHunk;
   84use indent_guides::ActiveIndentGuidesState;
   85use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   86pub use inline_completion_provider::*;
   87pub use items::MAX_TAB_TITLE_LEN;
   88use itertools::Itertools;
   89use language::{
   90    char_kind,
   91    language_settings::{self, all_language_settings, InlayHintSettings},
   92    markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
   93    CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
   94    Point, Selection, SelectionGoal, TransactionId,
   95};
   96use language::{point_to_lsp, BufferRow, Runnable, RunnableRange};
   97use linked_editing_ranges::refresh_linked_ranges;
   98use task::{ResolvedTask, TaskTemplate, TaskVariables};
   99
  100use hover_links::{HoverLink, HoveredLinkState, InlayHighlight};
  101pub use lsp::CompletionContext;
  102use lsp::{
  103    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  104    LanguageServerId,
  105};
  106use mouse_context_menu::MouseContextMenu;
  107use movement::TextLayoutDetails;
  108pub use multi_buffer::{
  109    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
  110    ToPoint,
  111};
  112use multi_buffer::{ExpandExcerptDirection, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16};
  113use ordered_float::OrderedFloat;
  114use parking_lot::{Mutex, RwLock};
  115use project::project_settings::{GitGutterSetting, ProjectSettings};
  116use project::{
  117    CodeAction, Completion, FormatTrigger, Item, Location, Project, ProjectPath,
  118    ProjectTransaction, TaskSourceKind, WorktreeId,
  119};
  120use rand::prelude::*;
  121use rpc::{proto::*, ErrorExt};
  122use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  123use selections_collection::{resolve_multiple, MutableSelectionsCollection, SelectionsCollection};
  124use serde::{Deserialize, Serialize};
  125use settings::{update_settings_file, Settings, SettingsStore};
  126use smallvec::SmallVec;
  127use snippet::Snippet;
  128use std::{
  129    any::TypeId,
  130    borrow::Cow,
  131    cell::RefCell,
  132    cmp::{self, Ordering, Reverse},
  133    mem,
  134    num::NonZeroU32,
  135    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  136    path::{Path, PathBuf},
  137    rc::Rc,
  138    sync::Arc,
  139    time::{Duration, Instant},
  140};
  141pub use sum_tree::Bias;
  142use sum_tree::TreeMap;
  143use text::{BufferId, OffsetUtf16, Rope};
  144use theme::{
  145    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  146    ThemeColors, ThemeSettings,
  147};
  148use ui::{
  149    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
  150    ListItem, Popover, Tooltip,
  151};
  152use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  153use workspace::item::{ItemHandle, PreviewTabsSettings};
  154use workspace::notifications::{DetachAndPromptErr, NotificationId};
  155use workspace::{
  156    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  157};
  158use workspace::{OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  159
  160use crate::hover_links::find_url;
  161use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  162
  163pub const FILE_HEADER_HEIGHT: u8 = 1;
  164pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u8 = 1;
  165pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u8 = 1;
  166pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  167const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  168const MAX_LINE_LEN: usize = 1024;
  169const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  170const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  171pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  172#[doc(hidden)]
  173pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  174#[doc(hidden)]
  175pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
  176
  177pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  178
  179pub fn render_parsed_markdown(
  180    element_id: impl Into<ElementId>,
  181    parsed: &language::ParsedMarkdown,
  182    editor_style: &EditorStyle,
  183    workspace: Option<WeakView<Workspace>>,
  184    cx: &mut WindowContext,
  185) -> InteractiveText {
  186    let code_span_background_color = cx
  187        .theme()
  188        .colors()
  189        .editor_document_highlight_read_background;
  190
  191    let highlights = gpui::combine_highlights(
  192        parsed.highlights.iter().filter_map(|(range, highlight)| {
  193            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  194            Some((range.clone(), highlight))
  195        }),
  196        parsed
  197            .regions
  198            .iter()
  199            .zip(&parsed.region_ranges)
  200            .filter_map(|(region, range)| {
  201                if region.code {
  202                    Some((
  203                        range.clone(),
  204                        HighlightStyle {
  205                            background_color: Some(code_span_background_color),
  206                            ..Default::default()
  207                        },
  208                    ))
  209                } else {
  210                    None
  211                }
  212            }),
  213    );
  214
  215    let mut links = Vec::new();
  216    let mut link_ranges = Vec::new();
  217    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  218        if let Some(link) = region.link.clone() {
  219            links.push(link);
  220            link_ranges.push(range.clone());
  221        }
  222    }
  223
  224    InteractiveText::new(
  225        element_id,
  226        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  227    )
  228    .on_click(link_ranges, move |clicked_range_ix, cx| {
  229        match &links[clicked_range_ix] {
  230            markdown::Link::Web { url } => cx.open_url(url),
  231            markdown::Link::Path { path } => {
  232                if let Some(workspace) = &workspace {
  233                    _ = workspace.update(cx, |workspace, cx| {
  234                        workspace.open_abs_path(path.clone(), false, cx).detach();
  235                    });
  236                }
  237            }
  238        }
  239    })
  240}
  241
  242#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  243pub(crate) enum InlayId {
  244    Suggestion(usize),
  245    Hint(usize),
  246}
  247
  248impl InlayId {
  249    fn id(&self) -> usize {
  250        match self {
  251            Self::Suggestion(id) => *id,
  252            Self::Hint(id) => *id,
  253        }
  254    }
  255}
  256
  257enum DiffRowHighlight {}
  258enum DocumentHighlightRead {}
  259enum DocumentHighlightWrite {}
  260enum InputComposition {}
  261
  262#[derive(Copy, Clone, PartialEq, Eq)]
  263pub enum Direction {
  264    Prev,
  265    Next,
  266}
  267
  268pub fn init_settings(cx: &mut AppContext) {
  269    EditorSettings::register(cx);
  270}
  271
  272pub fn init(cx: &mut AppContext) {
  273    init_settings(cx);
  274
  275    workspace::register_project_item::<Editor>(cx);
  276    workspace::FollowableViewRegistry::register::<Editor>(cx);
  277    workspace::register_serializable_item::<Editor>(cx);
  278
  279    cx.observe_new_views(
  280        |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
  281            workspace.register_action(Editor::new_file);
  282            workspace.register_action(Editor::new_file_in_direction);
  283        },
  284    )
  285    .detach();
  286
  287    cx.on_action(move |_: &workspace::NewFile, cx| {
  288        let app_state = workspace::AppState::global(cx);
  289        if let Some(app_state) = app_state.upgrade() {
  290            workspace::open_new(app_state, cx, |workspace, cx| {
  291                Editor::new_file(workspace, &Default::default(), cx)
  292            })
  293            .detach();
  294        }
  295    });
  296    cx.on_action(move |_: &workspace::NewWindow, cx| {
  297        let app_state = workspace::AppState::global(cx);
  298        if let Some(app_state) = app_state.upgrade() {
  299            workspace::open_new(app_state, cx, |workspace, cx| {
  300                Editor::new_file(workspace, &Default::default(), cx)
  301            })
  302            .detach();
  303        }
  304    });
  305}
  306
  307pub struct SearchWithinRange;
  308
  309trait InvalidationRegion {
  310    fn ranges(&self) -> &[Range<Anchor>];
  311}
  312
  313#[derive(Clone, Debug, PartialEq)]
  314pub enum SelectPhase {
  315    Begin {
  316        position: DisplayPoint,
  317        add: bool,
  318        click_count: usize,
  319    },
  320    BeginColumnar {
  321        position: DisplayPoint,
  322        reset: bool,
  323        goal_column: u32,
  324    },
  325    Extend {
  326        position: DisplayPoint,
  327        click_count: usize,
  328    },
  329    Update {
  330        position: DisplayPoint,
  331        goal_column: u32,
  332        scroll_delta: gpui::Point<f32>,
  333    },
  334    End,
  335}
  336
  337#[derive(Clone, Debug)]
  338pub enum SelectMode {
  339    Character,
  340    Word(Range<Anchor>),
  341    Line(Range<Anchor>),
  342    All,
  343}
  344
  345#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  346pub enum EditorMode {
  347    SingleLine { auto_width: bool },
  348    AutoHeight { max_lines: usize },
  349    Full,
  350}
  351
  352#[derive(Clone, Debug)]
  353pub enum SoftWrap {
  354    None,
  355    PreferLine,
  356    EditorWidth,
  357    Column(u32),
  358}
  359
  360#[derive(Clone)]
  361pub struct EditorStyle {
  362    pub background: Hsla,
  363    pub local_player: PlayerColor,
  364    pub text: TextStyle,
  365    pub scrollbar_width: Pixels,
  366    pub syntax: Arc<SyntaxTheme>,
  367    pub status: StatusColors,
  368    pub inlay_hints_style: HighlightStyle,
  369    pub suggestions_style: HighlightStyle,
  370}
  371
  372impl Default for EditorStyle {
  373    fn default() -> Self {
  374        Self {
  375            background: Hsla::default(),
  376            local_player: PlayerColor::default(),
  377            text: TextStyle::default(),
  378            scrollbar_width: Pixels::default(),
  379            syntax: Default::default(),
  380            // HACK: Status colors don't have a real default.
  381            // We should look into removing the status colors from the editor
  382            // style and retrieve them directly from the theme.
  383            status: StatusColors::dark(),
  384            inlay_hints_style: HighlightStyle::default(),
  385            suggestions_style: HighlightStyle::default(),
  386        }
  387    }
  388}
  389
  390type CompletionId = usize;
  391
  392#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  393struct EditorActionId(usize);
  394
  395impl EditorActionId {
  396    pub fn post_inc(&mut self) -> Self {
  397        let answer = self.0;
  398
  399        *self = Self(answer + 1);
  400
  401        Self(answer)
  402    }
  403}
  404
  405// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  406// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  407
  408type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  409type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
  410
  411struct ScrollbarMarkerState {
  412    scrollbar_size: Size<Pixels>,
  413    dirty: bool,
  414    markers: Arc<[PaintQuad]>,
  415    pending_refresh: Option<Task<Result<()>>>,
  416}
  417
  418impl ScrollbarMarkerState {
  419    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  420        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  421    }
  422}
  423
  424impl Default for ScrollbarMarkerState {
  425    fn default() -> Self {
  426        Self {
  427            scrollbar_size: Size::default(),
  428            dirty: false,
  429            markers: Arc::from([]),
  430            pending_refresh: None,
  431        }
  432    }
  433}
  434
  435#[derive(Clone, Debug)]
  436struct RunnableTasks {
  437    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  438    offset: MultiBufferOffset,
  439    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  440    column: u32,
  441    // Values of all named captures, including those starting with '_'
  442    extra_variables: HashMap<String, String>,
  443    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  444    context_range: Range<BufferOffset>,
  445}
  446
  447#[derive(Clone)]
  448struct ResolvedTasks {
  449    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  450    position: Anchor,
  451}
  452#[derive(Copy, Clone, Debug)]
  453struct MultiBufferOffset(usize);
  454#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  455struct BufferOffset(usize);
  456/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
  457///
  458/// See the [module level documentation](self) for more information.
  459pub struct Editor {
  460    focus_handle: FocusHandle,
  461    last_focused_descendant: Option<WeakFocusHandle>,
  462    /// The text buffer being edited
  463    buffer: Model<MultiBuffer>,
  464    /// Map of how text in the buffer should be displayed.
  465    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  466    pub display_map: Model<DisplayMap>,
  467    pub selections: SelectionsCollection,
  468    pub scroll_manager: ScrollManager,
  469    /// When inline assist editors are linked, they all render cursors because
  470    /// typing enters text into each of them, even the ones that aren't focused.
  471    pub(crate) show_cursor_when_unfocused: bool,
  472    columnar_selection_tail: Option<Anchor>,
  473    add_selections_state: Option<AddSelectionsState>,
  474    select_next_state: Option<SelectNextState>,
  475    select_prev_state: Option<SelectNextState>,
  476    selection_history: SelectionHistory,
  477    autoclose_regions: Vec<AutocloseRegion>,
  478    snippet_stack: InvalidationStack<SnippetState>,
  479    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  480    ime_transaction: Option<TransactionId>,
  481    active_diagnostics: Option<ActiveDiagnosticGroup>,
  482    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  483    project: Option<Model<Project>>,
  484    completion_provider: Option<Box<dyn CompletionProvider>>,
  485    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  486    blink_manager: Model<BlinkManager>,
  487    show_cursor_names: bool,
  488    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  489    pub show_local_selections: bool,
  490    mode: EditorMode,
  491    show_breadcrumbs: bool,
  492    show_gutter: bool,
  493    redact_all: bool,
  494    show_line_numbers: Option<bool>,
  495    show_git_diff_gutter: Option<bool>,
  496    show_code_actions: Option<bool>,
  497    show_runnables: Option<bool>,
  498    show_wrap_guides: Option<bool>,
  499    show_indent_guides: Option<bool>,
  500    placeholder_text: Option<Arc<str>>,
  501    highlight_order: usize,
  502    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  503    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  504    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  505    scrollbar_marker_state: ScrollbarMarkerState,
  506    active_indent_guides_state: ActiveIndentGuidesState,
  507    nav_history: Option<ItemNavHistory>,
  508    context_menu: RwLock<Option<ContextMenu>>,
  509    mouse_context_menu: Option<MouseContextMenu>,
  510    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  511    signature_help_state: SignatureHelpState,
  512    auto_signature_help: Option<bool>,
  513    find_all_references_task_sources: Vec<Anchor>,
  514    next_completion_id: CompletionId,
  515    completion_documentation_pre_resolve_debounce: DebouncedDelay,
  516    available_code_actions: Option<(Location, Arc<[CodeAction]>)>,
  517    code_actions_task: Option<Task<()>>,
  518    document_highlights_task: Option<Task<()>>,
  519    linked_editing_range_task: Option<Task<Option<()>>>,
  520    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  521    pending_rename: Option<RenameState>,
  522    searchable: bool,
  523    cursor_shape: CursorShape,
  524    current_line_highlight: Option<CurrentLineHighlight>,
  525    collapse_matches: bool,
  526    autoindent_mode: Option<AutoindentMode>,
  527    workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
  528    keymap_context_layers: BTreeMap<TypeId, KeyContext>,
  529    input_enabled: bool,
  530    use_modal_editing: bool,
  531    read_only: bool,
  532    leader_peer_id: Option<PeerId>,
  533    remote_id: Option<ViewId>,
  534    hover_state: HoverState,
  535    gutter_hovered: bool,
  536    hovered_link_state: Option<HoveredLinkState>,
  537    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  538    active_inline_completion: Option<(Inlay, Option<Range<Anchor>>)>,
  539    show_inline_completions: bool,
  540    inlay_hint_cache: InlayHintCache,
  541    expanded_hunks: ExpandedHunks,
  542    next_inlay_id: usize,
  543    _subscriptions: Vec<Subscription>,
  544    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  545    gutter_dimensions: GutterDimensions,
  546    pub vim_replace_map: HashMap<Range<usize>, String>,
  547    style: Option<EditorStyle>,
  548    next_editor_action_id: EditorActionId,
  549    editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
  550    use_autoclose: bool,
  551    use_auto_surround: bool,
  552    auto_replace_emoji_shortcode: bool,
  553    show_git_blame_gutter: bool,
  554    show_git_blame_inline: bool,
  555    show_git_blame_inline_delay_task: Option<Task<()>>,
  556    git_blame_inline_enabled: bool,
  557    serialize_dirty_buffers: bool,
  558    show_selection_menu: Option<bool>,
  559    blame: Option<Model<GitBlame>>,
  560    blame_subscription: Option<Subscription>,
  561    custom_context_menu: Option<
  562        Box<
  563            dyn 'static
  564                + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
  565        >,
  566    >,
  567    last_bounds: Option<Bounds<Pixels>>,
  568    expect_bounds_change: Option<Bounds<Pixels>>,
  569    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  570    tasks_update_task: Option<Task<()>>,
  571    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  572    file_header_size: u8,
  573    breadcrumb_header: Option<String>,
  574    focused_block: Option<FocusedBlock>,
  575}
  576
  577#[derive(Clone)]
  578pub struct EditorSnapshot {
  579    pub mode: EditorMode,
  580    show_gutter: bool,
  581    show_line_numbers: Option<bool>,
  582    show_git_diff_gutter: Option<bool>,
  583    show_code_actions: Option<bool>,
  584    show_runnables: Option<bool>,
  585    render_git_blame_gutter: bool,
  586    pub display_snapshot: DisplaySnapshot,
  587    pub placeholder_text: Option<Arc<str>>,
  588    is_focused: bool,
  589    scroll_anchor: ScrollAnchor,
  590    ongoing_scroll: OngoingScroll,
  591    current_line_highlight: CurrentLineHighlight,
  592    gutter_hovered: bool,
  593}
  594
  595const GIT_BLAME_GUTTER_WIDTH_CHARS: f32 = 53.;
  596
  597#[derive(Default, Debug, Clone, Copy)]
  598pub struct GutterDimensions {
  599    pub left_padding: Pixels,
  600    pub right_padding: Pixels,
  601    pub width: Pixels,
  602    pub margin: Pixels,
  603    pub git_blame_entries_width: Option<Pixels>,
  604}
  605
  606impl GutterDimensions {
  607    /// The full width of the space taken up by the gutter.
  608    pub fn full_width(&self) -> Pixels {
  609        self.margin + self.width
  610    }
  611
  612    /// The width of the space reserved for the fold indicators,
  613    /// use alongside 'justify_end' and `gutter_width` to
  614    /// right align content with the line numbers
  615    pub fn fold_area_width(&self) -> Pixels {
  616        self.margin + self.right_padding
  617    }
  618}
  619
  620#[derive(Debug)]
  621pub struct RemoteSelection {
  622    pub replica_id: ReplicaId,
  623    pub selection: Selection<Anchor>,
  624    pub cursor_shape: CursorShape,
  625    pub peer_id: PeerId,
  626    pub line_mode: bool,
  627    pub participant_index: Option<ParticipantIndex>,
  628    pub user_name: Option<SharedString>,
  629}
  630
  631#[derive(Clone, Debug)]
  632struct SelectionHistoryEntry {
  633    selections: Arc<[Selection<Anchor>]>,
  634    select_next_state: Option<SelectNextState>,
  635    select_prev_state: Option<SelectNextState>,
  636    add_selections_state: Option<AddSelectionsState>,
  637}
  638
  639enum SelectionHistoryMode {
  640    Normal,
  641    Undoing,
  642    Redoing,
  643}
  644
  645#[derive(Clone, PartialEq, Eq, Hash)]
  646struct HoveredCursor {
  647    replica_id: u16,
  648    selection_id: usize,
  649}
  650
  651impl Default for SelectionHistoryMode {
  652    fn default() -> Self {
  653        Self::Normal
  654    }
  655}
  656
  657#[derive(Default)]
  658struct SelectionHistory {
  659    #[allow(clippy::type_complexity)]
  660    selections_by_transaction:
  661        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  662    mode: SelectionHistoryMode,
  663    undo_stack: VecDeque<SelectionHistoryEntry>,
  664    redo_stack: VecDeque<SelectionHistoryEntry>,
  665}
  666
  667impl SelectionHistory {
  668    fn insert_transaction(
  669        &mut self,
  670        transaction_id: TransactionId,
  671        selections: Arc<[Selection<Anchor>]>,
  672    ) {
  673        self.selections_by_transaction
  674            .insert(transaction_id, (selections, None));
  675    }
  676
  677    #[allow(clippy::type_complexity)]
  678    fn transaction(
  679        &self,
  680        transaction_id: TransactionId,
  681    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  682        self.selections_by_transaction.get(&transaction_id)
  683    }
  684
  685    #[allow(clippy::type_complexity)]
  686    fn transaction_mut(
  687        &mut self,
  688        transaction_id: TransactionId,
  689    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  690        self.selections_by_transaction.get_mut(&transaction_id)
  691    }
  692
  693    fn push(&mut self, entry: SelectionHistoryEntry) {
  694        if !entry.selections.is_empty() {
  695            match self.mode {
  696                SelectionHistoryMode::Normal => {
  697                    self.push_undo(entry);
  698                    self.redo_stack.clear();
  699                }
  700                SelectionHistoryMode::Undoing => self.push_redo(entry),
  701                SelectionHistoryMode::Redoing => self.push_undo(entry),
  702            }
  703        }
  704    }
  705
  706    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  707        if self
  708            .undo_stack
  709            .back()
  710            .map_or(true, |e| e.selections != entry.selections)
  711        {
  712            self.undo_stack.push_back(entry);
  713            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  714                self.undo_stack.pop_front();
  715            }
  716        }
  717    }
  718
  719    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  720        if self
  721            .redo_stack
  722            .back()
  723            .map_or(true, |e| e.selections != entry.selections)
  724        {
  725            self.redo_stack.push_back(entry);
  726            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  727                self.redo_stack.pop_front();
  728            }
  729        }
  730    }
  731}
  732
  733struct RowHighlight {
  734    index: usize,
  735    range: RangeInclusive<Anchor>,
  736    color: Option<Hsla>,
  737    should_autoscroll: bool,
  738}
  739
  740#[derive(Clone, Debug)]
  741struct AddSelectionsState {
  742    above: bool,
  743    stack: Vec<usize>,
  744}
  745
  746#[derive(Clone)]
  747struct SelectNextState {
  748    query: AhoCorasick,
  749    wordwise: bool,
  750    done: bool,
  751}
  752
  753impl std::fmt::Debug for SelectNextState {
  754    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  755        f.debug_struct(std::any::type_name::<Self>())
  756            .field("wordwise", &self.wordwise)
  757            .field("done", &self.done)
  758            .finish()
  759    }
  760}
  761
  762#[derive(Debug)]
  763struct AutocloseRegion {
  764    selection_id: usize,
  765    range: Range<Anchor>,
  766    pair: BracketPair,
  767}
  768
  769#[derive(Debug)]
  770struct SnippetState {
  771    ranges: Vec<Vec<Range<Anchor>>>,
  772    active_index: usize,
  773}
  774
  775#[doc(hidden)]
  776pub struct RenameState {
  777    pub range: Range<Anchor>,
  778    pub old_name: Arc<str>,
  779    pub editor: View<Editor>,
  780    block_id: CustomBlockId,
  781}
  782
  783struct InvalidationStack<T>(Vec<T>);
  784
  785struct RegisteredInlineCompletionProvider {
  786    provider: Arc<dyn InlineCompletionProviderHandle>,
  787    _subscription: Subscription,
  788}
  789
  790enum ContextMenu {
  791    Completions(CompletionsMenu),
  792    CodeActions(CodeActionsMenu),
  793}
  794
  795impl ContextMenu {
  796    fn select_first(
  797        &mut self,
  798        project: Option<&Model<Project>>,
  799        cx: &mut ViewContext<Editor>,
  800    ) -> bool {
  801        if self.visible() {
  802            match self {
  803                ContextMenu::Completions(menu) => menu.select_first(project, cx),
  804                ContextMenu::CodeActions(menu) => menu.select_first(cx),
  805            }
  806            true
  807        } else {
  808            false
  809        }
  810    }
  811
  812    fn select_prev(
  813        &mut self,
  814        project: Option<&Model<Project>>,
  815        cx: &mut ViewContext<Editor>,
  816    ) -> bool {
  817        if self.visible() {
  818            match self {
  819                ContextMenu::Completions(menu) => menu.select_prev(project, cx),
  820                ContextMenu::CodeActions(menu) => menu.select_prev(cx),
  821            }
  822            true
  823        } else {
  824            false
  825        }
  826    }
  827
  828    fn select_next(
  829        &mut self,
  830        project: Option<&Model<Project>>,
  831        cx: &mut ViewContext<Editor>,
  832    ) -> bool {
  833        if self.visible() {
  834            match self {
  835                ContextMenu::Completions(menu) => menu.select_next(project, cx),
  836                ContextMenu::CodeActions(menu) => menu.select_next(cx),
  837            }
  838            true
  839        } else {
  840            false
  841        }
  842    }
  843
  844    fn select_last(
  845        &mut self,
  846        project: Option<&Model<Project>>,
  847        cx: &mut ViewContext<Editor>,
  848    ) -> bool {
  849        if self.visible() {
  850            match self {
  851                ContextMenu::Completions(menu) => menu.select_last(project, cx),
  852                ContextMenu::CodeActions(menu) => menu.select_last(cx),
  853            }
  854            true
  855        } else {
  856            false
  857        }
  858    }
  859
  860    fn visible(&self) -> bool {
  861        match self {
  862            ContextMenu::Completions(menu) => menu.visible(),
  863            ContextMenu::CodeActions(menu) => menu.visible(),
  864        }
  865    }
  866
  867    fn render(
  868        &self,
  869        cursor_position: DisplayPoint,
  870        style: &EditorStyle,
  871        max_height: Pixels,
  872        workspace: Option<WeakView<Workspace>>,
  873        cx: &mut ViewContext<Editor>,
  874    ) -> (ContextMenuOrigin, AnyElement) {
  875        match self {
  876            ContextMenu::Completions(menu) => (
  877                ContextMenuOrigin::EditorPoint(cursor_position),
  878                menu.render(style, max_height, workspace, cx),
  879            ),
  880            ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
  881        }
  882    }
  883}
  884
  885enum ContextMenuOrigin {
  886    EditorPoint(DisplayPoint),
  887    GutterIndicator(DisplayRow),
  888}
  889
  890#[derive(Clone)]
  891struct CompletionsMenu {
  892    id: CompletionId,
  893    initial_position: Anchor,
  894    buffer: Model<Buffer>,
  895    completions: Arc<RwLock<Box<[Completion]>>>,
  896    match_candidates: Arc<[StringMatchCandidate]>,
  897    matches: Arc<[StringMatch]>,
  898    selected_item: usize,
  899    scroll_handle: UniformListScrollHandle,
  900    selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
  901}
  902
  903impl CompletionsMenu {
  904    fn select_first(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
  905        self.selected_item = 0;
  906        self.scroll_handle.scroll_to_item(self.selected_item);
  907        self.attempt_resolve_selected_completion_documentation(project, cx);
  908        cx.notify();
  909    }
  910
  911    fn select_prev(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
  912        if self.selected_item > 0 {
  913            self.selected_item -= 1;
  914        } else {
  915            self.selected_item = self.matches.len() - 1;
  916        }
  917        self.scroll_handle.scroll_to_item(self.selected_item);
  918        self.attempt_resolve_selected_completion_documentation(project, cx);
  919        cx.notify();
  920    }
  921
  922    fn select_next(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
  923        if self.selected_item + 1 < self.matches.len() {
  924            self.selected_item += 1;
  925        } else {
  926            self.selected_item = 0;
  927        }
  928        self.scroll_handle.scroll_to_item(self.selected_item);
  929        self.attempt_resolve_selected_completion_documentation(project, cx);
  930        cx.notify();
  931    }
  932
  933    fn select_last(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
  934        self.selected_item = self.matches.len() - 1;
  935        self.scroll_handle.scroll_to_item(self.selected_item);
  936        self.attempt_resolve_selected_completion_documentation(project, cx);
  937        cx.notify();
  938    }
  939
  940    fn pre_resolve_completion_documentation(
  941        buffer: Model<Buffer>,
  942        completions: Arc<RwLock<Box<[Completion]>>>,
  943        matches: Arc<[StringMatch]>,
  944        editor: &Editor,
  945        cx: &mut ViewContext<Editor>,
  946    ) -> Task<()> {
  947        let settings = EditorSettings::get_global(cx);
  948        if !settings.show_completion_documentation {
  949            return Task::ready(());
  950        }
  951
  952        let Some(provider) = editor.completion_provider.as_ref() else {
  953            return Task::ready(());
  954        };
  955
  956        let resolve_task = provider.resolve_completions(
  957            buffer,
  958            matches.iter().map(|m| m.candidate_id).collect(),
  959            completions.clone(),
  960            cx,
  961        );
  962
  963        return cx.spawn(move |this, mut cx| async move {
  964            if let Some(true) = resolve_task.await.log_err() {
  965                this.update(&mut cx, |_, cx| cx.notify()).ok();
  966            }
  967        });
  968    }
  969
  970    fn attempt_resolve_selected_completion_documentation(
  971        &mut self,
  972        project: Option<&Model<Project>>,
  973        cx: &mut ViewContext<Editor>,
  974    ) {
  975        let settings = EditorSettings::get_global(cx);
  976        if !settings.show_completion_documentation {
  977            return;
  978        }
  979
  980        let completion_index = self.matches[self.selected_item].candidate_id;
  981        let Some(project) = project else {
  982            return;
  983        };
  984
  985        let resolve_task = project.update(cx, |project, cx| {
  986            project.resolve_completions(
  987                self.buffer.clone(),
  988                vec![completion_index],
  989                self.completions.clone(),
  990                cx,
  991            )
  992        });
  993
  994        let delay_ms =
  995            EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
  996        let delay = Duration::from_millis(delay_ms);
  997
  998        self.selected_completion_documentation_resolve_debounce
  999            .lock()
 1000            .fire_new(delay, cx, |_, cx| {
 1001                cx.spawn(move |this, mut cx| async move {
 1002                    if let Some(true) = resolve_task.await.log_err() {
 1003                        this.update(&mut cx, |_, cx| cx.notify()).ok();
 1004                    }
 1005                })
 1006            });
 1007    }
 1008
 1009    fn visible(&self) -> bool {
 1010        !self.matches.is_empty()
 1011    }
 1012
 1013    fn render(
 1014        &self,
 1015        style: &EditorStyle,
 1016        max_height: Pixels,
 1017        workspace: Option<WeakView<Workspace>>,
 1018        cx: &mut ViewContext<Editor>,
 1019    ) -> AnyElement {
 1020        let settings = EditorSettings::get_global(cx);
 1021        let show_completion_documentation = settings.show_completion_documentation;
 1022
 1023        let widest_completion_ix = self
 1024            .matches
 1025            .iter()
 1026            .enumerate()
 1027            .max_by_key(|(_, mat)| {
 1028                let completions = self.completions.read();
 1029                let completion = &completions[mat.candidate_id];
 1030                let documentation = &completion.documentation;
 1031
 1032                let mut len = completion.label.text.chars().count();
 1033                if let Some(Documentation::SingleLine(text)) = documentation {
 1034                    if show_completion_documentation {
 1035                        len += text.chars().count();
 1036                    }
 1037                }
 1038
 1039                len
 1040            })
 1041            .map(|(ix, _)| ix);
 1042
 1043        let completions = self.completions.clone();
 1044        let matches = self.matches.clone();
 1045        let selected_item = self.selected_item;
 1046        let style = style.clone();
 1047
 1048        let multiline_docs = if show_completion_documentation {
 1049            let mat = &self.matches[selected_item];
 1050            let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
 1051                Some(Documentation::MultiLinePlainText(text)) => {
 1052                    Some(div().child(SharedString::from(text.clone())))
 1053                }
 1054                Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
 1055                    Some(div().child(render_parsed_markdown(
 1056                        "completions_markdown",
 1057                        parsed,
 1058                        &style,
 1059                        workspace,
 1060                        cx,
 1061                    )))
 1062                }
 1063                _ => None,
 1064            };
 1065            multiline_docs.map(|div| {
 1066                div.id("multiline_docs")
 1067                    .max_h(max_height)
 1068                    .flex_1()
 1069                    .px_1p5()
 1070                    .py_1()
 1071                    .min_w(px(260.))
 1072                    .max_w(px(640.))
 1073                    .w(px(500.))
 1074                    .overflow_y_scroll()
 1075                    .occlude()
 1076            })
 1077        } else {
 1078            None
 1079        };
 1080
 1081        let list = uniform_list(
 1082            cx.view().clone(),
 1083            "completions",
 1084            matches.len(),
 1085            move |_editor, range, cx| {
 1086                let start_ix = range.start;
 1087                let completions_guard = completions.read();
 1088
 1089                matches[range]
 1090                    .iter()
 1091                    .enumerate()
 1092                    .map(|(ix, mat)| {
 1093                        let item_ix = start_ix + ix;
 1094                        let candidate_id = mat.candidate_id;
 1095                        let completion = &completions_guard[candidate_id];
 1096
 1097                        let documentation = if show_completion_documentation {
 1098                            &completion.documentation
 1099                        } else {
 1100                            &None
 1101                        };
 1102
 1103                        let highlights = gpui::combine_highlights(
 1104                            mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
 1105                            styled_runs_for_code_label(&completion.label, &style.syntax).map(
 1106                                |(range, mut highlight)| {
 1107                                    // Ignore font weight for syntax highlighting, as we'll use it
 1108                                    // for fuzzy matches.
 1109                                    highlight.font_weight = None;
 1110
 1111                                    if completion.lsp_completion.deprecated.unwrap_or(false) {
 1112                                        highlight.strikethrough = Some(StrikethroughStyle {
 1113                                            thickness: 1.0.into(),
 1114                                            ..Default::default()
 1115                                        });
 1116                                        highlight.color = Some(cx.theme().colors().text_muted);
 1117                                    }
 1118
 1119                                    (range, highlight)
 1120                                },
 1121                            ),
 1122                        );
 1123                        let completion_label = StyledText::new(completion.label.text.clone())
 1124                            .with_highlights(&style.text, highlights);
 1125                        let documentation_label =
 1126                            if let Some(Documentation::SingleLine(text)) = documentation {
 1127                                if text.trim().is_empty() {
 1128                                    None
 1129                                } else {
 1130                                    Some(
 1131                                        Label::new(text.clone())
 1132                                            .ml_4()
 1133                                            .size(LabelSize::Small)
 1134                                            .color(Color::Muted),
 1135                                    )
 1136                                }
 1137                            } else {
 1138                                None
 1139                            };
 1140
 1141                        div().min_w(px(220.)).max_w(px(540.)).child(
 1142                            ListItem::new(mat.candidate_id)
 1143                                .inset(true)
 1144                                .selected(item_ix == selected_item)
 1145                                .on_click(cx.listener(move |editor, _event, cx| {
 1146                                    cx.stop_propagation();
 1147                                    if let Some(task) = editor.confirm_completion(
 1148                                        &ConfirmCompletion {
 1149                                            item_ix: Some(item_ix),
 1150                                        },
 1151                                        cx,
 1152                                    ) {
 1153                                        task.detach_and_log_err(cx)
 1154                                    }
 1155                                }))
 1156                                .child(h_flex().overflow_hidden().child(completion_label))
 1157                                .end_slot::<Label>(documentation_label),
 1158                        )
 1159                    })
 1160                    .collect()
 1161            },
 1162        )
 1163        .occlude()
 1164        .max_h(max_height)
 1165        .track_scroll(self.scroll_handle.clone())
 1166        .with_width_from_item(widest_completion_ix)
 1167        .with_sizing_behavior(ListSizingBehavior::Infer);
 1168
 1169        Popover::new()
 1170            .child(list)
 1171            .when_some(multiline_docs, |popover, multiline_docs| {
 1172                popover.aside(multiline_docs)
 1173            })
 1174            .into_any_element()
 1175    }
 1176
 1177    pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
 1178        let mut matches = if let Some(query) = query {
 1179            fuzzy::match_strings(
 1180                &self.match_candidates,
 1181                query,
 1182                query.chars().any(|c| c.is_uppercase()),
 1183                100,
 1184                &Default::default(),
 1185                executor,
 1186            )
 1187            .await
 1188        } else {
 1189            self.match_candidates
 1190                .iter()
 1191                .enumerate()
 1192                .map(|(candidate_id, candidate)| StringMatch {
 1193                    candidate_id,
 1194                    score: Default::default(),
 1195                    positions: Default::default(),
 1196                    string: candidate.string.clone(),
 1197                })
 1198                .collect()
 1199        };
 1200
 1201        // Remove all candidates where the query's start does not match the start of any word in the candidate
 1202        if let Some(query) = query {
 1203            if let Some(query_start) = query.chars().next() {
 1204                matches.retain(|string_match| {
 1205                    split_words(&string_match.string).any(|word| {
 1206                        // Check that the first codepoint of the word as lowercase matches the first
 1207                        // codepoint of the query as lowercase
 1208                        word.chars()
 1209                            .flat_map(|codepoint| codepoint.to_lowercase())
 1210                            .zip(query_start.to_lowercase())
 1211                            .all(|(word_cp, query_cp)| word_cp == query_cp)
 1212                    })
 1213                });
 1214            }
 1215        }
 1216
 1217        let completions = self.completions.read();
 1218        matches.sort_unstable_by_key(|mat| {
 1219            // We do want to strike a balance here between what the language server tells us
 1220            // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
 1221            // `Creat` and there is a local variable called `CreateComponent`).
 1222            // So what we do is: we bucket all matches into two buckets
 1223            // - Strong matches
 1224            // - Weak matches
 1225            // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
 1226            // and the Weak matches are the rest.
 1227            //
 1228            // For the strong matches, we sort by the language-servers score first and for the weak
 1229            // matches, we prefer our fuzzy finder first.
 1230            //
 1231            // The thinking behind that: it's useless to take the sort_text the language-server gives
 1232            // us into account when it's obviously a bad match.
 1233
 1234            #[derive(PartialEq, Eq, PartialOrd, Ord)]
 1235            enum MatchScore<'a> {
 1236                Strong {
 1237                    sort_text: Option<&'a str>,
 1238                    score: Reverse<OrderedFloat<f64>>,
 1239                    sort_key: (usize, &'a str),
 1240                },
 1241                Weak {
 1242                    score: Reverse<OrderedFloat<f64>>,
 1243                    sort_text: Option<&'a str>,
 1244                    sort_key: (usize, &'a str),
 1245                },
 1246            }
 1247
 1248            let completion = &completions[mat.candidate_id];
 1249            let sort_key = completion.sort_key();
 1250            let sort_text = completion.lsp_completion.sort_text.as_deref();
 1251            let score = Reverse(OrderedFloat(mat.score));
 1252
 1253            if mat.score >= 0.2 {
 1254                MatchScore::Strong {
 1255                    sort_text,
 1256                    score,
 1257                    sort_key,
 1258                }
 1259            } else {
 1260                MatchScore::Weak {
 1261                    score,
 1262                    sort_text,
 1263                    sort_key,
 1264                }
 1265            }
 1266        });
 1267
 1268        for mat in &mut matches {
 1269            let completion = &completions[mat.candidate_id];
 1270            mat.string.clone_from(&completion.label.text);
 1271            for position in &mut mat.positions {
 1272                *position += completion.label.filter_range.start;
 1273            }
 1274        }
 1275        drop(completions);
 1276
 1277        self.matches = matches.into();
 1278        self.selected_item = 0;
 1279    }
 1280}
 1281
 1282#[derive(Clone)]
 1283struct CodeActionContents {
 1284    tasks: Option<Arc<ResolvedTasks>>,
 1285    actions: Option<Arc<[CodeAction]>>,
 1286}
 1287
 1288impl CodeActionContents {
 1289    fn len(&self) -> usize {
 1290        match (&self.tasks, &self.actions) {
 1291            (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
 1292            (Some(tasks), None) => tasks.templates.len(),
 1293            (None, Some(actions)) => actions.len(),
 1294            (None, None) => 0,
 1295        }
 1296    }
 1297
 1298    fn is_empty(&self) -> bool {
 1299        match (&self.tasks, &self.actions) {
 1300            (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
 1301            (Some(tasks), None) => tasks.templates.is_empty(),
 1302            (None, Some(actions)) => actions.is_empty(),
 1303            (None, None) => true,
 1304        }
 1305    }
 1306
 1307    fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
 1308        self.tasks
 1309            .iter()
 1310            .flat_map(|tasks| {
 1311                tasks
 1312                    .templates
 1313                    .iter()
 1314                    .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
 1315            })
 1316            .chain(self.actions.iter().flat_map(|actions| {
 1317                actions
 1318                    .iter()
 1319                    .map(|action| CodeActionsItem::CodeAction(action.clone()))
 1320            }))
 1321    }
 1322    fn get(&self, index: usize) -> Option<CodeActionsItem> {
 1323        match (&self.tasks, &self.actions) {
 1324            (Some(tasks), Some(actions)) => {
 1325                if index < tasks.templates.len() {
 1326                    tasks
 1327                        .templates
 1328                        .get(index)
 1329                        .cloned()
 1330                        .map(|(kind, task)| CodeActionsItem::Task(kind, task))
 1331                } else {
 1332                    actions
 1333                        .get(index - tasks.templates.len())
 1334                        .cloned()
 1335                        .map(CodeActionsItem::CodeAction)
 1336                }
 1337            }
 1338            (Some(tasks), None) => tasks
 1339                .templates
 1340                .get(index)
 1341                .cloned()
 1342                .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
 1343            (None, Some(actions)) => actions.get(index).cloned().map(CodeActionsItem::CodeAction),
 1344            (None, None) => None,
 1345        }
 1346    }
 1347}
 1348
 1349#[allow(clippy::large_enum_variant)]
 1350#[derive(Clone)]
 1351enum CodeActionsItem {
 1352    Task(TaskSourceKind, ResolvedTask),
 1353    CodeAction(CodeAction),
 1354}
 1355
 1356impl CodeActionsItem {
 1357    fn as_task(&self) -> Option<&ResolvedTask> {
 1358        let Self::Task(_, task) = self else {
 1359            return None;
 1360        };
 1361        Some(task)
 1362    }
 1363    fn as_code_action(&self) -> Option<&CodeAction> {
 1364        let Self::CodeAction(action) = self else {
 1365            return None;
 1366        };
 1367        Some(action)
 1368    }
 1369    fn label(&self) -> String {
 1370        match self {
 1371            Self::CodeAction(action) => action.lsp_action.title.clone(),
 1372            Self::Task(_, task) => task.resolved_label.clone(),
 1373        }
 1374    }
 1375}
 1376
 1377struct CodeActionsMenu {
 1378    actions: CodeActionContents,
 1379    buffer: Model<Buffer>,
 1380    selected_item: usize,
 1381    scroll_handle: UniformListScrollHandle,
 1382    deployed_from_indicator: Option<DisplayRow>,
 1383}
 1384
 1385impl CodeActionsMenu {
 1386    fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
 1387        self.selected_item = 0;
 1388        self.scroll_handle.scroll_to_item(self.selected_item);
 1389        cx.notify()
 1390    }
 1391
 1392    fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
 1393        if self.selected_item > 0 {
 1394            self.selected_item -= 1;
 1395        } else {
 1396            self.selected_item = self.actions.len() - 1;
 1397        }
 1398        self.scroll_handle.scroll_to_item(self.selected_item);
 1399        cx.notify();
 1400    }
 1401
 1402    fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
 1403        if self.selected_item + 1 < self.actions.len() {
 1404            self.selected_item += 1;
 1405        } else {
 1406            self.selected_item = 0;
 1407        }
 1408        self.scroll_handle.scroll_to_item(self.selected_item);
 1409        cx.notify();
 1410    }
 1411
 1412    fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
 1413        self.selected_item = self.actions.len() - 1;
 1414        self.scroll_handle.scroll_to_item(self.selected_item);
 1415        cx.notify()
 1416    }
 1417
 1418    fn visible(&self) -> bool {
 1419        !self.actions.is_empty()
 1420    }
 1421
 1422    fn render(
 1423        &self,
 1424        cursor_position: DisplayPoint,
 1425        _style: &EditorStyle,
 1426        max_height: Pixels,
 1427        cx: &mut ViewContext<Editor>,
 1428    ) -> (ContextMenuOrigin, AnyElement) {
 1429        let actions = self.actions.clone();
 1430        let selected_item = self.selected_item;
 1431        let element = uniform_list(
 1432            cx.view().clone(),
 1433            "code_actions_menu",
 1434            self.actions.len(),
 1435            move |_this, range, cx| {
 1436                actions
 1437                    .iter()
 1438                    .skip(range.start)
 1439                    .take(range.end - range.start)
 1440                    .enumerate()
 1441                    .map(|(ix, action)| {
 1442                        let item_ix = range.start + ix;
 1443                        let selected = selected_item == item_ix;
 1444                        let colors = cx.theme().colors();
 1445                        div()
 1446                            .px_2()
 1447                            .text_color(colors.text)
 1448                            .when(selected, |style| {
 1449                                style
 1450                                    .bg(colors.element_active)
 1451                                    .text_color(colors.text_accent)
 1452                            })
 1453                            .hover(|style| {
 1454                                style
 1455                                    .bg(colors.element_hover)
 1456                                    .text_color(colors.text_accent)
 1457                            })
 1458                            .whitespace_nowrap()
 1459                            .when_some(action.as_code_action(), |this, action| {
 1460                                this.on_mouse_down(
 1461                                    MouseButton::Left,
 1462                                    cx.listener(move |editor, _, cx| {
 1463                                        cx.stop_propagation();
 1464                                        if let Some(task) = editor.confirm_code_action(
 1465                                            &ConfirmCodeAction {
 1466                                                item_ix: Some(item_ix),
 1467                                            },
 1468                                            cx,
 1469                                        ) {
 1470                                            task.detach_and_log_err(cx)
 1471                                        }
 1472                                    }),
 1473                                )
 1474                                // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
 1475                                .child(SharedString::from(action.lsp_action.title.clone()))
 1476                            })
 1477                            .when_some(action.as_task(), |this, task| {
 1478                                this.on_mouse_down(
 1479                                    MouseButton::Left,
 1480                                    cx.listener(move |editor, _, cx| {
 1481                                        cx.stop_propagation();
 1482                                        if let Some(task) = editor.confirm_code_action(
 1483                                            &ConfirmCodeAction {
 1484                                                item_ix: Some(item_ix),
 1485                                            },
 1486                                            cx,
 1487                                        ) {
 1488                                            task.detach_and_log_err(cx)
 1489                                        }
 1490                                    }),
 1491                                )
 1492                                .child(SharedString::from(task.resolved_label.clone()))
 1493                            })
 1494                    })
 1495                    .collect()
 1496            },
 1497        )
 1498        .elevation_1(cx)
 1499        .px_2()
 1500        .py_1()
 1501        .max_h(max_height)
 1502        .occlude()
 1503        .track_scroll(self.scroll_handle.clone())
 1504        .with_width_from_item(
 1505            self.actions
 1506                .iter()
 1507                .enumerate()
 1508                .max_by_key(|(_, action)| match action {
 1509                    CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
 1510                    CodeActionsItem::CodeAction(action) => action.lsp_action.title.chars().count(),
 1511                })
 1512                .map(|(ix, _)| ix),
 1513        )
 1514        .with_sizing_behavior(ListSizingBehavior::Infer)
 1515        .into_any_element();
 1516
 1517        let cursor_position = if let Some(row) = self.deployed_from_indicator {
 1518            ContextMenuOrigin::GutterIndicator(row)
 1519        } else {
 1520            ContextMenuOrigin::EditorPoint(cursor_position)
 1521        };
 1522
 1523        (cursor_position, element)
 1524    }
 1525}
 1526
 1527#[derive(Debug)]
 1528struct ActiveDiagnosticGroup {
 1529    primary_range: Range<Anchor>,
 1530    primary_message: String,
 1531    group_id: usize,
 1532    blocks: HashMap<CustomBlockId, Diagnostic>,
 1533    is_valid: bool,
 1534}
 1535
 1536#[derive(Serialize, Deserialize, Clone, Debug)]
 1537pub struct ClipboardSelection {
 1538    pub len: usize,
 1539    pub is_entire_line: bool,
 1540    pub first_line_indent: u32,
 1541}
 1542
 1543#[derive(Debug)]
 1544pub(crate) struct NavigationData {
 1545    cursor_anchor: Anchor,
 1546    cursor_position: Point,
 1547    scroll_anchor: ScrollAnchor,
 1548    scroll_top_row: u32,
 1549}
 1550
 1551enum GotoDefinitionKind {
 1552    Symbol,
 1553    Type,
 1554    Implementation,
 1555}
 1556
 1557#[derive(Debug, Clone)]
 1558enum InlayHintRefreshReason {
 1559    Toggle(bool),
 1560    SettingsChange(InlayHintSettings),
 1561    NewLinesShown,
 1562    BufferEdited(HashSet<Arc<Language>>),
 1563    RefreshRequested,
 1564    ExcerptsRemoved(Vec<ExcerptId>),
 1565}
 1566
 1567impl InlayHintRefreshReason {
 1568    fn description(&self) -> &'static str {
 1569        match self {
 1570            Self::Toggle(_) => "toggle",
 1571            Self::SettingsChange(_) => "settings change",
 1572            Self::NewLinesShown => "new lines shown",
 1573            Self::BufferEdited(_) => "buffer edited",
 1574            Self::RefreshRequested => "refresh requested",
 1575            Self::ExcerptsRemoved(_) => "excerpts removed",
 1576        }
 1577    }
 1578}
 1579
 1580pub(crate) struct FocusedBlock {
 1581    id: BlockId,
 1582    focus_handle: WeakFocusHandle,
 1583}
 1584
 1585impl Editor {
 1586    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
 1587        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1588        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1589        Self::new(
 1590            EditorMode::SingleLine { auto_width: false },
 1591            buffer,
 1592            None,
 1593            false,
 1594            cx,
 1595        )
 1596    }
 1597
 1598    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
 1599        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1600        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1601        Self::new(EditorMode::Full, buffer, None, false, cx)
 1602    }
 1603
 1604    pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
 1605        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1606        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1607        Self::new(
 1608            EditorMode::SingleLine { auto_width: true },
 1609            buffer,
 1610            None,
 1611            false,
 1612            cx,
 1613        )
 1614    }
 1615
 1616    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
 1617        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1618        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1619        Self::new(
 1620            EditorMode::AutoHeight { max_lines },
 1621            buffer,
 1622            None,
 1623            false,
 1624            cx,
 1625        )
 1626    }
 1627
 1628    pub fn for_buffer(
 1629        buffer: Model<Buffer>,
 1630        project: Option<Model<Project>>,
 1631        cx: &mut ViewContext<Self>,
 1632    ) -> Self {
 1633        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1634        Self::new(EditorMode::Full, buffer, project, false, cx)
 1635    }
 1636
 1637    pub fn for_multibuffer(
 1638        buffer: Model<MultiBuffer>,
 1639        project: Option<Model<Project>>,
 1640        show_excerpt_controls: bool,
 1641        cx: &mut ViewContext<Self>,
 1642    ) -> Self {
 1643        Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
 1644    }
 1645
 1646    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 1647        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1648        let mut clone = Self::new(
 1649            self.mode,
 1650            self.buffer.clone(),
 1651            self.project.clone(),
 1652            show_excerpt_controls,
 1653            cx,
 1654        );
 1655        self.display_map.update(cx, |display_map, cx| {
 1656            let snapshot = display_map.snapshot(cx);
 1657            clone.display_map.update(cx, |display_map, cx| {
 1658                display_map.set_state(&snapshot, cx);
 1659            });
 1660        });
 1661        clone.selections.clone_state(&self.selections);
 1662        clone.scroll_manager.clone_state(&self.scroll_manager);
 1663        clone.searchable = self.searchable;
 1664        clone
 1665    }
 1666
 1667    pub fn new(
 1668        mode: EditorMode,
 1669        buffer: Model<MultiBuffer>,
 1670        project: Option<Model<Project>>,
 1671        show_excerpt_controls: bool,
 1672        cx: &mut ViewContext<Self>,
 1673    ) -> Self {
 1674        let style = cx.text_style();
 1675        let font_size = style.font_size.to_pixels(cx.rem_size());
 1676        let editor = cx.view().downgrade();
 1677        let fold_placeholder = FoldPlaceholder {
 1678            constrain_width: true,
 1679            render: Arc::new(move |fold_id, fold_range, cx| {
 1680                let editor = editor.clone();
 1681                div()
 1682                    .id(fold_id)
 1683                    .bg(cx.theme().colors().ghost_element_background)
 1684                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1685                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1686                    .rounded_sm()
 1687                    .size_full()
 1688                    .cursor_pointer()
 1689                    .child("")
 1690                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 1691                    .on_click(move |_, cx| {
 1692                        editor
 1693                            .update(cx, |editor, cx| {
 1694                                editor.unfold_ranges(
 1695                                    [fold_range.start..fold_range.end],
 1696                                    true,
 1697                                    false,
 1698                                    cx,
 1699                                );
 1700                                cx.stop_propagation();
 1701                            })
 1702                            .ok();
 1703                    })
 1704                    .into_any()
 1705            }),
 1706            merge_adjacent: true,
 1707        };
 1708        let file_header_size = if show_excerpt_controls { 3 } else { 2 };
 1709        let display_map = cx.new_model(|cx| {
 1710            DisplayMap::new(
 1711                buffer.clone(),
 1712                style.font(),
 1713                font_size,
 1714                None,
 1715                show_excerpt_controls,
 1716                file_header_size,
 1717                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1718                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1719                fold_placeholder,
 1720                cx,
 1721            )
 1722        });
 1723
 1724        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1725
 1726        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1727
 1728        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1729            .then(|| language_settings::SoftWrap::PreferLine);
 1730
 1731        let mut project_subscriptions = Vec::new();
 1732        if mode == EditorMode::Full {
 1733            if let Some(project) = project.as_ref() {
 1734                if buffer.read(cx).is_singleton() {
 1735                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
 1736                        cx.emit(EditorEvent::TitleChanged);
 1737                    }));
 1738                }
 1739                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
 1740                    if let project::Event::RefreshInlayHints = event {
 1741                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1742                    } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1743                        if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1744                            let focus_handle = editor.focus_handle(cx);
 1745                            if focus_handle.is_focused(cx) {
 1746                                let snapshot = buffer.read(cx).snapshot();
 1747                                for (range, snippet) in snippet_edits {
 1748                                    let editor_range =
 1749                                        language::range_from_lsp(*range).to_offset(&snapshot);
 1750                                    editor
 1751                                        .insert_snippet(&[editor_range], snippet.clone(), cx)
 1752                                        .ok();
 1753                                }
 1754                            }
 1755                        }
 1756                    }
 1757                }));
 1758                let task_inventory = project.read(cx).task_inventory().clone();
 1759                project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
 1760                    editor.tasks_update_task = Some(editor.refresh_runnables(cx));
 1761                }));
 1762            }
 1763        }
 1764
 1765        let inlay_hint_settings = inlay_hint_settings(
 1766            selections.newest_anchor().head(),
 1767            &buffer.read(cx).snapshot(cx),
 1768            cx,
 1769        );
 1770        let focus_handle = cx.focus_handle();
 1771        cx.on_focus(&focus_handle, Self::handle_focus).detach();
 1772        cx.on_focus_in(&focus_handle, Self::handle_focus_in)
 1773            .detach();
 1774        cx.on_focus_out(&focus_handle, Self::handle_focus_out)
 1775            .detach();
 1776        cx.on_blur(&focus_handle, Self::handle_blur).detach();
 1777
 1778        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1779            Some(false)
 1780        } else {
 1781            None
 1782        };
 1783
 1784        let mut this = Self {
 1785            focus_handle,
 1786            show_cursor_when_unfocused: false,
 1787            last_focused_descendant: None,
 1788            buffer: buffer.clone(),
 1789            display_map: display_map.clone(),
 1790            selections,
 1791            scroll_manager: ScrollManager::new(cx),
 1792            columnar_selection_tail: None,
 1793            add_selections_state: None,
 1794            select_next_state: None,
 1795            select_prev_state: None,
 1796            selection_history: Default::default(),
 1797            autoclose_regions: Default::default(),
 1798            snippet_stack: Default::default(),
 1799            select_larger_syntax_node_stack: Vec::new(),
 1800            ime_transaction: Default::default(),
 1801            active_diagnostics: None,
 1802            soft_wrap_mode_override,
 1803            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1804            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1805            project,
 1806            blink_manager: blink_manager.clone(),
 1807            show_local_selections: true,
 1808            mode,
 1809            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1810            show_gutter: mode == EditorMode::Full,
 1811            show_line_numbers: None,
 1812            show_git_diff_gutter: None,
 1813            show_code_actions: None,
 1814            show_runnables: None,
 1815            show_wrap_guides: None,
 1816            redact_all: false,
 1817            show_indent_guides,
 1818            placeholder_text: None,
 1819            highlight_order: 0,
 1820            highlighted_rows: HashMap::default(),
 1821            background_highlights: Default::default(),
 1822            gutter_highlights: TreeMap::default(),
 1823            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1824            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1825            nav_history: None,
 1826            context_menu: RwLock::new(None),
 1827            mouse_context_menu: None,
 1828            completion_tasks: Default::default(),
 1829            signature_help_state: SignatureHelpState::default(),
 1830            auto_signature_help: None,
 1831            find_all_references_task_sources: Vec::new(),
 1832            next_completion_id: 0,
 1833            completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
 1834            next_inlay_id: 0,
 1835            available_code_actions: Default::default(),
 1836            code_actions_task: Default::default(),
 1837            document_highlights_task: Default::default(),
 1838            linked_editing_range_task: Default::default(),
 1839            pending_rename: Default::default(),
 1840            searchable: true,
 1841            cursor_shape: Default::default(),
 1842            current_line_highlight: None,
 1843            autoindent_mode: Some(AutoindentMode::EachLine),
 1844            collapse_matches: false,
 1845            workspace: None,
 1846            keymap_context_layers: Default::default(),
 1847            input_enabled: true,
 1848            use_modal_editing: mode == EditorMode::Full,
 1849            read_only: false,
 1850            use_autoclose: true,
 1851            use_auto_surround: true,
 1852            auto_replace_emoji_shortcode: false,
 1853            leader_peer_id: None,
 1854            remote_id: None,
 1855            hover_state: Default::default(),
 1856            hovered_link_state: Default::default(),
 1857            inline_completion_provider: None,
 1858            active_inline_completion: None,
 1859            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1860            expanded_hunks: ExpandedHunks::default(),
 1861            gutter_hovered: false,
 1862            pixel_position_of_newest_cursor: None,
 1863            last_bounds: None,
 1864            expect_bounds_change: None,
 1865            gutter_dimensions: GutterDimensions::default(),
 1866            style: None,
 1867            show_cursor_names: false,
 1868            hovered_cursors: Default::default(),
 1869            next_editor_action_id: EditorActionId::default(),
 1870            editor_actions: Rc::default(),
 1871            vim_replace_map: Default::default(),
 1872            show_inline_completions: mode == EditorMode::Full,
 1873            custom_context_menu: None,
 1874            show_git_blame_gutter: false,
 1875            show_git_blame_inline: false,
 1876            show_selection_menu: None,
 1877            show_git_blame_inline_delay_task: None,
 1878            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1879            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1880                .session
 1881                .restore_unsaved_buffers,
 1882            blame: None,
 1883            blame_subscription: None,
 1884            file_header_size,
 1885            tasks: Default::default(),
 1886            _subscriptions: vec![
 1887                cx.observe(&buffer, Self::on_buffer_changed),
 1888                cx.subscribe(&buffer, Self::on_buffer_event),
 1889                cx.observe(&display_map, Self::on_display_map_changed),
 1890                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1891                cx.observe_global::<SettingsStore>(Self::settings_changed),
 1892                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1893                cx.observe_window_activation(|editor, cx| {
 1894                    let active = cx.is_window_active();
 1895                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1896                        if active {
 1897                            blink_manager.enable(cx);
 1898                        } else {
 1899                            blink_manager.show_cursor(cx);
 1900                            blink_manager.disable(cx);
 1901                        }
 1902                    });
 1903                }),
 1904            ],
 1905            tasks_update_task: None,
 1906            linked_edit_ranges: Default::default(),
 1907            previous_search_ranges: None,
 1908            breadcrumb_header: None,
 1909            focused_block: None,
 1910        };
 1911        this.tasks_update_task = Some(this.refresh_runnables(cx));
 1912        this._subscriptions.extend(project_subscriptions);
 1913
 1914        this.end_selection(cx);
 1915        this.scroll_manager.show_scrollbar(cx);
 1916
 1917        if mode == EditorMode::Full {
 1918            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1919            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1920
 1921            if this.git_blame_inline_enabled {
 1922                this.git_blame_inline_enabled = true;
 1923                this.start_git_blame_inline(false, cx);
 1924            }
 1925        }
 1926
 1927        this.report_editor_event("open", None, cx);
 1928        this
 1929    }
 1930
 1931    pub fn mouse_menu_is_focused(&self, cx: &mut WindowContext) -> bool {
 1932        self.mouse_context_menu
 1933            .as_ref()
 1934            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
 1935    }
 1936
 1937    fn key_context(&self, cx: &AppContext) -> KeyContext {
 1938        let mut key_context = KeyContext::new_with_defaults();
 1939        key_context.add("Editor");
 1940        let mode = match self.mode {
 1941            EditorMode::SingleLine { .. } => "single_line",
 1942            EditorMode::AutoHeight { .. } => "auto_height",
 1943            EditorMode::Full => "full",
 1944        };
 1945
 1946        if EditorSettings::jupyter_enabled(cx) {
 1947            key_context.add("jupyter");
 1948        }
 1949
 1950        key_context.set("mode", mode);
 1951        if self.pending_rename.is_some() {
 1952            key_context.add("renaming");
 1953        }
 1954        if self.context_menu_visible() {
 1955            match self.context_menu.read().as_ref() {
 1956                Some(ContextMenu::Completions(_)) => {
 1957                    key_context.add("menu");
 1958                    key_context.add("showing_completions")
 1959                }
 1960                Some(ContextMenu::CodeActions(_)) => {
 1961                    key_context.add("menu");
 1962                    key_context.add("showing_code_actions")
 1963                }
 1964                None => {}
 1965            }
 1966        }
 1967
 1968        for layer in self.keymap_context_layers.values() {
 1969            key_context.extend(layer);
 1970        }
 1971
 1972        if let Some(extension) = self
 1973            .buffer
 1974            .read(cx)
 1975            .as_singleton()
 1976            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1977        {
 1978            key_context.set("extension", extension.to_string());
 1979        }
 1980
 1981        if self.has_active_inline_completion(cx) {
 1982            key_context.add("copilot_suggestion");
 1983            key_context.add("inline_completion");
 1984        }
 1985
 1986        key_context
 1987    }
 1988
 1989    pub fn new_file(
 1990        workspace: &mut Workspace,
 1991        _: &workspace::NewFile,
 1992        cx: &mut ViewContext<Workspace>,
 1993    ) {
 1994        Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
 1995            "Failed to create buffer",
 1996            cx,
 1997            |e, _| match e.error_code() {
 1998                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1999                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2000                e.error_tag("required").unwrap_or("the latest version")
 2001            )),
 2002                _ => None,
 2003            },
 2004        );
 2005    }
 2006
 2007    pub fn new_in_workspace(
 2008        workspace: &mut Workspace,
 2009        cx: &mut ViewContext<Workspace>,
 2010    ) -> Task<Result<View<Editor>>> {
 2011        let project = workspace.project().clone();
 2012        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2013
 2014        cx.spawn(|workspace, mut cx| async move {
 2015            let buffer = create.await?;
 2016            workspace.update(&mut cx, |workspace, cx| {
 2017                let editor =
 2018                    cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
 2019                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 2020                editor
 2021            })
 2022        })
 2023    }
 2024
 2025    pub fn new_file_in_direction(
 2026        workspace: &mut Workspace,
 2027        action: &workspace::NewFileInDirection,
 2028        cx: &mut ViewContext<Workspace>,
 2029    ) {
 2030        let project = workspace.project().clone();
 2031        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2032        let direction = action.0;
 2033
 2034        cx.spawn(|workspace, mut cx| async move {
 2035            let buffer = create.await?;
 2036            workspace.update(&mut cx, move |workspace, cx| {
 2037                workspace.split_item(
 2038                    direction,
 2039                    Box::new(
 2040                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 2041                    ),
 2042                    cx,
 2043                )
 2044            })?;
 2045            anyhow::Ok(())
 2046        })
 2047        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 2048            ErrorCode::RemoteUpgradeRequired => Some(format!(
 2049                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2050                e.error_tag("required").unwrap_or("the latest version")
 2051            )),
 2052            _ => None,
 2053        });
 2054    }
 2055
 2056    pub fn replica_id(&self, cx: &AppContext) -> ReplicaId {
 2057        self.buffer.read(cx).replica_id()
 2058    }
 2059
 2060    pub fn leader_peer_id(&self) -> Option<PeerId> {
 2061        self.leader_peer_id
 2062    }
 2063
 2064    pub fn buffer(&self) -> &Model<MultiBuffer> {
 2065        &self.buffer
 2066    }
 2067
 2068    pub fn workspace(&self) -> Option<View<Workspace>> {
 2069        self.workspace.as_ref()?.0.upgrade()
 2070    }
 2071
 2072    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
 2073        self.buffer().read(cx).title(cx)
 2074    }
 2075
 2076    pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
 2077        EditorSnapshot {
 2078            mode: self.mode,
 2079            show_gutter: self.show_gutter,
 2080            show_line_numbers: self.show_line_numbers,
 2081            show_git_diff_gutter: self.show_git_diff_gutter,
 2082            show_code_actions: self.show_code_actions,
 2083            show_runnables: self.show_runnables,
 2084            render_git_blame_gutter: self.render_git_blame_gutter(cx),
 2085            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 2086            scroll_anchor: self.scroll_manager.anchor(),
 2087            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 2088            placeholder_text: self.placeholder_text.clone(),
 2089            is_focused: self.focus_handle.is_focused(cx),
 2090            current_line_highlight: self
 2091                .current_line_highlight
 2092                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 2093            gutter_hovered: self.gutter_hovered,
 2094        }
 2095    }
 2096
 2097    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
 2098        self.buffer.read(cx).language_at(point, cx)
 2099    }
 2100
 2101    pub fn file_at<T: ToOffset>(
 2102        &self,
 2103        point: T,
 2104        cx: &AppContext,
 2105    ) -> Option<Arc<dyn language::File>> {
 2106        self.buffer.read(cx).read(cx).file_at(point).cloned()
 2107    }
 2108
 2109    pub fn active_excerpt(
 2110        &self,
 2111        cx: &AppContext,
 2112    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
 2113        self.buffer
 2114            .read(cx)
 2115            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 2116    }
 2117
 2118    pub fn mode(&self) -> EditorMode {
 2119        self.mode
 2120    }
 2121
 2122    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 2123        self.collaboration_hub.as_deref()
 2124    }
 2125
 2126    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 2127        self.collaboration_hub = Some(hub);
 2128    }
 2129
 2130    pub fn set_custom_context_menu(
 2131        &mut self,
 2132        f: impl 'static
 2133            + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
 2134    ) {
 2135        self.custom_context_menu = Some(Box::new(f))
 2136    }
 2137
 2138    pub fn set_completion_provider(&mut self, provider: Box<dyn CompletionProvider>) {
 2139        self.completion_provider = Some(provider);
 2140    }
 2141
 2142    pub fn set_inline_completion_provider<T>(
 2143        &mut self,
 2144        provider: Option<Model<T>>,
 2145        cx: &mut ViewContext<Self>,
 2146    ) where
 2147        T: InlineCompletionProvider,
 2148    {
 2149        self.inline_completion_provider =
 2150            provider.map(|provider| RegisteredInlineCompletionProvider {
 2151                _subscription: cx.observe(&provider, |this, _, cx| {
 2152                    if this.focus_handle.is_focused(cx) {
 2153                        this.update_visible_inline_completion(cx);
 2154                    }
 2155                }),
 2156                provider: Arc::new(provider),
 2157            });
 2158        self.refresh_inline_completion(false, cx);
 2159    }
 2160
 2161    pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
 2162        self.placeholder_text.as_deref()
 2163    }
 2164
 2165    pub fn set_placeholder_text(
 2166        &mut self,
 2167        placeholder_text: impl Into<Arc<str>>,
 2168        cx: &mut ViewContext<Self>,
 2169    ) {
 2170        let placeholder_text = Some(placeholder_text.into());
 2171        if self.placeholder_text != placeholder_text {
 2172            self.placeholder_text = placeholder_text;
 2173            cx.notify();
 2174        }
 2175    }
 2176
 2177    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
 2178        self.cursor_shape = cursor_shape;
 2179
 2180        // Disrupt blink for immediate user feedback that the cursor shape has changed
 2181        self.blink_manager.update(cx, BlinkManager::show_cursor);
 2182
 2183        cx.notify();
 2184    }
 2185
 2186    pub fn set_current_line_highlight(
 2187        &mut self,
 2188        current_line_highlight: Option<CurrentLineHighlight>,
 2189    ) {
 2190        self.current_line_highlight = current_line_highlight;
 2191    }
 2192
 2193    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 2194        self.collapse_matches = collapse_matches;
 2195    }
 2196
 2197    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 2198        if self.collapse_matches {
 2199            return range.start..range.start;
 2200        }
 2201        range.clone()
 2202    }
 2203
 2204    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
 2205        if self.display_map.read(cx).clip_at_line_ends != clip {
 2206            self.display_map
 2207                .update(cx, |map, _| map.clip_at_line_ends = clip);
 2208        }
 2209    }
 2210
 2211    pub fn set_keymap_context_layer<Tag: 'static>(
 2212        &mut self,
 2213        context: KeyContext,
 2214        cx: &mut ViewContext<Self>,
 2215    ) {
 2216        self.keymap_context_layers
 2217            .insert(TypeId::of::<Tag>(), context);
 2218        cx.notify();
 2219    }
 2220
 2221    pub fn remove_keymap_context_layer<Tag: 'static>(&mut self, cx: &mut ViewContext<Self>) {
 2222        self.keymap_context_layers.remove(&TypeId::of::<Tag>());
 2223        cx.notify();
 2224    }
 2225
 2226    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 2227        self.input_enabled = input_enabled;
 2228    }
 2229
 2230    pub fn set_autoindent(&mut self, autoindent: bool) {
 2231        if autoindent {
 2232            self.autoindent_mode = Some(AutoindentMode::EachLine);
 2233        } else {
 2234            self.autoindent_mode = None;
 2235        }
 2236    }
 2237
 2238    pub fn read_only(&self, cx: &AppContext) -> bool {
 2239        self.read_only || self.buffer.read(cx).read_only()
 2240    }
 2241
 2242    pub fn set_read_only(&mut self, read_only: bool) {
 2243        self.read_only = read_only;
 2244    }
 2245
 2246    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 2247        self.use_autoclose = autoclose;
 2248    }
 2249
 2250    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 2251        self.use_auto_surround = auto_surround;
 2252    }
 2253
 2254    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 2255        self.auto_replace_emoji_shortcode = auto_replace;
 2256    }
 2257
 2258    pub fn set_show_inline_completions(&mut self, show_inline_completions: bool) {
 2259        self.show_inline_completions = show_inline_completions;
 2260    }
 2261
 2262    pub fn set_use_modal_editing(&mut self, to: bool) {
 2263        self.use_modal_editing = to;
 2264    }
 2265
 2266    pub fn use_modal_editing(&self) -> bool {
 2267        self.use_modal_editing
 2268    }
 2269
 2270    fn selections_did_change(
 2271        &mut self,
 2272        local: bool,
 2273        old_cursor_position: &Anchor,
 2274        show_completions: bool,
 2275        cx: &mut ViewContext<Self>,
 2276    ) {
 2277        // Copy selections to primary selection buffer
 2278        #[cfg(target_os = "linux")]
 2279        if local {
 2280            let selections = self.selections.all::<usize>(cx);
 2281            let buffer_handle = self.buffer.read(cx).read(cx);
 2282
 2283            let mut text = String::new();
 2284            for (index, selection) in selections.iter().enumerate() {
 2285                let text_for_selection = buffer_handle
 2286                    .text_for_range(selection.start..selection.end)
 2287                    .collect::<String>();
 2288
 2289                text.push_str(&text_for_selection);
 2290                if index != selections.len() - 1 {
 2291                    text.push('\n');
 2292                }
 2293            }
 2294
 2295            if !text.is_empty() {
 2296                cx.write_to_primary(ClipboardItem::new(text));
 2297            }
 2298        }
 2299
 2300        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
 2301            self.buffer.update(cx, |buffer, cx| {
 2302                buffer.set_active_selections(
 2303                    &self.selections.disjoint_anchors(),
 2304                    self.selections.line_mode,
 2305                    self.cursor_shape,
 2306                    cx,
 2307                )
 2308            });
 2309        }
 2310        let display_map = self
 2311            .display_map
 2312            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2313        let buffer = &display_map.buffer_snapshot;
 2314        self.add_selections_state = None;
 2315        self.select_next_state = None;
 2316        self.select_prev_state = None;
 2317        self.select_larger_syntax_node_stack.clear();
 2318        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2319        self.snippet_stack
 2320            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2321        self.take_rename(false, cx);
 2322
 2323        let new_cursor_position = self.selections.newest_anchor().head();
 2324
 2325        self.push_to_nav_history(
 2326            *old_cursor_position,
 2327            Some(new_cursor_position.to_point(buffer)),
 2328            cx,
 2329        );
 2330
 2331        if local {
 2332            let new_cursor_position = self.selections.newest_anchor().head();
 2333            let mut context_menu = self.context_menu.write();
 2334            let completion_menu = match context_menu.as_ref() {
 2335                Some(ContextMenu::Completions(menu)) => Some(menu),
 2336
 2337                _ => {
 2338                    *context_menu = None;
 2339                    None
 2340                }
 2341            };
 2342
 2343            if let Some(completion_menu) = completion_menu {
 2344                let cursor_position = new_cursor_position.to_offset(buffer);
 2345                let (word_range, kind) = buffer.surrounding_word(completion_menu.initial_position);
 2346                if kind == Some(CharKind::Word)
 2347                    && word_range.to_inclusive().contains(&cursor_position)
 2348                {
 2349                    let mut completion_menu = completion_menu.clone();
 2350                    drop(context_menu);
 2351
 2352                    let query = Self::completion_query(buffer, cursor_position);
 2353                    cx.spawn(move |this, mut cx| async move {
 2354                        completion_menu
 2355                            .filter(query.as_deref(), cx.background_executor().clone())
 2356                            .await;
 2357
 2358                        this.update(&mut cx, |this, cx| {
 2359                            let mut context_menu = this.context_menu.write();
 2360                            let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
 2361                                return;
 2362                            };
 2363
 2364                            if menu.id > completion_menu.id {
 2365                                return;
 2366                            }
 2367
 2368                            *context_menu = Some(ContextMenu::Completions(completion_menu));
 2369                            drop(context_menu);
 2370                            cx.notify();
 2371                        })
 2372                    })
 2373                    .detach();
 2374
 2375                    if show_completions {
 2376                        self.show_completions(&ShowCompletions { trigger: None }, cx);
 2377                    }
 2378                } else {
 2379                    drop(context_menu);
 2380                    self.hide_context_menu(cx);
 2381                }
 2382            } else {
 2383                drop(context_menu);
 2384            }
 2385
 2386            hide_hover(self, cx);
 2387
 2388            if old_cursor_position.to_display_point(&display_map).row()
 2389                != new_cursor_position.to_display_point(&display_map).row()
 2390            {
 2391                self.available_code_actions.take();
 2392            }
 2393            self.refresh_code_actions(cx);
 2394            self.refresh_document_highlights(cx);
 2395            refresh_matching_bracket_highlights(self, cx);
 2396            self.discard_inline_completion(false, cx);
 2397            linked_editing_ranges::refresh_linked_ranges(self, cx);
 2398            if self.git_blame_inline_enabled {
 2399                self.start_inline_blame_timer(cx);
 2400            }
 2401        }
 2402
 2403        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2404        cx.emit(EditorEvent::SelectionsChanged { local });
 2405
 2406        if self.selections.disjoint_anchors().len() == 1 {
 2407            cx.emit(SearchEvent::ActiveMatchChanged)
 2408        }
 2409        cx.notify();
 2410    }
 2411
 2412    pub fn change_selections<R>(
 2413        &mut self,
 2414        autoscroll: Option<Autoscroll>,
 2415        cx: &mut ViewContext<Self>,
 2416        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2417    ) -> R {
 2418        self.change_selections_inner(autoscroll, true, cx, change)
 2419    }
 2420
 2421    pub fn change_selections_inner<R>(
 2422        &mut self,
 2423        autoscroll: Option<Autoscroll>,
 2424        request_completions: bool,
 2425        cx: &mut ViewContext<Self>,
 2426        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2427    ) -> R {
 2428        let old_cursor_position = self.selections.newest_anchor().head();
 2429        self.push_to_selection_history();
 2430
 2431        let (changed, result) = self.selections.change_with(cx, change);
 2432
 2433        if changed {
 2434            if let Some(autoscroll) = autoscroll {
 2435                self.request_autoscroll(autoscroll, cx);
 2436            }
 2437            self.selections_did_change(true, &old_cursor_position, request_completions, cx);
 2438
 2439            if self.should_open_signature_help_automatically(
 2440                &old_cursor_position,
 2441                self.signature_help_state.backspace_pressed(),
 2442                cx,
 2443            ) {
 2444                self.show_signature_help(&ShowSignatureHelp, cx);
 2445            }
 2446            self.signature_help_state.set_backspace_pressed(false);
 2447        }
 2448
 2449        result
 2450    }
 2451
 2452    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2453    where
 2454        I: IntoIterator<Item = (Range<S>, T)>,
 2455        S: ToOffset,
 2456        T: Into<Arc<str>>,
 2457    {
 2458        if self.read_only(cx) {
 2459            return;
 2460        }
 2461
 2462        self.buffer
 2463            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2464    }
 2465
 2466    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2467    where
 2468        I: IntoIterator<Item = (Range<S>, T)>,
 2469        S: ToOffset,
 2470        T: Into<Arc<str>>,
 2471    {
 2472        if self.read_only(cx) {
 2473            return;
 2474        }
 2475
 2476        self.buffer.update(cx, |buffer, cx| {
 2477            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2478        });
 2479    }
 2480
 2481    pub fn edit_with_block_indent<I, S, T>(
 2482        &mut self,
 2483        edits: I,
 2484        original_indent_columns: Vec<u32>,
 2485        cx: &mut ViewContext<Self>,
 2486    ) where
 2487        I: IntoIterator<Item = (Range<S>, T)>,
 2488        S: ToOffset,
 2489        T: Into<Arc<str>>,
 2490    {
 2491        if self.read_only(cx) {
 2492            return;
 2493        }
 2494
 2495        self.buffer.update(cx, |buffer, cx| {
 2496            buffer.edit(
 2497                edits,
 2498                Some(AutoindentMode::Block {
 2499                    original_indent_columns,
 2500                }),
 2501                cx,
 2502            )
 2503        });
 2504    }
 2505
 2506    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
 2507        self.hide_context_menu(cx);
 2508
 2509        match phase {
 2510            SelectPhase::Begin {
 2511                position,
 2512                add,
 2513                click_count,
 2514            } => self.begin_selection(position, add, click_count, cx),
 2515            SelectPhase::BeginColumnar {
 2516                position,
 2517                goal_column,
 2518                reset,
 2519            } => self.begin_columnar_selection(position, goal_column, reset, cx),
 2520            SelectPhase::Extend {
 2521                position,
 2522                click_count,
 2523            } => self.extend_selection(position, click_count, cx),
 2524            SelectPhase::Update {
 2525                position,
 2526                goal_column,
 2527                scroll_delta,
 2528            } => self.update_selection(position, goal_column, scroll_delta, cx),
 2529            SelectPhase::End => self.end_selection(cx),
 2530        }
 2531    }
 2532
 2533    fn extend_selection(
 2534        &mut self,
 2535        position: DisplayPoint,
 2536        click_count: usize,
 2537        cx: &mut ViewContext<Self>,
 2538    ) {
 2539        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2540        let tail = self.selections.newest::<usize>(cx).tail();
 2541        self.begin_selection(position, false, click_count, cx);
 2542
 2543        let position = position.to_offset(&display_map, Bias::Left);
 2544        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2545
 2546        let mut pending_selection = self
 2547            .selections
 2548            .pending_anchor()
 2549            .expect("extend_selection not called with pending selection");
 2550        if position >= tail {
 2551            pending_selection.start = tail_anchor;
 2552        } else {
 2553            pending_selection.end = tail_anchor;
 2554            pending_selection.reversed = true;
 2555        }
 2556
 2557        let mut pending_mode = self.selections.pending_mode().unwrap();
 2558        match &mut pending_mode {
 2559            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2560            _ => {}
 2561        }
 2562
 2563        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 2564            s.set_pending(pending_selection, pending_mode)
 2565        });
 2566    }
 2567
 2568    fn begin_selection(
 2569        &mut self,
 2570        position: DisplayPoint,
 2571        add: bool,
 2572        click_count: usize,
 2573        cx: &mut ViewContext<Self>,
 2574    ) {
 2575        if !self.focus_handle.is_focused(cx) {
 2576            self.last_focused_descendant = None;
 2577            cx.focus(&self.focus_handle);
 2578        }
 2579
 2580        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2581        let buffer = &display_map.buffer_snapshot;
 2582        let newest_selection = self.selections.newest_anchor().clone();
 2583        let position = display_map.clip_point(position, Bias::Left);
 2584
 2585        let start;
 2586        let end;
 2587        let mode;
 2588        let auto_scroll;
 2589        match click_count {
 2590            1 => {
 2591                start = buffer.anchor_before(position.to_point(&display_map));
 2592                end = start;
 2593                mode = SelectMode::Character;
 2594                auto_scroll = true;
 2595            }
 2596            2 => {
 2597                let range = movement::surrounding_word(&display_map, position);
 2598                start = buffer.anchor_before(range.start.to_point(&display_map));
 2599                end = buffer.anchor_before(range.end.to_point(&display_map));
 2600                mode = SelectMode::Word(start..end);
 2601                auto_scroll = true;
 2602            }
 2603            3 => {
 2604                let position = display_map
 2605                    .clip_point(position, Bias::Left)
 2606                    .to_point(&display_map);
 2607                let line_start = display_map.prev_line_boundary(position).0;
 2608                let next_line_start = buffer.clip_point(
 2609                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2610                    Bias::Left,
 2611                );
 2612                start = buffer.anchor_before(line_start);
 2613                end = buffer.anchor_before(next_line_start);
 2614                mode = SelectMode::Line(start..end);
 2615                auto_scroll = true;
 2616            }
 2617            _ => {
 2618                start = buffer.anchor_before(0);
 2619                end = buffer.anchor_before(buffer.len());
 2620                mode = SelectMode::All;
 2621                auto_scroll = false;
 2622            }
 2623        }
 2624
 2625        let point_to_delete: Option<usize> = {
 2626            let selected_points: Vec<Selection<Point>> =
 2627                self.selections.disjoint_in_range(start..end, cx);
 2628
 2629            if !add || click_count > 1 {
 2630                None
 2631            } else if selected_points.len() > 0 {
 2632                Some(selected_points[0].id)
 2633            } else {
 2634                let clicked_point_already_selected =
 2635                    self.selections.disjoint.iter().find(|selection| {
 2636                        selection.start.to_point(buffer) == start.to_point(buffer)
 2637                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2638                    });
 2639
 2640                if let Some(selection) = clicked_point_already_selected {
 2641                    Some(selection.id)
 2642                } else {
 2643                    None
 2644                }
 2645            }
 2646        };
 2647
 2648        let selections_count = self.selections.count();
 2649
 2650        self.change_selections(auto_scroll.then(|| Autoscroll::newest()), cx, |s| {
 2651            if let Some(point_to_delete) = point_to_delete {
 2652                s.delete(point_to_delete);
 2653
 2654                if selections_count == 1 {
 2655                    s.set_pending_anchor_range(start..end, mode);
 2656                }
 2657            } else {
 2658                if !add {
 2659                    s.clear_disjoint();
 2660                } else if click_count > 1 {
 2661                    s.delete(newest_selection.id)
 2662                }
 2663
 2664                s.set_pending_anchor_range(start..end, mode);
 2665            }
 2666        });
 2667    }
 2668
 2669    fn begin_columnar_selection(
 2670        &mut self,
 2671        position: DisplayPoint,
 2672        goal_column: u32,
 2673        reset: bool,
 2674        cx: &mut ViewContext<Self>,
 2675    ) {
 2676        if !self.focus_handle.is_focused(cx) {
 2677            self.last_focused_descendant = None;
 2678            cx.focus(&self.focus_handle);
 2679        }
 2680
 2681        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2682
 2683        if reset {
 2684            let pointer_position = display_map
 2685                .buffer_snapshot
 2686                .anchor_before(position.to_point(&display_map));
 2687
 2688            self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 2689                s.clear_disjoint();
 2690                s.set_pending_anchor_range(
 2691                    pointer_position..pointer_position,
 2692                    SelectMode::Character,
 2693                );
 2694            });
 2695        }
 2696
 2697        let tail = self.selections.newest::<Point>(cx).tail();
 2698        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2699
 2700        if !reset {
 2701            self.select_columns(
 2702                tail.to_display_point(&display_map),
 2703                position,
 2704                goal_column,
 2705                &display_map,
 2706                cx,
 2707            );
 2708        }
 2709    }
 2710
 2711    fn update_selection(
 2712        &mut self,
 2713        position: DisplayPoint,
 2714        goal_column: u32,
 2715        scroll_delta: gpui::Point<f32>,
 2716        cx: &mut ViewContext<Self>,
 2717    ) {
 2718        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2719
 2720        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2721            let tail = tail.to_display_point(&display_map);
 2722            self.select_columns(tail, position, goal_column, &display_map, cx);
 2723        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2724            let buffer = self.buffer.read(cx).snapshot(cx);
 2725            let head;
 2726            let tail;
 2727            let mode = self.selections.pending_mode().unwrap();
 2728            match &mode {
 2729                SelectMode::Character => {
 2730                    head = position.to_point(&display_map);
 2731                    tail = pending.tail().to_point(&buffer);
 2732                }
 2733                SelectMode::Word(original_range) => {
 2734                    let original_display_range = original_range.start.to_display_point(&display_map)
 2735                        ..original_range.end.to_display_point(&display_map);
 2736                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2737                        ..original_display_range.end.to_point(&display_map);
 2738                    if movement::is_inside_word(&display_map, position)
 2739                        || original_display_range.contains(&position)
 2740                    {
 2741                        let word_range = movement::surrounding_word(&display_map, position);
 2742                        if word_range.start < original_display_range.start {
 2743                            head = word_range.start.to_point(&display_map);
 2744                        } else {
 2745                            head = word_range.end.to_point(&display_map);
 2746                        }
 2747                    } else {
 2748                        head = position.to_point(&display_map);
 2749                    }
 2750
 2751                    if head <= original_buffer_range.start {
 2752                        tail = original_buffer_range.end;
 2753                    } else {
 2754                        tail = original_buffer_range.start;
 2755                    }
 2756                }
 2757                SelectMode::Line(original_range) => {
 2758                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2759
 2760                    let position = display_map
 2761                        .clip_point(position, Bias::Left)
 2762                        .to_point(&display_map);
 2763                    let line_start = display_map.prev_line_boundary(position).0;
 2764                    let next_line_start = buffer.clip_point(
 2765                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2766                        Bias::Left,
 2767                    );
 2768
 2769                    if line_start < original_range.start {
 2770                        head = line_start
 2771                    } else {
 2772                        head = next_line_start
 2773                    }
 2774
 2775                    if head <= original_range.start {
 2776                        tail = original_range.end;
 2777                    } else {
 2778                        tail = original_range.start;
 2779                    }
 2780                }
 2781                SelectMode::All => {
 2782                    return;
 2783                }
 2784            };
 2785
 2786            if head < tail {
 2787                pending.start = buffer.anchor_before(head);
 2788                pending.end = buffer.anchor_before(tail);
 2789                pending.reversed = true;
 2790            } else {
 2791                pending.start = buffer.anchor_before(tail);
 2792                pending.end = buffer.anchor_before(head);
 2793                pending.reversed = false;
 2794            }
 2795
 2796            self.change_selections(None, cx, |s| {
 2797                s.set_pending(pending, mode);
 2798            });
 2799        } else {
 2800            log::error!("update_selection dispatched with no pending selection");
 2801            return;
 2802        }
 2803
 2804        self.apply_scroll_delta(scroll_delta, cx);
 2805        cx.notify();
 2806    }
 2807
 2808    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 2809        self.columnar_selection_tail.take();
 2810        if self.selections.pending_anchor().is_some() {
 2811            let selections = self.selections.all::<usize>(cx);
 2812            self.change_selections(None, cx, |s| {
 2813                s.select(selections);
 2814                s.clear_pending();
 2815            });
 2816        }
 2817    }
 2818
 2819    fn select_columns(
 2820        &mut self,
 2821        tail: DisplayPoint,
 2822        head: DisplayPoint,
 2823        goal_column: u32,
 2824        display_map: &DisplaySnapshot,
 2825        cx: &mut ViewContext<Self>,
 2826    ) {
 2827        let start_row = cmp::min(tail.row(), head.row());
 2828        let end_row = cmp::max(tail.row(), head.row());
 2829        let start_column = cmp::min(tail.column(), goal_column);
 2830        let end_column = cmp::max(tail.column(), goal_column);
 2831        let reversed = start_column < tail.column();
 2832
 2833        let selection_ranges = (start_row.0..=end_row.0)
 2834            .map(DisplayRow)
 2835            .filter_map(|row| {
 2836                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2837                    let start = display_map
 2838                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2839                        .to_point(display_map);
 2840                    let end = display_map
 2841                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2842                        .to_point(display_map);
 2843                    if reversed {
 2844                        Some(end..start)
 2845                    } else {
 2846                        Some(start..end)
 2847                    }
 2848                } else {
 2849                    None
 2850                }
 2851            })
 2852            .collect::<Vec<_>>();
 2853
 2854        self.change_selections(None, cx, |s| {
 2855            s.select_ranges(selection_ranges);
 2856        });
 2857        cx.notify();
 2858    }
 2859
 2860    pub fn has_pending_nonempty_selection(&self) -> bool {
 2861        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2862            Some(Selection { start, end, .. }) => start != end,
 2863            None => false,
 2864        };
 2865
 2866        pending_nonempty_selection
 2867            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2868    }
 2869
 2870    pub fn has_pending_selection(&self) -> bool {
 2871        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2872    }
 2873
 2874    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 2875        if self.clear_clicked_diff_hunks(cx) {
 2876            cx.notify();
 2877            return;
 2878        }
 2879        if self.dismiss_menus_and_popups(true, cx) {
 2880            return;
 2881        }
 2882
 2883        if self.mode == EditorMode::Full {
 2884            if self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel()) {
 2885                return;
 2886            }
 2887        }
 2888
 2889        cx.propagate();
 2890    }
 2891
 2892    pub fn dismiss_menus_and_popups(
 2893        &mut self,
 2894        should_report_inline_completion_event: bool,
 2895        cx: &mut ViewContext<Self>,
 2896    ) -> bool {
 2897        if self.take_rename(false, cx).is_some() {
 2898            return true;
 2899        }
 2900
 2901        if hide_hover(self, cx) {
 2902            return true;
 2903        }
 2904
 2905        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2906            return true;
 2907        }
 2908
 2909        if self.hide_context_menu(cx).is_some() {
 2910            return true;
 2911        }
 2912
 2913        if self.mouse_context_menu.take().is_some() {
 2914            return true;
 2915        }
 2916
 2917        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 2918            return true;
 2919        }
 2920
 2921        if self.snippet_stack.pop().is_some() {
 2922            return true;
 2923        }
 2924
 2925        if self.mode == EditorMode::Full {
 2926            if self.active_diagnostics.is_some() {
 2927                self.dismiss_diagnostics(cx);
 2928                return true;
 2929            }
 2930        }
 2931
 2932        false
 2933    }
 2934
 2935    fn linked_editing_ranges_for(
 2936        &self,
 2937        selection: Range<text::Anchor>,
 2938        cx: &AppContext,
 2939    ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
 2940        if self.linked_edit_ranges.is_empty() {
 2941            return None;
 2942        }
 2943        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2944            selection.end.buffer_id.and_then(|end_buffer_id| {
 2945                if selection.start.buffer_id != Some(end_buffer_id) {
 2946                    return None;
 2947                }
 2948                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2949                let snapshot = buffer.read(cx).snapshot();
 2950                self.linked_edit_ranges
 2951                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2952                    .map(|ranges| (ranges, snapshot, buffer))
 2953            })?;
 2954        use text::ToOffset as TO;
 2955        // find offset from the start of current range to current cursor position
 2956        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2957
 2958        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2959        let start_difference = start_offset - start_byte_offset;
 2960        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2961        let end_difference = end_offset - start_byte_offset;
 2962        // Current range has associated linked ranges.
 2963        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2964        for range in linked_ranges.iter() {
 2965            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2966            let end_offset = start_offset + end_difference;
 2967            let start_offset = start_offset + start_difference;
 2968            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2969                continue;
 2970            }
 2971            let start = buffer_snapshot.anchor_after(start_offset);
 2972            let end = buffer_snapshot.anchor_after(end_offset);
 2973            linked_edits
 2974                .entry(buffer.clone())
 2975                .or_default()
 2976                .push(start..end);
 2977        }
 2978        Some(linked_edits)
 2979    }
 2980
 2981    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 2982        let text: Arc<str> = text.into();
 2983
 2984        if self.read_only(cx) {
 2985            return;
 2986        }
 2987
 2988        let selections = self.selections.all_adjusted(cx);
 2989        let mut bracket_inserted = false;
 2990        let mut edits = Vec::new();
 2991        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2992        let mut new_selections = Vec::with_capacity(selections.len());
 2993        let mut new_autoclose_regions = Vec::new();
 2994        let snapshot = self.buffer.read(cx).read(cx);
 2995
 2996        for (selection, autoclose_region) in
 2997            self.selections_with_autoclose_regions(selections, &snapshot)
 2998        {
 2999            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 3000                // Determine if the inserted text matches the opening or closing
 3001                // bracket of any of this language's bracket pairs.
 3002                let mut bracket_pair = None;
 3003                let mut is_bracket_pair_start = false;
 3004                let mut is_bracket_pair_end = false;
 3005                if !text.is_empty() {
 3006                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 3007                    //  and they are removing the character that triggered IME popup.
 3008                    for (pair, enabled) in scope.brackets() {
 3009                        if !pair.close && !pair.surround {
 3010                            continue;
 3011                        }
 3012
 3013                        if enabled && pair.start.ends_with(text.as_ref()) {
 3014                            bracket_pair = Some(pair.clone());
 3015                            is_bracket_pair_start = true;
 3016                            break;
 3017                        }
 3018                        if pair.end.as_str() == text.as_ref() {
 3019                            bracket_pair = Some(pair.clone());
 3020                            is_bracket_pair_end = true;
 3021                            break;
 3022                        }
 3023                    }
 3024                }
 3025
 3026                if let Some(bracket_pair) = bracket_pair {
 3027                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 3028                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 3029                    let auto_surround =
 3030                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 3031                    if selection.is_empty() {
 3032                        if is_bracket_pair_start {
 3033                            let prefix_len = bracket_pair.start.len() - text.len();
 3034
 3035                            // If the inserted text is a suffix of an opening bracket and the
 3036                            // selection is preceded by the rest of the opening bracket, then
 3037                            // insert the closing bracket.
 3038                            let following_text_allows_autoclose = snapshot
 3039                                .chars_at(selection.start)
 3040                                .next()
 3041                                .map_or(true, |c| scope.should_autoclose_before(c));
 3042                            let preceding_text_matches_prefix = prefix_len == 0
 3043                                || (selection.start.column >= (prefix_len as u32)
 3044                                    && snapshot.contains_str_at(
 3045                                        Point::new(
 3046                                            selection.start.row,
 3047                                            selection.start.column - (prefix_len as u32),
 3048                                        ),
 3049                                        &bracket_pair.start[..prefix_len],
 3050                                    ));
 3051
 3052                            if autoclose
 3053                                && bracket_pair.close
 3054                                && following_text_allows_autoclose
 3055                                && preceding_text_matches_prefix
 3056                            {
 3057                                let anchor = snapshot.anchor_before(selection.end);
 3058                                new_selections.push((selection.map(|_| anchor), text.len()));
 3059                                new_autoclose_regions.push((
 3060                                    anchor,
 3061                                    text.len(),
 3062                                    selection.id,
 3063                                    bracket_pair.clone(),
 3064                                ));
 3065                                edits.push((
 3066                                    selection.range(),
 3067                                    format!("{}{}", text, bracket_pair.end).into(),
 3068                                ));
 3069                                bracket_inserted = true;
 3070                                continue;
 3071                            }
 3072                        }
 3073
 3074                        if let Some(region) = autoclose_region {
 3075                            // If the selection is followed by an auto-inserted closing bracket,
 3076                            // then don't insert that closing bracket again; just move the selection
 3077                            // past the closing bracket.
 3078                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3079                                && text.as_ref() == region.pair.end.as_str();
 3080                            if should_skip {
 3081                                let anchor = snapshot.anchor_after(selection.end);
 3082                                new_selections
 3083                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3084                                continue;
 3085                            }
 3086                        }
 3087
 3088                        let always_treat_brackets_as_autoclosed = snapshot
 3089                            .settings_at(selection.start, cx)
 3090                            .always_treat_brackets_as_autoclosed;
 3091                        if always_treat_brackets_as_autoclosed
 3092                            && is_bracket_pair_end
 3093                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3094                        {
 3095                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3096                            // and the inserted text is a closing bracket and the selection is followed
 3097                            // by the closing bracket then move the selection past the closing bracket.
 3098                            let anchor = snapshot.anchor_after(selection.end);
 3099                            new_selections.push((selection.map(|_| anchor), text.len()));
 3100                            continue;
 3101                        }
 3102                    }
 3103                    // If an opening bracket is 1 character long and is typed while
 3104                    // text is selected, then surround that text with the bracket pair.
 3105                    else if auto_surround
 3106                        && bracket_pair.surround
 3107                        && is_bracket_pair_start
 3108                        && bracket_pair.start.chars().count() == 1
 3109                    {
 3110                        edits.push((selection.start..selection.start, text.clone()));
 3111                        edits.push((
 3112                            selection.end..selection.end,
 3113                            bracket_pair.end.as_str().into(),
 3114                        ));
 3115                        bracket_inserted = true;
 3116                        new_selections.push((
 3117                            Selection {
 3118                                id: selection.id,
 3119                                start: snapshot.anchor_after(selection.start),
 3120                                end: snapshot.anchor_before(selection.end),
 3121                                reversed: selection.reversed,
 3122                                goal: selection.goal,
 3123                            },
 3124                            0,
 3125                        ));
 3126                        continue;
 3127                    }
 3128                }
 3129            }
 3130
 3131            if self.auto_replace_emoji_shortcode
 3132                && selection.is_empty()
 3133                && text.as_ref().ends_with(':')
 3134            {
 3135                if let Some(possible_emoji_short_code) =
 3136                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3137                {
 3138                    if !possible_emoji_short_code.is_empty() {
 3139                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3140                            let emoji_shortcode_start = Point::new(
 3141                                selection.start.row,
 3142                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3143                            );
 3144
 3145                            // Remove shortcode from buffer
 3146                            edits.push((
 3147                                emoji_shortcode_start..selection.start,
 3148                                "".to_string().into(),
 3149                            ));
 3150                            new_selections.push((
 3151                                Selection {
 3152                                    id: selection.id,
 3153                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3154                                    end: snapshot.anchor_before(selection.start),
 3155                                    reversed: selection.reversed,
 3156                                    goal: selection.goal,
 3157                                },
 3158                                0,
 3159                            ));
 3160
 3161                            // Insert emoji
 3162                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3163                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3164                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3165
 3166                            continue;
 3167                        }
 3168                    }
 3169                }
 3170            }
 3171
 3172            // If not handling any auto-close operation, then just replace the selected
 3173            // text with the given input and move the selection to the end of the
 3174            // newly inserted text.
 3175            let anchor = snapshot.anchor_after(selection.end);
 3176            if !self.linked_edit_ranges.is_empty() {
 3177                let start_anchor = snapshot.anchor_before(selection.start);
 3178
 3179                let is_word_char = text.chars().next().map_or(true, |char| {
 3180                    let scope = snapshot.language_scope_at(start_anchor.to_offset(&snapshot));
 3181                    let kind = char_kind(&scope, char);
 3182
 3183                    kind == CharKind::Word
 3184                });
 3185
 3186                if is_word_char {
 3187                    if let Some(ranges) = self
 3188                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3189                    {
 3190                        for (buffer, edits) in ranges {
 3191                            linked_edits
 3192                                .entry(buffer.clone())
 3193                                .or_default()
 3194                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3195                        }
 3196                    }
 3197                }
 3198            }
 3199
 3200            new_selections.push((selection.map(|_| anchor), 0));
 3201            edits.push((selection.start..selection.end, text.clone()));
 3202        }
 3203
 3204        drop(snapshot);
 3205
 3206        self.transact(cx, |this, cx| {
 3207            this.buffer.update(cx, |buffer, cx| {
 3208                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3209            });
 3210            for (buffer, edits) in linked_edits {
 3211                buffer.update(cx, |buffer, cx| {
 3212                    let snapshot = buffer.snapshot();
 3213                    let edits = edits
 3214                        .into_iter()
 3215                        .map(|(range, text)| {
 3216                            use text::ToPoint as TP;
 3217                            let end_point = TP::to_point(&range.end, &snapshot);
 3218                            let start_point = TP::to_point(&range.start, &snapshot);
 3219                            (start_point..end_point, text)
 3220                        })
 3221                        .sorted_by_key(|(range, _)| range.start)
 3222                        .collect::<Vec<_>>();
 3223                    buffer.edit(edits, None, cx);
 3224                })
 3225            }
 3226            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3227            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3228            let snapshot = this.buffer.read(cx).read(cx);
 3229            let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
 3230                .zip(new_selection_deltas)
 3231                .map(|(selection, delta)| Selection {
 3232                    id: selection.id,
 3233                    start: selection.start + delta,
 3234                    end: selection.end + delta,
 3235                    reversed: selection.reversed,
 3236                    goal: SelectionGoal::None,
 3237                })
 3238                .collect::<Vec<_>>();
 3239
 3240            let mut i = 0;
 3241            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3242                let position = position.to_offset(&snapshot) + delta;
 3243                let start = snapshot.anchor_before(position);
 3244                let end = snapshot.anchor_after(position);
 3245                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3246                    match existing_state.range.start.cmp(&start, &snapshot) {
 3247                        Ordering::Less => i += 1,
 3248                        Ordering::Greater => break,
 3249                        Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
 3250                            Ordering::Less => i += 1,
 3251                            Ordering::Equal => break,
 3252                            Ordering::Greater => break,
 3253                        },
 3254                    }
 3255                }
 3256                this.autoclose_regions.insert(
 3257                    i,
 3258                    AutocloseRegion {
 3259                        selection_id,
 3260                        range: start..end,
 3261                        pair,
 3262                    },
 3263                );
 3264            }
 3265
 3266            drop(snapshot);
 3267            let had_active_inline_completion = this.has_active_inline_completion(cx);
 3268            this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
 3269                s.select(new_selections)
 3270            });
 3271
 3272            if !bracket_inserted && EditorSettings::get_global(cx).use_on_type_format {
 3273                if let Some(on_type_format_task) =
 3274                    this.trigger_on_type_formatting(text.to_string(), cx)
 3275                {
 3276                    on_type_format_task.detach_and_log_err(cx);
 3277                }
 3278            }
 3279
 3280            let editor_settings = EditorSettings::get_global(cx);
 3281            if bracket_inserted
 3282                && (editor_settings.auto_signature_help
 3283                    || editor_settings.show_signature_help_after_edits)
 3284            {
 3285                this.show_signature_help(&ShowSignatureHelp, cx);
 3286            }
 3287
 3288            let trigger_in_words = !had_active_inline_completion;
 3289            this.trigger_completion_on_input(&text, trigger_in_words, cx);
 3290            linked_editing_ranges::refresh_linked_ranges(this, cx);
 3291            this.refresh_inline_completion(true, cx);
 3292        });
 3293    }
 3294
 3295    fn find_possible_emoji_shortcode_at_position(
 3296        snapshot: &MultiBufferSnapshot,
 3297        position: Point,
 3298    ) -> Option<String> {
 3299        let mut chars = Vec::new();
 3300        let mut found_colon = false;
 3301        for char in snapshot.reversed_chars_at(position).take(100) {
 3302            // Found a possible emoji shortcode in the middle of the buffer
 3303            if found_colon {
 3304                if char.is_whitespace() {
 3305                    chars.reverse();
 3306                    return Some(chars.iter().collect());
 3307                }
 3308                // If the previous character is not a whitespace, we are in the middle of a word
 3309                // and we only want to complete the shortcode if the word is made up of other emojis
 3310                let mut containing_word = String::new();
 3311                for ch in snapshot
 3312                    .reversed_chars_at(position)
 3313                    .skip(chars.len() + 1)
 3314                    .take(100)
 3315                {
 3316                    if ch.is_whitespace() {
 3317                        break;
 3318                    }
 3319                    containing_word.push(ch);
 3320                }
 3321                let containing_word = containing_word.chars().rev().collect::<String>();
 3322                if util::word_consists_of_emojis(containing_word.as_str()) {
 3323                    chars.reverse();
 3324                    return Some(chars.iter().collect());
 3325                }
 3326            }
 3327
 3328            if char.is_whitespace() || !char.is_ascii() {
 3329                return None;
 3330            }
 3331            if char == ':' {
 3332                found_colon = true;
 3333            } else {
 3334                chars.push(char);
 3335            }
 3336        }
 3337        // Found a possible emoji shortcode at the beginning of the buffer
 3338        chars.reverse();
 3339        Some(chars.iter().collect())
 3340    }
 3341
 3342    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 3343        self.transact(cx, |this, cx| {
 3344            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3345                let selections = this.selections.all::<usize>(cx);
 3346                let multi_buffer = this.buffer.read(cx);
 3347                let buffer = multi_buffer.snapshot(cx);
 3348                selections
 3349                    .iter()
 3350                    .map(|selection| {
 3351                        let start_point = selection.start.to_point(&buffer);
 3352                        let mut indent =
 3353                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3354                        indent.len = cmp::min(indent.len, start_point.column);
 3355                        let start = selection.start;
 3356                        let end = selection.end;
 3357                        let selection_is_empty = start == end;
 3358                        let language_scope = buffer.language_scope_at(start);
 3359                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3360                            &language_scope
 3361                        {
 3362                            let leading_whitespace_len = buffer
 3363                                .reversed_chars_at(start)
 3364                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3365                                .map(|c| c.len_utf8())
 3366                                .sum::<usize>();
 3367
 3368                            let trailing_whitespace_len = buffer
 3369                                .chars_at(end)
 3370                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3371                                .map(|c| c.len_utf8())
 3372                                .sum::<usize>();
 3373
 3374                            let insert_extra_newline =
 3375                                language.brackets().any(|(pair, enabled)| {
 3376                                    let pair_start = pair.start.trim_end();
 3377                                    let pair_end = pair.end.trim_start();
 3378
 3379                                    enabled
 3380                                        && pair.newline
 3381                                        && buffer.contains_str_at(
 3382                                            end + trailing_whitespace_len,
 3383                                            pair_end,
 3384                                        )
 3385                                        && buffer.contains_str_at(
 3386                                            (start - leading_whitespace_len)
 3387                                                .saturating_sub(pair_start.len()),
 3388                                            pair_start,
 3389                                        )
 3390                                });
 3391
 3392                            // Comment extension on newline is allowed only for cursor selections
 3393                            let comment_delimiter = maybe!({
 3394                                if !selection_is_empty {
 3395                                    return None;
 3396                                }
 3397
 3398                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3399                                    return None;
 3400                                }
 3401
 3402                                let delimiters = language.line_comment_prefixes();
 3403                                let max_len_of_delimiter =
 3404                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3405                                let (snapshot, range) =
 3406                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3407
 3408                                let mut index_of_first_non_whitespace = 0;
 3409                                let comment_candidate = snapshot
 3410                                    .chars_for_range(range)
 3411                                    .skip_while(|c| {
 3412                                        let should_skip = c.is_whitespace();
 3413                                        if should_skip {
 3414                                            index_of_first_non_whitespace += 1;
 3415                                        }
 3416                                        should_skip
 3417                                    })
 3418                                    .take(max_len_of_delimiter)
 3419                                    .collect::<String>();
 3420                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3421                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3422                                })?;
 3423                                let cursor_is_placed_after_comment_marker =
 3424                                    index_of_first_non_whitespace + comment_prefix.len()
 3425                                        <= start_point.column as usize;
 3426                                if cursor_is_placed_after_comment_marker {
 3427                                    Some(comment_prefix.clone())
 3428                                } else {
 3429                                    None
 3430                                }
 3431                            });
 3432                            (comment_delimiter, insert_extra_newline)
 3433                        } else {
 3434                            (None, false)
 3435                        };
 3436
 3437                        let capacity_for_delimiter = comment_delimiter
 3438                            .as_deref()
 3439                            .map(str::len)
 3440                            .unwrap_or_default();
 3441                        let mut new_text =
 3442                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3443                        new_text.push_str("\n");
 3444                        new_text.extend(indent.chars());
 3445                        if let Some(delimiter) = &comment_delimiter {
 3446                            new_text.push_str(&delimiter);
 3447                        }
 3448                        if insert_extra_newline {
 3449                            new_text = new_text.repeat(2);
 3450                        }
 3451
 3452                        let anchor = buffer.anchor_after(end);
 3453                        let new_selection = selection.map(|_| anchor);
 3454                        (
 3455                            (start..end, new_text),
 3456                            (insert_extra_newline, new_selection),
 3457                        )
 3458                    })
 3459                    .unzip()
 3460            };
 3461
 3462            this.edit_with_autoindent(edits, cx);
 3463            let buffer = this.buffer.read(cx).snapshot(cx);
 3464            let new_selections = selection_fixup_info
 3465                .into_iter()
 3466                .map(|(extra_newline_inserted, new_selection)| {
 3467                    let mut cursor = new_selection.end.to_point(&buffer);
 3468                    if extra_newline_inserted {
 3469                        cursor.row -= 1;
 3470                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3471                    }
 3472                    new_selection.map(|_| cursor)
 3473                })
 3474                .collect();
 3475
 3476            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3477            this.refresh_inline_completion(true, cx);
 3478        });
 3479    }
 3480
 3481    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3482        let buffer = self.buffer.read(cx);
 3483        let snapshot = buffer.snapshot(cx);
 3484
 3485        let mut edits = Vec::new();
 3486        let mut rows = Vec::new();
 3487
 3488        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3489            let cursor = selection.head();
 3490            let row = cursor.row;
 3491
 3492            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3493
 3494            let newline = "\n".to_string();
 3495            edits.push((start_of_line..start_of_line, newline));
 3496
 3497            rows.push(row + rows_inserted as u32);
 3498        }
 3499
 3500        self.transact(cx, |editor, cx| {
 3501            editor.edit(edits, cx);
 3502
 3503            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3504                let mut index = 0;
 3505                s.move_cursors_with(|map, _, _| {
 3506                    let row = rows[index];
 3507                    index += 1;
 3508
 3509                    let point = Point::new(row, 0);
 3510                    let boundary = map.next_line_boundary(point).1;
 3511                    let clipped = map.clip_point(boundary, Bias::Left);
 3512
 3513                    (clipped, SelectionGoal::None)
 3514                });
 3515            });
 3516
 3517            let mut indent_edits = Vec::new();
 3518            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3519            for row in rows {
 3520                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3521                for (row, indent) in indents {
 3522                    if indent.len == 0 {
 3523                        continue;
 3524                    }
 3525
 3526                    let text = match indent.kind {
 3527                        IndentKind::Space => " ".repeat(indent.len as usize),
 3528                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3529                    };
 3530                    let point = Point::new(row.0, 0);
 3531                    indent_edits.push((point..point, text));
 3532                }
 3533            }
 3534            editor.edit(indent_edits, cx);
 3535        });
 3536    }
 3537
 3538    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3539        let buffer = self.buffer.read(cx);
 3540        let snapshot = buffer.snapshot(cx);
 3541
 3542        let mut edits = Vec::new();
 3543        let mut rows = Vec::new();
 3544        let mut rows_inserted = 0;
 3545
 3546        for selection in self.selections.all_adjusted(cx) {
 3547            let cursor = selection.head();
 3548            let row = cursor.row;
 3549
 3550            let point = Point::new(row + 1, 0);
 3551            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3552
 3553            let newline = "\n".to_string();
 3554            edits.push((start_of_line..start_of_line, newline));
 3555
 3556            rows_inserted += 1;
 3557            rows.push(row + rows_inserted);
 3558        }
 3559
 3560        self.transact(cx, |editor, cx| {
 3561            editor.edit(edits, cx);
 3562
 3563            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3564                let mut index = 0;
 3565                s.move_cursors_with(|map, _, _| {
 3566                    let row = rows[index];
 3567                    index += 1;
 3568
 3569                    let point = Point::new(row, 0);
 3570                    let boundary = map.next_line_boundary(point).1;
 3571                    let clipped = map.clip_point(boundary, Bias::Left);
 3572
 3573                    (clipped, SelectionGoal::None)
 3574                });
 3575            });
 3576
 3577            let mut indent_edits = Vec::new();
 3578            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3579            for row in rows {
 3580                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3581                for (row, indent) in indents {
 3582                    if indent.len == 0 {
 3583                        continue;
 3584                    }
 3585
 3586                    let text = match indent.kind {
 3587                        IndentKind::Space => " ".repeat(indent.len as usize),
 3588                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3589                    };
 3590                    let point = Point::new(row.0, 0);
 3591                    indent_edits.push((point..point, text));
 3592                }
 3593            }
 3594            editor.edit(indent_edits, cx);
 3595        });
 3596    }
 3597
 3598    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3599        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3600            original_indent_columns: Vec::new(),
 3601        });
 3602        self.insert_with_autoindent_mode(text, autoindent, cx);
 3603    }
 3604
 3605    fn insert_with_autoindent_mode(
 3606        &mut self,
 3607        text: &str,
 3608        autoindent_mode: Option<AutoindentMode>,
 3609        cx: &mut ViewContext<Self>,
 3610    ) {
 3611        if self.read_only(cx) {
 3612            return;
 3613        }
 3614
 3615        let text: Arc<str> = text.into();
 3616        self.transact(cx, |this, cx| {
 3617            let old_selections = this.selections.all_adjusted(cx);
 3618            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3619                let anchors = {
 3620                    let snapshot = buffer.read(cx);
 3621                    old_selections
 3622                        .iter()
 3623                        .map(|s| {
 3624                            let anchor = snapshot.anchor_after(s.head());
 3625                            s.map(|_| anchor)
 3626                        })
 3627                        .collect::<Vec<_>>()
 3628                };
 3629                buffer.edit(
 3630                    old_selections
 3631                        .iter()
 3632                        .map(|s| (s.start..s.end, text.clone())),
 3633                    autoindent_mode,
 3634                    cx,
 3635                );
 3636                anchors
 3637            });
 3638
 3639            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3640                s.select_anchors(selection_anchors);
 3641            })
 3642        });
 3643    }
 3644
 3645    fn trigger_completion_on_input(
 3646        &mut self,
 3647        text: &str,
 3648        trigger_in_words: bool,
 3649        cx: &mut ViewContext<Self>,
 3650    ) {
 3651        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3652            self.show_completions(
 3653                &ShowCompletions {
 3654                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3655                },
 3656                cx,
 3657            );
 3658        } else {
 3659            self.hide_context_menu(cx);
 3660        }
 3661    }
 3662
 3663    fn is_completion_trigger(
 3664        &self,
 3665        text: &str,
 3666        trigger_in_words: bool,
 3667        cx: &mut ViewContext<Self>,
 3668    ) -> bool {
 3669        let position = self.selections.newest_anchor().head();
 3670        let multibuffer = self.buffer.read(cx);
 3671        let Some(buffer) = position
 3672            .buffer_id
 3673            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3674        else {
 3675            return false;
 3676        };
 3677
 3678        if let Some(completion_provider) = &self.completion_provider {
 3679            completion_provider.is_completion_trigger(
 3680                &buffer,
 3681                position.text_anchor,
 3682                text,
 3683                trigger_in_words,
 3684                cx,
 3685            )
 3686        } else {
 3687            false
 3688        }
 3689    }
 3690
 3691    /// If any empty selections is touching the start of its innermost containing autoclose
 3692    /// region, expand it to select the brackets.
 3693    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 3694        let selections = self.selections.all::<usize>(cx);
 3695        let buffer = self.buffer.read(cx).read(cx);
 3696        let new_selections = self
 3697            .selections_with_autoclose_regions(selections, &buffer)
 3698            .map(|(mut selection, region)| {
 3699                if !selection.is_empty() {
 3700                    return selection;
 3701                }
 3702
 3703                if let Some(region) = region {
 3704                    let mut range = region.range.to_offset(&buffer);
 3705                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3706                        range.start -= region.pair.start.len();
 3707                        if buffer.contains_str_at(range.start, &region.pair.start)
 3708                            && buffer.contains_str_at(range.end, &region.pair.end)
 3709                        {
 3710                            range.end += region.pair.end.len();
 3711                            selection.start = range.start;
 3712                            selection.end = range.end;
 3713
 3714                            return selection;
 3715                        }
 3716                    }
 3717                }
 3718
 3719                let always_treat_brackets_as_autoclosed = buffer
 3720                    .settings_at(selection.start, cx)
 3721                    .always_treat_brackets_as_autoclosed;
 3722
 3723                if !always_treat_brackets_as_autoclosed {
 3724                    return selection;
 3725                }
 3726
 3727                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3728                    for (pair, enabled) in scope.brackets() {
 3729                        if !enabled || !pair.close {
 3730                            continue;
 3731                        }
 3732
 3733                        if buffer.contains_str_at(selection.start, &pair.end) {
 3734                            let pair_start_len = pair.start.len();
 3735                            if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
 3736                            {
 3737                                selection.start -= pair_start_len;
 3738                                selection.end += pair.end.len();
 3739
 3740                                return selection;
 3741                            }
 3742                        }
 3743                    }
 3744                }
 3745
 3746                selection
 3747            })
 3748            .collect();
 3749
 3750        drop(buffer);
 3751        self.change_selections(None, cx, |selections| selections.select(new_selections));
 3752    }
 3753
 3754    /// Iterate the given selections, and for each one, find the smallest surrounding
 3755    /// autoclose region. This uses the ordering of the selections and the autoclose
 3756    /// regions to avoid repeated comparisons.
 3757    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3758        &'a self,
 3759        selections: impl IntoIterator<Item = Selection<D>>,
 3760        buffer: &'a MultiBufferSnapshot,
 3761    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3762        let mut i = 0;
 3763        let mut regions = self.autoclose_regions.as_slice();
 3764        selections.into_iter().map(move |selection| {
 3765            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3766
 3767            let mut enclosing = None;
 3768            while let Some(pair_state) = regions.get(i) {
 3769                if pair_state.range.end.to_offset(buffer) < range.start {
 3770                    regions = &regions[i + 1..];
 3771                    i = 0;
 3772                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3773                    break;
 3774                } else {
 3775                    if pair_state.selection_id == selection.id {
 3776                        enclosing = Some(pair_state);
 3777                    }
 3778                    i += 1;
 3779                }
 3780            }
 3781
 3782            (selection.clone(), enclosing)
 3783        })
 3784    }
 3785
 3786    /// Remove any autoclose regions that no longer contain their selection.
 3787    fn invalidate_autoclose_regions(
 3788        &mut self,
 3789        mut selections: &[Selection<Anchor>],
 3790        buffer: &MultiBufferSnapshot,
 3791    ) {
 3792        self.autoclose_regions.retain(|state| {
 3793            let mut i = 0;
 3794            while let Some(selection) = selections.get(i) {
 3795                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3796                    selections = &selections[1..];
 3797                    continue;
 3798                }
 3799                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3800                    break;
 3801                }
 3802                if selection.id == state.selection_id {
 3803                    return true;
 3804                } else {
 3805                    i += 1;
 3806                }
 3807            }
 3808            false
 3809        });
 3810    }
 3811
 3812    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3813        let offset = position.to_offset(buffer);
 3814        let (word_range, kind) = buffer.surrounding_word(offset);
 3815        if offset > word_range.start && kind == Some(CharKind::Word) {
 3816            Some(
 3817                buffer
 3818                    .text_for_range(word_range.start..offset)
 3819                    .collect::<String>(),
 3820            )
 3821        } else {
 3822            None
 3823        }
 3824    }
 3825
 3826    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 3827        self.refresh_inlay_hints(
 3828            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3829            cx,
 3830        );
 3831    }
 3832
 3833    pub fn inlay_hints_enabled(&self) -> bool {
 3834        self.inlay_hint_cache.enabled
 3835    }
 3836
 3837    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 3838        if self.project.is_none() || self.mode != EditorMode::Full {
 3839            return;
 3840        }
 3841
 3842        let reason_description = reason.description();
 3843        let ignore_debounce = matches!(
 3844            reason,
 3845            InlayHintRefreshReason::SettingsChange(_)
 3846                | InlayHintRefreshReason::Toggle(_)
 3847                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3848        );
 3849        let (invalidate_cache, required_languages) = match reason {
 3850            InlayHintRefreshReason::Toggle(enabled) => {
 3851                self.inlay_hint_cache.enabled = enabled;
 3852                if enabled {
 3853                    (InvalidationStrategy::RefreshRequested, None)
 3854                } else {
 3855                    self.inlay_hint_cache.clear();
 3856                    self.splice_inlays(
 3857                        self.visible_inlay_hints(cx)
 3858                            .iter()
 3859                            .map(|inlay| inlay.id)
 3860                            .collect(),
 3861                        Vec::new(),
 3862                        cx,
 3863                    );
 3864                    return;
 3865                }
 3866            }
 3867            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3868                match self.inlay_hint_cache.update_settings(
 3869                    &self.buffer,
 3870                    new_settings,
 3871                    self.visible_inlay_hints(cx),
 3872                    cx,
 3873                ) {
 3874                    ControlFlow::Break(Some(InlaySplice {
 3875                        to_remove,
 3876                        to_insert,
 3877                    })) => {
 3878                        self.splice_inlays(to_remove, to_insert, cx);
 3879                        return;
 3880                    }
 3881                    ControlFlow::Break(None) => return,
 3882                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3883                }
 3884            }
 3885            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3886                if let Some(InlaySplice {
 3887                    to_remove,
 3888                    to_insert,
 3889                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3890                {
 3891                    self.splice_inlays(to_remove, to_insert, cx);
 3892                }
 3893                return;
 3894            }
 3895            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3896            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3897                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3898            }
 3899            InlayHintRefreshReason::RefreshRequested => {
 3900                (InvalidationStrategy::RefreshRequested, None)
 3901            }
 3902        };
 3903
 3904        if let Some(InlaySplice {
 3905            to_remove,
 3906            to_insert,
 3907        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3908            reason_description,
 3909            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3910            invalidate_cache,
 3911            ignore_debounce,
 3912            cx,
 3913        ) {
 3914            self.splice_inlays(to_remove, to_insert, cx);
 3915        }
 3916    }
 3917
 3918    fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
 3919        self.display_map
 3920            .read(cx)
 3921            .current_inlays()
 3922            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3923            .cloned()
 3924            .collect()
 3925    }
 3926
 3927    pub fn excerpts_for_inlay_hints_query(
 3928        &self,
 3929        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3930        cx: &mut ViewContext<Editor>,
 3931    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 3932        let Some(project) = self.project.as_ref() else {
 3933            return HashMap::default();
 3934        };
 3935        let project = project.read(cx);
 3936        let multi_buffer = self.buffer().read(cx);
 3937        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3938        let multi_buffer_visible_start = self
 3939            .scroll_manager
 3940            .anchor()
 3941            .anchor
 3942            .to_point(&multi_buffer_snapshot);
 3943        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3944            multi_buffer_visible_start
 3945                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3946            Bias::Left,
 3947        );
 3948        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3949        multi_buffer
 3950            .range_to_buffer_ranges(multi_buffer_visible_range, cx)
 3951            .into_iter()
 3952            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3953            .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
 3954                let buffer = buffer_handle.read(cx);
 3955                let buffer_file = project::File::from_dyn(buffer.file())?;
 3956                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3957                let worktree_entry = buffer_worktree
 3958                    .read(cx)
 3959                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3960                if worktree_entry.is_ignored {
 3961                    return None;
 3962                }
 3963
 3964                let language = buffer.language()?;
 3965                if let Some(restrict_to_languages) = restrict_to_languages {
 3966                    if !restrict_to_languages.contains(language) {
 3967                        return None;
 3968                    }
 3969                }
 3970                Some((
 3971                    excerpt_id,
 3972                    (
 3973                        buffer_handle,
 3974                        buffer.version().clone(),
 3975                        excerpt_visible_range,
 3976                    ),
 3977                ))
 3978            })
 3979            .collect()
 3980    }
 3981
 3982    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 3983        TextLayoutDetails {
 3984            text_system: cx.text_system().clone(),
 3985            editor_style: self.style.clone().unwrap(),
 3986            rem_size: cx.rem_size(),
 3987            scroll_anchor: self.scroll_manager.anchor(),
 3988            visible_rows: self.visible_line_count(),
 3989            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3990        }
 3991    }
 3992
 3993    fn splice_inlays(
 3994        &self,
 3995        to_remove: Vec<InlayId>,
 3996        to_insert: Vec<Inlay>,
 3997        cx: &mut ViewContext<Self>,
 3998    ) {
 3999        self.display_map.update(cx, |display_map, cx| {
 4000            display_map.splice_inlays(to_remove, to_insert, cx);
 4001        });
 4002        cx.notify();
 4003    }
 4004
 4005    fn trigger_on_type_formatting(
 4006        &self,
 4007        input: String,
 4008        cx: &mut ViewContext<Self>,
 4009    ) -> Option<Task<Result<()>>> {
 4010        if input.len() != 1 {
 4011            return None;
 4012        }
 4013
 4014        let project = self.project.as_ref()?;
 4015        let position = self.selections.newest_anchor().head();
 4016        let (buffer, buffer_position) = self
 4017            .buffer
 4018            .read(cx)
 4019            .text_anchor_for_position(position, cx)?;
 4020
 4021        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 4022        // hence we do LSP request & edit on host side only — add formats to host's history.
 4023        let push_to_lsp_host_history = true;
 4024        // If this is not the host, append its history with new edits.
 4025        let push_to_client_history = project.read(cx).is_remote();
 4026
 4027        let on_type_formatting = project.update(cx, |project, cx| {
 4028            project.on_type_format(
 4029                buffer.clone(),
 4030                buffer_position,
 4031                input,
 4032                push_to_lsp_host_history,
 4033                cx,
 4034            )
 4035        });
 4036        Some(cx.spawn(|editor, mut cx| async move {
 4037            if let Some(transaction) = on_type_formatting.await? {
 4038                if push_to_client_history {
 4039                    buffer
 4040                        .update(&mut cx, |buffer, _| {
 4041                            buffer.push_transaction(transaction, Instant::now());
 4042                        })
 4043                        .ok();
 4044                }
 4045                editor.update(&mut cx, |editor, cx| {
 4046                    editor.refresh_document_highlights(cx);
 4047                })?;
 4048            }
 4049            Ok(())
 4050        }))
 4051    }
 4052
 4053    pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
 4054        if self.pending_rename.is_some() {
 4055            return;
 4056        }
 4057
 4058        let Some(provider) = self.completion_provider.as_ref() else {
 4059            return;
 4060        };
 4061
 4062        let position = self.selections.newest_anchor().head();
 4063        let (buffer, buffer_position) =
 4064            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4065                output
 4066            } else {
 4067                return;
 4068            };
 4069
 4070        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4071        let is_followup_invoke = {
 4072            let context_menu_state = self.context_menu.read();
 4073            matches!(
 4074                context_menu_state.deref(),
 4075                Some(ContextMenu::Completions(_))
 4076            )
 4077        };
 4078        let trigger_kind = match (&options.trigger, is_followup_invoke) {
 4079            (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
 4080            (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(&trigger) => {
 4081                CompletionTriggerKind::TRIGGER_CHARACTER
 4082            }
 4083
 4084            _ => CompletionTriggerKind::INVOKED,
 4085        };
 4086        let completion_context = CompletionContext {
 4087            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 4088                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4089                    Some(String::from(trigger))
 4090                } else {
 4091                    None
 4092                }
 4093            }),
 4094            trigger_kind,
 4095        };
 4096        let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
 4097
 4098        let id = post_inc(&mut self.next_completion_id);
 4099        let task = cx.spawn(|this, mut cx| {
 4100            async move {
 4101                this.update(&mut cx, |this, _| {
 4102                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4103                })?;
 4104                let completions = completions.await.log_err();
 4105                let menu = if let Some(completions) = completions {
 4106                    let mut menu = CompletionsMenu {
 4107                        id,
 4108                        initial_position: position,
 4109                        match_candidates: completions
 4110                            .iter()
 4111                            .enumerate()
 4112                            .map(|(id, completion)| {
 4113                                StringMatchCandidate::new(
 4114                                    id,
 4115                                    completion.label.text[completion.label.filter_range.clone()]
 4116                                        .into(),
 4117                                )
 4118                            })
 4119                            .collect(),
 4120                        buffer: buffer.clone(),
 4121                        completions: Arc::new(RwLock::new(completions.into())),
 4122                        matches: Vec::new().into(),
 4123                        selected_item: 0,
 4124                        scroll_handle: UniformListScrollHandle::new(),
 4125                        selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
 4126                            DebouncedDelay::new(),
 4127                        )),
 4128                    };
 4129                    menu.filter(query.as_deref(), cx.background_executor().clone())
 4130                        .await;
 4131
 4132                    if menu.matches.is_empty() {
 4133                        None
 4134                    } else {
 4135                        this.update(&mut cx, |editor, cx| {
 4136                            let completions = menu.completions.clone();
 4137                            let matches = menu.matches.clone();
 4138
 4139                            let delay_ms = EditorSettings::get_global(cx)
 4140                                .completion_documentation_secondary_query_debounce;
 4141                            let delay = Duration::from_millis(delay_ms);
 4142                            editor
 4143                                .completion_documentation_pre_resolve_debounce
 4144                                .fire_new(delay, cx, |editor, cx| {
 4145                                    CompletionsMenu::pre_resolve_completion_documentation(
 4146                                        buffer,
 4147                                        completions,
 4148                                        matches,
 4149                                        editor,
 4150                                        cx,
 4151                                    )
 4152                                });
 4153                        })
 4154                        .ok();
 4155                        Some(menu)
 4156                    }
 4157                } else {
 4158                    None
 4159                };
 4160
 4161                this.update(&mut cx, |this, cx| {
 4162                    let mut context_menu = this.context_menu.write();
 4163                    match context_menu.as_ref() {
 4164                        None => {}
 4165
 4166                        Some(ContextMenu::Completions(prev_menu)) => {
 4167                            if prev_menu.id > id {
 4168                                return;
 4169                            }
 4170                        }
 4171
 4172                        _ => return,
 4173                    }
 4174
 4175                    if this.focus_handle.is_focused(cx) && menu.is_some() {
 4176                        let menu = menu.unwrap();
 4177                        *context_menu = Some(ContextMenu::Completions(menu));
 4178                        drop(context_menu);
 4179                        this.discard_inline_completion(false, cx);
 4180                        cx.notify();
 4181                    } else if this.completion_tasks.len() <= 1 {
 4182                        // If there are no more completion tasks and the last menu was
 4183                        // empty, we should hide it. If it was already hidden, we should
 4184                        // also show the copilot completion when available.
 4185                        drop(context_menu);
 4186                        if this.hide_context_menu(cx).is_none() {
 4187                            this.update_visible_inline_completion(cx);
 4188                        }
 4189                    }
 4190                })?;
 4191
 4192                Ok::<_, anyhow::Error>(())
 4193            }
 4194            .log_err()
 4195        });
 4196
 4197        self.completion_tasks.push((id, task));
 4198    }
 4199
 4200    pub fn confirm_completion(
 4201        &mut self,
 4202        action: &ConfirmCompletion,
 4203        cx: &mut ViewContext<Self>,
 4204    ) -> Option<Task<Result<()>>> {
 4205        use language::ToOffset as _;
 4206
 4207        let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 4208            menu
 4209        } else {
 4210            return None;
 4211        };
 4212
 4213        let mat = completions_menu
 4214            .matches
 4215            .get(action.item_ix.unwrap_or(completions_menu.selected_item))?;
 4216        let buffer_handle = completions_menu.buffer;
 4217        let completions = completions_menu.completions.read();
 4218        let completion = completions.get(mat.candidate_id)?;
 4219        cx.stop_propagation();
 4220
 4221        let snippet;
 4222        let text;
 4223
 4224        if completion.is_snippet() {
 4225            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4226            text = snippet.as_ref().unwrap().text.clone();
 4227        } else {
 4228            snippet = None;
 4229            text = completion.new_text.clone();
 4230        };
 4231        let selections = self.selections.all::<usize>(cx);
 4232        let buffer = buffer_handle.read(cx);
 4233        let old_range = completion.old_range.to_offset(buffer);
 4234        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4235
 4236        let newest_selection = self.selections.newest_anchor();
 4237        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4238            return None;
 4239        }
 4240
 4241        let lookbehind = newest_selection
 4242            .start
 4243            .text_anchor
 4244            .to_offset(buffer)
 4245            .saturating_sub(old_range.start);
 4246        let lookahead = old_range
 4247            .end
 4248            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4249        let mut common_prefix_len = old_text
 4250            .bytes()
 4251            .zip(text.bytes())
 4252            .take_while(|(a, b)| a == b)
 4253            .count();
 4254
 4255        let snapshot = self.buffer.read(cx).snapshot(cx);
 4256        let mut range_to_replace: Option<Range<isize>> = None;
 4257        let mut ranges = Vec::new();
 4258        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4259        for selection in &selections {
 4260            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4261                let start = selection.start.saturating_sub(lookbehind);
 4262                let end = selection.end + lookahead;
 4263                if selection.id == newest_selection.id {
 4264                    range_to_replace = Some(
 4265                        ((start + common_prefix_len) as isize - selection.start as isize)
 4266                            ..(end as isize - selection.start as isize),
 4267                    );
 4268                }
 4269                ranges.push(start + common_prefix_len..end);
 4270            } else {
 4271                common_prefix_len = 0;
 4272                ranges.clear();
 4273                ranges.extend(selections.iter().map(|s| {
 4274                    if s.id == newest_selection.id {
 4275                        range_to_replace = Some(
 4276                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4277                                - selection.start as isize
 4278                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4279                                    - selection.start as isize,
 4280                        );
 4281                        old_range.clone()
 4282                    } else {
 4283                        s.start..s.end
 4284                    }
 4285                }));
 4286                break;
 4287            }
 4288            if !self.linked_edit_ranges.is_empty() {
 4289                let start_anchor = snapshot.anchor_before(selection.head());
 4290                let end_anchor = snapshot.anchor_after(selection.tail());
 4291                if let Some(ranges) = self
 4292                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4293                {
 4294                    for (buffer, edits) in ranges {
 4295                        linked_edits.entry(buffer.clone()).or_default().extend(
 4296                            edits
 4297                                .into_iter()
 4298                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4299                        );
 4300                    }
 4301                }
 4302            }
 4303        }
 4304        let text = &text[common_prefix_len..];
 4305
 4306        cx.emit(EditorEvent::InputHandled {
 4307            utf16_range_to_replace: range_to_replace,
 4308            text: text.into(),
 4309        });
 4310
 4311        self.transact(cx, |this, cx| {
 4312            if let Some(mut snippet) = snippet {
 4313                snippet.text = text.to_string();
 4314                for tabstop in snippet.tabstops.iter_mut().flatten() {
 4315                    tabstop.start -= common_prefix_len as isize;
 4316                    tabstop.end -= common_prefix_len as isize;
 4317                }
 4318
 4319                this.insert_snippet(&ranges, snippet, cx).log_err();
 4320            } else {
 4321                this.buffer.update(cx, |buffer, cx| {
 4322                    buffer.edit(
 4323                        ranges.iter().map(|range| (range.clone(), text)),
 4324                        this.autoindent_mode.clone(),
 4325                        cx,
 4326                    );
 4327                });
 4328            }
 4329            for (buffer, edits) in linked_edits {
 4330                buffer.update(cx, |buffer, cx| {
 4331                    let snapshot = buffer.snapshot();
 4332                    let edits = edits
 4333                        .into_iter()
 4334                        .map(|(range, text)| {
 4335                            use text::ToPoint as TP;
 4336                            let end_point = TP::to_point(&range.end, &snapshot);
 4337                            let start_point = TP::to_point(&range.start, &snapshot);
 4338                            (start_point..end_point, text)
 4339                        })
 4340                        .sorted_by_key(|(range, _)| range.start)
 4341                        .collect::<Vec<_>>();
 4342                    buffer.edit(edits, None, cx);
 4343                })
 4344            }
 4345
 4346            this.refresh_inline_completion(true, cx);
 4347        });
 4348
 4349        if let Some(confirm) = completion.confirm.as_ref() {
 4350            (confirm)(cx);
 4351        }
 4352
 4353        if completion.show_new_completions_on_confirm {
 4354            self.show_completions(&ShowCompletions { trigger: None }, cx);
 4355        }
 4356
 4357        let provider = self.completion_provider.as_ref()?;
 4358        let apply_edits = provider.apply_additional_edits_for_completion(
 4359            buffer_handle,
 4360            completion.clone(),
 4361            true,
 4362            cx,
 4363        );
 4364
 4365        let editor_settings = EditorSettings::get_global(cx);
 4366        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4367            // After the code completion is finished, users often want to know what signatures are needed.
 4368            // so we should automatically call signature_help
 4369            self.show_signature_help(&ShowSignatureHelp, cx);
 4370        }
 4371
 4372        Some(cx.foreground_executor().spawn(async move {
 4373            apply_edits.await?;
 4374            Ok(())
 4375        }))
 4376    }
 4377
 4378    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 4379        let mut context_menu = self.context_menu.write();
 4380        if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4381            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4382                // Toggle if we're selecting the same one
 4383                *context_menu = None;
 4384                cx.notify();
 4385                return;
 4386            } else {
 4387                // Otherwise, clear it and start a new one
 4388                *context_menu = None;
 4389                cx.notify();
 4390            }
 4391        }
 4392        drop(context_menu);
 4393        let snapshot = self.snapshot(cx);
 4394        let deployed_from_indicator = action.deployed_from_indicator;
 4395        let mut task = self.code_actions_task.take();
 4396        let action = action.clone();
 4397        cx.spawn(|editor, mut cx| async move {
 4398            while let Some(prev_task) = task {
 4399                prev_task.await;
 4400                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4401            }
 4402
 4403            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 4404                if editor.focus_handle.is_focused(cx) {
 4405                    let multibuffer_point = action
 4406                        .deployed_from_indicator
 4407                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4408                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4409                    let (buffer, buffer_row) = snapshot
 4410                        .buffer_snapshot
 4411                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4412                        .and_then(|(buffer_snapshot, range)| {
 4413                            editor
 4414                                .buffer
 4415                                .read(cx)
 4416                                .buffer(buffer_snapshot.remote_id())
 4417                                .map(|buffer| (buffer, range.start.row))
 4418                        })?;
 4419                    let (_, code_actions) = editor
 4420                        .available_code_actions
 4421                        .clone()
 4422                        .and_then(|(location, code_actions)| {
 4423                            let snapshot = location.buffer.read(cx).snapshot();
 4424                            let point_range = location.range.to_point(&snapshot);
 4425                            let point_range = point_range.start.row..=point_range.end.row;
 4426                            if point_range.contains(&buffer_row) {
 4427                                Some((location, code_actions))
 4428                            } else {
 4429                                None
 4430                            }
 4431                        })
 4432                        .unzip();
 4433                    let buffer_id = buffer.read(cx).remote_id();
 4434                    let tasks = editor
 4435                        .tasks
 4436                        .get(&(buffer_id, buffer_row))
 4437                        .map(|t| Arc::new(t.to_owned()));
 4438                    if tasks.is_none() && code_actions.is_none() {
 4439                        return None;
 4440                    }
 4441
 4442                    editor.completion_tasks.clear();
 4443                    editor.discard_inline_completion(false, cx);
 4444                    let task_context =
 4445                        tasks
 4446                            .as_ref()
 4447                            .zip(editor.project.clone())
 4448                            .map(|(tasks, project)| {
 4449                                let position = Point::new(buffer_row, tasks.column);
 4450                                let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 4451                                let location = Location {
 4452                                    buffer: buffer.clone(),
 4453                                    range: range_start..range_start,
 4454                                };
 4455                                // Fill in the environmental variables from the tree-sitter captures
 4456                                let mut captured_task_variables = TaskVariables::default();
 4457                                for (capture_name, value) in tasks.extra_variables.clone() {
 4458                                    captured_task_variables.insert(
 4459                                        task::VariableName::Custom(capture_name.into()),
 4460                                        value.clone(),
 4461                                    );
 4462                                }
 4463                                project.update(cx, |project, cx| {
 4464                                    project.task_context_for_location(
 4465                                        captured_task_variables,
 4466                                        location,
 4467                                        cx,
 4468                                    )
 4469                                })
 4470                            });
 4471
 4472                    Some(cx.spawn(|editor, mut cx| async move {
 4473                        let task_context = match task_context {
 4474                            Some(task_context) => task_context.await,
 4475                            None => None,
 4476                        };
 4477                        let resolved_tasks =
 4478                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4479                                Arc::new(ResolvedTasks {
 4480                                    templates: tasks
 4481                                        .templates
 4482                                        .iter()
 4483                                        .filter_map(|(kind, template)| {
 4484                                            template
 4485                                                .resolve_task(&kind.to_id_base(), &task_context)
 4486                                                .map(|task| (kind.clone(), task))
 4487                                        })
 4488                                        .collect(),
 4489                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4490                                        multibuffer_point.row,
 4491                                        tasks.column,
 4492                                    )),
 4493                                })
 4494                            });
 4495                        let spawn_straight_away = resolved_tasks
 4496                            .as_ref()
 4497                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4498                            && code_actions
 4499                                .as_ref()
 4500                                .map_or(true, |actions| actions.is_empty());
 4501                        if let Some(task) = editor
 4502                            .update(&mut cx, |editor, cx| {
 4503                                *editor.context_menu.write() =
 4504                                    Some(ContextMenu::CodeActions(CodeActionsMenu {
 4505                                        buffer,
 4506                                        actions: CodeActionContents {
 4507                                            tasks: resolved_tasks,
 4508                                            actions: code_actions,
 4509                                        },
 4510                                        selected_item: Default::default(),
 4511                                        scroll_handle: UniformListScrollHandle::default(),
 4512                                        deployed_from_indicator,
 4513                                    }));
 4514                                if spawn_straight_away {
 4515                                    if let Some(task) = editor.confirm_code_action(
 4516                                        &ConfirmCodeAction { item_ix: Some(0) },
 4517                                        cx,
 4518                                    ) {
 4519                                        cx.notify();
 4520                                        return task;
 4521                                    }
 4522                                }
 4523                                cx.notify();
 4524                                Task::ready(Ok(()))
 4525                            })
 4526                            .ok()
 4527                        {
 4528                            task.await
 4529                        } else {
 4530                            Ok(())
 4531                        }
 4532                    }))
 4533                } else {
 4534                    Some(Task::ready(Ok(())))
 4535                }
 4536            })?;
 4537            if let Some(task) = spawned_test_task {
 4538                task.await?;
 4539            }
 4540
 4541            Ok::<_, anyhow::Error>(())
 4542        })
 4543        .detach_and_log_err(cx);
 4544    }
 4545
 4546    pub fn confirm_code_action(
 4547        &mut self,
 4548        action: &ConfirmCodeAction,
 4549        cx: &mut ViewContext<Self>,
 4550    ) -> Option<Task<Result<()>>> {
 4551        let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4552            menu
 4553        } else {
 4554            return None;
 4555        };
 4556        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4557        let action = actions_menu.actions.get(action_ix)?;
 4558        let title = action.label();
 4559        let buffer = actions_menu.buffer;
 4560        let workspace = self.workspace()?;
 4561
 4562        match action {
 4563            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4564                workspace.update(cx, |workspace, cx| {
 4565                    workspace::tasks::schedule_resolved_task(
 4566                        workspace,
 4567                        task_source_kind,
 4568                        resolved_task,
 4569                        false,
 4570                        cx,
 4571                    );
 4572
 4573                    Some(Task::ready(Ok(())))
 4574                })
 4575            }
 4576            CodeActionsItem::CodeAction(action) => {
 4577                let apply_code_actions = workspace
 4578                    .read(cx)
 4579                    .project()
 4580                    .clone()
 4581                    .update(cx, |project, cx| {
 4582                        project.apply_code_action(buffer, action, true, cx)
 4583                    });
 4584                let workspace = workspace.downgrade();
 4585                Some(cx.spawn(|editor, cx| async move {
 4586                    let project_transaction = apply_code_actions.await?;
 4587                    Self::open_project_transaction(
 4588                        &editor,
 4589                        workspace,
 4590                        project_transaction,
 4591                        title,
 4592                        cx,
 4593                    )
 4594                    .await
 4595                }))
 4596            }
 4597        }
 4598    }
 4599
 4600    pub async fn open_project_transaction(
 4601        this: &WeakView<Editor>,
 4602        workspace: WeakView<Workspace>,
 4603        transaction: ProjectTransaction,
 4604        title: String,
 4605        mut cx: AsyncWindowContext,
 4606    ) -> Result<()> {
 4607        let replica_id = this.update(&mut cx, |this, cx| this.replica_id(cx))?;
 4608
 4609        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4610        cx.update(|cx| {
 4611            entries.sort_unstable_by_key(|(buffer, _)| {
 4612                buffer.read(cx).file().map(|f| f.path().clone())
 4613            });
 4614        })?;
 4615
 4616        // If the project transaction's edits are all contained within this editor, then
 4617        // avoid opening a new editor to display them.
 4618
 4619        if let Some((buffer, transaction)) = entries.first() {
 4620            if entries.len() == 1 {
 4621                let excerpt = this.update(&mut cx, |editor, cx| {
 4622                    editor
 4623                        .buffer()
 4624                        .read(cx)
 4625                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4626                })?;
 4627                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4628                    if excerpted_buffer == *buffer {
 4629                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4630                            let excerpt_range = excerpt_range.to_offset(buffer);
 4631                            buffer
 4632                                .edited_ranges_for_transaction::<usize>(transaction)
 4633                                .all(|range| {
 4634                                    excerpt_range.start <= range.start
 4635                                        && excerpt_range.end >= range.end
 4636                                })
 4637                        })?;
 4638
 4639                        if all_edits_within_excerpt {
 4640                            return Ok(());
 4641                        }
 4642                    }
 4643                }
 4644            }
 4645        } else {
 4646            return Ok(());
 4647        }
 4648
 4649        let mut ranges_to_highlight = Vec::new();
 4650        let excerpt_buffer = cx.new_model(|cx| {
 4651            let mut multibuffer =
 4652                MultiBuffer::new(replica_id, Capability::ReadWrite).with_title(title);
 4653            for (buffer_handle, transaction) in &entries {
 4654                let buffer = buffer_handle.read(cx);
 4655                ranges_to_highlight.extend(
 4656                    multibuffer.push_excerpts_with_context_lines(
 4657                        buffer_handle.clone(),
 4658                        buffer
 4659                            .edited_ranges_for_transaction::<usize>(transaction)
 4660                            .collect(),
 4661                        DEFAULT_MULTIBUFFER_CONTEXT,
 4662                        cx,
 4663                    ),
 4664                );
 4665            }
 4666            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4667            multibuffer
 4668        })?;
 4669
 4670        workspace.update(&mut cx, |workspace, cx| {
 4671            let project = workspace.project().clone();
 4672            let editor =
 4673                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 4674            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 4675            editor.update(cx, |editor, cx| {
 4676                editor.highlight_background::<Self>(
 4677                    &ranges_to_highlight,
 4678                    |theme| theme.editor_highlighted_line_background,
 4679                    cx,
 4680                );
 4681            });
 4682        })?;
 4683
 4684        Ok(())
 4685    }
 4686
 4687    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4688        let project = self.project.clone()?;
 4689        let buffer = self.buffer.read(cx);
 4690        let newest_selection = self.selections.newest_anchor().clone();
 4691        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4692        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4693        if start_buffer != end_buffer {
 4694            return None;
 4695        }
 4696
 4697        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 4698            cx.background_executor()
 4699                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4700                .await;
 4701
 4702            let actions = if let Ok(code_actions) = project.update(&mut cx, |project, cx| {
 4703                project.code_actions(&start_buffer, start..end, cx)
 4704            }) {
 4705                code_actions.await
 4706            } else {
 4707                Vec::new()
 4708            };
 4709
 4710            this.update(&mut cx, |this, cx| {
 4711                this.available_code_actions = if actions.is_empty() {
 4712                    None
 4713                } else {
 4714                    Some((
 4715                        Location {
 4716                            buffer: start_buffer,
 4717                            range: start..end,
 4718                        },
 4719                        actions.into(),
 4720                    ))
 4721                };
 4722                cx.notify();
 4723            })
 4724            .log_err();
 4725        }));
 4726        None
 4727    }
 4728
 4729    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 4730        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4731            self.show_git_blame_inline = false;
 4732
 4733            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 4734                cx.background_executor().timer(delay).await;
 4735
 4736                this.update(&mut cx, |this, cx| {
 4737                    this.show_git_blame_inline = true;
 4738                    cx.notify();
 4739                })
 4740                .log_err();
 4741            }));
 4742        }
 4743    }
 4744
 4745    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4746        if self.pending_rename.is_some() {
 4747            return None;
 4748        }
 4749
 4750        let project = self.project.clone()?;
 4751        let buffer = self.buffer.read(cx);
 4752        let newest_selection = self.selections.newest_anchor().clone();
 4753        let cursor_position = newest_selection.head();
 4754        let (cursor_buffer, cursor_buffer_position) =
 4755            buffer.text_anchor_for_position(cursor_position, cx)?;
 4756        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4757        if cursor_buffer != tail_buffer {
 4758            return None;
 4759        }
 4760
 4761        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4762            cx.background_executor()
 4763                .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
 4764                .await;
 4765
 4766            let highlights = if let Some(highlights) = project
 4767                .update(&mut cx, |project, cx| {
 4768                    project.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4769                })
 4770                .log_err()
 4771            {
 4772                highlights.await.log_err()
 4773            } else {
 4774                None
 4775            };
 4776
 4777            if let Some(highlights) = highlights {
 4778                this.update(&mut cx, |this, cx| {
 4779                    if this.pending_rename.is_some() {
 4780                        return;
 4781                    }
 4782
 4783                    let buffer_id = cursor_position.buffer_id;
 4784                    let buffer = this.buffer.read(cx);
 4785                    if !buffer
 4786                        .text_anchor_for_position(cursor_position, cx)
 4787                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4788                    {
 4789                        return;
 4790                    }
 4791
 4792                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4793                    let mut write_ranges = Vec::new();
 4794                    let mut read_ranges = Vec::new();
 4795                    for highlight in highlights {
 4796                        for (excerpt_id, excerpt_range) in
 4797                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 4798                        {
 4799                            let start = highlight
 4800                                .range
 4801                                .start
 4802                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4803                            let end = highlight
 4804                                .range
 4805                                .end
 4806                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4807                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4808                                continue;
 4809                            }
 4810
 4811                            let range = Anchor {
 4812                                buffer_id,
 4813                                excerpt_id: excerpt_id,
 4814                                text_anchor: start,
 4815                            }..Anchor {
 4816                                buffer_id,
 4817                                excerpt_id,
 4818                                text_anchor: end,
 4819                            };
 4820                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4821                                write_ranges.push(range);
 4822                            } else {
 4823                                read_ranges.push(range);
 4824                            }
 4825                        }
 4826                    }
 4827
 4828                    this.highlight_background::<DocumentHighlightRead>(
 4829                        &read_ranges,
 4830                        |theme| theme.editor_document_highlight_read_background,
 4831                        cx,
 4832                    );
 4833                    this.highlight_background::<DocumentHighlightWrite>(
 4834                        &write_ranges,
 4835                        |theme| theme.editor_document_highlight_write_background,
 4836                        cx,
 4837                    );
 4838                    cx.notify();
 4839                })
 4840                .log_err();
 4841            }
 4842        }));
 4843        None
 4844    }
 4845
 4846    fn refresh_inline_completion(
 4847        &mut self,
 4848        debounce: bool,
 4849        cx: &mut ViewContext<Self>,
 4850    ) -> Option<()> {
 4851        let provider = self.inline_completion_provider()?;
 4852        let cursor = self.selections.newest_anchor().head();
 4853        let (buffer, cursor_buffer_position) =
 4854            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4855        if !self.show_inline_completions
 4856            || !provider.is_enabled(&buffer, cursor_buffer_position, cx)
 4857        {
 4858            self.discard_inline_completion(false, cx);
 4859            return None;
 4860        }
 4861
 4862        self.update_visible_inline_completion(cx);
 4863        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 4864        Some(())
 4865    }
 4866
 4867    fn cycle_inline_completion(
 4868        &mut self,
 4869        direction: Direction,
 4870        cx: &mut ViewContext<Self>,
 4871    ) -> Option<()> {
 4872        let provider = self.inline_completion_provider()?;
 4873        let cursor = self.selections.newest_anchor().head();
 4874        let (buffer, cursor_buffer_position) =
 4875            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4876        if !self.show_inline_completions
 4877            || !provider.is_enabled(&buffer, cursor_buffer_position, cx)
 4878        {
 4879            return None;
 4880        }
 4881
 4882        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4883        self.update_visible_inline_completion(cx);
 4884
 4885        Some(())
 4886    }
 4887
 4888    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 4889        if !self.has_active_inline_completion(cx) {
 4890            self.refresh_inline_completion(false, cx);
 4891            return;
 4892        }
 4893
 4894        self.update_visible_inline_completion(cx);
 4895    }
 4896
 4897    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 4898        self.show_cursor_names(cx);
 4899    }
 4900
 4901    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 4902        self.show_cursor_names = true;
 4903        cx.notify();
 4904        cx.spawn(|this, mut cx| async move {
 4905            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 4906            this.update(&mut cx, |this, cx| {
 4907                this.show_cursor_names = false;
 4908                cx.notify()
 4909            })
 4910            .ok()
 4911        })
 4912        .detach();
 4913    }
 4914
 4915    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 4916        if self.has_active_inline_completion(cx) {
 4917            self.cycle_inline_completion(Direction::Next, cx);
 4918        } else {
 4919            let is_copilot_disabled = self.refresh_inline_completion(false, cx).is_none();
 4920            if is_copilot_disabled {
 4921                cx.propagate();
 4922            }
 4923        }
 4924    }
 4925
 4926    pub fn previous_inline_completion(
 4927        &mut self,
 4928        _: &PreviousInlineCompletion,
 4929        cx: &mut ViewContext<Self>,
 4930    ) {
 4931        if self.has_active_inline_completion(cx) {
 4932            self.cycle_inline_completion(Direction::Prev, cx);
 4933        } else {
 4934            let is_copilot_disabled = self.refresh_inline_completion(false, cx).is_none();
 4935            if is_copilot_disabled {
 4936                cx.propagate();
 4937            }
 4938        }
 4939    }
 4940
 4941    pub fn accept_inline_completion(
 4942        &mut self,
 4943        _: &AcceptInlineCompletion,
 4944        cx: &mut ViewContext<Self>,
 4945    ) {
 4946        let Some((completion, delete_range)) = self.take_active_inline_completion(cx) else {
 4947            return;
 4948        };
 4949        if let Some(provider) = self.inline_completion_provider() {
 4950            provider.accept(cx);
 4951        }
 4952
 4953        cx.emit(EditorEvent::InputHandled {
 4954            utf16_range_to_replace: None,
 4955            text: completion.text.to_string().into(),
 4956        });
 4957
 4958        if let Some(range) = delete_range {
 4959            self.change_selections(None, cx, |s| s.select_ranges([range]))
 4960        }
 4961        self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
 4962        self.refresh_inline_completion(true, cx);
 4963        cx.notify();
 4964    }
 4965
 4966    pub fn accept_partial_inline_completion(
 4967        &mut self,
 4968        _: &AcceptPartialInlineCompletion,
 4969        cx: &mut ViewContext<Self>,
 4970    ) {
 4971        if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
 4972            if let Some((completion, delete_range)) = self.take_active_inline_completion(cx) {
 4973                let mut partial_completion = completion
 4974                    .text
 4975                    .chars()
 4976                    .by_ref()
 4977                    .take_while(|c| c.is_alphabetic())
 4978                    .collect::<String>();
 4979                if partial_completion.is_empty() {
 4980                    partial_completion = completion
 4981                        .text
 4982                        .chars()
 4983                        .by_ref()
 4984                        .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 4985                        .collect::<String>();
 4986                }
 4987
 4988                cx.emit(EditorEvent::InputHandled {
 4989                    utf16_range_to_replace: None,
 4990                    text: partial_completion.clone().into(),
 4991                });
 4992
 4993                if let Some(range) = delete_range {
 4994                    self.change_selections(None, cx, |s| s.select_ranges([range]))
 4995                }
 4996                self.insert_with_autoindent_mode(&partial_completion, None, cx);
 4997
 4998                self.refresh_inline_completion(true, cx);
 4999                cx.notify();
 5000            }
 5001        }
 5002    }
 5003
 5004    fn discard_inline_completion(
 5005        &mut self,
 5006        should_report_inline_completion_event: bool,
 5007        cx: &mut ViewContext<Self>,
 5008    ) -> bool {
 5009        if let Some(provider) = self.inline_completion_provider() {
 5010            provider.discard(should_report_inline_completion_event, cx);
 5011        }
 5012
 5013        self.take_active_inline_completion(cx).is_some()
 5014    }
 5015
 5016    pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
 5017        if let Some(completion) = self.active_inline_completion.as_ref() {
 5018            let buffer = self.buffer.read(cx).read(cx);
 5019            completion.0.position.is_valid(&buffer)
 5020        } else {
 5021            false
 5022        }
 5023    }
 5024
 5025    fn take_active_inline_completion(
 5026        &mut self,
 5027        cx: &mut ViewContext<Self>,
 5028    ) -> Option<(Inlay, Option<Range<Anchor>>)> {
 5029        let completion = self.active_inline_completion.take()?;
 5030        self.display_map.update(cx, |map, cx| {
 5031            map.splice_inlays(vec![completion.0.id], Default::default(), cx);
 5032        });
 5033        let buffer = self.buffer.read(cx).read(cx);
 5034
 5035        if completion.0.position.is_valid(&buffer) {
 5036            Some(completion)
 5037        } else {
 5038            None
 5039        }
 5040    }
 5041
 5042    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
 5043        let selection = self.selections.newest_anchor();
 5044        let cursor = selection.head();
 5045
 5046        let excerpt_id = cursor.excerpt_id;
 5047
 5048        if self.context_menu.read().is_none()
 5049            && self.completion_tasks.is_empty()
 5050            && selection.start == selection.end
 5051        {
 5052            if let Some(provider) = self.inline_completion_provider() {
 5053                if let Some((buffer, cursor_buffer_position)) =
 5054                    self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5055                {
 5056                    if let Some((text, text_anchor_range)) =
 5057                        provider.active_completion_text(&buffer, cursor_buffer_position, cx)
 5058                    {
 5059                        let text = Rope::from(text);
 5060                        let mut to_remove = Vec::new();
 5061                        if let Some(completion) = self.active_inline_completion.take() {
 5062                            to_remove.push(completion.0.id);
 5063                        }
 5064
 5065                        let completion_inlay =
 5066                            Inlay::suggestion(post_inc(&mut self.next_inlay_id), cursor, text);
 5067
 5068                        let multibuffer_anchor_range = text_anchor_range.and_then(|range| {
 5069                            let snapshot = self.buffer.read(cx).snapshot(cx);
 5070                            Some(
 5071                                snapshot.anchor_in_excerpt(excerpt_id, range.start)?
 5072                                    ..snapshot.anchor_in_excerpt(excerpt_id, range.end)?,
 5073                            )
 5074                        });
 5075                        self.active_inline_completion =
 5076                            Some((completion_inlay.clone(), multibuffer_anchor_range));
 5077
 5078                        self.display_map.update(cx, move |map, cx| {
 5079                            map.splice_inlays(to_remove, vec![completion_inlay], cx)
 5080                        });
 5081                        cx.notify();
 5082                        return;
 5083                    }
 5084                }
 5085            }
 5086        }
 5087
 5088        self.discard_inline_completion(false, cx);
 5089    }
 5090
 5091    fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5092        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 5093    }
 5094
 5095    fn render_code_actions_indicator(
 5096        &self,
 5097        _style: &EditorStyle,
 5098        row: DisplayRow,
 5099        is_active: bool,
 5100        cx: &mut ViewContext<Self>,
 5101    ) -> Option<IconButton> {
 5102        if self.available_code_actions.is_some() {
 5103            Some(
 5104                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5105                    .shape(ui::IconButtonShape::Square)
 5106                    .icon_size(IconSize::XSmall)
 5107                    .icon_color(Color::Muted)
 5108                    .selected(is_active)
 5109                    .on_click(cx.listener(move |editor, _e, cx| {
 5110                        editor.focus(cx);
 5111                        editor.toggle_code_actions(
 5112                            &ToggleCodeActions {
 5113                                deployed_from_indicator: Some(row),
 5114                            },
 5115                            cx,
 5116                        );
 5117                    })),
 5118            )
 5119        } else {
 5120            None
 5121        }
 5122    }
 5123
 5124    fn clear_tasks(&mut self) {
 5125        self.tasks.clear()
 5126    }
 5127
 5128    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5129        if let Some(_) = self.tasks.insert(key, value) {
 5130            // This case should hopefully be rare, but just in case...
 5131            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5132        }
 5133    }
 5134
 5135    fn render_run_indicator(
 5136        &self,
 5137        _style: &EditorStyle,
 5138        is_active: bool,
 5139        row: DisplayRow,
 5140        cx: &mut ViewContext<Self>,
 5141    ) -> IconButton {
 5142        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5143            .shape(ui::IconButtonShape::Square)
 5144            .icon_size(IconSize::XSmall)
 5145            .icon_color(Color::Muted)
 5146            .selected(is_active)
 5147            .on_click(cx.listener(move |editor, _e, cx| {
 5148                editor.focus(cx);
 5149                editor.toggle_code_actions(
 5150                    &ToggleCodeActions {
 5151                        deployed_from_indicator: Some(row),
 5152                    },
 5153                    cx,
 5154                );
 5155            }))
 5156    }
 5157
 5158    fn close_hunk_diff_button(
 5159        &self,
 5160        hunk: HoveredHunk,
 5161        row: DisplayRow,
 5162        cx: &mut ViewContext<Self>,
 5163    ) -> IconButton {
 5164        IconButton::new(
 5165            ("close_hunk_diff_indicator", row.0 as usize),
 5166            ui::IconName::Close,
 5167        )
 5168        .shape(ui::IconButtonShape::Square)
 5169        .icon_size(IconSize::XSmall)
 5170        .icon_color(Color::Muted)
 5171        .tooltip(|cx| Tooltip::for_action("Close hunk diff", &ToggleHunkDiff, cx))
 5172        .on_click(cx.listener(move |editor, _e, cx| editor.toggle_hovered_hunk(&hunk, cx)))
 5173    }
 5174
 5175    pub fn context_menu_visible(&self) -> bool {
 5176        self.context_menu
 5177            .read()
 5178            .as_ref()
 5179            .map_or(false, |menu| menu.visible())
 5180    }
 5181
 5182    fn render_context_menu(
 5183        &self,
 5184        cursor_position: DisplayPoint,
 5185        style: &EditorStyle,
 5186        max_height: Pixels,
 5187        cx: &mut ViewContext<Editor>,
 5188    ) -> Option<(ContextMenuOrigin, AnyElement)> {
 5189        self.context_menu.read().as_ref().map(|menu| {
 5190            menu.render(
 5191                cursor_position,
 5192                style,
 5193                max_height,
 5194                self.workspace.as_ref().map(|(w, _)| w.clone()),
 5195                cx,
 5196            )
 5197        })
 5198    }
 5199
 5200    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
 5201        cx.notify();
 5202        self.completion_tasks.clear();
 5203        let context_menu = self.context_menu.write().take();
 5204        if context_menu.is_some() {
 5205            self.update_visible_inline_completion(cx);
 5206        }
 5207        context_menu
 5208    }
 5209
 5210    pub fn insert_snippet(
 5211        &mut self,
 5212        insertion_ranges: &[Range<usize>],
 5213        snippet: Snippet,
 5214        cx: &mut ViewContext<Self>,
 5215    ) -> Result<()> {
 5216        struct Tabstop<T> {
 5217            is_end_tabstop: bool,
 5218            ranges: Vec<Range<T>>,
 5219        }
 5220
 5221        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5222            let snippet_text: Arc<str> = snippet.text.clone().into();
 5223            buffer.edit(
 5224                insertion_ranges
 5225                    .iter()
 5226                    .cloned()
 5227                    .map(|range| (range, snippet_text.clone())),
 5228                Some(AutoindentMode::EachLine),
 5229                cx,
 5230            );
 5231
 5232            let snapshot = &*buffer.read(cx);
 5233            let snippet = &snippet;
 5234            snippet
 5235                .tabstops
 5236                .iter()
 5237                .map(|tabstop| {
 5238                    let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
 5239                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5240                    });
 5241                    let mut tabstop_ranges = tabstop
 5242                        .iter()
 5243                        .flat_map(|tabstop_range| {
 5244                            let mut delta = 0_isize;
 5245                            insertion_ranges.iter().map(move |insertion_range| {
 5246                                let insertion_start = insertion_range.start as isize + delta;
 5247                                delta +=
 5248                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5249
 5250                                let start = ((insertion_start + tabstop_range.start) as usize)
 5251                                    .min(snapshot.len());
 5252                                let end = ((insertion_start + tabstop_range.end) as usize)
 5253                                    .min(snapshot.len());
 5254                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5255                            })
 5256                        })
 5257                        .collect::<Vec<_>>();
 5258                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5259
 5260                    Tabstop {
 5261                        is_end_tabstop,
 5262                        ranges: tabstop_ranges,
 5263                    }
 5264                })
 5265                .collect::<Vec<_>>()
 5266        });
 5267        if let Some(tabstop) = tabstops.first() {
 5268            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5269                s.select_ranges(tabstop.ranges.iter().cloned());
 5270            });
 5271
 5272            // If we're already at the last tabstop and it's at the end of the snippet,
 5273            // we're done, we don't need to keep the state around.
 5274            if !tabstop.is_end_tabstop {
 5275                let ranges = tabstops
 5276                    .into_iter()
 5277                    .map(|tabstop| tabstop.ranges)
 5278                    .collect::<Vec<_>>();
 5279                self.snippet_stack.push(SnippetState {
 5280                    active_index: 0,
 5281                    ranges,
 5282                });
 5283            }
 5284
 5285            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5286            if self.autoclose_regions.is_empty() {
 5287                let snapshot = self.buffer.read(cx).snapshot(cx);
 5288                for selection in &mut self.selections.all::<Point>(cx) {
 5289                    let selection_head = selection.head();
 5290                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5291                        continue;
 5292                    };
 5293
 5294                    let mut bracket_pair = None;
 5295                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5296                    let prev_chars = snapshot
 5297                        .reversed_chars_at(selection_head)
 5298                        .collect::<String>();
 5299                    for (pair, enabled) in scope.brackets() {
 5300                        if enabled
 5301                            && pair.close
 5302                            && prev_chars.starts_with(pair.start.as_str())
 5303                            && next_chars.starts_with(pair.end.as_str())
 5304                        {
 5305                            bracket_pair = Some(pair.clone());
 5306                            break;
 5307                        }
 5308                    }
 5309                    if let Some(pair) = bracket_pair {
 5310                        let start = snapshot.anchor_after(selection_head);
 5311                        let end = snapshot.anchor_after(selection_head);
 5312                        self.autoclose_regions.push(AutocloseRegion {
 5313                            selection_id: selection.id,
 5314                            range: start..end,
 5315                            pair,
 5316                        });
 5317                    }
 5318                }
 5319            }
 5320        }
 5321        Ok(())
 5322    }
 5323
 5324    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5325        self.move_to_snippet_tabstop(Bias::Right, cx)
 5326    }
 5327
 5328    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5329        self.move_to_snippet_tabstop(Bias::Left, cx)
 5330    }
 5331
 5332    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5333        if let Some(mut snippet) = self.snippet_stack.pop() {
 5334            match bias {
 5335                Bias::Left => {
 5336                    if snippet.active_index > 0 {
 5337                        snippet.active_index -= 1;
 5338                    } else {
 5339                        self.snippet_stack.push(snippet);
 5340                        return false;
 5341                    }
 5342                }
 5343                Bias::Right => {
 5344                    if snippet.active_index + 1 < snippet.ranges.len() {
 5345                        snippet.active_index += 1;
 5346                    } else {
 5347                        self.snippet_stack.push(snippet);
 5348                        return false;
 5349                    }
 5350                }
 5351            }
 5352            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5353                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5354                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5355                });
 5356                // If snippet state is not at the last tabstop, push it back on the stack
 5357                if snippet.active_index + 1 < snippet.ranges.len() {
 5358                    self.snippet_stack.push(snippet);
 5359                }
 5360                return true;
 5361            }
 5362        }
 5363
 5364        false
 5365    }
 5366
 5367    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 5368        self.transact(cx, |this, cx| {
 5369            this.select_all(&SelectAll, cx);
 5370            this.insert("", cx);
 5371        });
 5372    }
 5373
 5374    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 5375        self.transact(cx, |this, cx| {
 5376            this.select_autoclose_pair(cx);
 5377            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5378            if !this.linked_edit_ranges.is_empty() {
 5379                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5380                let snapshot = this.buffer.read(cx).snapshot(cx);
 5381
 5382                for selection in selections.iter() {
 5383                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5384                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 5385                    if selection_start.buffer_id != selection_end.buffer_id {
 5386                        continue;
 5387                    }
 5388                    if let Some(ranges) =
 5389                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 5390                    {
 5391                        for (buffer, entries) in ranges {
 5392                            linked_ranges.entry(buffer).or_default().extend(entries);
 5393                        }
 5394                    }
 5395                }
 5396            }
 5397
 5398            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 5399            if !this.selections.line_mode {
 5400                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 5401                for selection in &mut selections {
 5402                    if selection.is_empty() {
 5403                        let old_head = selection.head();
 5404                        let mut new_head =
 5405                            movement::left(&display_map, old_head.to_display_point(&display_map))
 5406                                .to_point(&display_map);
 5407                        if let Some((buffer, line_buffer_range)) = display_map
 5408                            .buffer_snapshot
 5409                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 5410                        {
 5411                            let indent_size =
 5412                                buffer.indent_size_for_line(line_buffer_range.start.row);
 5413                            let indent_len = match indent_size.kind {
 5414                                IndentKind::Space => {
 5415                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 5416                                }
 5417                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 5418                            };
 5419                            if old_head.column <= indent_size.len && old_head.column > 0 {
 5420                                let indent_len = indent_len.get();
 5421                                new_head = cmp::min(
 5422                                    new_head,
 5423                                    MultiBufferPoint::new(
 5424                                        old_head.row,
 5425                                        ((old_head.column - 1) / indent_len) * indent_len,
 5426                                    ),
 5427                                );
 5428                            }
 5429                        }
 5430
 5431                        selection.set_head(new_head, SelectionGoal::None);
 5432                    }
 5433                }
 5434            }
 5435
 5436            this.signature_help_state.set_backspace_pressed(true);
 5437            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5438            this.insert("", cx);
 5439            let empty_str: Arc<str> = Arc::from("");
 5440            for (buffer, edits) in linked_ranges {
 5441                let snapshot = buffer.read(cx).snapshot();
 5442                use text::ToPoint as TP;
 5443
 5444                let edits = edits
 5445                    .into_iter()
 5446                    .map(|range| {
 5447                        let end_point = TP::to_point(&range.end, &snapshot);
 5448                        let mut start_point = TP::to_point(&range.start, &snapshot);
 5449
 5450                        if end_point == start_point {
 5451                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 5452                                .saturating_sub(1);
 5453                            start_point = TP::to_point(&offset, &snapshot);
 5454                        };
 5455
 5456                        (start_point..end_point, empty_str.clone())
 5457                    })
 5458                    .sorted_by_key(|(range, _)| range.start)
 5459                    .collect::<Vec<_>>();
 5460                buffer.update(cx, |this, cx| {
 5461                    this.edit(edits, None, cx);
 5462                })
 5463            }
 5464            this.refresh_inline_completion(true, cx);
 5465            linked_editing_ranges::refresh_linked_ranges(this, cx);
 5466        });
 5467    }
 5468
 5469    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 5470        self.transact(cx, |this, cx| {
 5471            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5472                let line_mode = s.line_mode;
 5473                s.move_with(|map, selection| {
 5474                    if selection.is_empty() && !line_mode {
 5475                        let cursor = movement::right(map, selection.head());
 5476                        selection.end = cursor;
 5477                        selection.reversed = true;
 5478                        selection.goal = SelectionGoal::None;
 5479                    }
 5480                })
 5481            });
 5482            this.insert("", cx);
 5483            this.refresh_inline_completion(true, cx);
 5484        });
 5485    }
 5486
 5487    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 5488        if self.move_to_prev_snippet_tabstop(cx) {
 5489            return;
 5490        }
 5491
 5492        self.outdent(&Outdent, cx);
 5493    }
 5494
 5495    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 5496        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 5497            return;
 5498        }
 5499
 5500        let mut selections = self.selections.all_adjusted(cx);
 5501        let buffer = self.buffer.read(cx);
 5502        let snapshot = buffer.snapshot(cx);
 5503        let rows_iter = selections.iter().map(|s| s.head().row);
 5504        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 5505
 5506        let mut edits = Vec::new();
 5507        let mut prev_edited_row = 0;
 5508        let mut row_delta = 0;
 5509        for selection in &mut selections {
 5510            if selection.start.row != prev_edited_row {
 5511                row_delta = 0;
 5512            }
 5513            prev_edited_row = selection.end.row;
 5514
 5515            // If the selection is non-empty, then increase the indentation of the selected lines.
 5516            if !selection.is_empty() {
 5517                row_delta =
 5518                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5519                continue;
 5520            }
 5521
 5522            // If the selection is empty and the cursor is in the leading whitespace before the
 5523            // suggested indentation, then auto-indent the line.
 5524            let cursor = selection.head();
 5525            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 5526            if let Some(suggested_indent) =
 5527                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 5528            {
 5529                if cursor.column < suggested_indent.len
 5530                    && cursor.column <= current_indent.len
 5531                    && current_indent.len <= suggested_indent.len
 5532                {
 5533                    selection.start = Point::new(cursor.row, suggested_indent.len);
 5534                    selection.end = selection.start;
 5535                    if row_delta == 0 {
 5536                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 5537                            cursor.row,
 5538                            current_indent,
 5539                            suggested_indent,
 5540                        ));
 5541                        row_delta = suggested_indent.len - current_indent.len;
 5542                    }
 5543                    continue;
 5544                }
 5545            }
 5546
 5547            // Otherwise, insert a hard or soft tab.
 5548            let settings = buffer.settings_at(cursor, cx);
 5549            let tab_size = if settings.hard_tabs {
 5550                IndentSize::tab()
 5551            } else {
 5552                let tab_size = settings.tab_size.get();
 5553                let char_column = snapshot
 5554                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 5555                    .flat_map(str::chars)
 5556                    .count()
 5557                    + row_delta as usize;
 5558                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 5559                IndentSize::spaces(chars_to_next_tab_stop)
 5560            };
 5561            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 5562            selection.end = selection.start;
 5563            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 5564            row_delta += tab_size.len;
 5565        }
 5566
 5567        self.transact(cx, |this, cx| {
 5568            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5569            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5570            this.refresh_inline_completion(true, cx);
 5571        });
 5572    }
 5573
 5574    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 5575        if self.read_only(cx) {
 5576            return;
 5577        }
 5578        let mut selections = self.selections.all::<Point>(cx);
 5579        let mut prev_edited_row = 0;
 5580        let mut row_delta = 0;
 5581        let mut edits = Vec::new();
 5582        let buffer = self.buffer.read(cx);
 5583        let snapshot = buffer.snapshot(cx);
 5584        for selection in &mut selections {
 5585            if selection.start.row != prev_edited_row {
 5586                row_delta = 0;
 5587            }
 5588            prev_edited_row = selection.end.row;
 5589
 5590            row_delta =
 5591                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5592        }
 5593
 5594        self.transact(cx, |this, cx| {
 5595            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5596            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5597        });
 5598    }
 5599
 5600    fn indent_selection(
 5601        buffer: &MultiBuffer,
 5602        snapshot: &MultiBufferSnapshot,
 5603        selection: &mut Selection<Point>,
 5604        edits: &mut Vec<(Range<Point>, String)>,
 5605        delta_for_start_row: u32,
 5606        cx: &AppContext,
 5607    ) -> u32 {
 5608        let settings = buffer.settings_at(selection.start, cx);
 5609        let tab_size = settings.tab_size.get();
 5610        let indent_kind = if settings.hard_tabs {
 5611            IndentKind::Tab
 5612        } else {
 5613            IndentKind::Space
 5614        };
 5615        let mut start_row = selection.start.row;
 5616        let mut end_row = selection.end.row + 1;
 5617
 5618        // If a selection ends at the beginning of a line, don't indent
 5619        // that last line.
 5620        if selection.end.column == 0 && selection.end.row > selection.start.row {
 5621            end_row -= 1;
 5622        }
 5623
 5624        // Avoid re-indenting a row that has already been indented by a
 5625        // previous selection, but still update this selection's column
 5626        // to reflect that indentation.
 5627        if delta_for_start_row > 0 {
 5628            start_row += 1;
 5629            selection.start.column += delta_for_start_row;
 5630            if selection.end.row == selection.start.row {
 5631                selection.end.column += delta_for_start_row;
 5632            }
 5633        }
 5634
 5635        let mut delta_for_end_row = 0;
 5636        let has_multiple_rows = start_row + 1 != end_row;
 5637        for row in start_row..end_row {
 5638            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 5639            let indent_delta = match (current_indent.kind, indent_kind) {
 5640                (IndentKind::Space, IndentKind::Space) => {
 5641                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 5642                    IndentSize::spaces(columns_to_next_tab_stop)
 5643                }
 5644                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 5645                (_, IndentKind::Tab) => IndentSize::tab(),
 5646            };
 5647
 5648            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 5649                0
 5650            } else {
 5651                selection.start.column
 5652            };
 5653            let row_start = Point::new(row, start);
 5654            edits.push((
 5655                row_start..row_start,
 5656                indent_delta.chars().collect::<String>(),
 5657            ));
 5658
 5659            // Update this selection's endpoints to reflect the indentation.
 5660            if row == selection.start.row {
 5661                selection.start.column += indent_delta.len;
 5662            }
 5663            if row == selection.end.row {
 5664                selection.end.column += indent_delta.len;
 5665                delta_for_end_row = indent_delta.len;
 5666            }
 5667        }
 5668
 5669        if selection.start.row == selection.end.row {
 5670            delta_for_start_row + delta_for_end_row
 5671        } else {
 5672            delta_for_end_row
 5673        }
 5674    }
 5675
 5676    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 5677        if self.read_only(cx) {
 5678            return;
 5679        }
 5680        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5681        let selections = self.selections.all::<Point>(cx);
 5682        let mut deletion_ranges = Vec::new();
 5683        let mut last_outdent = None;
 5684        {
 5685            let buffer = self.buffer.read(cx);
 5686            let snapshot = buffer.snapshot(cx);
 5687            for selection in &selections {
 5688                let settings = buffer.settings_at(selection.start, cx);
 5689                let tab_size = settings.tab_size.get();
 5690                let mut rows = selection.spanned_rows(false, &display_map);
 5691
 5692                // Avoid re-outdenting a row that has already been outdented by a
 5693                // previous selection.
 5694                if let Some(last_row) = last_outdent {
 5695                    if last_row == rows.start {
 5696                        rows.start = rows.start.next_row();
 5697                    }
 5698                }
 5699                let has_multiple_rows = rows.len() > 1;
 5700                for row in rows.iter_rows() {
 5701                    let indent_size = snapshot.indent_size_for_line(row);
 5702                    if indent_size.len > 0 {
 5703                        let deletion_len = match indent_size.kind {
 5704                            IndentKind::Space => {
 5705                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 5706                                if columns_to_prev_tab_stop == 0 {
 5707                                    tab_size
 5708                                } else {
 5709                                    columns_to_prev_tab_stop
 5710                                }
 5711                            }
 5712                            IndentKind::Tab => 1,
 5713                        };
 5714                        let start = if has_multiple_rows
 5715                            || deletion_len > selection.start.column
 5716                            || indent_size.len < selection.start.column
 5717                        {
 5718                            0
 5719                        } else {
 5720                            selection.start.column - deletion_len
 5721                        };
 5722                        deletion_ranges.push(
 5723                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 5724                        );
 5725                        last_outdent = Some(row);
 5726                    }
 5727                }
 5728            }
 5729        }
 5730
 5731        self.transact(cx, |this, cx| {
 5732            this.buffer.update(cx, |buffer, cx| {
 5733                let empty_str: Arc<str> = "".into();
 5734                buffer.edit(
 5735                    deletion_ranges
 5736                        .into_iter()
 5737                        .map(|range| (range, empty_str.clone())),
 5738                    None,
 5739                    cx,
 5740                );
 5741            });
 5742            let selections = this.selections.all::<usize>(cx);
 5743            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5744        });
 5745    }
 5746
 5747    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 5748        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5749        let selections = self.selections.all::<Point>(cx);
 5750
 5751        let mut new_cursors = Vec::new();
 5752        let mut edit_ranges = Vec::new();
 5753        let mut selections = selections.iter().peekable();
 5754        while let Some(selection) = selections.next() {
 5755            let mut rows = selection.spanned_rows(false, &display_map);
 5756            let goal_display_column = selection.head().to_display_point(&display_map).column();
 5757
 5758            // Accumulate contiguous regions of rows that we want to delete.
 5759            while let Some(next_selection) = selections.peek() {
 5760                let next_rows = next_selection.spanned_rows(false, &display_map);
 5761                if next_rows.start <= rows.end {
 5762                    rows.end = next_rows.end;
 5763                    selections.next().unwrap();
 5764                } else {
 5765                    break;
 5766                }
 5767            }
 5768
 5769            let buffer = &display_map.buffer_snapshot;
 5770            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 5771            let edit_end;
 5772            let cursor_buffer_row;
 5773            if buffer.max_point().row >= rows.end.0 {
 5774                // If there's a line after the range, delete the \n from the end of the row range
 5775                // and position the cursor on the next line.
 5776                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 5777                cursor_buffer_row = rows.end;
 5778            } else {
 5779                // If there isn't a line after the range, delete the \n from the line before the
 5780                // start of the row range and position the cursor there.
 5781                edit_start = edit_start.saturating_sub(1);
 5782                edit_end = buffer.len();
 5783                cursor_buffer_row = rows.start.previous_row();
 5784            }
 5785
 5786            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 5787            *cursor.column_mut() =
 5788                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 5789
 5790            new_cursors.push((
 5791                selection.id,
 5792                buffer.anchor_after(cursor.to_point(&display_map)),
 5793            ));
 5794            edit_ranges.push(edit_start..edit_end);
 5795        }
 5796
 5797        self.transact(cx, |this, cx| {
 5798            let buffer = this.buffer.update(cx, |buffer, cx| {
 5799                let empty_str: Arc<str> = "".into();
 5800                buffer.edit(
 5801                    edit_ranges
 5802                        .into_iter()
 5803                        .map(|range| (range, empty_str.clone())),
 5804                    None,
 5805                    cx,
 5806                );
 5807                buffer.snapshot(cx)
 5808            });
 5809            let new_selections = new_cursors
 5810                .into_iter()
 5811                .map(|(id, cursor)| {
 5812                    let cursor = cursor.to_point(&buffer);
 5813                    Selection {
 5814                        id,
 5815                        start: cursor,
 5816                        end: cursor,
 5817                        reversed: false,
 5818                        goal: SelectionGoal::None,
 5819                    }
 5820                })
 5821                .collect();
 5822
 5823            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5824                s.select(new_selections);
 5825            });
 5826        });
 5827    }
 5828
 5829    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 5830        if self.read_only(cx) {
 5831            return;
 5832        }
 5833        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 5834        for selection in self.selections.all::<Point>(cx) {
 5835            let start = MultiBufferRow(selection.start.row);
 5836            let end = if selection.start.row == selection.end.row {
 5837                MultiBufferRow(selection.start.row + 1)
 5838            } else {
 5839                MultiBufferRow(selection.end.row)
 5840            };
 5841
 5842            if let Some(last_row_range) = row_ranges.last_mut() {
 5843                if start <= last_row_range.end {
 5844                    last_row_range.end = end;
 5845                    continue;
 5846                }
 5847            }
 5848            row_ranges.push(start..end);
 5849        }
 5850
 5851        let snapshot = self.buffer.read(cx).snapshot(cx);
 5852        let mut cursor_positions = Vec::new();
 5853        for row_range in &row_ranges {
 5854            let anchor = snapshot.anchor_before(Point::new(
 5855                row_range.end.previous_row().0,
 5856                snapshot.line_len(row_range.end.previous_row()),
 5857            ));
 5858            cursor_positions.push(anchor..anchor);
 5859        }
 5860
 5861        self.transact(cx, |this, cx| {
 5862            for row_range in row_ranges.into_iter().rev() {
 5863                for row in row_range.iter_rows().rev() {
 5864                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 5865                    let next_line_row = row.next_row();
 5866                    let indent = snapshot.indent_size_for_line(next_line_row);
 5867                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 5868
 5869                    let replace = if snapshot.line_len(next_line_row) > indent.len {
 5870                        " "
 5871                    } else {
 5872                        ""
 5873                    };
 5874
 5875                    this.buffer.update(cx, |buffer, cx| {
 5876                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 5877                    });
 5878                }
 5879            }
 5880
 5881            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5882                s.select_anchor_ranges(cursor_positions)
 5883            });
 5884        });
 5885    }
 5886
 5887    pub fn sort_lines_case_sensitive(
 5888        &mut self,
 5889        _: &SortLinesCaseSensitive,
 5890        cx: &mut ViewContext<Self>,
 5891    ) {
 5892        self.manipulate_lines(cx, |lines| lines.sort())
 5893    }
 5894
 5895    pub fn sort_lines_case_insensitive(
 5896        &mut self,
 5897        _: &SortLinesCaseInsensitive,
 5898        cx: &mut ViewContext<Self>,
 5899    ) {
 5900        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 5901    }
 5902
 5903    pub fn unique_lines_case_insensitive(
 5904        &mut self,
 5905        _: &UniqueLinesCaseInsensitive,
 5906        cx: &mut ViewContext<Self>,
 5907    ) {
 5908        self.manipulate_lines(cx, |lines| {
 5909            let mut seen = HashSet::default();
 5910            lines.retain(|line| seen.insert(line.to_lowercase()));
 5911        })
 5912    }
 5913
 5914    pub fn unique_lines_case_sensitive(
 5915        &mut self,
 5916        _: &UniqueLinesCaseSensitive,
 5917        cx: &mut ViewContext<Self>,
 5918    ) {
 5919        self.manipulate_lines(cx, |lines| {
 5920            let mut seen = HashSet::default();
 5921            lines.retain(|line| seen.insert(*line));
 5922        })
 5923    }
 5924
 5925    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 5926        let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
 5927        if !revert_changes.is_empty() {
 5928            self.transact(cx, |editor, cx| {
 5929                editor.revert(revert_changes, cx);
 5930            });
 5931        }
 5932    }
 5933
 5934    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 5935        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 5936            let project_path = buffer.read(cx).project_path(cx)?;
 5937            let project = self.project.as_ref()?.read(cx);
 5938            let entry = project.entry_for_path(&project_path, cx)?;
 5939            let abs_path = project.absolute_path(&project_path, cx)?;
 5940            let parent = if entry.is_symlink {
 5941                abs_path.canonicalize().ok()?
 5942            } else {
 5943                abs_path
 5944            }
 5945            .parent()?
 5946            .to_path_buf();
 5947            Some(parent)
 5948        }) {
 5949            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 5950        }
 5951    }
 5952
 5953    fn gather_revert_changes(
 5954        &mut self,
 5955        selections: &[Selection<Anchor>],
 5956        cx: &mut ViewContext<'_, Editor>,
 5957    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 5958        let mut revert_changes = HashMap::default();
 5959        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 5960        for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
 5961            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 5962        }
 5963        revert_changes
 5964    }
 5965
 5966    pub fn prepare_revert_change(
 5967        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 5968        multi_buffer: &Model<MultiBuffer>,
 5969        hunk: &DiffHunk<MultiBufferRow>,
 5970        cx: &AppContext,
 5971    ) -> Option<()> {
 5972        let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
 5973        let buffer = buffer.read(cx);
 5974        let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
 5975        let buffer_snapshot = buffer.snapshot();
 5976        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 5977        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 5978            probe
 5979                .0
 5980                .start
 5981                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 5982                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 5983        }) {
 5984            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 5985            Some(())
 5986        } else {
 5987            None
 5988        }
 5989    }
 5990
 5991    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 5992        self.manipulate_lines(cx, |lines| lines.reverse())
 5993    }
 5994
 5995    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 5996        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 5997    }
 5998
 5999    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6000    where
 6001        Fn: FnMut(&mut Vec<&str>),
 6002    {
 6003        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6004        let buffer = self.buffer.read(cx).snapshot(cx);
 6005
 6006        let mut edits = Vec::new();
 6007
 6008        let selections = self.selections.all::<Point>(cx);
 6009        let mut selections = selections.iter().peekable();
 6010        let mut contiguous_row_selections = Vec::new();
 6011        let mut new_selections = Vec::new();
 6012        let mut added_lines = 0;
 6013        let mut removed_lines = 0;
 6014
 6015        while let Some(selection) = selections.next() {
 6016            let (start_row, end_row) = consume_contiguous_rows(
 6017                &mut contiguous_row_selections,
 6018                selection,
 6019                &display_map,
 6020                &mut selections,
 6021            );
 6022
 6023            let start_point = Point::new(start_row.0, 0);
 6024            let end_point = Point::new(
 6025                end_row.previous_row().0,
 6026                buffer.line_len(end_row.previous_row()),
 6027            );
 6028            let text = buffer
 6029                .text_for_range(start_point..end_point)
 6030                .collect::<String>();
 6031
 6032            let mut lines = text.split('\n').collect_vec();
 6033
 6034            let lines_before = lines.len();
 6035            callback(&mut lines);
 6036            let lines_after = lines.len();
 6037
 6038            edits.push((start_point..end_point, lines.join("\n")));
 6039
 6040            // Selections must change based on added and removed line count
 6041            let start_row =
 6042                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6043            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6044            new_selections.push(Selection {
 6045                id: selection.id,
 6046                start: start_row,
 6047                end: end_row,
 6048                goal: SelectionGoal::None,
 6049                reversed: selection.reversed,
 6050            });
 6051
 6052            if lines_after > lines_before {
 6053                added_lines += lines_after - lines_before;
 6054            } else if lines_before > lines_after {
 6055                removed_lines += lines_before - lines_after;
 6056            }
 6057        }
 6058
 6059        self.transact(cx, |this, cx| {
 6060            let buffer = this.buffer.update(cx, |buffer, cx| {
 6061                buffer.edit(edits, None, cx);
 6062                buffer.snapshot(cx)
 6063            });
 6064
 6065            // Recalculate offsets on newly edited buffer
 6066            let new_selections = new_selections
 6067                .iter()
 6068                .map(|s| {
 6069                    let start_point = Point::new(s.start.0, 0);
 6070                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6071                    Selection {
 6072                        id: s.id,
 6073                        start: buffer.point_to_offset(start_point),
 6074                        end: buffer.point_to_offset(end_point),
 6075                        goal: s.goal,
 6076                        reversed: s.reversed,
 6077                    }
 6078                })
 6079                .collect();
 6080
 6081            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6082                s.select(new_selections);
 6083            });
 6084
 6085            this.request_autoscroll(Autoscroll::fit(), cx);
 6086        });
 6087    }
 6088
 6089    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 6090        self.manipulate_text(cx, |text| text.to_uppercase())
 6091    }
 6092
 6093    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 6094        self.manipulate_text(cx, |text| text.to_lowercase())
 6095    }
 6096
 6097    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 6098        self.manipulate_text(cx, |text| {
 6099            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6100            // https://github.com/rutrum/convert-case/issues/16
 6101            text.split('\n')
 6102                .map(|line| line.to_case(Case::Title))
 6103                .join("\n")
 6104        })
 6105    }
 6106
 6107    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6108        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6109    }
 6110
 6111    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6112        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6113    }
 6114
 6115    pub fn convert_to_upper_camel_case(
 6116        &mut self,
 6117        _: &ConvertToUpperCamelCase,
 6118        cx: &mut ViewContext<Self>,
 6119    ) {
 6120        self.manipulate_text(cx, |text| {
 6121            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6122            // https://github.com/rutrum/convert-case/issues/16
 6123            text.split('\n')
 6124                .map(|line| line.to_case(Case::UpperCamel))
 6125                .join("\n")
 6126        })
 6127    }
 6128
 6129    pub fn convert_to_lower_camel_case(
 6130        &mut self,
 6131        _: &ConvertToLowerCamelCase,
 6132        cx: &mut ViewContext<Self>,
 6133    ) {
 6134        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6135    }
 6136
 6137    pub fn convert_to_opposite_case(
 6138        &mut self,
 6139        _: &ConvertToOppositeCase,
 6140        cx: &mut ViewContext<Self>,
 6141    ) {
 6142        self.manipulate_text(cx, |text| {
 6143            text.chars()
 6144                .fold(String::with_capacity(text.len()), |mut t, c| {
 6145                    if c.is_uppercase() {
 6146                        t.extend(c.to_lowercase());
 6147                    } else {
 6148                        t.extend(c.to_uppercase());
 6149                    }
 6150                    t
 6151                })
 6152        })
 6153    }
 6154
 6155    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6156    where
 6157        Fn: FnMut(&str) -> String,
 6158    {
 6159        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6160        let buffer = self.buffer.read(cx).snapshot(cx);
 6161
 6162        let mut new_selections = Vec::new();
 6163        let mut edits = Vec::new();
 6164        let mut selection_adjustment = 0i32;
 6165
 6166        for selection in self.selections.all::<usize>(cx) {
 6167            let selection_is_empty = selection.is_empty();
 6168
 6169            let (start, end) = if selection_is_empty {
 6170                let word_range = movement::surrounding_word(
 6171                    &display_map,
 6172                    selection.start.to_display_point(&display_map),
 6173                );
 6174                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6175                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6176                (start, end)
 6177            } else {
 6178                (selection.start, selection.end)
 6179            };
 6180
 6181            let text = buffer.text_for_range(start..end).collect::<String>();
 6182            let old_length = text.len() as i32;
 6183            let text = callback(&text);
 6184
 6185            new_selections.push(Selection {
 6186                start: (start as i32 - selection_adjustment) as usize,
 6187                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6188                goal: SelectionGoal::None,
 6189                ..selection
 6190            });
 6191
 6192            selection_adjustment += old_length - text.len() as i32;
 6193
 6194            edits.push((start..end, text));
 6195        }
 6196
 6197        self.transact(cx, |this, cx| {
 6198            this.buffer.update(cx, |buffer, cx| {
 6199                buffer.edit(edits, None, cx);
 6200            });
 6201
 6202            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6203                s.select(new_selections);
 6204            });
 6205
 6206            this.request_autoscroll(Autoscroll::fit(), cx);
 6207        });
 6208    }
 6209
 6210    pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
 6211        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6212        let buffer = &display_map.buffer_snapshot;
 6213        let selections = self.selections.all::<Point>(cx);
 6214
 6215        let mut edits = Vec::new();
 6216        let mut selections_iter = selections.iter().peekable();
 6217        while let Some(selection) = selections_iter.next() {
 6218            // Avoid duplicating the same lines twice.
 6219            let mut rows = selection.spanned_rows(false, &display_map);
 6220
 6221            while let Some(next_selection) = selections_iter.peek() {
 6222                let next_rows = next_selection.spanned_rows(false, &display_map);
 6223                if next_rows.start < rows.end {
 6224                    rows.end = next_rows.end;
 6225                    selections_iter.next().unwrap();
 6226                } else {
 6227                    break;
 6228                }
 6229            }
 6230
 6231            // Copy the text from the selected row region and splice it either at the start
 6232            // or end of the region.
 6233            let start = Point::new(rows.start.0, 0);
 6234            let end = Point::new(
 6235                rows.end.previous_row().0,
 6236                buffer.line_len(rows.end.previous_row()),
 6237            );
 6238            let text = buffer
 6239                .text_for_range(start..end)
 6240                .chain(Some("\n"))
 6241                .collect::<String>();
 6242            let insert_location = if upwards {
 6243                Point::new(rows.end.0, 0)
 6244            } else {
 6245                start
 6246            };
 6247            edits.push((insert_location..insert_location, text));
 6248        }
 6249
 6250        self.transact(cx, |this, cx| {
 6251            this.buffer.update(cx, |buffer, cx| {
 6252                buffer.edit(edits, None, cx);
 6253            });
 6254
 6255            this.request_autoscroll(Autoscroll::fit(), cx);
 6256        });
 6257    }
 6258
 6259    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6260        self.duplicate_line(true, cx);
 6261    }
 6262
 6263    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6264        self.duplicate_line(false, cx);
 6265    }
 6266
 6267    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6268        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6269        let buffer = self.buffer.read(cx).snapshot(cx);
 6270
 6271        let mut edits = Vec::new();
 6272        let mut unfold_ranges = Vec::new();
 6273        let mut refold_ranges = Vec::new();
 6274
 6275        let selections = self.selections.all::<Point>(cx);
 6276        let mut selections = selections.iter().peekable();
 6277        let mut contiguous_row_selections = Vec::new();
 6278        let mut new_selections = Vec::new();
 6279
 6280        while let Some(selection) = selections.next() {
 6281            // Find all the selections that span a contiguous row range
 6282            let (start_row, end_row) = consume_contiguous_rows(
 6283                &mut contiguous_row_selections,
 6284                selection,
 6285                &display_map,
 6286                &mut selections,
 6287            );
 6288
 6289            // Move the text spanned by the row range to be before the line preceding the row range
 6290            if start_row.0 > 0 {
 6291                let range_to_move = Point::new(
 6292                    start_row.previous_row().0,
 6293                    buffer.line_len(start_row.previous_row()),
 6294                )
 6295                    ..Point::new(
 6296                        end_row.previous_row().0,
 6297                        buffer.line_len(end_row.previous_row()),
 6298                    );
 6299                let insertion_point = display_map
 6300                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6301                    .0;
 6302
 6303                // Don't move lines across excerpts
 6304                if buffer
 6305                    .excerpt_boundaries_in_range((
 6306                        Bound::Excluded(insertion_point),
 6307                        Bound::Included(range_to_move.end),
 6308                    ))
 6309                    .next()
 6310                    .is_none()
 6311                {
 6312                    let text = buffer
 6313                        .text_for_range(range_to_move.clone())
 6314                        .flat_map(|s| s.chars())
 6315                        .skip(1)
 6316                        .chain(['\n'])
 6317                        .collect::<String>();
 6318
 6319                    edits.push((
 6320                        buffer.anchor_after(range_to_move.start)
 6321                            ..buffer.anchor_before(range_to_move.end),
 6322                        String::new(),
 6323                    ));
 6324                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6325                    edits.push((insertion_anchor..insertion_anchor, text));
 6326
 6327                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6328
 6329                    // Move selections up
 6330                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6331                        |mut selection| {
 6332                            selection.start.row -= row_delta;
 6333                            selection.end.row -= row_delta;
 6334                            selection
 6335                        },
 6336                    ));
 6337
 6338                    // Move folds up
 6339                    unfold_ranges.push(range_to_move.clone());
 6340                    for fold in display_map.folds_in_range(
 6341                        buffer.anchor_before(range_to_move.start)
 6342                            ..buffer.anchor_after(range_to_move.end),
 6343                    ) {
 6344                        let mut start = fold.range.start.to_point(&buffer);
 6345                        let mut end = fold.range.end.to_point(&buffer);
 6346                        start.row -= row_delta;
 6347                        end.row -= row_delta;
 6348                        refold_ranges.push((start..end, fold.placeholder.clone()));
 6349                    }
 6350                }
 6351            }
 6352
 6353            // If we didn't move line(s), preserve the existing selections
 6354            new_selections.append(&mut contiguous_row_selections);
 6355        }
 6356
 6357        self.transact(cx, |this, cx| {
 6358            this.unfold_ranges(unfold_ranges, true, true, cx);
 6359            this.buffer.update(cx, |buffer, cx| {
 6360                for (range, text) in edits {
 6361                    buffer.edit([(range, text)], None, cx);
 6362                }
 6363            });
 6364            this.fold_ranges(refold_ranges, true, cx);
 6365            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6366                s.select(new_selections);
 6367            })
 6368        });
 6369    }
 6370
 6371    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 6372        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6373        let buffer = self.buffer.read(cx).snapshot(cx);
 6374
 6375        let mut edits = Vec::new();
 6376        let mut unfold_ranges = Vec::new();
 6377        let mut refold_ranges = Vec::new();
 6378
 6379        let selections = self.selections.all::<Point>(cx);
 6380        let mut selections = selections.iter().peekable();
 6381        let mut contiguous_row_selections = Vec::new();
 6382        let mut new_selections = Vec::new();
 6383
 6384        while let Some(selection) = selections.next() {
 6385            // Find all the selections that span a contiguous row range
 6386            let (start_row, end_row) = consume_contiguous_rows(
 6387                &mut contiguous_row_selections,
 6388                selection,
 6389                &display_map,
 6390                &mut selections,
 6391            );
 6392
 6393            // Move the text spanned by the row range to be after the last line of the row range
 6394            if end_row.0 <= buffer.max_point().row {
 6395                let range_to_move =
 6396                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 6397                let insertion_point = display_map
 6398                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 6399                    .0;
 6400
 6401                // Don't move lines across excerpt boundaries
 6402                if buffer
 6403                    .excerpt_boundaries_in_range((
 6404                        Bound::Excluded(range_to_move.start),
 6405                        Bound::Included(insertion_point),
 6406                    ))
 6407                    .next()
 6408                    .is_none()
 6409                {
 6410                    let mut text = String::from("\n");
 6411                    text.extend(buffer.text_for_range(range_to_move.clone()));
 6412                    text.pop(); // Drop trailing newline
 6413                    edits.push((
 6414                        buffer.anchor_after(range_to_move.start)
 6415                            ..buffer.anchor_before(range_to_move.end),
 6416                        String::new(),
 6417                    ));
 6418                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6419                    edits.push((insertion_anchor..insertion_anchor, text));
 6420
 6421                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 6422
 6423                    // Move selections down
 6424                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6425                        |mut selection| {
 6426                            selection.start.row += row_delta;
 6427                            selection.end.row += row_delta;
 6428                            selection
 6429                        },
 6430                    ));
 6431
 6432                    // Move folds down
 6433                    unfold_ranges.push(range_to_move.clone());
 6434                    for fold in display_map.folds_in_range(
 6435                        buffer.anchor_before(range_to_move.start)
 6436                            ..buffer.anchor_after(range_to_move.end),
 6437                    ) {
 6438                        let mut start = fold.range.start.to_point(&buffer);
 6439                        let mut end = fold.range.end.to_point(&buffer);
 6440                        start.row += row_delta;
 6441                        end.row += row_delta;
 6442                        refold_ranges.push((start..end, fold.placeholder.clone()));
 6443                    }
 6444                }
 6445            }
 6446
 6447            // If we didn't move line(s), preserve the existing selections
 6448            new_selections.append(&mut contiguous_row_selections);
 6449        }
 6450
 6451        self.transact(cx, |this, cx| {
 6452            this.unfold_ranges(unfold_ranges, true, true, cx);
 6453            this.buffer.update(cx, |buffer, cx| {
 6454                for (range, text) in edits {
 6455                    buffer.edit([(range, text)], None, cx);
 6456                }
 6457            });
 6458            this.fold_ranges(refold_ranges, true, cx);
 6459            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 6460        });
 6461    }
 6462
 6463    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 6464        let text_layout_details = &self.text_layout_details(cx);
 6465        self.transact(cx, |this, cx| {
 6466            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6467                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 6468                let line_mode = s.line_mode;
 6469                s.move_with(|display_map, selection| {
 6470                    if !selection.is_empty() || line_mode {
 6471                        return;
 6472                    }
 6473
 6474                    let mut head = selection.head();
 6475                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 6476                    if head.column() == display_map.line_len(head.row()) {
 6477                        transpose_offset = display_map
 6478                            .buffer_snapshot
 6479                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6480                    }
 6481
 6482                    if transpose_offset == 0 {
 6483                        return;
 6484                    }
 6485
 6486                    *head.column_mut() += 1;
 6487                    head = display_map.clip_point(head, Bias::Right);
 6488                    let goal = SelectionGoal::HorizontalPosition(
 6489                        display_map
 6490                            .x_for_display_point(head, &text_layout_details)
 6491                            .into(),
 6492                    );
 6493                    selection.collapse_to(head, goal);
 6494
 6495                    let transpose_start = display_map
 6496                        .buffer_snapshot
 6497                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6498                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 6499                        let transpose_end = display_map
 6500                            .buffer_snapshot
 6501                            .clip_offset(transpose_offset + 1, Bias::Right);
 6502                        if let Some(ch) =
 6503                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 6504                        {
 6505                            edits.push((transpose_start..transpose_offset, String::new()));
 6506                            edits.push((transpose_end..transpose_end, ch.to_string()));
 6507                        }
 6508                    }
 6509                });
 6510                edits
 6511            });
 6512            this.buffer
 6513                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6514            let selections = this.selections.all::<usize>(cx);
 6515            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6516                s.select(selections);
 6517            });
 6518        });
 6519    }
 6520
 6521    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 6522        let mut text = String::new();
 6523        let buffer = self.buffer.read(cx).snapshot(cx);
 6524        let mut selections = self.selections.all::<Point>(cx);
 6525        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6526        {
 6527            let max_point = buffer.max_point();
 6528            let mut is_first = true;
 6529            for selection in &mut selections {
 6530                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6531                if is_entire_line {
 6532                    selection.start = Point::new(selection.start.row, 0);
 6533                    selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 6534                    selection.goal = SelectionGoal::None;
 6535                }
 6536                if is_first {
 6537                    is_first = false;
 6538                } else {
 6539                    text += "\n";
 6540                }
 6541                let mut len = 0;
 6542                for chunk in buffer.text_for_range(selection.start..selection.end) {
 6543                    text.push_str(chunk);
 6544                    len += chunk.len();
 6545                }
 6546                clipboard_selections.push(ClipboardSelection {
 6547                    len,
 6548                    is_entire_line,
 6549                    first_line_indent: buffer
 6550                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 6551                        .len,
 6552                });
 6553            }
 6554        }
 6555
 6556        self.transact(cx, |this, cx| {
 6557            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6558                s.select(selections);
 6559            });
 6560            this.insert("", cx);
 6561            cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
 6562        });
 6563    }
 6564
 6565    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 6566        let selections = self.selections.all::<Point>(cx);
 6567        let buffer = self.buffer.read(cx).read(cx);
 6568        let mut text = String::new();
 6569
 6570        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6571        {
 6572            let max_point = buffer.max_point();
 6573            let mut is_first = true;
 6574            for selection in selections.iter() {
 6575                let mut start = selection.start;
 6576                let mut end = selection.end;
 6577                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6578                if is_entire_line {
 6579                    start = Point::new(start.row, 0);
 6580                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 6581                }
 6582                if is_first {
 6583                    is_first = false;
 6584                } else {
 6585                    text += "\n";
 6586                }
 6587                let mut len = 0;
 6588                for chunk in buffer.text_for_range(start..end) {
 6589                    text.push_str(chunk);
 6590                    len += chunk.len();
 6591                }
 6592                clipboard_selections.push(ClipboardSelection {
 6593                    len,
 6594                    is_entire_line,
 6595                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 6596                });
 6597            }
 6598        }
 6599
 6600        cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
 6601    }
 6602
 6603    pub fn do_paste(
 6604        &mut self,
 6605        text: &String,
 6606        clipboard_selections: Option<Vec<ClipboardSelection>>,
 6607        handle_entire_lines: bool,
 6608        cx: &mut ViewContext<Self>,
 6609    ) {
 6610        if self.read_only(cx) {
 6611            return;
 6612        }
 6613
 6614        let clipboard_text = Cow::Borrowed(text);
 6615
 6616        self.transact(cx, |this, cx| {
 6617            if let Some(mut clipboard_selections) = clipboard_selections {
 6618                let old_selections = this.selections.all::<usize>(cx);
 6619                let all_selections_were_entire_line =
 6620                    clipboard_selections.iter().all(|s| s.is_entire_line);
 6621                let first_selection_indent_column =
 6622                    clipboard_selections.first().map(|s| s.first_line_indent);
 6623                if clipboard_selections.len() != old_selections.len() {
 6624                    clipboard_selections.drain(..);
 6625                }
 6626
 6627                this.buffer.update(cx, |buffer, cx| {
 6628                    let snapshot = buffer.read(cx);
 6629                    let mut start_offset = 0;
 6630                    let mut edits = Vec::new();
 6631                    let mut original_indent_columns = Vec::new();
 6632                    for (ix, selection) in old_selections.iter().enumerate() {
 6633                        let to_insert;
 6634                        let entire_line;
 6635                        let original_indent_column;
 6636                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 6637                            let end_offset = start_offset + clipboard_selection.len;
 6638                            to_insert = &clipboard_text[start_offset..end_offset];
 6639                            entire_line = clipboard_selection.is_entire_line;
 6640                            start_offset = end_offset + 1;
 6641                            original_indent_column = Some(clipboard_selection.first_line_indent);
 6642                        } else {
 6643                            to_insert = clipboard_text.as_str();
 6644                            entire_line = all_selections_were_entire_line;
 6645                            original_indent_column = first_selection_indent_column
 6646                        }
 6647
 6648                        // If the corresponding selection was empty when this slice of the
 6649                        // clipboard text was written, then the entire line containing the
 6650                        // selection was copied. If this selection is also currently empty,
 6651                        // then paste the line before the current line of the buffer.
 6652                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 6653                            let column = selection.start.to_point(&snapshot).column as usize;
 6654                            let line_start = selection.start - column;
 6655                            line_start..line_start
 6656                        } else {
 6657                            selection.range()
 6658                        };
 6659
 6660                        edits.push((range, to_insert));
 6661                        original_indent_columns.extend(original_indent_column);
 6662                    }
 6663                    drop(snapshot);
 6664
 6665                    buffer.edit(
 6666                        edits,
 6667                        Some(AutoindentMode::Block {
 6668                            original_indent_columns,
 6669                        }),
 6670                        cx,
 6671                    );
 6672                });
 6673
 6674                let selections = this.selections.all::<usize>(cx);
 6675                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6676            } else {
 6677                this.insert(&clipboard_text, cx);
 6678            }
 6679        });
 6680    }
 6681
 6682    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 6683        if let Some(item) = cx.read_from_clipboard() {
 6684            self.do_paste(
 6685                item.text(),
 6686                item.metadata::<Vec<ClipboardSelection>>(),
 6687                true,
 6688                cx,
 6689            )
 6690        };
 6691    }
 6692
 6693    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 6694        if self.read_only(cx) {
 6695            return;
 6696        }
 6697
 6698        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 6699            if let Some((selections, _)) =
 6700                self.selection_history.transaction(transaction_id).cloned()
 6701            {
 6702                self.change_selections(None, cx, |s| {
 6703                    s.select_anchors(selections.to_vec());
 6704                });
 6705            }
 6706            self.request_autoscroll(Autoscroll::fit(), cx);
 6707            self.unmark_text(cx);
 6708            self.refresh_inline_completion(true, cx);
 6709            cx.emit(EditorEvent::Edited { transaction_id });
 6710            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 6711        }
 6712    }
 6713
 6714    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 6715        if self.read_only(cx) {
 6716            return;
 6717        }
 6718
 6719        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 6720            if let Some((_, Some(selections))) =
 6721                self.selection_history.transaction(transaction_id).cloned()
 6722            {
 6723                self.change_selections(None, cx, |s| {
 6724                    s.select_anchors(selections.to_vec());
 6725                });
 6726            }
 6727            self.request_autoscroll(Autoscroll::fit(), cx);
 6728            self.unmark_text(cx);
 6729            self.refresh_inline_completion(true, cx);
 6730            cx.emit(EditorEvent::Edited { transaction_id });
 6731        }
 6732    }
 6733
 6734    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 6735        self.buffer
 6736            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 6737    }
 6738
 6739    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 6740        self.buffer
 6741            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 6742    }
 6743
 6744    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 6745        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6746            let line_mode = s.line_mode;
 6747            s.move_with(|map, selection| {
 6748                let cursor = if selection.is_empty() && !line_mode {
 6749                    movement::left(map, selection.start)
 6750                } else {
 6751                    selection.start
 6752                };
 6753                selection.collapse_to(cursor, SelectionGoal::None);
 6754            });
 6755        })
 6756    }
 6757
 6758    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 6759        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6760            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 6761        })
 6762    }
 6763
 6764    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 6765        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6766            let line_mode = s.line_mode;
 6767            s.move_with(|map, selection| {
 6768                let cursor = if selection.is_empty() && !line_mode {
 6769                    movement::right(map, selection.end)
 6770                } else {
 6771                    selection.end
 6772                };
 6773                selection.collapse_to(cursor, SelectionGoal::None)
 6774            });
 6775        })
 6776    }
 6777
 6778    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 6779        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6780            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 6781        })
 6782    }
 6783
 6784    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 6785        if self.take_rename(true, cx).is_some() {
 6786            return;
 6787        }
 6788
 6789        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6790            cx.propagate();
 6791            return;
 6792        }
 6793
 6794        let text_layout_details = &self.text_layout_details(cx);
 6795        let selection_count = self.selections.count();
 6796        let first_selection = self.selections.first_anchor();
 6797
 6798        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6799            let line_mode = s.line_mode;
 6800            s.move_with(|map, selection| {
 6801                if !selection.is_empty() && !line_mode {
 6802                    selection.goal = SelectionGoal::None;
 6803                }
 6804                let (cursor, goal) = movement::up(
 6805                    map,
 6806                    selection.start,
 6807                    selection.goal,
 6808                    false,
 6809                    &text_layout_details,
 6810                );
 6811                selection.collapse_to(cursor, goal);
 6812            });
 6813        });
 6814
 6815        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 6816        {
 6817            cx.propagate();
 6818        }
 6819    }
 6820
 6821    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 6822        if self.take_rename(true, cx).is_some() {
 6823            return;
 6824        }
 6825
 6826        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6827            cx.propagate();
 6828            return;
 6829        }
 6830
 6831        let text_layout_details = &self.text_layout_details(cx);
 6832
 6833        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6834            let line_mode = s.line_mode;
 6835            s.move_with(|map, selection| {
 6836                if !selection.is_empty() && !line_mode {
 6837                    selection.goal = SelectionGoal::None;
 6838                }
 6839                let (cursor, goal) = movement::up_by_rows(
 6840                    map,
 6841                    selection.start,
 6842                    action.lines,
 6843                    selection.goal,
 6844                    false,
 6845                    &text_layout_details,
 6846                );
 6847                selection.collapse_to(cursor, goal);
 6848            });
 6849        })
 6850    }
 6851
 6852    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 6853        if self.take_rename(true, cx).is_some() {
 6854            return;
 6855        }
 6856
 6857        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6858            cx.propagate();
 6859            return;
 6860        }
 6861
 6862        let text_layout_details = &self.text_layout_details(cx);
 6863
 6864        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6865            let line_mode = s.line_mode;
 6866            s.move_with(|map, selection| {
 6867                if !selection.is_empty() && !line_mode {
 6868                    selection.goal = SelectionGoal::None;
 6869                }
 6870                let (cursor, goal) = movement::down_by_rows(
 6871                    map,
 6872                    selection.start,
 6873                    action.lines,
 6874                    selection.goal,
 6875                    false,
 6876                    &text_layout_details,
 6877                );
 6878                selection.collapse_to(cursor, goal);
 6879            });
 6880        })
 6881    }
 6882
 6883    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 6884        let text_layout_details = &self.text_layout_details(cx);
 6885        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6886            s.move_heads_with(|map, head, goal| {
 6887                movement::down_by_rows(map, head, action.lines, goal, false, &text_layout_details)
 6888            })
 6889        })
 6890    }
 6891
 6892    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 6893        let text_layout_details = &self.text_layout_details(cx);
 6894        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6895            s.move_heads_with(|map, head, goal| {
 6896                movement::up_by_rows(map, head, action.lines, goal, false, &text_layout_details)
 6897            })
 6898        })
 6899    }
 6900
 6901    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 6902        let Some(row_count) = self.visible_row_count() else {
 6903            return;
 6904        };
 6905
 6906        let text_layout_details = &self.text_layout_details(cx);
 6907
 6908        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6909            s.move_heads_with(|map, head, goal| {
 6910                movement::up_by_rows(map, head, row_count, goal, false, &text_layout_details)
 6911            })
 6912        })
 6913    }
 6914
 6915    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 6916        if self.take_rename(true, cx).is_some() {
 6917            return;
 6918        }
 6919
 6920        if self
 6921            .context_menu
 6922            .write()
 6923            .as_mut()
 6924            .map(|menu| menu.select_first(self.project.as_ref(), cx))
 6925            .unwrap_or(false)
 6926        {
 6927            return;
 6928        }
 6929
 6930        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6931            cx.propagate();
 6932            return;
 6933        }
 6934
 6935        let Some(row_count) = self.visible_row_count() else {
 6936            return;
 6937        };
 6938
 6939        let autoscroll = if action.center_cursor {
 6940            Autoscroll::center()
 6941        } else {
 6942            Autoscroll::fit()
 6943        };
 6944
 6945        let text_layout_details = &self.text_layout_details(cx);
 6946
 6947        self.change_selections(Some(autoscroll), cx, |s| {
 6948            let line_mode = s.line_mode;
 6949            s.move_with(|map, selection| {
 6950                if !selection.is_empty() && !line_mode {
 6951                    selection.goal = SelectionGoal::None;
 6952                }
 6953                let (cursor, goal) = movement::up_by_rows(
 6954                    map,
 6955                    selection.end,
 6956                    row_count,
 6957                    selection.goal,
 6958                    false,
 6959                    &text_layout_details,
 6960                );
 6961                selection.collapse_to(cursor, goal);
 6962            });
 6963        });
 6964    }
 6965
 6966    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 6967        let text_layout_details = &self.text_layout_details(cx);
 6968        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6969            s.move_heads_with(|map, head, goal| {
 6970                movement::up(map, head, goal, false, &text_layout_details)
 6971            })
 6972        })
 6973    }
 6974
 6975    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 6976        self.take_rename(true, cx);
 6977
 6978        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6979            cx.propagate();
 6980            return;
 6981        }
 6982
 6983        let text_layout_details = &self.text_layout_details(cx);
 6984        let selection_count = self.selections.count();
 6985        let first_selection = self.selections.first_anchor();
 6986
 6987        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6988            let line_mode = s.line_mode;
 6989            s.move_with(|map, selection| {
 6990                if !selection.is_empty() && !line_mode {
 6991                    selection.goal = SelectionGoal::None;
 6992                }
 6993                let (cursor, goal) = movement::down(
 6994                    map,
 6995                    selection.end,
 6996                    selection.goal,
 6997                    false,
 6998                    &text_layout_details,
 6999                );
 7000                selection.collapse_to(cursor, goal);
 7001            });
 7002        });
 7003
 7004        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7005        {
 7006            cx.propagate();
 7007        }
 7008    }
 7009
 7010    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 7011        let Some(row_count) = self.visible_row_count() else {
 7012            return;
 7013        };
 7014
 7015        let text_layout_details = &self.text_layout_details(cx);
 7016
 7017        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7018            s.move_heads_with(|map, head, goal| {
 7019                movement::down_by_rows(map, head, row_count, goal, false, &text_layout_details)
 7020            })
 7021        })
 7022    }
 7023
 7024    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 7025        if self.take_rename(true, cx).is_some() {
 7026            return;
 7027        }
 7028
 7029        if self
 7030            .context_menu
 7031            .write()
 7032            .as_mut()
 7033            .map(|menu| menu.select_last(self.project.as_ref(), cx))
 7034            .unwrap_or(false)
 7035        {
 7036            return;
 7037        }
 7038
 7039        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7040            cx.propagate();
 7041            return;
 7042        }
 7043
 7044        let Some(row_count) = self.visible_row_count() else {
 7045            return;
 7046        };
 7047
 7048        let autoscroll = if action.center_cursor {
 7049            Autoscroll::center()
 7050        } else {
 7051            Autoscroll::fit()
 7052        };
 7053
 7054        let text_layout_details = &self.text_layout_details(cx);
 7055        self.change_selections(Some(autoscroll), cx, |s| {
 7056            let line_mode = s.line_mode;
 7057            s.move_with(|map, selection| {
 7058                if !selection.is_empty() && !line_mode {
 7059                    selection.goal = SelectionGoal::None;
 7060                }
 7061                let (cursor, goal) = movement::down_by_rows(
 7062                    map,
 7063                    selection.end,
 7064                    row_count,
 7065                    selection.goal,
 7066                    false,
 7067                    &text_layout_details,
 7068                );
 7069                selection.collapse_to(cursor, goal);
 7070            });
 7071        });
 7072    }
 7073
 7074    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 7075        let text_layout_details = &self.text_layout_details(cx);
 7076        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7077            s.move_heads_with(|map, head, goal| {
 7078                movement::down(map, head, goal, false, &text_layout_details)
 7079            })
 7080        });
 7081    }
 7082
 7083    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 7084        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7085            context_menu.select_first(self.project.as_ref(), cx);
 7086        }
 7087    }
 7088
 7089    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 7090        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7091            context_menu.select_prev(self.project.as_ref(), cx);
 7092        }
 7093    }
 7094
 7095    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7096        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7097            context_menu.select_next(self.project.as_ref(), cx);
 7098        }
 7099    }
 7100
 7101    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 7102        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7103            context_menu.select_last(self.project.as_ref(), cx);
 7104        }
 7105    }
 7106
 7107    pub fn move_to_previous_word_start(
 7108        &mut self,
 7109        _: &MoveToPreviousWordStart,
 7110        cx: &mut ViewContext<Self>,
 7111    ) {
 7112        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7113            s.move_cursors_with(|map, head, _| {
 7114                (
 7115                    movement::previous_word_start(map, head),
 7116                    SelectionGoal::None,
 7117                )
 7118            });
 7119        })
 7120    }
 7121
 7122    pub fn move_to_previous_subword_start(
 7123        &mut self,
 7124        _: &MoveToPreviousSubwordStart,
 7125        cx: &mut ViewContext<Self>,
 7126    ) {
 7127        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7128            s.move_cursors_with(|map, head, _| {
 7129                (
 7130                    movement::previous_subword_start(map, head),
 7131                    SelectionGoal::None,
 7132                )
 7133            });
 7134        })
 7135    }
 7136
 7137    pub fn select_to_previous_word_start(
 7138        &mut self,
 7139        _: &SelectToPreviousWordStart,
 7140        cx: &mut ViewContext<Self>,
 7141    ) {
 7142        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7143            s.move_heads_with(|map, head, _| {
 7144                (
 7145                    movement::previous_word_start(map, head),
 7146                    SelectionGoal::None,
 7147                )
 7148            });
 7149        })
 7150    }
 7151
 7152    pub fn select_to_previous_subword_start(
 7153        &mut self,
 7154        _: &SelectToPreviousSubwordStart,
 7155        cx: &mut ViewContext<Self>,
 7156    ) {
 7157        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7158            s.move_heads_with(|map, head, _| {
 7159                (
 7160                    movement::previous_subword_start(map, head),
 7161                    SelectionGoal::None,
 7162                )
 7163            });
 7164        })
 7165    }
 7166
 7167    pub fn delete_to_previous_word_start(
 7168        &mut self,
 7169        _: &DeleteToPreviousWordStart,
 7170        cx: &mut ViewContext<Self>,
 7171    ) {
 7172        self.transact(cx, |this, cx| {
 7173            this.select_autoclose_pair(cx);
 7174            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7175                let line_mode = s.line_mode;
 7176                s.move_with(|map, selection| {
 7177                    if selection.is_empty() && !line_mode {
 7178                        let cursor = movement::previous_word_start(map, selection.head());
 7179                        selection.set_head(cursor, SelectionGoal::None);
 7180                    }
 7181                });
 7182            });
 7183            this.insert("", cx);
 7184        });
 7185    }
 7186
 7187    pub fn delete_to_previous_subword_start(
 7188        &mut self,
 7189        _: &DeleteToPreviousSubwordStart,
 7190        cx: &mut ViewContext<Self>,
 7191    ) {
 7192        self.transact(cx, |this, cx| {
 7193            this.select_autoclose_pair(cx);
 7194            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7195                let line_mode = s.line_mode;
 7196                s.move_with(|map, selection| {
 7197                    if selection.is_empty() && !line_mode {
 7198                        let cursor = movement::previous_subword_start(map, selection.head());
 7199                        selection.set_head(cursor, SelectionGoal::None);
 7200                    }
 7201                });
 7202            });
 7203            this.insert("", cx);
 7204        });
 7205    }
 7206
 7207    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 7208        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7209            s.move_cursors_with(|map, head, _| {
 7210                (movement::next_word_end(map, head), SelectionGoal::None)
 7211            });
 7212        })
 7213    }
 7214
 7215    pub fn move_to_next_subword_end(
 7216        &mut self,
 7217        _: &MoveToNextSubwordEnd,
 7218        cx: &mut ViewContext<Self>,
 7219    ) {
 7220        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7221            s.move_cursors_with(|map, head, _| {
 7222                (movement::next_subword_end(map, head), SelectionGoal::None)
 7223            });
 7224        })
 7225    }
 7226
 7227    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 7228        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7229            s.move_heads_with(|map, head, _| {
 7230                (movement::next_word_end(map, head), SelectionGoal::None)
 7231            });
 7232        })
 7233    }
 7234
 7235    pub fn select_to_next_subword_end(
 7236        &mut self,
 7237        _: &SelectToNextSubwordEnd,
 7238        cx: &mut ViewContext<Self>,
 7239    ) {
 7240        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7241            s.move_heads_with(|map, head, _| {
 7242                (movement::next_subword_end(map, head), SelectionGoal::None)
 7243            });
 7244        })
 7245    }
 7246
 7247    pub fn delete_to_next_word_end(&mut self, _: &DeleteToNextWordEnd, cx: &mut ViewContext<Self>) {
 7248        self.transact(cx, |this, cx| {
 7249            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7250                let line_mode = s.line_mode;
 7251                s.move_with(|map, selection| {
 7252                    if selection.is_empty() && !line_mode {
 7253                        let cursor = movement::next_word_end(map, selection.head());
 7254                        selection.set_head(cursor, SelectionGoal::None);
 7255                    }
 7256                });
 7257            });
 7258            this.insert("", cx);
 7259        });
 7260    }
 7261
 7262    pub fn delete_to_next_subword_end(
 7263        &mut self,
 7264        _: &DeleteToNextSubwordEnd,
 7265        cx: &mut ViewContext<Self>,
 7266    ) {
 7267        self.transact(cx, |this, cx| {
 7268            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7269                s.move_with(|map, selection| {
 7270                    if selection.is_empty() {
 7271                        let cursor = movement::next_subword_end(map, selection.head());
 7272                        selection.set_head(cursor, SelectionGoal::None);
 7273                    }
 7274                });
 7275            });
 7276            this.insert("", cx);
 7277        });
 7278    }
 7279
 7280    pub fn move_to_beginning_of_line(
 7281        &mut self,
 7282        action: &MoveToBeginningOfLine,
 7283        cx: &mut ViewContext<Self>,
 7284    ) {
 7285        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7286            s.move_cursors_with(|map, head, _| {
 7287                (
 7288                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7289                    SelectionGoal::None,
 7290                )
 7291            });
 7292        })
 7293    }
 7294
 7295    pub fn select_to_beginning_of_line(
 7296        &mut self,
 7297        action: &SelectToBeginningOfLine,
 7298        cx: &mut ViewContext<Self>,
 7299    ) {
 7300        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7301            s.move_heads_with(|map, head, _| {
 7302                (
 7303                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7304                    SelectionGoal::None,
 7305                )
 7306            });
 7307        });
 7308    }
 7309
 7310    pub fn delete_to_beginning_of_line(
 7311        &mut self,
 7312        _: &DeleteToBeginningOfLine,
 7313        cx: &mut ViewContext<Self>,
 7314    ) {
 7315        self.transact(cx, |this, cx| {
 7316            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7317                s.move_with(|_, selection| {
 7318                    selection.reversed = true;
 7319                });
 7320            });
 7321
 7322            this.select_to_beginning_of_line(
 7323                &SelectToBeginningOfLine {
 7324                    stop_at_soft_wraps: false,
 7325                },
 7326                cx,
 7327            );
 7328            this.backspace(&Backspace, cx);
 7329        });
 7330    }
 7331
 7332    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 7333        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7334            s.move_cursors_with(|map, head, _| {
 7335                (
 7336                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7337                    SelectionGoal::None,
 7338                )
 7339            });
 7340        })
 7341    }
 7342
 7343    pub fn select_to_end_of_line(
 7344        &mut self,
 7345        action: &SelectToEndOfLine,
 7346        cx: &mut ViewContext<Self>,
 7347    ) {
 7348        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7349            s.move_heads_with(|map, head, _| {
 7350                (
 7351                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7352                    SelectionGoal::None,
 7353                )
 7354            });
 7355        })
 7356    }
 7357
 7358    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 7359        self.transact(cx, |this, cx| {
 7360            this.select_to_end_of_line(
 7361                &SelectToEndOfLine {
 7362                    stop_at_soft_wraps: false,
 7363                },
 7364                cx,
 7365            );
 7366            this.delete(&Delete, cx);
 7367        });
 7368    }
 7369
 7370    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 7371        self.transact(cx, |this, cx| {
 7372            this.select_to_end_of_line(
 7373                &SelectToEndOfLine {
 7374                    stop_at_soft_wraps: false,
 7375                },
 7376                cx,
 7377            );
 7378            this.cut(&Cut, cx);
 7379        });
 7380    }
 7381
 7382    pub fn move_to_start_of_paragraph(
 7383        &mut self,
 7384        _: &MoveToStartOfParagraph,
 7385        cx: &mut ViewContext<Self>,
 7386    ) {
 7387        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7388            cx.propagate();
 7389            return;
 7390        }
 7391
 7392        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7393            s.move_with(|map, selection| {
 7394                selection.collapse_to(
 7395                    movement::start_of_paragraph(map, selection.head(), 1),
 7396                    SelectionGoal::None,
 7397                )
 7398            });
 7399        })
 7400    }
 7401
 7402    pub fn move_to_end_of_paragraph(
 7403        &mut self,
 7404        _: &MoveToEndOfParagraph,
 7405        cx: &mut ViewContext<Self>,
 7406    ) {
 7407        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7408            cx.propagate();
 7409            return;
 7410        }
 7411
 7412        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7413            s.move_with(|map, selection| {
 7414                selection.collapse_to(
 7415                    movement::end_of_paragraph(map, selection.head(), 1),
 7416                    SelectionGoal::None,
 7417                )
 7418            });
 7419        })
 7420    }
 7421
 7422    pub fn select_to_start_of_paragraph(
 7423        &mut self,
 7424        _: &SelectToStartOfParagraph,
 7425        cx: &mut ViewContext<Self>,
 7426    ) {
 7427        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7428            cx.propagate();
 7429            return;
 7430        }
 7431
 7432        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7433            s.move_heads_with(|map, head, _| {
 7434                (
 7435                    movement::start_of_paragraph(map, head, 1),
 7436                    SelectionGoal::None,
 7437                )
 7438            });
 7439        })
 7440    }
 7441
 7442    pub fn select_to_end_of_paragraph(
 7443        &mut self,
 7444        _: &SelectToEndOfParagraph,
 7445        cx: &mut ViewContext<Self>,
 7446    ) {
 7447        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7448            cx.propagate();
 7449            return;
 7450        }
 7451
 7452        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7453            s.move_heads_with(|map, head, _| {
 7454                (
 7455                    movement::end_of_paragraph(map, head, 1),
 7456                    SelectionGoal::None,
 7457                )
 7458            });
 7459        })
 7460    }
 7461
 7462    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 7463        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7464            cx.propagate();
 7465            return;
 7466        }
 7467
 7468        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7469            s.select_ranges(vec![0..0]);
 7470        });
 7471    }
 7472
 7473    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 7474        let mut selection = self.selections.last::<Point>(cx);
 7475        selection.set_head(Point::zero(), SelectionGoal::None);
 7476
 7477        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7478            s.select(vec![selection]);
 7479        });
 7480    }
 7481
 7482    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 7483        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7484            cx.propagate();
 7485            return;
 7486        }
 7487
 7488        let cursor = self.buffer.read(cx).read(cx).len();
 7489        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7490            s.select_ranges(vec![cursor..cursor])
 7491        });
 7492    }
 7493
 7494    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 7495        self.nav_history = nav_history;
 7496    }
 7497
 7498    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 7499        self.nav_history.as_ref()
 7500    }
 7501
 7502    fn push_to_nav_history(
 7503        &mut self,
 7504        cursor_anchor: Anchor,
 7505        new_position: Option<Point>,
 7506        cx: &mut ViewContext<Self>,
 7507    ) {
 7508        if let Some(nav_history) = self.nav_history.as_mut() {
 7509            let buffer = self.buffer.read(cx).read(cx);
 7510            let cursor_position = cursor_anchor.to_point(&buffer);
 7511            let scroll_state = self.scroll_manager.anchor();
 7512            let scroll_top_row = scroll_state.top_row(&buffer);
 7513            drop(buffer);
 7514
 7515            if let Some(new_position) = new_position {
 7516                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 7517                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 7518                    return;
 7519                }
 7520            }
 7521
 7522            nav_history.push(
 7523                Some(NavigationData {
 7524                    cursor_anchor,
 7525                    cursor_position,
 7526                    scroll_anchor: scroll_state,
 7527                    scroll_top_row,
 7528                }),
 7529                cx,
 7530            );
 7531        }
 7532    }
 7533
 7534    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 7535        let buffer = self.buffer.read(cx).snapshot(cx);
 7536        let mut selection = self.selections.first::<usize>(cx);
 7537        selection.set_head(buffer.len(), SelectionGoal::None);
 7538        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7539            s.select(vec![selection]);
 7540        });
 7541    }
 7542
 7543    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 7544        let end = self.buffer.read(cx).read(cx).len();
 7545        self.change_selections(None, cx, |s| {
 7546            s.select_ranges(vec![0..end]);
 7547        });
 7548    }
 7549
 7550    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 7551        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7552        let mut selections = self.selections.all::<Point>(cx);
 7553        let max_point = display_map.buffer_snapshot.max_point();
 7554        for selection in &mut selections {
 7555            let rows = selection.spanned_rows(true, &display_map);
 7556            selection.start = Point::new(rows.start.0, 0);
 7557            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 7558            selection.reversed = false;
 7559        }
 7560        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7561            s.select(selections);
 7562        });
 7563    }
 7564
 7565    pub fn split_selection_into_lines(
 7566        &mut self,
 7567        _: &SplitSelectionIntoLines,
 7568        cx: &mut ViewContext<Self>,
 7569    ) {
 7570        let mut to_unfold = Vec::new();
 7571        let mut new_selection_ranges = Vec::new();
 7572        {
 7573            let selections = self.selections.all::<Point>(cx);
 7574            let buffer = self.buffer.read(cx).read(cx);
 7575            for selection in selections {
 7576                for row in selection.start.row..selection.end.row {
 7577                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 7578                    new_selection_ranges.push(cursor..cursor);
 7579                }
 7580                new_selection_ranges.push(selection.end..selection.end);
 7581                to_unfold.push(selection.start..selection.end);
 7582            }
 7583        }
 7584        self.unfold_ranges(to_unfold, true, true, cx);
 7585        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7586            s.select_ranges(new_selection_ranges);
 7587        });
 7588    }
 7589
 7590    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 7591        self.add_selection(true, cx);
 7592    }
 7593
 7594    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 7595        self.add_selection(false, cx);
 7596    }
 7597
 7598    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 7599        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7600        let mut selections = self.selections.all::<Point>(cx);
 7601        let text_layout_details = self.text_layout_details(cx);
 7602        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 7603            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 7604            let range = oldest_selection.display_range(&display_map).sorted();
 7605
 7606            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 7607            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 7608            let positions = start_x.min(end_x)..start_x.max(end_x);
 7609
 7610            selections.clear();
 7611            let mut stack = Vec::new();
 7612            for row in range.start.row().0..=range.end.row().0 {
 7613                if let Some(selection) = self.selections.build_columnar_selection(
 7614                    &display_map,
 7615                    DisplayRow(row),
 7616                    &positions,
 7617                    oldest_selection.reversed,
 7618                    &text_layout_details,
 7619                ) {
 7620                    stack.push(selection.id);
 7621                    selections.push(selection);
 7622                }
 7623            }
 7624
 7625            if above {
 7626                stack.reverse();
 7627            }
 7628
 7629            AddSelectionsState { above, stack }
 7630        });
 7631
 7632        let last_added_selection = *state.stack.last().unwrap();
 7633        let mut new_selections = Vec::new();
 7634        if above == state.above {
 7635            let end_row = if above {
 7636                DisplayRow(0)
 7637            } else {
 7638                display_map.max_point().row()
 7639            };
 7640
 7641            'outer: for selection in selections {
 7642                if selection.id == last_added_selection {
 7643                    let range = selection.display_range(&display_map).sorted();
 7644                    debug_assert_eq!(range.start.row(), range.end.row());
 7645                    let mut row = range.start.row();
 7646                    let positions =
 7647                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 7648                            px(start)..px(end)
 7649                        } else {
 7650                            let start_x =
 7651                                display_map.x_for_display_point(range.start, &text_layout_details);
 7652                            let end_x =
 7653                                display_map.x_for_display_point(range.end, &text_layout_details);
 7654                            start_x.min(end_x)..start_x.max(end_x)
 7655                        };
 7656
 7657                    while row != end_row {
 7658                        if above {
 7659                            row.0 -= 1;
 7660                        } else {
 7661                            row.0 += 1;
 7662                        }
 7663
 7664                        if let Some(new_selection) = self.selections.build_columnar_selection(
 7665                            &display_map,
 7666                            row,
 7667                            &positions,
 7668                            selection.reversed,
 7669                            &text_layout_details,
 7670                        ) {
 7671                            state.stack.push(new_selection.id);
 7672                            if above {
 7673                                new_selections.push(new_selection);
 7674                                new_selections.push(selection);
 7675                            } else {
 7676                                new_selections.push(selection);
 7677                                new_selections.push(new_selection);
 7678                            }
 7679
 7680                            continue 'outer;
 7681                        }
 7682                    }
 7683                }
 7684
 7685                new_selections.push(selection);
 7686            }
 7687        } else {
 7688            new_selections = selections;
 7689            new_selections.retain(|s| s.id != last_added_selection);
 7690            state.stack.pop();
 7691        }
 7692
 7693        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7694            s.select(new_selections);
 7695        });
 7696        if state.stack.len() > 1 {
 7697            self.add_selections_state = Some(state);
 7698        }
 7699    }
 7700
 7701    pub fn select_next_match_internal(
 7702        &mut self,
 7703        display_map: &DisplaySnapshot,
 7704        replace_newest: bool,
 7705        autoscroll: Option<Autoscroll>,
 7706        cx: &mut ViewContext<Self>,
 7707    ) -> Result<()> {
 7708        fn select_next_match_ranges(
 7709            this: &mut Editor,
 7710            range: Range<usize>,
 7711            replace_newest: bool,
 7712            auto_scroll: Option<Autoscroll>,
 7713            cx: &mut ViewContext<Editor>,
 7714        ) {
 7715            this.unfold_ranges([range.clone()], false, true, cx);
 7716            this.change_selections(auto_scroll, cx, |s| {
 7717                if replace_newest {
 7718                    s.delete(s.newest_anchor().id);
 7719                }
 7720                s.insert_range(range.clone());
 7721            });
 7722        }
 7723
 7724        let buffer = &display_map.buffer_snapshot;
 7725        let mut selections = self.selections.all::<usize>(cx);
 7726        if let Some(mut select_next_state) = self.select_next_state.take() {
 7727            let query = &select_next_state.query;
 7728            if !select_next_state.done {
 7729                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 7730                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 7731                let mut next_selected_range = None;
 7732
 7733                let bytes_after_last_selection =
 7734                    buffer.bytes_in_range(last_selection.end..buffer.len());
 7735                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 7736                let query_matches = query
 7737                    .stream_find_iter(bytes_after_last_selection)
 7738                    .map(|result| (last_selection.end, result))
 7739                    .chain(
 7740                        query
 7741                            .stream_find_iter(bytes_before_first_selection)
 7742                            .map(|result| (0, result)),
 7743                    );
 7744
 7745                for (start_offset, query_match) in query_matches {
 7746                    let query_match = query_match.unwrap(); // can only fail due to I/O
 7747                    let offset_range =
 7748                        start_offset + query_match.start()..start_offset + query_match.end();
 7749                    let display_range = offset_range.start.to_display_point(&display_map)
 7750                        ..offset_range.end.to_display_point(&display_map);
 7751
 7752                    if !select_next_state.wordwise
 7753                        || (!movement::is_inside_word(&display_map, display_range.start)
 7754                            && !movement::is_inside_word(&display_map, display_range.end))
 7755                    {
 7756                        // TODO: This is n^2, because we might check all the selections
 7757                        if !selections
 7758                            .iter()
 7759                            .any(|selection| selection.range().overlaps(&offset_range))
 7760                        {
 7761                            next_selected_range = Some(offset_range);
 7762                            break;
 7763                        }
 7764                    }
 7765                }
 7766
 7767                if let Some(next_selected_range) = next_selected_range {
 7768                    select_next_match_ranges(
 7769                        self,
 7770                        next_selected_range,
 7771                        replace_newest,
 7772                        autoscroll,
 7773                        cx,
 7774                    );
 7775                } else {
 7776                    select_next_state.done = true;
 7777                }
 7778            }
 7779
 7780            self.select_next_state = Some(select_next_state);
 7781        } else {
 7782            let mut only_carets = true;
 7783            let mut same_text_selected = true;
 7784            let mut selected_text = None;
 7785
 7786            let mut selections_iter = selections.iter().peekable();
 7787            while let Some(selection) = selections_iter.next() {
 7788                if selection.start != selection.end {
 7789                    only_carets = false;
 7790                }
 7791
 7792                if same_text_selected {
 7793                    if selected_text.is_none() {
 7794                        selected_text =
 7795                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 7796                    }
 7797
 7798                    if let Some(next_selection) = selections_iter.peek() {
 7799                        if next_selection.range().len() == selection.range().len() {
 7800                            let next_selected_text = buffer
 7801                                .text_for_range(next_selection.range())
 7802                                .collect::<String>();
 7803                            if Some(next_selected_text) != selected_text {
 7804                                same_text_selected = false;
 7805                                selected_text = None;
 7806                            }
 7807                        } else {
 7808                            same_text_selected = false;
 7809                            selected_text = None;
 7810                        }
 7811                    }
 7812                }
 7813            }
 7814
 7815            if only_carets {
 7816                for selection in &mut selections {
 7817                    let word_range = movement::surrounding_word(
 7818                        &display_map,
 7819                        selection.start.to_display_point(&display_map),
 7820                    );
 7821                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 7822                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 7823                    selection.goal = SelectionGoal::None;
 7824                    selection.reversed = false;
 7825                    select_next_match_ranges(
 7826                        self,
 7827                        selection.start..selection.end,
 7828                        replace_newest,
 7829                        autoscroll,
 7830                        cx,
 7831                    );
 7832                }
 7833
 7834                if selections.len() == 1 {
 7835                    let selection = selections
 7836                        .last()
 7837                        .expect("ensured that there's only one selection");
 7838                    let query = buffer
 7839                        .text_for_range(selection.start..selection.end)
 7840                        .collect::<String>();
 7841                    let is_empty = query.is_empty();
 7842                    let select_state = SelectNextState {
 7843                        query: AhoCorasick::new(&[query])?,
 7844                        wordwise: true,
 7845                        done: is_empty,
 7846                    };
 7847                    self.select_next_state = Some(select_state);
 7848                } else {
 7849                    self.select_next_state = None;
 7850                }
 7851            } else if let Some(selected_text) = selected_text {
 7852                self.select_next_state = Some(SelectNextState {
 7853                    query: AhoCorasick::new(&[selected_text])?,
 7854                    wordwise: false,
 7855                    done: false,
 7856                });
 7857                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 7858            }
 7859        }
 7860        Ok(())
 7861    }
 7862
 7863    pub fn select_all_matches(
 7864        &mut self,
 7865        _action: &SelectAllMatches,
 7866        cx: &mut ViewContext<Self>,
 7867    ) -> Result<()> {
 7868        self.push_to_selection_history();
 7869        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7870
 7871        self.select_next_match_internal(&display_map, false, None, cx)?;
 7872        let Some(select_next_state) = self.select_next_state.as_mut() else {
 7873            return Ok(());
 7874        };
 7875        if select_next_state.done {
 7876            return Ok(());
 7877        }
 7878
 7879        let mut new_selections = self.selections.all::<usize>(cx);
 7880
 7881        let buffer = &display_map.buffer_snapshot;
 7882        let query_matches = select_next_state
 7883            .query
 7884            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 7885
 7886        for query_match in query_matches {
 7887            let query_match = query_match.unwrap(); // can only fail due to I/O
 7888            let offset_range = query_match.start()..query_match.end();
 7889            let display_range = offset_range.start.to_display_point(&display_map)
 7890                ..offset_range.end.to_display_point(&display_map);
 7891
 7892            if !select_next_state.wordwise
 7893                || (!movement::is_inside_word(&display_map, display_range.start)
 7894                    && !movement::is_inside_word(&display_map, display_range.end))
 7895            {
 7896                self.selections.change_with(cx, |selections| {
 7897                    new_selections.push(Selection {
 7898                        id: selections.new_selection_id(),
 7899                        start: offset_range.start,
 7900                        end: offset_range.end,
 7901                        reversed: false,
 7902                        goal: SelectionGoal::None,
 7903                    });
 7904                });
 7905            }
 7906        }
 7907
 7908        new_selections.sort_by_key(|selection| selection.start);
 7909        let mut ix = 0;
 7910        while ix + 1 < new_selections.len() {
 7911            let current_selection = &new_selections[ix];
 7912            let next_selection = &new_selections[ix + 1];
 7913            if current_selection.range().overlaps(&next_selection.range()) {
 7914                if current_selection.id < next_selection.id {
 7915                    new_selections.remove(ix + 1);
 7916                } else {
 7917                    new_selections.remove(ix);
 7918                }
 7919            } else {
 7920                ix += 1;
 7921            }
 7922        }
 7923
 7924        select_next_state.done = true;
 7925        self.unfold_ranges(
 7926            new_selections.iter().map(|selection| selection.range()),
 7927            false,
 7928            false,
 7929            cx,
 7930        );
 7931        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 7932            selections.select(new_selections)
 7933        });
 7934
 7935        Ok(())
 7936    }
 7937
 7938    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 7939        self.push_to_selection_history();
 7940        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7941        self.select_next_match_internal(
 7942            &display_map,
 7943            action.replace_newest,
 7944            Some(Autoscroll::newest()),
 7945            cx,
 7946        )?;
 7947        Ok(())
 7948    }
 7949
 7950    pub fn select_previous(
 7951        &mut self,
 7952        action: &SelectPrevious,
 7953        cx: &mut ViewContext<Self>,
 7954    ) -> Result<()> {
 7955        self.push_to_selection_history();
 7956        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7957        let buffer = &display_map.buffer_snapshot;
 7958        let mut selections = self.selections.all::<usize>(cx);
 7959        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 7960            let query = &select_prev_state.query;
 7961            if !select_prev_state.done {
 7962                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 7963                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 7964                let mut next_selected_range = None;
 7965                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 7966                let bytes_before_last_selection =
 7967                    buffer.reversed_bytes_in_range(0..last_selection.start);
 7968                let bytes_after_first_selection =
 7969                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 7970                let query_matches = query
 7971                    .stream_find_iter(bytes_before_last_selection)
 7972                    .map(|result| (last_selection.start, result))
 7973                    .chain(
 7974                        query
 7975                            .stream_find_iter(bytes_after_first_selection)
 7976                            .map(|result| (buffer.len(), result)),
 7977                    );
 7978                for (end_offset, query_match) in query_matches {
 7979                    let query_match = query_match.unwrap(); // can only fail due to I/O
 7980                    let offset_range =
 7981                        end_offset - query_match.end()..end_offset - query_match.start();
 7982                    let display_range = offset_range.start.to_display_point(&display_map)
 7983                        ..offset_range.end.to_display_point(&display_map);
 7984
 7985                    if !select_prev_state.wordwise
 7986                        || (!movement::is_inside_word(&display_map, display_range.start)
 7987                            && !movement::is_inside_word(&display_map, display_range.end))
 7988                    {
 7989                        next_selected_range = Some(offset_range);
 7990                        break;
 7991                    }
 7992                }
 7993
 7994                if let Some(next_selected_range) = next_selected_range {
 7995                    self.unfold_ranges([next_selected_range.clone()], false, true, cx);
 7996                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 7997                        if action.replace_newest {
 7998                            s.delete(s.newest_anchor().id);
 7999                        }
 8000                        s.insert_range(next_selected_range);
 8001                    });
 8002                } else {
 8003                    select_prev_state.done = true;
 8004                }
 8005            }
 8006
 8007            self.select_prev_state = Some(select_prev_state);
 8008        } else {
 8009            let mut only_carets = true;
 8010            let mut same_text_selected = true;
 8011            let mut selected_text = None;
 8012
 8013            let mut selections_iter = selections.iter().peekable();
 8014            while let Some(selection) = selections_iter.next() {
 8015                if selection.start != selection.end {
 8016                    only_carets = false;
 8017                }
 8018
 8019                if same_text_selected {
 8020                    if selected_text.is_none() {
 8021                        selected_text =
 8022                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8023                    }
 8024
 8025                    if let Some(next_selection) = selections_iter.peek() {
 8026                        if next_selection.range().len() == selection.range().len() {
 8027                            let next_selected_text = buffer
 8028                                .text_for_range(next_selection.range())
 8029                                .collect::<String>();
 8030                            if Some(next_selected_text) != selected_text {
 8031                                same_text_selected = false;
 8032                                selected_text = None;
 8033                            }
 8034                        } else {
 8035                            same_text_selected = false;
 8036                            selected_text = None;
 8037                        }
 8038                    }
 8039                }
 8040            }
 8041
 8042            if only_carets {
 8043                for selection in &mut selections {
 8044                    let word_range = movement::surrounding_word(
 8045                        &display_map,
 8046                        selection.start.to_display_point(&display_map),
 8047                    );
 8048                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8049                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8050                    selection.goal = SelectionGoal::None;
 8051                    selection.reversed = false;
 8052                }
 8053                if selections.len() == 1 {
 8054                    let selection = selections
 8055                        .last()
 8056                        .expect("ensured that there's only one selection");
 8057                    let query = buffer
 8058                        .text_for_range(selection.start..selection.end)
 8059                        .collect::<String>();
 8060                    let is_empty = query.is_empty();
 8061                    let select_state = SelectNextState {
 8062                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8063                        wordwise: true,
 8064                        done: is_empty,
 8065                    };
 8066                    self.select_prev_state = Some(select_state);
 8067                } else {
 8068                    self.select_prev_state = None;
 8069                }
 8070
 8071                self.unfold_ranges(
 8072                    selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8073                    false,
 8074                    true,
 8075                    cx,
 8076                );
 8077                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8078                    s.select(selections);
 8079                });
 8080            } else if let Some(selected_text) = selected_text {
 8081                self.select_prev_state = Some(SelectNextState {
 8082                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8083                    wordwise: false,
 8084                    done: false,
 8085                });
 8086                self.select_previous(action, cx)?;
 8087            }
 8088        }
 8089        Ok(())
 8090    }
 8091
 8092    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 8093        let text_layout_details = &self.text_layout_details(cx);
 8094        self.transact(cx, |this, cx| {
 8095            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8096            let mut edits = Vec::new();
 8097            let mut selection_edit_ranges = Vec::new();
 8098            let mut last_toggled_row = None;
 8099            let snapshot = this.buffer.read(cx).read(cx);
 8100            let empty_str: Arc<str> = "".into();
 8101            let mut suffixes_inserted = Vec::new();
 8102
 8103            fn comment_prefix_range(
 8104                snapshot: &MultiBufferSnapshot,
 8105                row: MultiBufferRow,
 8106                comment_prefix: &str,
 8107                comment_prefix_whitespace: &str,
 8108            ) -> Range<Point> {
 8109                let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
 8110
 8111                let mut line_bytes = snapshot
 8112                    .bytes_in_range(start..snapshot.max_point())
 8113                    .flatten()
 8114                    .copied();
 8115
 8116                // If this line currently begins with the line comment prefix, then record
 8117                // the range containing the prefix.
 8118                if line_bytes
 8119                    .by_ref()
 8120                    .take(comment_prefix.len())
 8121                    .eq(comment_prefix.bytes())
 8122                {
 8123                    // Include any whitespace that matches the comment prefix.
 8124                    let matching_whitespace_len = line_bytes
 8125                        .zip(comment_prefix_whitespace.bytes())
 8126                        .take_while(|(a, b)| a == b)
 8127                        .count() as u32;
 8128                    let end = Point::new(
 8129                        start.row,
 8130                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 8131                    );
 8132                    start..end
 8133                } else {
 8134                    start..start
 8135                }
 8136            }
 8137
 8138            fn comment_suffix_range(
 8139                snapshot: &MultiBufferSnapshot,
 8140                row: MultiBufferRow,
 8141                comment_suffix: &str,
 8142                comment_suffix_has_leading_space: bool,
 8143            ) -> Range<Point> {
 8144                let end = Point::new(row.0, snapshot.line_len(row));
 8145                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 8146
 8147                let mut line_end_bytes = snapshot
 8148                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 8149                    .flatten()
 8150                    .copied();
 8151
 8152                let leading_space_len = if suffix_start_column > 0
 8153                    && line_end_bytes.next() == Some(b' ')
 8154                    && comment_suffix_has_leading_space
 8155                {
 8156                    1
 8157                } else {
 8158                    0
 8159                };
 8160
 8161                // If this line currently begins with the line comment prefix, then record
 8162                // the range containing the prefix.
 8163                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 8164                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 8165                    start..end
 8166                } else {
 8167                    end..end
 8168                }
 8169            }
 8170
 8171            // TODO: Handle selections that cross excerpts
 8172            for selection in &mut selections {
 8173                let start_column = snapshot
 8174                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 8175                    .len;
 8176                let language = if let Some(language) =
 8177                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 8178                {
 8179                    language
 8180                } else {
 8181                    continue;
 8182                };
 8183
 8184                selection_edit_ranges.clear();
 8185
 8186                // If multiple selections contain a given row, avoid processing that
 8187                // row more than once.
 8188                let mut start_row = MultiBufferRow(selection.start.row);
 8189                if last_toggled_row == Some(start_row) {
 8190                    start_row = start_row.next_row();
 8191                }
 8192                let end_row =
 8193                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 8194                        MultiBufferRow(selection.end.row - 1)
 8195                    } else {
 8196                        MultiBufferRow(selection.end.row)
 8197                    };
 8198                last_toggled_row = Some(end_row);
 8199
 8200                if start_row > end_row {
 8201                    continue;
 8202                }
 8203
 8204                // If the language has line comments, toggle those.
 8205                let full_comment_prefixes = language.line_comment_prefixes();
 8206                if !full_comment_prefixes.is_empty() {
 8207                    let first_prefix = full_comment_prefixes
 8208                        .first()
 8209                        .expect("prefixes is non-empty");
 8210                    let prefix_trimmed_lengths = full_comment_prefixes
 8211                        .iter()
 8212                        .map(|p| p.trim_end_matches(' ').len())
 8213                        .collect::<SmallVec<[usize; 4]>>();
 8214
 8215                    let mut all_selection_lines_are_comments = true;
 8216
 8217                    for row in start_row.0..=end_row.0 {
 8218                        let row = MultiBufferRow(row);
 8219                        if start_row < end_row && snapshot.is_line_blank(row) {
 8220                            continue;
 8221                        }
 8222
 8223                        let prefix_range = full_comment_prefixes
 8224                            .iter()
 8225                            .zip(prefix_trimmed_lengths.iter().copied())
 8226                            .map(|(prefix, trimmed_prefix_len)| {
 8227                                comment_prefix_range(
 8228                                    snapshot.deref(),
 8229                                    row,
 8230                                    &prefix[..trimmed_prefix_len],
 8231                                    &prefix[trimmed_prefix_len..],
 8232                                )
 8233                            })
 8234                            .max_by_key(|range| range.end.column - range.start.column)
 8235                            .expect("prefixes is non-empty");
 8236
 8237                        if prefix_range.is_empty() {
 8238                            all_selection_lines_are_comments = false;
 8239                        }
 8240
 8241                        selection_edit_ranges.push(prefix_range);
 8242                    }
 8243
 8244                    if all_selection_lines_are_comments {
 8245                        edits.extend(
 8246                            selection_edit_ranges
 8247                                .iter()
 8248                                .cloned()
 8249                                .map(|range| (range, empty_str.clone())),
 8250                        );
 8251                    } else {
 8252                        let min_column = selection_edit_ranges
 8253                            .iter()
 8254                            .map(|range| range.start.column)
 8255                            .min()
 8256                            .unwrap_or(0);
 8257                        edits.extend(selection_edit_ranges.iter().map(|range| {
 8258                            let position = Point::new(range.start.row, min_column);
 8259                            (position..position, first_prefix.clone())
 8260                        }));
 8261                    }
 8262                } else if let Some((full_comment_prefix, comment_suffix)) =
 8263                    language.block_comment_delimiters()
 8264                {
 8265                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 8266                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 8267                    let prefix_range = comment_prefix_range(
 8268                        snapshot.deref(),
 8269                        start_row,
 8270                        comment_prefix,
 8271                        comment_prefix_whitespace,
 8272                    );
 8273                    let suffix_range = comment_suffix_range(
 8274                        snapshot.deref(),
 8275                        end_row,
 8276                        comment_suffix.trim_start_matches(' '),
 8277                        comment_suffix.starts_with(' '),
 8278                    );
 8279
 8280                    if prefix_range.is_empty() || suffix_range.is_empty() {
 8281                        edits.push((
 8282                            prefix_range.start..prefix_range.start,
 8283                            full_comment_prefix.clone(),
 8284                        ));
 8285                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 8286                        suffixes_inserted.push((end_row, comment_suffix.len()));
 8287                    } else {
 8288                        edits.push((prefix_range, empty_str.clone()));
 8289                        edits.push((suffix_range, empty_str.clone()));
 8290                    }
 8291                } else {
 8292                    continue;
 8293                }
 8294            }
 8295
 8296            drop(snapshot);
 8297            this.buffer.update(cx, |buffer, cx| {
 8298                buffer.edit(edits, None, cx);
 8299            });
 8300
 8301            // Adjust selections so that they end before any comment suffixes that
 8302            // were inserted.
 8303            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 8304            let mut selections = this.selections.all::<Point>(cx);
 8305            let snapshot = this.buffer.read(cx).read(cx);
 8306            for selection in &mut selections {
 8307                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 8308                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 8309                        Ordering::Less => {
 8310                            suffixes_inserted.next();
 8311                            continue;
 8312                        }
 8313                        Ordering::Greater => break,
 8314                        Ordering::Equal => {
 8315                            if selection.end.column == snapshot.line_len(row) {
 8316                                if selection.is_empty() {
 8317                                    selection.start.column -= suffix_len as u32;
 8318                                }
 8319                                selection.end.column -= suffix_len as u32;
 8320                            }
 8321                            break;
 8322                        }
 8323                    }
 8324                }
 8325            }
 8326
 8327            drop(snapshot);
 8328            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 8329
 8330            let selections = this.selections.all::<Point>(cx);
 8331            let selections_on_single_row = selections.windows(2).all(|selections| {
 8332                selections[0].start.row == selections[1].start.row
 8333                    && selections[0].end.row == selections[1].end.row
 8334                    && selections[0].start.row == selections[0].end.row
 8335            });
 8336            let selections_selecting = selections
 8337                .iter()
 8338                .any(|selection| selection.start != selection.end);
 8339            let advance_downwards = action.advance_downwards
 8340                && selections_on_single_row
 8341                && !selections_selecting
 8342                && !matches!(this.mode, EditorMode::SingleLine { .. });
 8343
 8344            if advance_downwards {
 8345                let snapshot = this.buffer.read(cx).snapshot(cx);
 8346
 8347                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8348                    s.move_cursors_with(|display_snapshot, display_point, _| {
 8349                        let mut point = display_point.to_point(display_snapshot);
 8350                        point.row += 1;
 8351                        point = snapshot.clip_point(point, Bias::Left);
 8352                        let display_point = point.to_display_point(display_snapshot);
 8353                        let goal = SelectionGoal::HorizontalPosition(
 8354                            display_snapshot
 8355                                .x_for_display_point(display_point, &text_layout_details)
 8356                                .into(),
 8357                        );
 8358                        (display_point, goal)
 8359                    })
 8360                });
 8361            }
 8362        });
 8363    }
 8364
 8365    pub fn select_enclosing_symbol(
 8366        &mut self,
 8367        _: &SelectEnclosingSymbol,
 8368        cx: &mut ViewContext<Self>,
 8369    ) {
 8370        let buffer = self.buffer.read(cx).snapshot(cx);
 8371        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8372
 8373        fn update_selection(
 8374            selection: &Selection<usize>,
 8375            buffer_snap: &MultiBufferSnapshot,
 8376        ) -> Option<Selection<usize>> {
 8377            let cursor = selection.head();
 8378            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 8379            for symbol in symbols.iter().rev() {
 8380                let start = symbol.range.start.to_offset(&buffer_snap);
 8381                let end = symbol.range.end.to_offset(&buffer_snap);
 8382                let new_range = start..end;
 8383                if start < selection.start || end > selection.end {
 8384                    return Some(Selection {
 8385                        id: selection.id,
 8386                        start: new_range.start,
 8387                        end: new_range.end,
 8388                        goal: SelectionGoal::None,
 8389                        reversed: selection.reversed,
 8390                    });
 8391                }
 8392            }
 8393            None
 8394        }
 8395
 8396        let mut selected_larger_symbol = false;
 8397        let new_selections = old_selections
 8398            .iter()
 8399            .map(|selection| match update_selection(selection, &buffer) {
 8400                Some(new_selection) => {
 8401                    if new_selection.range() != selection.range() {
 8402                        selected_larger_symbol = true;
 8403                    }
 8404                    new_selection
 8405                }
 8406                None => selection.clone(),
 8407            })
 8408            .collect::<Vec<_>>();
 8409
 8410        if selected_larger_symbol {
 8411            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8412                s.select(new_selections);
 8413            });
 8414        }
 8415    }
 8416
 8417    pub fn select_larger_syntax_node(
 8418        &mut self,
 8419        _: &SelectLargerSyntaxNode,
 8420        cx: &mut ViewContext<Self>,
 8421    ) {
 8422        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8423        let buffer = self.buffer.read(cx).snapshot(cx);
 8424        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8425
 8426        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8427        let mut selected_larger_node = false;
 8428        let new_selections = old_selections
 8429            .iter()
 8430            .map(|selection| {
 8431                let old_range = selection.start..selection.end;
 8432                let mut new_range = old_range.clone();
 8433                while let Some(containing_range) =
 8434                    buffer.range_for_syntax_ancestor(new_range.clone())
 8435                {
 8436                    new_range = containing_range;
 8437                    if !display_map.intersects_fold(new_range.start)
 8438                        && !display_map.intersects_fold(new_range.end)
 8439                    {
 8440                        break;
 8441                    }
 8442                }
 8443
 8444                selected_larger_node |= new_range != old_range;
 8445                Selection {
 8446                    id: selection.id,
 8447                    start: new_range.start,
 8448                    end: new_range.end,
 8449                    goal: SelectionGoal::None,
 8450                    reversed: selection.reversed,
 8451                }
 8452            })
 8453            .collect::<Vec<_>>();
 8454
 8455        if selected_larger_node {
 8456            stack.push(old_selections);
 8457            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8458                s.select(new_selections);
 8459            });
 8460        }
 8461        self.select_larger_syntax_node_stack = stack;
 8462    }
 8463
 8464    pub fn select_smaller_syntax_node(
 8465        &mut self,
 8466        _: &SelectSmallerSyntaxNode,
 8467        cx: &mut ViewContext<Self>,
 8468    ) {
 8469        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8470        if let Some(selections) = stack.pop() {
 8471            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8472                s.select(selections.to_vec());
 8473            });
 8474        }
 8475        self.select_larger_syntax_node_stack = stack;
 8476    }
 8477
 8478    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 8479        if !EditorSettings::get_global(cx).gutter.runnables {
 8480            self.clear_tasks();
 8481            return Task::ready(());
 8482        }
 8483        let project = self.project.clone();
 8484        cx.spawn(|this, mut cx| async move {
 8485            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 8486                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 8487            }) else {
 8488                return;
 8489            };
 8490
 8491            let Some(project) = project else {
 8492                return;
 8493            };
 8494
 8495            let hide_runnables = project
 8496                .update(&mut cx, |project, cx| {
 8497                    // Do not display any test indicators in non-dev server remote projects.
 8498                    project.is_remote() && project.ssh_connection_string(cx).is_none()
 8499                })
 8500                .unwrap_or(true);
 8501            if hide_runnables {
 8502                return;
 8503            }
 8504            let new_rows =
 8505                cx.background_executor()
 8506                    .spawn({
 8507                        let snapshot = display_snapshot.clone();
 8508                        async move {
 8509                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 8510                        }
 8511                    })
 8512                    .await;
 8513            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 8514
 8515            this.update(&mut cx, |this, _| {
 8516                this.clear_tasks();
 8517                for (key, value) in rows {
 8518                    this.insert_tasks(key, value);
 8519                }
 8520            })
 8521            .ok();
 8522        })
 8523    }
 8524    fn fetch_runnable_ranges(
 8525        snapshot: &DisplaySnapshot,
 8526        range: Range<Anchor>,
 8527    ) -> Vec<language::RunnableRange> {
 8528        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 8529    }
 8530
 8531    fn runnable_rows(
 8532        project: Model<Project>,
 8533        snapshot: DisplaySnapshot,
 8534        runnable_ranges: Vec<RunnableRange>,
 8535        mut cx: AsyncWindowContext,
 8536    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 8537        runnable_ranges
 8538            .into_iter()
 8539            .filter_map(|mut runnable| {
 8540                let tasks = cx
 8541                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 8542                    .ok()?;
 8543                if tasks.is_empty() {
 8544                    return None;
 8545                }
 8546
 8547                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 8548
 8549                let row = snapshot
 8550                    .buffer_snapshot
 8551                    .buffer_line_for_row(MultiBufferRow(point.row))?
 8552                    .1
 8553                    .start
 8554                    .row;
 8555
 8556                let context_range =
 8557                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 8558                Some((
 8559                    (runnable.buffer_id, row),
 8560                    RunnableTasks {
 8561                        templates: tasks,
 8562                        offset: MultiBufferOffset(runnable.run_range.start),
 8563                        context_range,
 8564                        column: point.column,
 8565                        extra_variables: runnable.extra_captures,
 8566                    },
 8567                ))
 8568            })
 8569            .collect()
 8570    }
 8571
 8572    fn templates_with_tags(
 8573        project: &Model<Project>,
 8574        runnable: &mut Runnable,
 8575        cx: &WindowContext<'_>,
 8576    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 8577        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 8578            let (worktree_id, file) = project
 8579                .buffer_for_id(runnable.buffer, cx)
 8580                .and_then(|buffer| buffer.read(cx).file())
 8581                .map(|file| (WorktreeId::from_usize(file.worktree_id()), file.clone()))
 8582                .unzip();
 8583
 8584            (project.task_inventory().clone(), worktree_id, file)
 8585        });
 8586
 8587        let inventory = inventory.read(cx);
 8588        let tags = mem::take(&mut runnable.tags);
 8589        let mut tags: Vec<_> = tags
 8590            .into_iter()
 8591            .flat_map(|tag| {
 8592                let tag = tag.0.clone();
 8593                inventory
 8594                    .list_tasks(
 8595                        file.clone(),
 8596                        Some(runnable.language.clone()),
 8597                        worktree_id,
 8598                        cx,
 8599                    )
 8600                    .into_iter()
 8601                    .filter(move |(_, template)| {
 8602                        template.tags.iter().any(|source_tag| source_tag == &tag)
 8603                    })
 8604            })
 8605            .sorted_by_key(|(kind, _)| kind.to_owned())
 8606            .collect();
 8607        if let Some((leading_tag_source, _)) = tags.first() {
 8608            // Strongest source wins; if we have worktree tag binding, prefer that to
 8609            // global and language bindings;
 8610            // if we have a global binding, prefer that to language binding.
 8611            let first_mismatch = tags
 8612                .iter()
 8613                .position(|(tag_source, _)| tag_source != leading_tag_source);
 8614            if let Some(index) = first_mismatch {
 8615                tags.truncate(index);
 8616            }
 8617        }
 8618
 8619        tags
 8620    }
 8621
 8622    pub fn move_to_enclosing_bracket(
 8623        &mut self,
 8624        _: &MoveToEnclosingBracket,
 8625        cx: &mut ViewContext<Self>,
 8626    ) {
 8627        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8628            s.move_offsets_with(|snapshot, selection| {
 8629                let Some(enclosing_bracket_ranges) =
 8630                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 8631                else {
 8632                    return;
 8633                };
 8634
 8635                let mut best_length = usize::MAX;
 8636                let mut best_inside = false;
 8637                let mut best_in_bracket_range = false;
 8638                let mut best_destination = None;
 8639                for (open, close) in enclosing_bracket_ranges {
 8640                    let close = close.to_inclusive();
 8641                    let length = close.end() - open.start;
 8642                    let inside = selection.start >= open.end && selection.end <= *close.start();
 8643                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 8644                        || close.contains(&selection.head());
 8645
 8646                    // If best is next to a bracket and current isn't, skip
 8647                    if !in_bracket_range && best_in_bracket_range {
 8648                        continue;
 8649                    }
 8650
 8651                    // Prefer smaller lengths unless best is inside and current isn't
 8652                    if length > best_length && (best_inside || !inside) {
 8653                        continue;
 8654                    }
 8655
 8656                    best_length = length;
 8657                    best_inside = inside;
 8658                    best_in_bracket_range = in_bracket_range;
 8659                    best_destination = Some(
 8660                        if close.contains(&selection.start) && close.contains(&selection.end) {
 8661                            if inside {
 8662                                open.end
 8663                            } else {
 8664                                open.start
 8665                            }
 8666                        } else {
 8667                            if inside {
 8668                                *close.start()
 8669                            } else {
 8670                                *close.end()
 8671                            }
 8672                        },
 8673                    );
 8674                }
 8675
 8676                if let Some(destination) = best_destination {
 8677                    selection.collapse_to(destination, SelectionGoal::None);
 8678                }
 8679            })
 8680        });
 8681    }
 8682
 8683    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 8684        self.end_selection(cx);
 8685        self.selection_history.mode = SelectionHistoryMode::Undoing;
 8686        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 8687            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 8688            self.select_next_state = entry.select_next_state;
 8689            self.select_prev_state = entry.select_prev_state;
 8690            self.add_selections_state = entry.add_selections_state;
 8691            self.request_autoscroll(Autoscroll::newest(), cx);
 8692        }
 8693        self.selection_history.mode = SelectionHistoryMode::Normal;
 8694    }
 8695
 8696    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 8697        self.end_selection(cx);
 8698        self.selection_history.mode = SelectionHistoryMode::Redoing;
 8699        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 8700            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 8701            self.select_next_state = entry.select_next_state;
 8702            self.select_prev_state = entry.select_prev_state;
 8703            self.add_selections_state = entry.add_selections_state;
 8704            self.request_autoscroll(Autoscroll::newest(), cx);
 8705        }
 8706        self.selection_history.mode = SelectionHistoryMode::Normal;
 8707    }
 8708
 8709    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 8710        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 8711    }
 8712
 8713    pub fn expand_excerpts_down(
 8714        &mut self,
 8715        action: &ExpandExcerptsDown,
 8716        cx: &mut ViewContext<Self>,
 8717    ) {
 8718        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 8719    }
 8720
 8721    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 8722        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 8723    }
 8724
 8725    pub fn expand_excerpts_for_direction(
 8726        &mut self,
 8727        lines: u32,
 8728        direction: ExpandExcerptDirection,
 8729        cx: &mut ViewContext<Self>,
 8730    ) {
 8731        let selections = self.selections.disjoint_anchors();
 8732
 8733        let lines = if lines == 0 {
 8734            EditorSettings::get_global(cx).expand_excerpt_lines
 8735        } else {
 8736            lines
 8737        };
 8738
 8739        self.buffer.update(cx, |buffer, cx| {
 8740            buffer.expand_excerpts(
 8741                selections
 8742                    .into_iter()
 8743                    .map(|selection| selection.head().excerpt_id)
 8744                    .dedup(),
 8745                lines,
 8746                direction,
 8747                cx,
 8748            )
 8749        })
 8750    }
 8751
 8752    pub fn expand_excerpt(
 8753        &mut self,
 8754        excerpt: ExcerptId,
 8755        direction: ExpandExcerptDirection,
 8756        cx: &mut ViewContext<Self>,
 8757    ) {
 8758        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 8759        self.buffer.update(cx, |buffer, cx| {
 8760            buffer.expand_excerpts([excerpt], lines, direction, cx)
 8761        })
 8762    }
 8763
 8764    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 8765        self.go_to_diagnostic_impl(Direction::Next, cx)
 8766    }
 8767
 8768    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 8769        self.go_to_diagnostic_impl(Direction::Prev, cx)
 8770    }
 8771
 8772    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 8773        let buffer = self.buffer.read(cx).snapshot(cx);
 8774        let selection = self.selections.newest::<usize>(cx);
 8775
 8776        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 8777        if direction == Direction::Next {
 8778            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 8779                let (group_id, jump_to) = popover.activation_info();
 8780                if self.activate_diagnostics(group_id, cx) {
 8781                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8782                        let mut new_selection = s.newest_anchor().clone();
 8783                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 8784                        s.select_anchors(vec![new_selection.clone()]);
 8785                    });
 8786                }
 8787                return;
 8788            }
 8789        }
 8790
 8791        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 8792            active_diagnostics
 8793                .primary_range
 8794                .to_offset(&buffer)
 8795                .to_inclusive()
 8796        });
 8797        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 8798            if active_primary_range.contains(&selection.head()) {
 8799                *active_primary_range.start()
 8800            } else {
 8801                selection.head()
 8802            }
 8803        } else {
 8804            selection.head()
 8805        };
 8806        let snapshot = self.snapshot(cx);
 8807        loop {
 8808            let diagnostics = if direction == Direction::Prev {
 8809                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 8810            } else {
 8811                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 8812            }
 8813            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 8814            let group = diagnostics
 8815                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 8816                // be sorted in a stable way
 8817                // skip until we are at current active diagnostic, if it exists
 8818                .skip_while(|entry| {
 8819                    (match direction {
 8820                        Direction::Prev => entry.range.start >= search_start,
 8821                        Direction::Next => entry.range.start <= search_start,
 8822                    }) && self
 8823                        .active_diagnostics
 8824                        .as_ref()
 8825                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 8826                })
 8827                .find_map(|entry| {
 8828                    if entry.diagnostic.is_primary
 8829                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 8830                        && !entry.range.is_empty()
 8831                        // if we match with the active diagnostic, skip it
 8832                        && Some(entry.diagnostic.group_id)
 8833                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 8834                    {
 8835                        Some((entry.range, entry.diagnostic.group_id))
 8836                    } else {
 8837                        None
 8838                    }
 8839                });
 8840
 8841            if let Some((primary_range, group_id)) = group {
 8842                if self.activate_diagnostics(group_id, cx) {
 8843                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8844                        s.select(vec![Selection {
 8845                            id: selection.id,
 8846                            start: primary_range.start,
 8847                            end: primary_range.start,
 8848                            reversed: false,
 8849                            goal: SelectionGoal::None,
 8850                        }]);
 8851                    });
 8852                }
 8853                break;
 8854            } else {
 8855                // Cycle around to the start of the buffer, potentially moving back to the start of
 8856                // the currently active diagnostic.
 8857                active_primary_range.take();
 8858                if direction == Direction::Prev {
 8859                    if search_start == buffer.len() {
 8860                        break;
 8861                    } else {
 8862                        search_start = buffer.len();
 8863                    }
 8864                } else if search_start == 0 {
 8865                    break;
 8866                } else {
 8867                    search_start = 0;
 8868                }
 8869            }
 8870        }
 8871    }
 8872
 8873    fn go_to_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 8874        let snapshot = self
 8875            .display_map
 8876            .update(cx, |display_map, cx| display_map.snapshot(cx));
 8877        let selection = self.selections.newest::<Point>(cx);
 8878
 8879        if !self.seek_in_direction(
 8880            &snapshot,
 8881            selection.head(),
 8882            false,
 8883            snapshot.buffer_snapshot.git_diff_hunks_in_range(
 8884                MultiBufferRow(selection.head().row + 1)..MultiBufferRow::MAX,
 8885            ),
 8886            cx,
 8887        ) {
 8888            let wrapped_point = Point::zero();
 8889            self.seek_in_direction(
 8890                &snapshot,
 8891                wrapped_point,
 8892                true,
 8893                snapshot.buffer_snapshot.git_diff_hunks_in_range(
 8894                    MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
 8895                ),
 8896                cx,
 8897            );
 8898        }
 8899    }
 8900
 8901    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 8902        let snapshot = self
 8903            .display_map
 8904            .update(cx, |display_map, cx| display_map.snapshot(cx));
 8905        let selection = self.selections.newest::<Point>(cx);
 8906
 8907        if !self.seek_in_direction(
 8908            &snapshot,
 8909            selection.head(),
 8910            false,
 8911            snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
 8912                MultiBufferRow(0)..MultiBufferRow(selection.head().row),
 8913            ),
 8914            cx,
 8915        ) {
 8916            let wrapped_point = snapshot.buffer_snapshot.max_point();
 8917            self.seek_in_direction(
 8918                &snapshot,
 8919                wrapped_point,
 8920                true,
 8921                snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
 8922                    MultiBufferRow(0)..MultiBufferRow(wrapped_point.row),
 8923                ),
 8924                cx,
 8925            );
 8926        }
 8927    }
 8928
 8929    fn seek_in_direction(
 8930        &mut self,
 8931        snapshot: &DisplaySnapshot,
 8932        initial_point: Point,
 8933        is_wrapped: bool,
 8934        hunks: impl Iterator<Item = DiffHunk<MultiBufferRow>>,
 8935        cx: &mut ViewContext<Editor>,
 8936    ) -> bool {
 8937        let display_point = initial_point.to_display_point(snapshot);
 8938        let mut hunks = hunks
 8939            .map(|hunk| diff_hunk_to_display(&hunk, &snapshot))
 8940            .filter(|hunk| is_wrapped || !hunk.contains_display_row(display_point.row()))
 8941            .dedup();
 8942
 8943        if let Some(hunk) = hunks.next() {
 8944            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8945                let row = hunk.start_display_row();
 8946                let point = DisplayPoint::new(row, 0);
 8947                s.select_display_ranges([point..point]);
 8948            });
 8949
 8950            true
 8951        } else {
 8952            false
 8953        }
 8954    }
 8955
 8956    pub fn go_to_definition(
 8957        &mut self,
 8958        _: &GoToDefinition,
 8959        cx: &mut ViewContext<Self>,
 8960    ) -> Task<Result<bool>> {
 8961        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx)
 8962    }
 8963
 8964    pub fn go_to_implementation(
 8965        &mut self,
 8966        _: &GoToImplementation,
 8967        cx: &mut ViewContext<Self>,
 8968    ) -> Task<Result<bool>> {
 8969        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 8970    }
 8971
 8972    pub fn go_to_implementation_split(
 8973        &mut self,
 8974        _: &GoToImplementationSplit,
 8975        cx: &mut ViewContext<Self>,
 8976    ) -> Task<Result<bool>> {
 8977        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 8978    }
 8979
 8980    pub fn go_to_type_definition(
 8981        &mut self,
 8982        _: &GoToTypeDefinition,
 8983        cx: &mut ViewContext<Self>,
 8984    ) -> Task<Result<bool>> {
 8985        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 8986    }
 8987
 8988    pub fn go_to_definition_split(
 8989        &mut self,
 8990        _: &GoToDefinitionSplit,
 8991        cx: &mut ViewContext<Self>,
 8992    ) -> Task<Result<bool>> {
 8993        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 8994    }
 8995
 8996    pub fn go_to_type_definition_split(
 8997        &mut self,
 8998        _: &GoToTypeDefinitionSplit,
 8999        cx: &mut ViewContext<Self>,
 9000    ) -> Task<Result<bool>> {
 9001        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 9002    }
 9003
 9004    fn go_to_definition_of_kind(
 9005        &mut self,
 9006        kind: GotoDefinitionKind,
 9007        split: bool,
 9008        cx: &mut ViewContext<Self>,
 9009    ) -> Task<Result<bool>> {
 9010        let Some(workspace) = self.workspace() else {
 9011            return Task::ready(Ok(false));
 9012        };
 9013        let buffer = self.buffer.read(cx);
 9014        let head = self.selections.newest::<usize>(cx).head();
 9015        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 9016            text_anchor
 9017        } else {
 9018            return Task::ready(Ok(false));
 9019        };
 9020
 9021        let project = workspace.read(cx).project().clone();
 9022        let definitions = project.update(cx, |project, cx| match kind {
 9023            GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
 9024            GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
 9025            GotoDefinitionKind::Implementation => project.implementation(&buffer, head, cx),
 9026        });
 9027
 9028        cx.spawn(|editor, mut cx| async move {
 9029            let definitions = definitions.await?;
 9030            let navigated = editor
 9031                .update(&mut cx, |editor, cx| {
 9032                    editor.navigate_to_hover_links(
 9033                        Some(kind),
 9034                        definitions
 9035                            .into_iter()
 9036                            .filter(|location| {
 9037                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 9038                            })
 9039                            .map(HoverLink::Text)
 9040                            .collect::<Vec<_>>(),
 9041                        split,
 9042                        cx,
 9043                    )
 9044                })?
 9045                .await?;
 9046            anyhow::Ok(navigated)
 9047        })
 9048    }
 9049
 9050    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 9051        let position = self.selections.newest_anchor().head();
 9052        let Some((buffer, buffer_position)) =
 9053            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9054        else {
 9055            return;
 9056        };
 9057
 9058        cx.spawn(|editor, mut cx| async move {
 9059            if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
 9060                editor.update(&mut cx, |_, cx| {
 9061                    cx.open_url(&url);
 9062                })
 9063            } else {
 9064                Ok(())
 9065            }
 9066        })
 9067        .detach();
 9068    }
 9069
 9070    pub(crate) fn navigate_to_hover_links(
 9071        &mut self,
 9072        kind: Option<GotoDefinitionKind>,
 9073        mut definitions: Vec<HoverLink>,
 9074        split: bool,
 9075        cx: &mut ViewContext<Editor>,
 9076    ) -> Task<Result<bool>> {
 9077        // If there is one definition, just open it directly
 9078        if definitions.len() == 1 {
 9079            let definition = definitions.pop().unwrap();
 9080            let target_task = match definition {
 9081                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 9082                HoverLink::InlayHint(lsp_location, server_id) => {
 9083                    self.compute_target_location(lsp_location, server_id, cx)
 9084                }
 9085                HoverLink::Url(url) => {
 9086                    cx.open_url(&url);
 9087                    Task::ready(Ok(None))
 9088                }
 9089            };
 9090            cx.spawn(|editor, mut cx| async move {
 9091                let target = target_task.await.context("target resolution task")?;
 9092                if let Some(target) = target {
 9093                    editor.update(&mut cx, |editor, cx| {
 9094                        let Some(workspace) = editor.workspace() else {
 9095                            return false;
 9096                        };
 9097                        let pane = workspace.read(cx).active_pane().clone();
 9098
 9099                        let range = target.range.to_offset(target.buffer.read(cx));
 9100                        let range = editor.range_for_match(&range);
 9101
 9102                        /// If select range has more than one line, we
 9103                        /// just point the cursor to range.start.
 9104                        fn check_multiline_range(
 9105                            buffer: &Buffer,
 9106                            range: Range<usize>,
 9107                        ) -> Range<usize> {
 9108                            if buffer.offset_to_point(range.start).row
 9109                                == buffer.offset_to_point(range.end).row
 9110                            {
 9111                                range
 9112                            } else {
 9113                                range.start..range.start
 9114                            }
 9115                        }
 9116
 9117                        if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 9118                            let buffer = target.buffer.read(cx);
 9119                            let range = check_multiline_range(buffer, range);
 9120                            editor.change_selections(Some(Autoscroll::focused()), cx, |s| {
 9121                                s.select_ranges([range]);
 9122                            });
 9123                        } else {
 9124                            cx.window_context().defer(move |cx| {
 9125                                let target_editor: View<Self> =
 9126                                    workspace.update(cx, |workspace, cx| {
 9127                                        let pane = if split {
 9128                                            workspace.adjacent_pane(cx)
 9129                                        } else {
 9130                                            workspace.active_pane().clone()
 9131                                        };
 9132
 9133                                        workspace.open_project_item(
 9134                                            pane,
 9135                                            target.buffer.clone(),
 9136                                            true,
 9137                                            true,
 9138                                            cx,
 9139                                        )
 9140                                    });
 9141                                target_editor.update(cx, |target_editor, cx| {
 9142                                    // When selecting a definition in a different buffer, disable the nav history
 9143                                    // to avoid creating a history entry at the previous cursor location.
 9144                                    pane.update(cx, |pane, _| pane.disable_history());
 9145                                    let buffer = target.buffer.read(cx);
 9146                                    let range = check_multiline_range(buffer, range);
 9147                                    target_editor.change_selections(
 9148                                        Some(Autoscroll::focused()),
 9149                                        cx,
 9150                                        |s| {
 9151                                            s.select_ranges([range]);
 9152                                        },
 9153                                    );
 9154                                    pane.update(cx, |pane, _| pane.enable_history());
 9155                                });
 9156                            });
 9157                        }
 9158                        true
 9159                    })
 9160                } else {
 9161                    Ok(false)
 9162                }
 9163            })
 9164        } else if !definitions.is_empty() {
 9165            let replica_id = self.replica_id(cx);
 9166            cx.spawn(|editor, mut cx| async move {
 9167                let (title, location_tasks, workspace) = editor
 9168                    .update(&mut cx, |editor, cx| {
 9169                        let tab_kind = match kind {
 9170                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 9171                            _ => "Definitions",
 9172                        };
 9173                        let title = definitions
 9174                            .iter()
 9175                            .find_map(|definition| match definition {
 9176                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 9177                                    let buffer = origin.buffer.read(cx);
 9178                                    format!(
 9179                                        "{} for {}",
 9180                                        tab_kind,
 9181                                        buffer
 9182                                            .text_for_range(origin.range.clone())
 9183                                            .collect::<String>()
 9184                                    )
 9185                                }),
 9186                                HoverLink::InlayHint(_, _) => None,
 9187                                HoverLink::Url(_) => None,
 9188                            })
 9189                            .unwrap_or(tab_kind.to_string());
 9190                        let location_tasks = definitions
 9191                            .into_iter()
 9192                            .map(|definition| match definition {
 9193                                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 9194                                HoverLink::InlayHint(lsp_location, server_id) => {
 9195                                    editor.compute_target_location(lsp_location, server_id, cx)
 9196                                }
 9197                                HoverLink::Url(_) => Task::ready(Ok(None)),
 9198                            })
 9199                            .collect::<Vec<_>>();
 9200                        (title, location_tasks, editor.workspace().clone())
 9201                    })
 9202                    .context("location tasks preparation")?;
 9203
 9204                let locations = futures::future::join_all(location_tasks)
 9205                    .await
 9206                    .into_iter()
 9207                    .filter_map(|location| location.transpose())
 9208                    .collect::<Result<_>>()
 9209                    .context("location tasks")?;
 9210
 9211                let Some(workspace) = workspace else {
 9212                    return Ok(false);
 9213                };
 9214                let opened = workspace
 9215                    .update(&mut cx, |workspace, cx| {
 9216                        Self::open_locations_in_multibuffer(
 9217                            workspace, locations, replica_id, title, split, cx,
 9218                        )
 9219                    })
 9220                    .ok();
 9221
 9222                anyhow::Ok(opened.is_some())
 9223            })
 9224        } else {
 9225            Task::ready(Ok(false))
 9226        }
 9227    }
 9228
 9229    fn compute_target_location(
 9230        &self,
 9231        lsp_location: lsp::Location,
 9232        server_id: LanguageServerId,
 9233        cx: &mut ViewContext<Editor>,
 9234    ) -> Task<anyhow::Result<Option<Location>>> {
 9235        let Some(project) = self.project.clone() else {
 9236            return Task::Ready(Some(Ok(None)));
 9237        };
 9238
 9239        cx.spawn(move |editor, mut cx| async move {
 9240            let location_task = editor.update(&mut cx, |editor, cx| {
 9241                project.update(cx, |project, cx| {
 9242                    let language_server_name =
 9243                        editor.buffer.read(cx).as_singleton().and_then(|buffer| {
 9244                            project
 9245                                .language_server_for_buffer(buffer.read(cx), server_id, cx)
 9246                                .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
 9247                        });
 9248                    language_server_name.map(|language_server_name| {
 9249                        project.open_local_buffer_via_lsp(
 9250                            lsp_location.uri.clone(),
 9251                            server_id,
 9252                            language_server_name,
 9253                            cx,
 9254                        )
 9255                    })
 9256                })
 9257            })?;
 9258            let location = match location_task {
 9259                Some(task) => Some({
 9260                    let target_buffer_handle = task.await.context("open local buffer")?;
 9261                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
 9262                        let target_start = target_buffer
 9263                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
 9264                        let target_end = target_buffer
 9265                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
 9266                        target_buffer.anchor_after(target_start)
 9267                            ..target_buffer.anchor_before(target_end)
 9268                    })?;
 9269                    Location {
 9270                        buffer: target_buffer_handle,
 9271                        range,
 9272                    }
 9273                }),
 9274                None => None,
 9275            };
 9276            Ok(location)
 9277        })
 9278    }
 9279
 9280    pub fn find_all_references(
 9281        &mut self,
 9282        _: &FindAllReferences,
 9283        cx: &mut ViewContext<Self>,
 9284    ) -> Option<Task<Result<()>>> {
 9285        let multi_buffer = self.buffer.read(cx);
 9286        let selection = self.selections.newest::<usize>(cx);
 9287        let head = selection.head();
 9288
 9289        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 9290        let head_anchor = multi_buffer_snapshot.anchor_at(
 9291            head,
 9292            if head < selection.tail() {
 9293                Bias::Right
 9294            } else {
 9295                Bias::Left
 9296            },
 9297        );
 9298
 9299        match self
 9300            .find_all_references_task_sources
 9301            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
 9302        {
 9303            Ok(_) => {
 9304                log::info!(
 9305                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
 9306                );
 9307                return None;
 9308            }
 9309            Err(i) => {
 9310                self.find_all_references_task_sources.insert(i, head_anchor);
 9311            }
 9312        }
 9313
 9314        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
 9315        let replica_id = self.replica_id(cx);
 9316        let workspace = self.workspace()?;
 9317        let project = workspace.read(cx).project().clone();
 9318        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
 9319        Some(cx.spawn(|editor, mut cx| async move {
 9320            let _cleanup = defer({
 9321                let mut cx = cx.clone();
 9322                move || {
 9323                    let _ = editor.update(&mut cx, |editor, _| {
 9324                        if let Ok(i) =
 9325                            editor
 9326                                .find_all_references_task_sources
 9327                                .binary_search_by(|anchor| {
 9328                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
 9329                                })
 9330                        {
 9331                            editor.find_all_references_task_sources.remove(i);
 9332                        }
 9333                    });
 9334                }
 9335            });
 9336
 9337            let locations = references.await?;
 9338            if locations.is_empty() {
 9339                return anyhow::Ok(());
 9340            }
 9341
 9342            workspace.update(&mut cx, |workspace, cx| {
 9343                let title = locations
 9344                    .first()
 9345                    .as_ref()
 9346                    .map(|location| {
 9347                        let buffer = location.buffer.read(cx);
 9348                        format!(
 9349                            "References to `{}`",
 9350                            buffer
 9351                                .text_for_range(location.range.clone())
 9352                                .collect::<String>()
 9353                        )
 9354                    })
 9355                    .unwrap();
 9356                Self::open_locations_in_multibuffer(
 9357                    workspace, locations, replica_id, title, false, cx,
 9358                );
 9359            })
 9360        }))
 9361    }
 9362
 9363    /// Opens a multibuffer with the given project locations in it
 9364    pub fn open_locations_in_multibuffer(
 9365        workspace: &mut Workspace,
 9366        mut locations: Vec<Location>,
 9367        replica_id: ReplicaId,
 9368        title: String,
 9369        split: bool,
 9370        cx: &mut ViewContext<Workspace>,
 9371    ) {
 9372        // If there are multiple definitions, open them in a multibuffer
 9373        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
 9374        let mut locations = locations.into_iter().peekable();
 9375        let mut ranges_to_highlight = Vec::new();
 9376        let capability = workspace.project().read(cx).capability();
 9377
 9378        let excerpt_buffer = cx.new_model(|cx| {
 9379            let mut multibuffer = MultiBuffer::new(replica_id, capability);
 9380            while let Some(location) = locations.next() {
 9381                let buffer = location.buffer.read(cx);
 9382                let mut ranges_for_buffer = Vec::new();
 9383                let range = location.range.to_offset(buffer);
 9384                ranges_for_buffer.push(range.clone());
 9385
 9386                while let Some(next_location) = locations.peek() {
 9387                    if next_location.buffer == location.buffer {
 9388                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
 9389                        locations.next();
 9390                    } else {
 9391                        break;
 9392                    }
 9393                }
 9394
 9395                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
 9396                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
 9397                    location.buffer.clone(),
 9398                    ranges_for_buffer,
 9399                    DEFAULT_MULTIBUFFER_CONTEXT,
 9400                    cx,
 9401                ))
 9402            }
 9403
 9404            multibuffer.with_title(title)
 9405        });
 9406
 9407        let editor = cx.new_view(|cx| {
 9408            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
 9409        });
 9410        editor.update(cx, |editor, cx| {
 9411            if let Some(first_range) = ranges_to_highlight.first() {
 9412                editor.change_selections(None, cx, |selections| {
 9413                    selections.clear_disjoint();
 9414                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
 9415                });
 9416            }
 9417            editor.highlight_background::<Self>(
 9418                &ranges_to_highlight,
 9419                |theme| theme.editor_highlighted_line_background,
 9420                cx,
 9421            );
 9422        });
 9423
 9424        let item = Box::new(editor);
 9425        let item_id = item.item_id();
 9426
 9427        if split {
 9428            workspace.split_item(SplitDirection::Right, item.clone(), cx);
 9429        } else {
 9430            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
 9431                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
 9432                    pane.close_current_preview_item(cx)
 9433                } else {
 9434                    None
 9435                }
 9436            });
 9437            workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
 9438        }
 9439        workspace.active_pane().update(cx, |pane, cx| {
 9440            pane.set_preview_item_id(Some(item_id), cx);
 9441        });
 9442    }
 9443
 9444    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 9445        use language::ToOffset as _;
 9446
 9447        let project = self.project.clone()?;
 9448        let selection = self.selections.newest_anchor().clone();
 9449        let (cursor_buffer, cursor_buffer_position) = self
 9450            .buffer
 9451            .read(cx)
 9452            .text_anchor_for_position(selection.head(), cx)?;
 9453        let (tail_buffer, cursor_buffer_position_end) = self
 9454            .buffer
 9455            .read(cx)
 9456            .text_anchor_for_position(selection.tail(), cx)?;
 9457        if tail_buffer != cursor_buffer {
 9458            return None;
 9459        }
 9460
 9461        let snapshot = cursor_buffer.read(cx).snapshot();
 9462        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
 9463        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
 9464        let prepare_rename = project.update(cx, |project, cx| {
 9465            project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
 9466        });
 9467        drop(snapshot);
 9468
 9469        Some(cx.spawn(|this, mut cx| async move {
 9470            let rename_range = if let Some(range) = prepare_rename.await? {
 9471                Some(range)
 9472            } else {
 9473                this.update(&mut cx, |this, cx| {
 9474                    let buffer = this.buffer.read(cx).snapshot(cx);
 9475                    let mut buffer_highlights = this
 9476                        .document_highlights_for_position(selection.head(), &buffer)
 9477                        .filter(|highlight| {
 9478                            highlight.start.excerpt_id == selection.head().excerpt_id
 9479                                && highlight.end.excerpt_id == selection.head().excerpt_id
 9480                        });
 9481                    buffer_highlights
 9482                        .next()
 9483                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
 9484                })?
 9485            };
 9486            if let Some(rename_range) = rename_range {
 9487                this.update(&mut cx, |this, cx| {
 9488                    let snapshot = cursor_buffer.read(cx).snapshot();
 9489                    let rename_buffer_range = rename_range.to_offset(&snapshot);
 9490                    let cursor_offset_in_rename_range =
 9491                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
 9492                    let cursor_offset_in_rename_range_end =
 9493                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
 9494
 9495                    this.take_rename(false, cx);
 9496                    let buffer = this.buffer.read(cx).read(cx);
 9497                    let cursor_offset = selection.head().to_offset(&buffer);
 9498                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
 9499                    let rename_end = rename_start + rename_buffer_range.len();
 9500                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
 9501                    let mut old_highlight_id = None;
 9502                    let old_name: Arc<str> = buffer
 9503                        .chunks(rename_start..rename_end, true)
 9504                        .map(|chunk| {
 9505                            if old_highlight_id.is_none() {
 9506                                old_highlight_id = chunk.syntax_highlight_id;
 9507                            }
 9508                            chunk.text
 9509                        })
 9510                        .collect::<String>()
 9511                        .into();
 9512
 9513                    drop(buffer);
 9514
 9515                    // Position the selection in the rename editor so that it matches the current selection.
 9516                    this.show_local_selections = false;
 9517                    let rename_editor = cx.new_view(|cx| {
 9518                        let mut editor = Editor::single_line(cx);
 9519                        editor.buffer.update(cx, |buffer, cx| {
 9520                            buffer.edit([(0..0, old_name.clone())], None, cx)
 9521                        });
 9522                        let rename_selection_range = match cursor_offset_in_rename_range
 9523                            .cmp(&cursor_offset_in_rename_range_end)
 9524                        {
 9525                            Ordering::Equal => {
 9526                                editor.select_all(&SelectAll, cx);
 9527                                return editor;
 9528                            }
 9529                            Ordering::Less => {
 9530                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
 9531                            }
 9532                            Ordering::Greater => {
 9533                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
 9534                            }
 9535                        };
 9536                        if rename_selection_range.end > old_name.len() {
 9537                            editor.select_all(&SelectAll, cx);
 9538                        } else {
 9539                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9540                                s.select_ranges([rename_selection_range]);
 9541                            });
 9542                        }
 9543                        editor
 9544                    });
 9545                    cx.subscribe(&rename_editor, |_, _, e, cx| match e {
 9546                        EditorEvent::Focused => cx.emit(EditorEvent::FocusedIn),
 9547                        _ => {}
 9548                    })
 9549                    .detach();
 9550
 9551                    let write_highlights =
 9552                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
 9553                    let read_highlights =
 9554                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
 9555                    let ranges = write_highlights
 9556                        .iter()
 9557                        .flat_map(|(_, ranges)| ranges.iter())
 9558                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
 9559                        .cloned()
 9560                        .collect();
 9561
 9562                    this.highlight_text::<Rename>(
 9563                        ranges,
 9564                        HighlightStyle {
 9565                            fade_out: Some(0.6),
 9566                            ..Default::default()
 9567                        },
 9568                        cx,
 9569                    );
 9570                    let rename_focus_handle = rename_editor.focus_handle(cx);
 9571                    cx.focus(&rename_focus_handle);
 9572                    let block_id = this.insert_blocks(
 9573                        [BlockProperties {
 9574                            style: BlockStyle::Flex,
 9575                            position: range.start,
 9576                            height: 1,
 9577                            render: Box::new({
 9578                                let rename_editor = rename_editor.clone();
 9579                                move |cx: &mut BlockContext| {
 9580                                    let mut text_style = cx.editor_style.text.clone();
 9581                                    if let Some(highlight_style) = old_highlight_id
 9582                                        .and_then(|h| h.style(&cx.editor_style.syntax))
 9583                                    {
 9584                                        text_style = text_style.highlight(highlight_style);
 9585                                    }
 9586                                    div()
 9587                                        .pl(cx.anchor_x)
 9588                                        .child(EditorElement::new(
 9589                                            &rename_editor,
 9590                                            EditorStyle {
 9591                                                background: cx.theme().system().transparent,
 9592                                                local_player: cx.editor_style.local_player,
 9593                                                text: text_style,
 9594                                                scrollbar_width: cx.editor_style.scrollbar_width,
 9595                                                syntax: cx.editor_style.syntax.clone(),
 9596                                                status: cx.editor_style.status.clone(),
 9597                                                inlay_hints_style: HighlightStyle {
 9598                                                    color: Some(cx.theme().status().hint),
 9599                                                    font_weight: Some(FontWeight::BOLD),
 9600                                                    ..HighlightStyle::default()
 9601                                                },
 9602                                                suggestions_style: HighlightStyle {
 9603                                                    color: Some(cx.theme().status().predictive),
 9604                                                    ..HighlightStyle::default()
 9605                                                },
 9606                                            },
 9607                                        ))
 9608                                        .into_any_element()
 9609                                }
 9610                            }),
 9611                            disposition: BlockDisposition::Below,
 9612                        }],
 9613                        Some(Autoscroll::fit()),
 9614                        cx,
 9615                    )[0];
 9616                    this.pending_rename = Some(RenameState {
 9617                        range,
 9618                        old_name,
 9619                        editor: rename_editor,
 9620                        block_id,
 9621                    });
 9622                })?;
 9623            }
 9624
 9625            Ok(())
 9626        }))
 9627    }
 9628
 9629    pub fn confirm_rename(
 9630        &mut self,
 9631        _: &ConfirmRename,
 9632        cx: &mut ViewContext<Self>,
 9633    ) -> Option<Task<Result<()>>> {
 9634        let rename = self.take_rename(false, cx)?;
 9635        let workspace = self.workspace()?;
 9636        let (start_buffer, start) = self
 9637            .buffer
 9638            .read(cx)
 9639            .text_anchor_for_position(rename.range.start, cx)?;
 9640        let (end_buffer, end) = self
 9641            .buffer
 9642            .read(cx)
 9643            .text_anchor_for_position(rename.range.end, cx)?;
 9644        if start_buffer != end_buffer {
 9645            return None;
 9646        }
 9647
 9648        let buffer = start_buffer;
 9649        let range = start..end;
 9650        let old_name = rename.old_name;
 9651        let new_name = rename.editor.read(cx).text(cx);
 9652
 9653        let rename = workspace
 9654            .read(cx)
 9655            .project()
 9656            .clone()
 9657            .update(cx, |project, cx| {
 9658                project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
 9659            });
 9660        let workspace = workspace.downgrade();
 9661
 9662        Some(cx.spawn(|editor, mut cx| async move {
 9663            let project_transaction = rename.await?;
 9664            Self::open_project_transaction(
 9665                &editor,
 9666                workspace,
 9667                project_transaction,
 9668                format!("Rename: {}{}", old_name, new_name),
 9669                cx.clone(),
 9670            )
 9671            .await?;
 9672
 9673            editor.update(&mut cx, |editor, cx| {
 9674                editor.refresh_document_highlights(cx);
 9675            })?;
 9676            Ok(())
 9677        }))
 9678    }
 9679
 9680    fn take_rename(
 9681        &mut self,
 9682        moving_cursor: bool,
 9683        cx: &mut ViewContext<Self>,
 9684    ) -> Option<RenameState> {
 9685        let rename = self.pending_rename.take()?;
 9686        if rename.editor.focus_handle(cx).is_focused(cx) {
 9687            cx.focus(&self.focus_handle);
 9688        }
 9689
 9690        self.remove_blocks(
 9691            [rename.block_id].into_iter().collect(),
 9692            Some(Autoscroll::fit()),
 9693            cx,
 9694        );
 9695        self.clear_highlights::<Rename>(cx);
 9696        self.show_local_selections = true;
 9697
 9698        if moving_cursor {
 9699            let rename_editor = rename.editor.read(cx);
 9700            let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
 9701
 9702            // Update the selection to match the position of the selection inside
 9703            // the rename editor.
 9704            let snapshot = self.buffer.read(cx).read(cx);
 9705            let rename_range = rename.range.to_offset(&snapshot);
 9706            let cursor_in_editor = snapshot
 9707                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
 9708                .min(rename_range.end);
 9709            drop(snapshot);
 9710
 9711            self.change_selections(None, cx, |s| {
 9712                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
 9713            });
 9714        } else {
 9715            self.refresh_document_highlights(cx);
 9716        }
 9717
 9718        Some(rename)
 9719    }
 9720
 9721    pub fn pending_rename(&self) -> Option<&RenameState> {
 9722        self.pending_rename.as_ref()
 9723    }
 9724
 9725    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 9726        let project = match &self.project {
 9727            Some(project) => project.clone(),
 9728            None => return None,
 9729        };
 9730
 9731        Some(self.perform_format(project, FormatTrigger::Manual, cx))
 9732    }
 9733
 9734    fn perform_format(
 9735        &mut self,
 9736        project: Model<Project>,
 9737        trigger: FormatTrigger,
 9738        cx: &mut ViewContext<Self>,
 9739    ) -> Task<Result<()>> {
 9740        let buffer = self.buffer().clone();
 9741        let mut buffers = buffer.read(cx).all_buffers();
 9742        if trigger == FormatTrigger::Save {
 9743            buffers.retain(|buffer| buffer.read(cx).is_dirty());
 9744        }
 9745
 9746        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
 9747        let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
 9748
 9749        cx.spawn(|_, mut cx| async move {
 9750            let transaction = futures::select_biased! {
 9751                () = timeout => {
 9752                    log::warn!("timed out waiting for formatting");
 9753                    None
 9754                }
 9755                transaction = format.log_err().fuse() => transaction,
 9756            };
 9757
 9758            buffer
 9759                .update(&mut cx, |buffer, cx| {
 9760                    if let Some(transaction) = transaction {
 9761                        if !buffer.is_singleton() {
 9762                            buffer.push_transaction(&transaction.0, cx);
 9763                        }
 9764                    }
 9765
 9766                    cx.notify();
 9767                })
 9768                .ok();
 9769
 9770            Ok(())
 9771        })
 9772    }
 9773
 9774    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
 9775        if let Some(project) = self.project.clone() {
 9776            self.buffer.update(cx, |multi_buffer, cx| {
 9777                project.update(cx, |project, cx| {
 9778                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
 9779                });
 9780            })
 9781        }
 9782    }
 9783
 9784    fn cancel_language_server_work(
 9785        &mut self,
 9786        _: &CancelLanguageServerWork,
 9787        cx: &mut ViewContext<Self>,
 9788    ) {
 9789        if let Some(project) = self.project.clone() {
 9790            self.buffer.update(cx, |multi_buffer, cx| {
 9791                project.update(cx, |project, cx| {
 9792                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
 9793                });
 9794            })
 9795        }
 9796    }
 9797
 9798    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
 9799        cx.show_character_palette();
 9800    }
 9801
 9802    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
 9803        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
 9804            let buffer = self.buffer.read(cx).snapshot(cx);
 9805            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
 9806            let is_valid = buffer
 9807                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
 9808                .any(|entry| {
 9809                    entry.diagnostic.is_primary
 9810                        && !entry.range.is_empty()
 9811                        && entry.range.start == primary_range_start
 9812                        && entry.diagnostic.message == active_diagnostics.primary_message
 9813                });
 9814
 9815            if is_valid != active_diagnostics.is_valid {
 9816                active_diagnostics.is_valid = is_valid;
 9817                let mut new_styles = HashMap::default();
 9818                for (block_id, diagnostic) in &active_diagnostics.blocks {
 9819                    new_styles.insert(
 9820                        *block_id,
 9821                        (
 9822                            None,
 9823                            diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
 9824                        ),
 9825                    );
 9826                }
 9827                self.display_map.update(cx, |display_map, cx| {
 9828                    display_map.replace_blocks(new_styles, cx)
 9829                });
 9830            }
 9831        }
 9832    }
 9833
 9834    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
 9835        self.dismiss_diagnostics(cx);
 9836        let snapshot = self.snapshot(cx);
 9837        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
 9838            let buffer = self.buffer.read(cx).snapshot(cx);
 9839
 9840            let mut primary_range = None;
 9841            let mut primary_message = None;
 9842            let mut group_end = Point::zero();
 9843            let diagnostic_group = buffer
 9844                .diagnostic_group::<MultiBufferPoint>(group_id)
 9845                .filter_map(|entry| {
 9846                    if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
 9847                        && (entry.range.start.row == entry.range.end.row
 9848                            || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
 9849                    {
 9850                        return None;
 9851                    }
 9852                    if entry.range.end > group_end {
 9853                        group_end = entry.range.end;
 9854                    }
 9855                    if entry.diagnostic.is_primary {
 9856                        primary_range = Some(entry.range.clone());
 9857                        primary_message = Some(entry.diagnostic.message.clone());
 9858                    }
 9859                    Some(entry)
 9860                })
 9861                .collect::<Vec<_>>();
 9862            let primary_range = primary_range?;
 9863            let primary_message = primary_message?;
 9864            let primary_range =
 9865                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
 9866
 9867            let blocks = display_map
 9868                .insert_blocks(
 9869                    diagnostic_group.iter().map(|entry| {
 9870                        let diagnostic = entry.diagnostic.clone();
 9871                        let message_height = diagnostic.message.matches('\n').count() as u8 + 1;
 9872                        BlockProperties {
 9873                            style: BlockStyle::Fixed,
 9874                            position: buffer.anchor_after(entry.range.start),
 9875                            height: message_height,
 9876                            render: diagnostic_block_renderer(diagnostic, None, true, true),
 9877                            disposition: BlockDisposition::Below,
 9878                        }
 9879                    }),
 9880                    cx,
 9881                )
 9882                .into_iter()
 9883                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
 9884                .collect();
 9885
 9886            Some(ActiveDiagnosticGroup {
 9887                primary_range,
 9888                primary_message,
 9889                group_id,
 9890                blocks,
 9891                is_valid: true,
 9892            })
 9893        });
 9894        self.active_diagnostics.is_some()
 9895    }
 9896
 9897    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
 9898        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
 9899            self.display_map.update(cx, |display_map, cx| {
 9900                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
 9901            });
 9902            cx.notify();
 9903        }
 9904    }
 9905
 9906    pub fn set_selections_from_remote(
 9907        &mut self,
 9908        selections: Vec<Selection<Anchor>>,
 9909        pending_selection: Option<Selection<Anchor>>,
 9910        cx: &mut ViewContext<Self>,
 9911    ) {
 9912        let old_cursor_position = self.selections.newest_anchor().head();
 9913        self.selections.change_with(cx, |s| {
 9914            s.select_anchors(selections);
 9915            if let Some(pending_selection) = pending_selection {
 9916                s.set_pending(pending_selection, SelectMode::Character);
 9917            } else {
 9918                s.clear_pending();
 9919            }
 9920        });
 9921        self.selections_did_change(false, &old_cursor_position, true, cx);
 9922    }
 9923
 9924    fn push_to_selection_history(&mut self) {
 9925        self.selection_history.push(SelectionHistoryEntry {
 9926            selections: self.selections.disjoint_anchors(),
 9927            select_next_state: self.select_next_state.clone(),
 9928            select_prev_state: self.select_prev_state.clone(),
 9929            add_selections_state: self.add_selections_state.clone(),
 9930        });
 9931    }
 9932
 9933    pub fn transact(
 9934        &mut self,
 9935        cx: &mut ViewContext<Self>,
 9936        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
 9937    ) -> Option<TransactionId> {
 9938        self.start_transaction_at(Instant::now(), cx);
 9939        update(self, cx);
 9940        self.end_transaction_at(Instant::now(), cx)
 9941    }
 9942
 9943    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
 9944        self.end_selection(cx);
 9945        if let Some(tx_id) = self
 9946            .buffer
 9947            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
 9948        {
 9949            self.selection_history
 9950                .insert_transaction(tx_id, self.selections.disjoint_anchors());
 9951            cx.emit(EditorEvent::TransactionBegun {
 9952                transaction_id: tx_id,
 9953            })
 9954        }
 9955    }
 9956
 9957    fn end_transaction_at(
 9958        &mut self,
 9959        now: Instant,
 9960        cx: &mut ViewContext<Self>,
 9961    ) -> Option<TransactionId> {
 9962        if let Some(transaction_id) = self
 9963            .buffer
 9964            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
 9965        {
 9966            if let Some((_, end_selections)) =
 9967                self.selection_history.transaction_mut(transaction_id)
 9968            {
 9969                *end_selections = Some(self.selections.disjoint_anchors());
 9970            } else {
 9971                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
 9972            }
 9973
 9974            cx.emit(EditorEvent::Edited { transaction_id });
 9975            Some(transaction_id)
 9976        } else {
 9977            None
 9978        }
 9979    }
 9980
 9981    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
 9982        let mut fold_ranges = Vec::new();
 9983
 9984        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9985
 9986        let selections = self.selections.all_adjusted(cx);
 9987        for selection in selections {
 9988            let range = selection.range().sorted();
 9989            let buffer_start_row = range.start.row;
 9990
 9991            for row in (0..=range.end.row).rev() {
 9992                if let Some((foldable_range, fold_text)) =
 9993                    display_map.foldable_range(MultiBufferRow(row))
 9994                {
 9995                    if foldable_range.end.row >= buffer_start_row {
 9996                        fold_ranges.push((foldable_range, fold_text));
 9997                        if row <= range.start.row {
 9998                            break;
 9999                        }
10000                    }
10001                }
10002            }
10003        }
10004
10005        self.fold_ranges(fold_ranges, true, cx);
10006    }
10007
10008    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10009        let buffer_row = fold_at.buffer_row;
10010        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10011
10012        if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
10013            let autoscroll = self
10014                .selections
10015                .all::<Point>(cx)
10016                .iter()
10017                .any(|selection| fold_range.overlaps(&selection.range()));
10018
10019            self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
10020        }
10021    }
10022
10023    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10024        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10025        let buffer = &display_map.buffer_snapshot;
10026        let selections = self.selections.all::<Point>(cx);
10027        let ranges = selections
10028            .iter()
10029            .map(|s| {
10030                let range = s.display_range(&display_map).sorted();
10031                let mut start = range.start.to_point(&display_map);
10032                let mut end = range.end.to_point(&display_map);
10033                start.column = 0;
10034                end.column = buffer.line_len(MultiBufferRow(end.row));
10035                start..end
10036            })
10037            .collect::<Vec<_>>();
10038
10039        self.unfold_ranges(ranges, true, true, cx);
10040    }
10041
10042    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10043        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10044
10045        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10046            ..Point::new(
10047                unfold_at.buffer_row.0,
10048                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10049            );
10050
10051        let autoscroll = self
10052            .selections
10053            .all::<Point>(cx)
10054            .iter()
10055            .any(|selection| selection.range().overlaps(&intersection_range));
10056
10057        self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
10058    }
10059
10060    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10061        let selections = self.selections.all::<Point>(cx);
10062        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10063        let line_mode = self.selections.line_mode;
10064        let ranges = selections.into_iter().map(|s| {
10065            if line_mode {
10066                let start = Point::new(s.start.row, 0);
10067                let end = Point::new(
10068                    s.end.row,
10069                    display_map
10070                        .buffer_snapshot
10071                        .line_len(MultiBufferRow(s.end.row)),
10072                );
10073                (start..end, display_map.fold_placeholder.clone())
10074            } else {
10075                (s.start..s.end, display_map.fold_placeholder.clone())
10076            }
10077        });
10078        self.fold_ranges(ranges, true, cx);
10079    }
10080
10081    pub fn fold_ranges<T: ToOffset + Clone>(
10082        &mut self,
10083        ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
10084        auto_scroll: bool,
10085        cx: &mut ViewContext<Self>,
10086    ) {
10087        let mut fold_ranges = Vec::new();
10088        let mut buffers_affected = HashMap::default();
10089        let multi_buffer = self.buffer().read(cx);
10090        for (fold_range, fold_text) in ranges {
10091            if let Some((_, buffer, _)) =
10092                multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
10093            {
10094                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10095            };
10096            fold_ranges.push((fold_range, fold_text));
10097        }
10098
10099        let mut ranges = fold_ranges.into_iter().peekable();
10100        if ranges.peek().is_some() {
10101            self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
10102
10103            if auto_scroll {
10104                self.request_autoscroll(Autoscroll::fit(), cx);
10105            }
10106
10107            for buffer in buffers_affected.into_values() {
10108                self.sync_expanded_diff_hunks(buffer, cx);
10109            }
10110
10111            cx.notify();
10112
10113            if let Some(active_diagnostics) = self.active_diagnostics.take() {
10114                // Clear diagnostics block when folding a range that contains it.
10115                let snapshot = self.snapshot(cx);
10116                if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10117                    drop(snapshot);
10118                    self.active_diagnostics = Some(active_diagnostics);
10119                    self.dismiss_diagnostics(cx);
10120                } else {
10121                    self.active_diagnostics = Some(active_diagnostics);
10122                }
10123            }
10124
10125            self.scrollbar_marker_state.dirty = true;
10126        }
10127    }
10128
10129    pub fn unfold_ranges<T: ToOffset + Clone>(
10130        &mut self,
10131        ranges: impl IntoIterator<Item = Range<T>>,
10132        inclusive: bool,
10133        auto_scroll: bool,
10134        cx: &mut ViewContext<Self>,
10135    ) {
10136        let mut unfold_ranges = Vec::new();
10137        let mut buffers_affected = HashMap::default();
10138        let multi_buffer = self.buffer().read(cx);
10139        for range in ranges {
10140            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10141                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10142            };
10143            unfold_ranges.push(range);
10144        }
10145
10146        let mut ranges = unfold_ranges.into_iter().peekable();
10147        if ranges.peek().is_some() {
10148            self.display_map
10149                .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
10150            if auto_scroll {
10151                self.request_autoscroll(Autoscroll::fit(), cx);
10152            }
10153
10154            for buffer in buffers_affected.into_values() {
10155                self.sync_expanded_diff_hunks(buffer, cx);
10156            }
10157
10158            cx.notify();
10159            self.scrollbar_marker_state.dirty = true;
10160            self.active_indent_guides_state.dirty = true;
10161        }
10162    }
10163
10164    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10165        if hovered != self.gutter_hovered {
10166            self.gutter_hovered = hovered;
10167            cx.notify();
10168        }
10169    }
10170
10171    pub fn insert_blocks(
10172        &mut self,
10173        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10174        autoscroll: Option<Autoscroll>,
10175        cx: &mut ViewContext<Self>,
10176    ) -> Vec<CustomBlockId> {
10177        let blocks = self
10178            .display_map
10179            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10180        if let Some(autoscroll) = autoscroll {
10181            self.request_autoscroll(autoscroll, cx);
10182        }
10183        blocks
10184    }
10185
10186    pub fn replace_blocks(
10187        &mut self,
10188        blocks: HashMap<CustomBlockId, (Option<u8>, RenderBlock)>,
10189        autoscroll: Option<Autoscroll>,
10190        cx: &mut ViewContext<Self>,
10191    ) {
10192        self.display_map
10193            .update(cx, |display_map, cx| display_map.replace_blocks(blocks, cx));
10194        if let Some(autoscroll) = autoscroll {
10195            self.request_autoscroll(autoscroll, cx);
10196        }
10197    }
10198
10199    pub fn remove_blocks(
10200        &mut self,
10201        block_ids: HashSet<CustomBlockId>,
10202        autoscroll: Option<Autoscroll>,
10203        cx: &mut ViewContext<Self>,
10204    ) {
10205        self.display_map.update(cx, |display_map, cx| {
10206            display_map.remove_blocks(block_ids, cx)
10207        });
10208        if let Some(autoscroll) = autoscroll {
10209            self.request_autoscroll(autoscroll, cx);
10210        }
10211    }
10212
10213    pub fn row_for_block(
10214        &self,
10215        block_id: CustomBlockId,
10216        cx: &mut ViewContext<Self>,
10217    ) -> Option<DisplayRow> {
10218        self.display_map
10219            .update(cx, |map, cx| map.row_for_block(block_id, cx))
10220    }
10221
10222    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
10223        self.focused_block = Some(focused_block);
10224    }
10225
10226    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
10227        self.focused_block.take()
10228    }
10229
10230    pub fn insert_creases(
10231        &mut self,
10232        creases: impl IntoIterator<Item = Crease>,
10233        cx: &mut ViewContext<Self>,
10234    ) -> Vec<CreaseId> {
10235        self.display_map
10236            .update(cx, |map, cx| map.insert_creases(creases, cx))
10237    }
10238
10239    pub fn remove_creases(
10240        &mut self,
10241        ids: impl IntoIterator<Item = CreaseId>,
10242        cx: &mut ViewContext<Self>,
10243    ) {
10244        self.display_map
10245            .update(cx, |map, cx| map.remove_creases(ids, cx));
10246    }
10247
10248    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
10249        self.display_map
10250            .update(cx, |map, cx| map.snapshot(cx))
10251            .longest_row()
10252    }
10253
10254    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
10255        self.display_map
10256            .update(cx, |map, cx| map.snapshot(cx))
10257            .max_point()
10258    }
10259
10260    pub fn text(&self, cx: &AppContext) -> String {
10261        self.buffer.read(cx).read(cx).text()
10262    }
10263
10264    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
10265        let text = self.text(cx);
10266        let text = text.trim();
10267
10268        if text.is_empty() {
10269            return None;
10270        }
10271
10272        Some(text.to_string())
10273    }
10274
10275    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
10276        self.transact(cx, |this, cx| {
10277            this.buffer
10278                .read(cx)
10279                .as_singleton()
10280                .expect("you can only call set_text on editors for singleton buffers")
10281                .update(cx, |buffer, cx| buffer.set_text(text, cx));
10282        });
10283    }
10284
10285    pub fn display_text(&self, cx: &mut AppContext) -> String {
10286        self.display_map
10287            .update(cx, |map, cx| map.snapshot(cx))
10288            .text()
10289    }
10290
10291    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
10292        let mut wrap_guides = smallvec::smallvec![];
10293
10294        if self.show_wrap_guides == Some(false) {
10295            return wrap_guides;
10296        }
10297
10298        let settings = self.buffer.read(cx).settings_at(0, cx);
10299        if settings.show_wrap_guides {
10300            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
10301                wrap_guides.push((soft_wrap as usize, true));
10302            }
10303            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
10304        }
10305
10306        wrap_guides
10307    }
10308
10309    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
10310        let settings = self.buffer.read(cx).settings_at(0, cx);
10311        let mode = self
10312            .soft_wrap_mode_override
10313            .unwrap_or_else(|| settings.soft_wrap);
10314        match mode {
10315            language_settings::SoftWrap::None => SoftWrap::None,
10316            language_settings::SoftWrap::PreferLine => SoftWrap::PreferLine,
10317            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
10318            language_settings::SoftWrap::PreferredLineLength => {
10319                SoftWrap::Column(settings.preferred_line_length)
10320            }
10321        }
10322    }
10323
10324    pub fn set_soft_wrap_mode(
10325        &mut self,
10326        mode: language_settings::SoftWrap,
10327        cx: &mut ViewContext<Self>,
10328    ) {
10329        self.soft_wrap_mode_override = Some(mode);
10330        cx.notify();
10331    }
10332
10333    pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
10334        let rem_size = cx.rem_size();
10335        self.display_map.update(cx, |map, cx| {
10336            map.set_font(
10337                style.text.font(),
10338                style.text.font_size.to_pixels(rem_size),
10339                cx,
10340            )
10341        });
10342        self.style = Some(style);
10343    }
10344
10345    pub fn style(&self) -> Option<&EditorStyle> {
10346        self.style.as_ref()
10347    }
10348
10349    // Called by the element. This method is not designed to be called outside of the editor
10350    // element's layout code because it does not notify when rewrapping is computed synchronously.
10351    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
10352        self.display_map
10353            .update(cx, |map, cx| map.set_wrap_width(width, cx))
10354    }
10355
10356    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
10357        if self.soft_wrap_mode_override.is_some() {
10358            self.soft_wrap_mode_override.take();
10359        } else {
10360            let soft_wrap = match self.soft_wrap_mode(cx) {
10361                SoftWrap::None | SoftWrap::PreferLine => language_settings::SoftWrap::EditorWidth,
10362                SoftWrap::EditorWidth | SoftWrap::Column(_) => {
10363                    language_settings::SoftWrap::PreferLine
10364                }
10365            };
10366            self.soft_wrap_mode_override = Some(soft_wrap);
10367        }
10368        cx.notify();
10369    }
10370
10371    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
10372        let Some(workspace) = self.workspace() else {
10373            return;
10374        };
10375        let fs = workspace.read(cx).app_state().fs.clone();
10376        let current_show = TabBarSettings::get_global(cx).show;
10377        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
10378            setting.show = Some(!current_show);
10379        });
10380    }
10381
10382    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
10383        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
10384            self.buffer
10385                .read(cx)
10386                .settings_at(0, cx)
10387                .indent_guides
10388                .enabled
10389        });
10390        self.show_indent_guides = Some(!currently_enabled);
10391        cx.notify();
10392    }
10393
10394    fn should_show_indent_guides(&self) -> Option<bool> {
10395        self.show_indent_guides
10396    }
10397
10398    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
10399        let mut editor_settings = EditorSettings::get_global(cx).clone();
10400        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
10401        EditorSettings::override_global(editor_settings, cx);
10402    }
10403
10404    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
10405        self.show_gutter = show_gutter;
10406        cx.notify();
10407    }
10408
10409    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
10410        self.show_line_numbers = Some(show_line_numbers);
10411        cx.notify();
10412    }
10413
10414    pub fn set_show_git_diff_gutter(
10415        &mut self,
10416        show_git_diff_gutter: bool,
10417        cx: &mut ViewContext<Self>,
10418    ) {
10419        self.show_git_diff_gutter = Some(show_git_diff_gutter);
10420        cx.notify();
10421    }
10422
10423    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
10424        self.show_code_actions = Some(show_code_actions);
10425        cx.notify();
10426    }
10427
10428    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
10429        self.show_runnables = Some(show_runnables);
10430        cx.notify();
10431    }
10432
10433    pub fn set_redact_all(&mut self, redact_all: bool, cx: &mut ViewContext<Self>) {
10434        self.redact_all = redact_all;
10435        cx.notify();
10436    }
10437
10438    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
10439        self.show_wrap_guides = Some(show_wrap_guides);
10440        cx.notify();
10441    }
10442
10443    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
10444        self.show_indent_guides = Some(show_indent_guides);
10445        cx.notify();
10446    }
10447
10448    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
10449        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10450            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10451                if let Some(dir) = file.abs_path(cx).parent() {
10452                    return Some(dir.to_owned());
10453                }
10454            }
10455
10456            if let Some(project_path) = buffer.read(cx).project_path(cx) {
10457                return Some(project_path.path.to_path_buf());
10458            }
10459        }
10460
10461        None
10462    }
10463
10464    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
10465        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10466            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10467                cx.reveal_path(&file.abs_path(cx));
10468            }
10469        }
10470    }
10471
10472    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
10473        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10474            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10475                if let Some(path) = file.abs_path(cx).to_str() {
10476                    cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
10477                }
10478            }
10479        }
10480    }
10481
10482    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
10483        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10484            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10485                if let Some(path) = file.path().to_str() {
10486                    cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
10487                }
10488            }
10489        }
10490    }
10491
10492    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
10493        self.show_git_blame_gutter = !self.show_git_blame_gutter;
10494
10495        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
10496            self.start_git_blame(true, cx);
10497        }
10498
10499        cx.notify();
10500    }
10501
10502    pub fn toggle_git_blame_inline(
10503        &mut self,
10504        _: &ToggleGitBlameInline,
10505        cx: &mut ViewContext<Self>,
10506    ) {
10507        self.toggle_git_blame_inline_internal(true, cx);
10508        cx.notify();
10509    }
10510
10511    pub fn git_blame_inline_enabled(&self) -> bool {
10512        self.git_blame_inline_enabled
10513    }
10514
10515    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
10516        self.show_selection_menu = self
10517            .show_selection_menu
10518            .map(|show_selections_menu| !show_selections_menu)
10519            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
10520
10521        cx.notify();
10522    }
10523
10524    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
10525        self.show_selection_menu
10526            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
10527    }
10528
10529    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10530        if let Some(project) = self.project.as_ref() {
10531            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
10532                return;
10533            };
10534
10535            if buffer.read(cx).file().is_none() {
10536                return;
10537            }
10538
10539            let focused = self.focus_handle(cx).contains_focused(cx);
10540
10541            let project = project.clone();
10542            let blame =
10543                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
10544            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
10545            self.blame = Some(blame);
10546        }
10547    }
10548
10549    fn toggle_git_blame_inline_internal(
10550        &mut self,
10551        user_triggered: bool,
10552        cx: &mut ViewContext<Self>,
10553    ) {
10554        if self.git_blame_inline_enabled {
10555            self.git_blame_inline_enabled = false;
10556            self.show_git_blame_inline = false;
10557            self.show_git_blame_inline_delay_task.take();
10558        } else {
10559            self.git_blame_inline_enabled = true;
10560            self.start_git_blame_inline(user_triggered, cx);
10561        }
10562
10563        cx.notify();
10564    }
10565
10566    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10567        self.start_git_blame(user_triggered, cx);
10568
10569        if ProjectSettings::get_global(cx)
10570            .git
10571            .inline_blame_delay()
10572            .is_some()
10573        {
10574            self.start_inline_blame_timer(cx);
10575        } else {
10576            self.show_git_blame_inline = true
10577        }
10578    }
10579
10580    pub fn blame(&self) -> Option<&Model<GitBlame>> {
10581        self.blame.as_ref()
10582    }
10583
10584    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
10585        self.show_git_blame_gutter && self.has_blame_entries(cx)
10586    }
10587
10588    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
10589        self.show_git_blame_inline
10590            && self.focus_handle.is_focused(cx)
10591            && !self.newest_selection_head_on_empty_line(cx)
10592            && self.has_blame_entries(cx)
10593    }
10594
10595    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
10596        self.blame()
10597            .map_or(false, |blame| blame.read(cx).has_generated_entries())
10598    }
10599
10600    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
10601        let cursor_anchor = self.selections.newest_anchor().head();
10602
10603        let snapshot = self.buffer.read(cx).snapshot(cx);
10604        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
10605
10606        snapshot.line_len(buffer_row) == 0
10607    }
10608
10609    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
10610        let (path, selection, repo) = maybe!({
10611            let project_handle = self.project.as_ref()?.clone();
10612            let project = project_handle.read(cx);
10613
10614            let selection = self.selections.newest::<Point>(cx);
10615            let selection_range = selection.range();
10616
10617            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10618                (buffer, selection_range.start.row..selection_range.end.row)
10619            } else {
10620                let buffer_ranges = self
10621                    .buffer()
10622                    .read(cx)
10623                    .range_to_buffer_ranges(selection_range, cx);
10624
10625                let (buffer, range, _) = if selection.reversed {
10626                    buffer_ranges.first()
10627                } else {
10628                    buffer_ranges.last()
10629                }?;
10630
10631                let snapshot = buffer.read(cx).snapshot();
10632                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
10633                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
10634                (buffer.clone(), selection)
10635            };
10636
10637            let path = buffer
10638                .read(cx)
10639                .file()?
10640                .as_local()?
10641                .path()
10642                .to_str()?
10643                .to_string();
10644            let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
10645            Some((path, selection, repo))
10646        })
10647        .ok_or_else(|| anyhow!("unable to open git repository"))?;
10648
10649        const REMOTE_NAME: &str = "origin";
10650        let origin_url = repo
10651            .remote_url(REMOTE_NAME)
10652            .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
10653        let sha = repo
10654            .head_sha()
10655            .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
10656
10657        let (provider, remote) =
10658            parse_git_remote_url(GitHostingProviderRegistry::default_global(cx), &origin_url)
10659                .ok_or_else(|| anyhow!("failed to parse Git remote URL"))?;
10660
10661        Ok(provider.build_permalink(
10662            remote,
10663            BuildPermalinkParams {
10664                sha: &sha,
10665                path: &path,
10666                selection: Some(selection),
10667            },
10668        ))
10669    }
10670
10671    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
10672        let permalink = self.get_permalink_to_line(cx);
10673
10674        match permalink {
10675            Ok(permalink) => {
10676                cx.write_to_clipboard(ClipboardItem::new(permalink.to_string()));
10677            }
10678            Err(err) => {
10679                let message = format!("Failed to copy permalink: {err}");
10680
10681                Err::<(), anyhow::Error>(err).log_err();
10682
10683                if let Some(workspace) = self.workspace() {
10684                    workspace.update(cx, |workspace, cx| {
10685                        struct CopyPermalinkToLine;
10686
10687                        workspace.show_toast(
10688                            Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
10689                            cx,
10690                        )
10691                    })
10692                }
10693            }
10694        }
10695    }
10696
10697    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
10698        let permalink = self.get_permalink_to_line(cx);
10699
10700        match permalink {
10701            Ok(permalink) => {
10702                cx.open_url(permalink.as_ref());
10703            }
10704            Err(err) => {
10705                let message = format!("Failed to open permalink: {err}");
10706
10707                Err::<(), anyhow::Error>(err).log_err();
10708
10709                if let Some(workspace) = self.workspace() {
10710                    workspace.update(cx, |workspace, cx| {
10711                        struct OpenPermalinkToLine;
10712
10713                        workspace.show_toast(
10714                            Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
10715                            cx,
10716                        )
10717                    })
10718                }
10719            }
10720        }
10721    }
10722
10723    /// Adds or removes (on `None` color) a highlight for the rows corresponding to the anchor range given.
10724    /// On matching anchor range, replaces the old highlight; does not clear the other existing highlights.
10725    /// If multiple anchor ranges will produce highlights for the same row, the last range added will be used.
10726    pub fn highlight_rows<T: 'static>(
10727        &mut self,
10728        rows: RangeInclusive<Anchor>,
10729        color: Option<Hsla>,
10730        should_autoscroll: bool,
10731        cx: &mut ViewContext<Self>,
10732    ) {
10733        let snapshot = self.buffer().read(cx).snapshot(cx);
10734        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
10735        let existing_highlight_index = row_highlights.binary_search_by(|highlight| {
10736            highlight
10737                .range
10738                .start()
10739                .cmp(&rows.start(), &snapshot)
10740                .then(highlight.range.end().cmp(&rows.end(), &snapshot))
10741        });
10742        match (color, existing_highlight_index) {
10743            (Some(_), Ok(ix)) | (_, Err(ix)) => row_highlights.insert(
10744                ix,
10745                RowHighlight {
10746                    index: post_inc(&mut self.highlight_order),
10747                    range: rows,
10748                    should_autoscroll,
10749                    color,
10750                },
10751            ),
10752            (None, Ok(i)) => {
10753                row_highlights.remove(i);
10754            }
10755        }
10756    }
10757
10758    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
10759    pub fn clear_row_highlights<T: 'static>(&mut self) {
10760        self.highlighted_rows.remove(&TypeId::of::<T>());
10761    }
10762
10763    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
10764    pub fn highlighted_rows<T: 'static>(
10765        &self,
10766    ) -> Option<impl Iterator<Item = (&RangeInclusive<Anchor>, Option<&Hsla>)>> {
10767        Some(
10768            self.highlighted_rows
10769                .get(&TypeId::of::<T>())?
10770                .iter()
10771                .map(|highlight| (&highlight.range, highlight.color.as_ref())),
10772        )
10773    }
10774
10775    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
10776    /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
10777    /// Allows to ignore certain kinds of highlights.
10778    pub fn highlighted_display_rows(
10779        &mut self,
10780        cx: &mut WindowContext,
10781    ) -> BTreeMap<DisplayRow, Hsla> {
10782        let snapshot = self.snapshot(cx);
10783        let mut used_highlight_orders = HashMap::default();
10784        self.highlighted_rows
10785            .iter()
10786            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
10787            .fold(
10788                BTreeMap::<DisplayRow, Hsla>::new(),
10789                |mut unique_rows, highlight| {
10790                    let start_row = highlight.range.start().to_display_point(&snapshot).row();
10791                    let end_row = highlight.range.end().to_display_point(&snapshot).row();
10792                    for row in start_row.0..=end_row.0 {
10793                        let used_index =
10794                            used_highlight_orders.entry(row).or_insert(highlight.index);
10795                        if highlight.index >= *used_index {
10796                            *used_index = highlight.index;
10797                            match highlight.color {
10798                                Some(hsla) => unique_rows.insert(DisplayRow(row), hsla),
10799                                None => unique_rows.remove(&DisplayRow(row)),
10800                            };
10801                        }
10802                    }
10803                    unique_rows
10804                },
10805            )
10806    }
10807
10808    pub fn highlighted_display_row_for_autoscroll(
10809        &self,
10810        snapshot: &DisplaySnapshot,
10811    ) -> Option<DisplayRow> {
10812        self.highlighted_rows
10813            .values()
10814            .flat_map(|highlighted_rows| highlighted_rows.iter())
10815            .filter_map(|highlight| {
10816                if highlight.color.is_none() || !highlight.should_autoscroll {
10817                    return None;
10818                }
10819                Some(highlight.range.start().to_display_point(&snapshot).row())
10820            })
10821            .min()
10822    }
10823
10824    pub fn set_search_within_ranges(
10825        &mut self,
10826        ranges: &[Range<Anchor>],
10827        cx: &mut ViewContext<Self>,
10828    ) {
10829        self.highlight_background::<SearchWithinRange>(
10830            ranges,
10831            |colors| colors.editor_document_highlight_read_background,
10832            cx,
10833        )
10834    }
10835
10836    pub fn set_breadcrumb_header(&mut self, new_header: String) {
10837        self.breadcrumb_header = Some(new_header);
10838    }
10839
10840    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
10841        self.clear_background_highlights::<SearchWithinRange>(cx);
10842    }
10843
10844    pub fn highlight_background<T: 'static>(
10845        &mut self,
10846        ranges: &[Range<Anchor>],
10847        color_fetcher: fn(&ThemeColors) -> Hsla,
10848        cx: &mut ViewContext<Self>,
10849    ) {
10850        self.background_highlights
10851            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
10852        self.scrollbar_marker_state.dirty = true;
10853        cx.notify();
10854    }
10855
10856    pub fn clear_background_highlights<T: 'static>(
10857        &mut self,
10858        cx: &mut ViewContext<Self>,
10859    ) -> Option<BackgroundHighlight> {
10860        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
10861        if !text_highlights.1.is_empty() {
10862            self.scrollbar_marker_state.dirty = true;
10863            cx.notify();
10864        }
10865        Some(text_highlights)
10866    }
10867
10868    pub fn highlight_gutter<T: 'static>(
10869        &mut self,
10870        ranges: &[Range<Anchor>],
10871        color_fetcher: fn(&AppContext) -> Hsla,
10872        cx: &mut ViewContext<Self>,
10873    ) {
10874        self.gutter_highlights
10875            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
10876        cx.notify();
10877    }
10878
10879    pub fn clear_gutter_highlights<T: 'static>(
10880        &mut self,
10881        cx: &mut ViewContext<Self>,
10882    ) -> Option<GutterHighlight> {
10883        cx.notify();
10884        self.gutter_highlights.remove(&TypeId::of::<T>())
10885    }
10886
10887    #[cfg(feature = "test-support")]
10888    pub fn all_text_background_highlights(
10889        &mut self,
10890        cx: &mut ViewContext<Self>,
10891    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
10892        let snapshot = self.snapshot(cx);
10893        let buffer = &snapshot.buffer_snapshot;
10894        let start = buffer.anchor_before(0);
10895        let end = buffer.anchor_after(buffer.len());
10896        let theme = cx.theme().colors();
10897        self.background_highlights_in_range(start..end, &snapshot, theme)
10898    }
10899
10900    #[cfg(feature = "test-support")]
10901    pub fn search_background_highlights(
10902        &mut self,
10903        cx: &mut ViewContext<Self>,
10904    ) -> Vec<Range<Point>> {
10905        let snapshot = self.buffer().read(cx).snapshot(cx);
10906
10907        let highlights = self
10908            .background_highlights
10909            .get(&TypeId::of::<items::BufferSearchHighlights>());
10910
10911        if let Some((_color, ranges)) = highlights {
10912            ranges
10913                .iter()
10914                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
10915                .collect_vec()
10916        } else {
10917            vec![]
10918        }
10919    }
10920
10921    fn document_highlights_for_position<'a>(
10922        &'a self,
10923        position: Anchor,
10924        buffer: &'a MultiBufferSnapshot,
10925    ) -> impl 'a + Iterator<Item = &Range<Anchor>> {
10926        let read_highlights = self
10927            .background_highlights
10928            .get(&TypeId::of::<DocumentHighlightRead>())
10929            .map(|h| &h.1);
10930        let write_highlights = self
10931            .background_highlights
10932            .get(&TypeId::of::<DocumentHighlightWrite>())
10933            .map(|h| &h.1);
10934        let left_position = position.bias_left(buffer);
10935        let right_position = position.bias_right(buffer);
10936        read_highlights
10937            .into_iter()
10938            .chain(write_highlights)
10939            .flat_map(move |ranges| {
10940                let start_ix = match ranges.binary_search_by(|probe| {
10941                    let cmp = probe.end.cmp(&left_position, buffer);
10942                    if cmp.is_ge() {
10943                        Ordering::Greater
10944                    } else {
10945                        Ordering::Less
10946                    }
10947                }) {
10948                    Ok(i) | Err(i) => i,
10949                };
10950
10951                ranges[start_ix..]
10952                    .iter()
10953                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
10954            })
10955    }
10956
10957    pub fn has_background_highlights<T: 'static>(&self) -> bool {
10958        self.background_highlights
10959            .get(&TypeId::of::<T>())
10960            .map_or(false, |(_, highlights)| !highlights.is_empty())
10961    }
10962
10963    pub fn background_highlights_in_range(
10964        &self,
10965        search_range: Range<Anchor>,
10966        display_snapshot: &DisplaySnapshot,
10967        theme: &ThemeColors,
10968    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
10969        let mut results = Vec::new();
10970        for (color_fetcher, ranges) in self.background_highlights.values() {
10971            let color = color_fetcher(theme);
10972            let start_ix = match ranges.binary_search_by(|probe| {
10973                let cmp = probe
10974                    .end
10975                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
10976                if cmp.is_gt() {
10977                    Ordering::Greater
10978                } else {
10979                    Ordering::Less
10980                }
10981            }) {
10982                Ok(i) | Err(i) => i,
10983            };
10984            for range in &ranges[start_ix..] {
10985                if range
10986                    .start
10987                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
10988                    .is_ge()
10989                {
10990                    break;
10991                }
10992
10993                let start = range.start.to_display_point(&display_snapshot);
10994                let end = range.end.to_display_point(&display_snapshot);
10995                results.push((start..end, color))
10996            }
10997        }
10998        results
10999    }
11000
11001    pub fn background_highlight_row_ranges<T: 'static>(
11002        &self,
11003        search_range: Range<Anchor>,
11004        display_snapshot: &DisplaySnapshot,
11005        count: usize,
11006    ) -> Vec<RangeInclusive<DisplayPoint>> {
11007        let mut results = Vec::new();
11008        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11009            return vec![];
11010        };
11011
11012        let start_ix = match ranges.binary_search_by(|probe| {
11013            let cmp = probe
11014                .end
11015                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11016            if cmp.is_gt() {
11017                Ordering::Greater
11018            } else {
11019                Ordering::Less
11020            }
11021        }) {
11022            Ok(i) | Err(i) => i,
11023        };
11024        let mut push_region = |start: Option<Point>, end: Option<Point>| {
11025            if let (Some(start_display), Some(end_display)) = (start, end) {
11026                results.push(
11027                    start_display.to_display_point(display_snapshot)
11028                        ..=end_display.to_display_point(display_snapshot),
11029                );
11030            }
11031        };
11032        let mut start_row: Option<Point> = None;
11033        let mut end_row: Option<Point> = None;
11034        if ranges.len() > count {
11035            return Vec::new();
11036        }
11037        for range in &ranges[start_ix..] {
11038            if range
11039                .start
11040                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11041                .is_ge()
11042            {
11043                break;
11044            }
11045            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
11046            if let Some(current_row) = &end_row {
11047                if end.row == current_row.row {
11048                    continue;
11049                }
11050            }
11051            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
11052            if start_row.is_none() {
11053                assert_eq!(end_row, None);
11054                start_row = Some(start);
11055                end_row = Some(end);
11056                continue;
11057            }
11058            if let Some(current_end) = end_row.as_mut() {
11059                if start.row > current_end.row + 1 {
11060                    push_region(start_row, end_row);
11061                    start_row = Some(start);
11062                    end_row = Some(end);
11063                } else {
11064                    // Merge two hunks.
11065                    *current_end = end;
11066                }
11067            } else {
11068                unreachable!();
11069            }
11070        }
11071        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
11072        push_region(start_row, end_row);
11073        results
11074    }
11075
11076    pub fn gutter_highlights_in_range(
11077        &self,
11078        search_range: Range<Anchor>,
11079        display_snapshot: &DisplaySnapshot,
11080        cx: &AppContext,
11081    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11082        let mut results = Vec::new();
11083        for (color_fetcher, ranges) in self.gutter_highlights.values() {
11084            let color = color_fetcher(cx);
11085            let start_ix = match ranges.binary_search_by(|probe| {
11086                let cmp = probe
11087                    .end
11088                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11089                if cmp.is_gt() {
11090                    Ordering::Greater
11091                } else {
11092                    Ordering::Less
11093                }
11094            }) {
11095                Ok(i) | Err(i) => i,
11096            };
11097            for range in &ranges[start_ix..] {
11098                if range
11099                    .start
11100                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11101                    .is_ge()
11102                {
11103                    break;
11104                }
11105
11106                let start = range.start.to_display_point(&display_snapshot);
11107                let end = range.end.to_display_point(&display_snapshot);
11108                results.push((start..end, color))
11109            }
11110        }
11111        results
11112    }
11113
11114    /// Get the text ranges corresponding to the redaction query
11115    pub fn redacted_ranges(
11116        &self,
11117        search_range: Range<Anchor>,
11118        display_snapshot: &DisplaySnapshot,
11119        cx: &WindowContext,
11120    ) -> Vec<Range<DisplayPoint>> {
11121        if self.redact_all {
11122            return vec![DisplayPoint::zero()..display_snapshot.max_point()];
11123        }
11124
11125        display_snapshot
11126            .buffer_snapshot
11127            .redacted_ranges(search_range, |file| {
11128                if let Some(file) = file {
11129                    file.is_private()
11130                        && EditorSettings::get(Some(file.as_ref().into()), cx).redact_private_values
11131                } else {
11132                    false
11133                }
11134            })
11135            .map(|range| {
11136                range.start.to_display_point(display_snapshot)
11137                    ..range.end.to_display_point(display_snapshot)
11138            })
11139            .collect()
11140    }
11141
11142    pub fn highlight_text<T: 'static>(
11143        &mut self,
11144        ranges: Vec<Range<Anchor>>,
11145        style: HighlightStyle,
11146        cx: &mut ViewContext<Self>,
11147    ) {
11148        self.display_map.update(cx, |map, _| {
11149            map.highlight_text(TypeId::of::<T>(), ranges, style)
11150        });
11151        cx.notify();
11152    }
11153
11154    pub(crate) fn highlight_inlays<T: 'static>(
11155        &mut self,
11156        highlights: Vec<InlayHighlight>,
11157        style: HighlightStyle,
11158        cx: &mut ViewContext<Self>,
11159    ) {
11160        self.display_map.update(cx, |map, _| {
11161            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
11162        });
11163        cx.notify();
11164    }
11165
11166    pub fn text_highlights<'a, T: 'static>(
11167        &'a self,
11168        cx: &'a AppContext,
11169    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
11170        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
11171    }
11172
11173    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
11174        let cleared = self
11175            .display_map
11176            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
11177        if cleared {
11178            cx.notify();
11179        }
11180    }
11181
11182    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
11183        (self.read_only(cx) || self.blink_manager.read(cx).visible())
11184            && self.focus_handle.is_focused(cx)
11185    }
11186
11187    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
11188        self.show_cursor_when_unfocused = is_enabled;
11189        cx.notify();
11190    }
11191
11192    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
11193        cx.notify();
11194    }
11195
11196    fn on_buffer_event(
11197        &mut self,
11198        multibuffer: Model<MultiBuffer>,
11199        event: &multi_buffer::Event,
11200        cx: &mut ViewContext<Self>,
11201    ) {
11202        match event {
11203            multi_buffer::Event::Edited {
11204                singleton_buffer_edited,
11205            } => {
11206                self.scrollbar_marker_state.dirty = true;
11207                self.active_indent_guides_state.dirty = true;
11208                self.refresh_active_diagnostics(cx);
11209                self.refresh_code_actions(cx);
11210                if self.has_active_inline_completion(cx) {
11211                    self.update_visible_inline_completion(cx);
11212                }
11213                cx.emit(EditorEvent::BufferEdited);
11214                cx.emit(SearchEvent::MatchesInvalidated);
11215                if *singleton_buffer_edited {
11216                    if let Some(project) = &self.project {
11217                        let project = project.read(cx);
11218                        #[allow(clippy::mutable_key_type)]
11219                        let languages_affected = multibuffer
11220                            .read(cx)
11221                            .all_buffers()
11222                            .into_iter()
11223                            .filter_map(|buffer| {
11224                                let buffer = buffer.read(cx);
11225                                let language = buffer.language()?;
11226                                if project.is_local()
11227                                    && project.language_servers_for_buffer(buffer, cx).count() == 0
11228                                {
11229                                    None
11230                                } else {
11231                                    Some(language)
11232                                }
11233                            })
11234                            .cloned()
11235                            .collect::<HashSet<_>>();
11236                        if !languages_affected.is_empty() {
11237                            self.refresh_inlay_hints(
11238                                InlayHintRefreshReason::BufferEdited(languages_affected),
11239                                cx,
11240                            );
11241                        }
11242                    }
11243                }
11244
11245                let Some(project) = &self.project else { return };
11246                let telemetry = project.read(cx).client().telemetry().clone();
11247                refresh_linked_ranges(self, cx);
11248                telemetry.log_edit_event("editor");
11249            }
11250            multi_buffer::Event::ExcerptsAdded {
11251                buffer,
11252                predecessor,
11253                excerpts,
11254            } => {
11255                self.tasks_update_task = Some(self.refresh_runnables(cx));
11256                cx.emit(EditorEvent::ExcerptsAdded {
11257                    buffer: buffer.clone(),
11258                    predecessor: *predecessor,
11259                    excerpts: excerpts.clone(),
11260                });
11261                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
11262            }
11263            multi_buffer::Event::ExcerptsRemoved { ids } => {
11264                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
11265                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
11266            }
11267            multi_buffer::Event::ExcerptsEdited { ids } => {
11268                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
11269            }
11270            multi_buffer::Event::ExcerptsExpanded { ids } => {
11271                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
11272            }
11273            multi_buffer::Event::Reparsed(buffer_id) => {
11274                self.tasks_update_task = Some(self.refresh_runnables(cx));
11275
11276                cx.emit(EditorEvent::Reparsed(*buffer_id));
11277            }
11278            multi_buffer::Event::LanguageChanged(buffer_id) => {
11279                linked_editing_ranges::refresh_linked_ranges(self, cx);
11280                cx.emit(EditorEvent::Reparsed(*buffer_id));
11281                cx.notify();
11282            }
11283            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
11284            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
11285            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
11286                cx.emit(EditorEvent::TitleChanged)
11287            }
11288            multi_buffer::Event::DiffBaseChanged => {
11289                self.scrollbar_marker_state.dirty = true;
11290                cx.emit(EditorEvent::DiffBaseChanged);
11291                cx.notify();
11292            }
11293            multi_buffer::Event::DiffUpdated { buffer } => {
11294                self.sync_expanded_diff_hunks(buffer.clone(), cx);
11295                cx.notify();
11296            }
11297            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
11298            multi_buffer::Event::DiagnosticsUpdated => {
11299                self.refresh_active_diagnostics(cx);
11300                self.scrollbar_marker_state.dirty = true;
11301                cx.notify();
11302            }
11303            _ => {}
11304        };
11305    }
11306
11307    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
11308        cx.notify();
11309    }
11310
11311    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
11312        self.tasks_update_task = Some(self.refresh_runnables(cx));
11313        self.refresh_inline_completion(true, cx);
11314        self.refresh_inlay_hints(
11315            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
11316                self.selections.newest_anchor().head(),
11317                &self.buffer.read(cx).snapshot(cx),
11318                cx,
11319            )),
11320            cx,
11321        );
11322        let editor_settings = EditorSettings::get_global(cx);
11323        self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
11324        self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
11325
11326        let project_settings = ProjectSettings::get_global(cx);
11327        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
11328
11329        if self.mode == EditorMode::Full {
11330            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
11331            if self.git_blame_inline_enabled != inline_blame_enabled {
11332                self.toggle_git_blame_inline_internal(false, cx);
11333            }
11334        }
11335
11336        cx.notify();
11337    }
11338
11339    pub fn set_searchable(&mut self, searchable: bool) {
11340        self.searchable = searchable;
11341    }
11342
11343    pub fn searchable(&self) -> bool {
11344        self.searchable
11345    }
11346
11347    fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
11348        self.open_excerpts_common(true, cx)
11349    }
11350
11351    fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
11352        self.open_excerpts_common(false, cx)
11353    }
11354
11355    fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
11356        let buffer = self.buffer.read(cx);
11357        if buffer.is_singleton() {
11358            cx.propagate();
11359            return;
11360        }
11361
11362        let Some(workspace) = self.workspace() else {
11363            cx.propagate();
11364            return;
11365        };
11366
11367        let mut new_selections_by_buffer = HashMap::default();
11368        for selection in self.selections.all::<usize>(cx) {
11369            for (buffer, mut range, _) in
11370                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
11371            {
11372                if selection.reversed {
11373                    mem::swap(&mut range.start, &mut range.end);
11374                }
11375                new_selections_by_buffer
11376                    .entry(buffer)
11377                    .or_insert(Vec::new())
11378                    .push(range)
11379            }
11380        }
11381
11382        // We defer the pane interaction because we ourselves are a workspace item
11383        // and activating a new item causes the pane to call a method on us reentrantly,
11384        // which panics if we're on the stack.
11385        cx.window_context().defer(move |cx| {
11386            workspace.update(cx, |workspace, cx| {
11387                let pane = if split {
11388                    workspace.adjacent_pane(cx)
11389                } else {
11390                    workspace.active_pane().clone()
11391                };
11392
11393                for (buffer, ranges) in new_selections_by_buffer {
11394                    let editor =
11395                        workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
11396                    editor.update(cx, |editor, cx| {
11397                        editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
11398                            s.select_ranges(ranges);
11399                        });
11400                    });
11401                }
11402            })
11403        });
11404    }
11405
11406    fn jump(
11407        &mut self,
11408        path: ProjectPath,
11409        position: Point,
11410        anchor: language::Anchor,
11411        offset_from_top: u32,
11412        cx: &mut ViewContext<Self>,
11413    ) {
11414        let workspace = self.workspace();
11415        cx.spawn(|_, mut cx| async move {
11416            let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
11417            let editor = workspace.update(&mut cx, |workspace, cx| {
11418                // Reset the preview item id before opening the new item
11419                workspace.active_pane().update(cx, |pane, cx| {
11420                    pane.set_preview_item_id(None, cx);
11421                });
11422                workspace.open_path_preview(path, None, true, true, cx)
11423            })?;
11424            let editor = editor
11425                .await?
11426                .downcast::<Editor>()
11427                .ok_or_else(|| anyhow!("opened item was not an editor"))?
11428                .downgrade();
11429            editor.update(&mut cx, |editor, cx| {
11430                let buffer = editor
11431                    .buffer()
11432                    .read(cx)
11433                    .as_singleton()
11434                    .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
11435                let buffer = buffer.read(cx);
11436                let cursor = if buffer.can_resolve(&anchor) {
11437                    language::ToPoint::to_point(&anchor, buffer)
11438                } else {
11439                    buffer.clip_point(position, Bias::Left)
11440                };
11441
11442                let nav_history = editor.nav_history.take();
11443                editor.change_selections(
11444                    Some(Autoscroll::top_relative(offset_from_top as usize)),
11445                    cx,
11446                    |s| {
11447                        s.select_ranges([cursor..cursor]);
11448                    },
11449                );
11450                editor.nav_history = nav_history;
11451
11452                anyhow::Ok(())
11453            })??;
11454
11455            anyhow::Ok(())
11456        })
11457        .detach_and_log_err(cx);
11458    }
11459
11460    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
11461        let snapshot = self.buffer.read(cx).read(cx);
11462        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
11463        Some(
11464            ranges
11465                .iter()
11466                .map(move |range| {
11467                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
11468                })
11469                .collect(),
11470        )
11471    }
11472
11473    fn selection_replacement_ranges(
11474        &self,
11475        range: Range<OffsetUtf16>,
11476        cx: &AppContext,
11477    ) -> Vec<Range<OffsetUtf16>> {
11478        let selections = self.selections.all::<OffsetUtf16>(cx);
11479        let newest_selection = selections
11480            .iter()
11481            .max_by_key(|selection| selection.id)
11482            .unwrap();
11483        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
11484        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
11485        let snapshot = self.buffer.read(cx).read(cx);
11486        selections
11487            .into_iter()
11488            .map(|mut selection| {
11489                selection.start.0 =
11490                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
11491                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
11492                snapshot.clip_offset_utf16(selection.start, Bias::Left)
11493                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
11494            })
11495            .collect()
11496    }
11497
11498    fn report_editor_event(
11499        &self,
11500        operation: &'static str,
11501        file_extension: Option<String>,
11502        cx: &AppContext,
11503    ) {
11504        if cfg!(any(test, feature = "test-support")) {
11505            return;
11506        }
11507
11508        let Some(project) = &self.project else { return };
11509
11510        // If None, we are in a file without an extension
11511        let file = self
11512            .buffer
11513            .read(cx)
11514            .as_singleton()
11515            .and_then(|b| b.read(cx).file());
11516        let file_extension = file_extension.or(file
11517            .as_ref()
11518            .and_then(|file| Path::new(file.file_name(cx)).extension())
11519            .and_then(|e| e.to_str())
11520            .map(|a| a.to_string()));
11521
11522        let vim_mode = cx
11523            .global::<SettingsStore>()
11524            .raw_user_settings()
11525            .get("vim_mode")
11526            == Some(&serde_json::Value::Bool(true));
11527
11528        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
11529            == language::language_settings::InlineCompletionProvider::Copilot;
11530        let copilot_enabled_for_language = self
11531            .buffer
11532            .read(cx)
11533            .settings_at(0, cx)
11534            .show_inline_completions;
11535
11536        let telemetry = project.read(cx).client().telemetry().clone();
11537        telemetry.report_editor_event(
11538            file_extension,
11539            vim_mode,
11540            operation,
11541            copilot_enabled,
11542            copilot_enabled_for_language,
11543        )
11544    }
11545
11546    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
11547    /// with each line being an array of {text, highlight} objects.
11548    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
11549        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
11550            return;
11551        };
11552
11553        #[derive(Serialize)]
11554        struct Chunk<'a> {
11555            text: String,
11556            highlight: Option<&'a str>,
11557        }
11558
11559        let snapshot = buffer.read(cx).snapshot();
11560        let range = self
11561            .selected_text_range(cx)
11562            .and_then(|selected_range| {
11563                if selected_range.is_empty() {
11564                    None
11565                } else {
11566                    Some(selected_range)
11567                }
11568            })
11569            .unwrap_or_else(|| 0..snapshot.len());
11570
11571        let chunks = snapshot.chunks(range, true);
11572        let mut lines = Vec::new();
11573        let mut line: VecDeque<Chunk> = VecDeque::new();
11574
11575        let Some(style) = self.style.as_ref() else {
11576            return;
11577        };
11578
11579        for chunk in chunks {
11580            let highlight = chunk
11581                .syntax_highlight_id
11582                .and_then(|id| id.name(&style.syntax));
11583            let mut chunk_lines = chunk.text.split('\n').peekable();
11584            while let Some(text) = chunk_lines.next() {
11585                let mut merged_with_last_token = false;
11586                if let Some(last_token) = line.back_mut() {
11587                    if last_token.highlight == highlight {
11588                        last_token.text.push_str(text);
11589                        merged_with_last_token = true;
11590                    }
11591                }
11592
11593                if !merged_with_last_token {
11594                    line.push_back(Chunk {
11595                        text: text.into(),
11596                        highlight,
11597                    });
11598                }
11599
11600                if chunk_lines.peek().is_some() {
11601                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
11602                        line.pop_front();
11603                    }
11604                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
11605                        line.pop_back();
11606                    }
11607
11608                    lines.push(mem::take(&mut line));
11609                }
11610            }
11611        }
11612
11613        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
11614            return;
11615        };
11616        cx.write_to_clipboard(ClipboardItem::new(lines));
11617    }
11618
11619    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
11620        &self.inlay_hint_cache
11621    }
11622
11623    pub fn replay_insert_event(
11624        &mut self,
11625        text: &str,
11626        relative_utf16_range: Option<Range<isize>>,
11627        cx: &mut ViewContext<Self>,
11628    ) {
11629        if !self.input_enabled {
11630            cx.emit(EditorEvent::InputIgnored { text: text.into() });
11631            return;
11632        }
11633        if let Some(relative_utf16_range) = relative_utf16_range {
11634            let selections = self.selections.all::<OffsetUtf16>(cx);
11635            self.change_selections(None, cx, |s| {
11636                let new_ranges = selections.into_iter().map(|range| {
11637                    let start = OffsetUtf16(
11638                        range
11639                            .head()
11640                            .0
11641                            .saturating_add_signed(relative_utf16_range.start),
11642                    );
11643                    let end = OffsetUtf16(
11644                        range
11645                            .head()
11646                            .0
11647                            .saturating_add_signed(relative_utf16_range.end),
11648                    );
11649                    start..end
11650                });
11651                s.select_ranges(new_ranges);
11652            });
11653        }
11654
11655        self.handle_input(text, cx);
11656    }
11657
11658    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
11659        let Some(project) = self.project.as_ref() else {
11660            return false;
11661        };
11662        let project = project.read(cx);
11663
11664        let mut supports = false;
11665        self.buffer().read(cx).for_each_buffer(|buffer| {
11666            if !supports {
11667                supports = project
11668                    .language_servers_for_buffer(buffer.read(cx), cx)
11669                    .any(
11670                        |(_, server)| match server.capabilities().inlay_hint_provider {
11671                            Some(lsp::OneOf::Left(enabled)) => enabled,
11672                            Some(lsp::OneOf::Right(_)) => true,
11673                            None => false,
11674                        },
11675                    )
11676            }
11677        });
11678        supports
11679    }
11680
11681    pub fn focus(&self, cx: &mut WindowContext) {
11682        cx.focus(&self.focus_handle)
11683    }
11684
11685    pub fn is_focused(&self, cx: &WindowContext) -> bool {
11686        self.focus_handle.is_focused(cx)
11687    }
11688
11689    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
11690        cx.emit(EditorEvent::Focused);
11691
11692        if let Some(descendant) = self
11693            .last_focused_descendant
11694            .take()
11695            .and_then(|descendant| descendant.upgrade())
11696        {
11697            cx.focus(&descendant);
11698        } else {
11699            if let Some(blame) = self.blame.as_ref() {
11700                blame.update(cx, GitBlame::focus)
11701            }
11702
11703            self.blink_manager.update(cx, BlinkManager::enable);
11704            self.show_cursor_names(cx);
11705            self.buffer.update(cx, |buffer, cx| {
11706                buffer.finalize_last_transaction(cx);
11707                if self.leader_peer_id.is_none() {
11708                    buffer.set_active_selections(
11709                        &self.selections.disjoint_anchors(),
11710                        self.selections.line_mode,
11711                        self.cursor_shape,
11712                        cx,
11713                    );
11714                }
11715            });
11716        }
11717    }
11718
11719    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
11720        cx.emit(EditorEvent::FocusedIn)
11721    }
11722
11723    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
11724        if event.blurred != self.focus_handle {
11725            self.last_focused_descendant = Some(event.blurred);
11726        }
11727    }
11728
11729    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
11730        self.blink_manager.update(cx, BlinkManager::disable);
11731        self.buffer
11732            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
11733
11734        if let Some(blame) = self.blame.as_ref() {
11735            blame.update(cx, GitBlame::blur)
11736        }
11737        if !self.hover_state.focused(cx) {
11738            hide_hover(self, cx);
11739        }
11740
11741        self.hide_context_menu(cx);
11742        cx.emit(EditorEvent::Blurred);
11743        cx.notify();
11744    }
11745
11746    pub fn register_action<A: Action>(
11747        &mut self,
11748        listener: impl Fn(&A, &mut WindowContext) + 'static,
11749    ) -> Subscription {
11750        let id = self.next_editor_action_id.post_inc();
11751        let listener = Arc::new(listener);
11752        self.editor_actions.borrow_mut().insert(
11753            id,
11754            Box::new(move |cx| {
11755                let _view = cx.view().clone();
11756                let cx = cx.window_context();
11757                let listener = listener.clone();
11758                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
11759                    let action = action.downcast_ref().unwrap();
11760                    if phase == DispatchPhase::Bubble {
11761                        listener(action, cx)
11762                    }
11763                })
11764            }),
11765        );
11766
11767        let editor_actions = self.editor_actions.clone();
11768        Subscription::new(move || {
11769            editor_actions.borrow_mut().remove(&id);
11770        })
11771    }
11772
11773    pub fn file_header_size(&self) -> u8 {
11774        self.file_header_size
11775    }
11776
11777    pub fn revert(
11778        &mut self,
11779        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
11780        cx: &mut ViewContext<Self>,
11781    ) {
11782        self.buffer().update(cx, |multi_buffer, cx| {
11783            for (buffer_id, changes) in revert_changes {
11784                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
11785                    buffer.update(cx, |buffer, cx| {
11786                        buffer.edit(
11787                            changes.into_iter().map(|(range, text)| {
11788                                (range, text.to_string().map(Arc::<str>::from))
11789                            }),
11790                            None,
11791                            cx,
11792                        );
11793                    });
11794                }
11795            }
11796        });
11797        self.change_selections(None, cx, |selections| selections.refresh());
11798    }
11799
11800    pub fn to_pixel_point(
11801        &mut self,
11802        source: multi_buffer::Anchor,
11803        editor_snapshot: &EditorSnapshot,
11804        cx: &mut ViewContext<Self>,
11805    ) -> Option<gpui::Point<Pixels>> {
11806        let text_layout_details = self.text_layout_details(cx);
11807        let line_height = text_layout_details
11808            .editor_style
11809            .text
11810            .line_height_in_pixels(cx.rem_size());
11811        let source_point = source.to_display_point(editor_snapshot);
11812        let first_visible_line = text_layout_details
11813            .scroll_anchor
11814            .anchor
11815            .to_display_point(editor_snapshot);
11816        if first_visible_line > source_point {
11817            return None;
11818        }
11819        let source_x = editor_snapshot.x_for_display_point(source_point, &text_layout_details);
11820        let source_y = line_height
11821            * ((source_point.row() - first_visible_line.row()).0 as f32
11822                - text_layout_details.scroll_anchor.offset.y);
11823        Some(gpui::Point::new(source_x, source_y))
11824    }
11825
11826    pub fn display_to_pixel_point(
11827        &mut self,
11828        source: DisplayPoint,
11829        editor_snapshot: &EditorSnapshot,
11830        cx: &mut ViewContext<Self>,
11831    ) -> Option<gpui::Point<Pixels>> {
11832        let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
11833        let text_layout_details = self.text_layout_details(cx);
11834        let first_visible_line = text_layout_details
11835            .scroll_anchor
11836            .anchor
11837            .to_display_point(editor_snapshot);
11838        if first_visible_line > source {
11839            return None;
11840        }
11841        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
11842        let source_y = line_height * (source.row() - first_visible_line.row()).0 as f32;
11843        Some(gpui::Point::new(source_x, source_y))
11844    }
11845
11846    fn gutter_bounds(&self) -> Option<Bounds<Pixels>> {
11847        let bounds = self.last_bounds?;
11848        Some(element::gutter_bounds(bounds, self.gutter_dimensions))
11849    }
11850}
11851
11852fn hunks_for_selections(
11853    multi_buffer_snapshot: &MultiBufferSnapshot,
11854    selections: &[Selection<Anchor>],
11855) -> Vec<DiffHunk<MultiBufferRow>> {
11856    let buffer_rows_for_selections = selections.iter().map(|selection| {
11857        let head = selection.head();
11858        let tail = selection.tail();
11859        let start = MultiBufferRow(tail.to_point(&multi_buffer_snapshot).row);
11860        let end = MultiBufferRow(head.to_point(&multi_buffer_snapshot).row);
11861        if start > end {
11862            end..start
11863        } else {
11864            start..end
11865        }
11866    });
11867
11868    hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
11869}
11870
11871pub fn hunks_for_rows(
11872    rows: impl Iterator<Item = Range<MultiBufferRow>>,
11873    multi_buffer_snapshot: &MultiBufferSnapshot,
11874) -> Vec<DiffHunk<MultiBufferRow>> {
11875    let mut hunks = Vec::new();
11876    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
11877        HashMap::default();
11878    for selected_multi_buffer_rows in rows {
11879        let query_rows =
11880            selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
11881        for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
11882            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
11883            // when the caret is just above or just below the deleted hunk.
11884            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
11885            let related_to_selection = if allow_adjacent {
11886                hunk.associated_range.overlaps(&query_rows)
11887                    || hunk.associated_range.start == query_rows.end
11888                    || hunk.associated_range.end == query_rows.start
11889            } else {
11890                // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
11891                // `hunk.associated_range` is exclusive (e.g. [2..3] means 2nd row is selected)
11892                hunk.associated_range.overlaps(&selected_multi_buffer_rows)
11893                    || selected_multi_buffer_rows.end == hunk.associated_range.start
11894            };
11895            if related_to_selection {
11896                if !processed_buffer_rows
11897                    .entry(hunk.buffer_id)
11898                    .or_default()
11899                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
11900                {
11901                    continue;
11902                }
11903                hunks.push(hunk);
11904            }
11905        }
11906    }
11907
11908    hunks
11909}
11910
11911pub trait CollaborationHub {
11912    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
11913    fn user_participant_indices<'a>(
11914        &self,
11915        cx: &'a AppContext,
11916    ) -> &'a HashMap<u64, ParticipantIndex>;
11917    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
11918}
11919
11920impl CollaborationHub for Model<Project> {
11921    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
11922        self.read(cx).collaborators()
11923    }
11924
11925    fn user_participant_indices<'a>(
11926        &self,
11927        cx: &'a AppContext,
11928    ) -> &'a HashMap<u64, ParticipantIndex> {
11929        self.read(cx).user_store().read(cx).participant_indices()
11930    }
11931
11932    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
11933        let this = self.read(cx);
11934        let user_ids = this.collaborators().values().map(|c| c.user_id);
11935        this.user_store().read_with(cx, |user_store, cx| {
11936            user_store.participant_names(user_ids, cx)
11937        })
11938    }
11939}
11940
11941pub trait CompletionProvider {
11942    fn completions(
11943        &self,
11944        buffer: &Model<Buffer>,
11945        buffer_position: text::Anchor,
11946        trigger: CompletionContext,
11947        cx: &mut ViewContext<Editor>,
11948    ) -> Task<Result<Vec<Completion>>>;
11949
11950    fn resolve_completions(
11951        &self,
11952        buffer: Model<Buffer>,
11953        completion_indices: Vec<usize>,
11954        completions: Arc<RwLock<Box<[Completion]>>>,
11955        cx: &mut ViewContext<Editor>,
11956    ) -> Task<Result<bool>>;
11957
11958    fn apply_additional_edits_for_completion(
11959        &self,
11960        buffer: Model<Buffer>,
11961        completion: Completion,
11962        push_to_history: bool,
11963        cx: &mut ViewContext<Editor>,
11964    ) -> Task<Result<Option<language::Transaction>>>;
11965
11966    fn is_completion_trigger(
11967        &self,
11968        buffer: &Model<Buffer>,
11969        position: language::Anchor,
11970        text: &str,
11971        trigger_in_words: bool,
11972        cx: &mut ViewContext<Editor>,
11973    ) -> bool;
11974}
11975
11976fn snippet_completions(
11977    project: &Project,
11978    buffer: &Model<Buffer>,
11979    buffer_position: text::Anchor,
11980    cx: &mut AppContext,
11981) -> Vec<Completion> {
11982    let language = buffer.read(cx).language_at(buffer_position);
11983    let language_name = language.as_ref().map(|language| language.lsp_id());
11984    let snippet_store = project.snippets().read(cx);
11985    let snippets = snippet_store.snippets_for(language_name, cx);
11986
11987    if snippets.is_empty() {
11988        return vec![];
11989    }
11990    let snapshot = buffer.read(cx).text_snapshot();
11991    let chunks = snapshot.reversed_chunks_in_range(text::Anchor::MIN..buffer_position);
11992
11993    let mut lines = chunks.lines();
11994    let Some(line_at) = lines.next().filter(|line| !line.is_empty()) else {
11995        return vec![];
11996    };
11997
11998    let scope = language.map(|language| language.default_scope());
11999    let mut last_word = line_at
12000        .chars()
12001        .rev()
12002        .take_while(|c| char_kind(&scope, *c) == CharKind::Word)
12003        .collect::<String>();
12004    last_word = last_word.chars().rev().collect();
12005    let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
12006    let to_lsp = |point: &text::Anchor| {
12007        let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
12008        point_to_lsp(end)
12009    };
12010    let lsp_end = to_lsp(&buffer_position);
12011    snippets
12012        .into_iter()
12013        .filter_map(|snippet| {
12014            let matching_prefix = snippet
12015                .prefix
12016                .iter()
12017                .find(|prefix| prefix.starts_with(&last_word))?;
12018            let start = as_offset - last_word.len();
12019            let start = snapshot.anchor_before(start);
12020            let range = start..buffer_position;
12021            let lsp_start = to_lsp(&start);
12022            let lsp_range = lsp::Range {
12023                start: lsp_start,
12024                end: lsp_end,
12025            };
12026            Some(Completion {
12027                old_range: range,
12028                new_text: snippet.body.clone(),
12029                label: CodeLabel {
12030                    text: matching_prefix.clone(),
12031                    runs: vec![],
12032                    filter_range: 0..matching_prefix.len(),
12033                },
12034                server_id: LanguageServerId(usize::MAX),
12035                documentation: snippet
12036                    .description
12037                    .clone()
12038                    .map(|description| Documentation::SingleLine(description)),
12039                lsp_completion: lsp::CompletionItem {
12040                    label: snippet.prefix.first().unwrap().clone(),
12041                    kind: Some(CompletionItemKind::SNIPPET),
12042                    label_details: snippet.description.as_ref().map(|description| {
12043                        lsp::CompletionItemLabelDetails {
12044                            detail: Some(description.clone()),
12045                            description: None,
12046                        }
12047                    }),
12048                    insert_text_format: Some(InsertTextFormat::SNIPPET),
12049                    text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
12050                        lsp::InsertReplaceEdit {
12051                            new_text: snippet.body.clone(),
12052                            insert: lsp_range,
12053                            replace: lsp_range,
12054                        },
12055                    )),
12056                    filter_text: Some(snippet.body.clone()),
12057                    sort_text: Some(char::MAX.to_string()),
12058                    ..Default::default()
12059                },
12060                confirm: None,
12061                show_new_completions_on_confirm: false,
12062            })
12063        })
12064        .collect()
12065}
12066
12067impl CompletionProvider for Model<Project> {
12068    fn completions(
12069        &self,
12070        buffer: &Model<Buffer>,
12071        buffer_position: text::Anchor,
12072        options: CompletionContext,
12073        cx: &mut ViewContext<Editor>,
12074    ) -> Task<Result<Vec<Completion>>> {
12075        self.update(cx, |project, cx| {
12076            let snippets = snippet_completions(project, buffer, buffer_position, cx);
12077            let project_completions = project.completions(&buffer, buffer_position, options, cx);
12078            cx.background_executor().spawn(async move {
12079                let mut completions = project_completions.await?;
12080                //let snippets = snippets.into_iter().;
12081                completions.extend(snippets);
12082                Ok(completions)
12083            })
12084        })
12085    }
12086
12087    fn resolve_completions(
12088        &self,
12089        buffer: Model<Buffer>,
12090        completion_indices: Vec<usize>,
12091        completions: Arc<RwLock<Box<[Completion]>>>,
12092        cx: &mut ViewContext<Editor>,
12093    ) -> Task<Result<bool>> {
12094        self.update(cx, |project, cx| {
12095            project.resolve_completions(buffer, completion_indices, completions, cx)
12096        })
12097    }
12098
12099    fn apply_additional_edits_for_completion(
12100        &self,
12101        buffer: Model<Buffer>,
12102        completion: Completion,
12103        push_to_history: bool,
12104        cx: &mut ViewContext<Editor>,
12105    ) -> Task<Result<Option<language::Transaction>>> {
12106        self.update(cx, |project, cx| {
12107            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
12108        })
12109    }
12110
12111    fn is_completion_trigger(
12112        &self,
12113        buffer: &Model<Buffer>,
12114        position: language::Anchor,
12115        text: &str,
12116        trigger_in_words: bool,
12117        cx: &mut ViewContext<Editor>,
12118    ) -> bool {
12119        if !EditorSettings::get_global(cx).show_completions_on_input {
12120            return false;
12121        }
12122
12123        let mut chars = text.chars();
12124        let char = if let Some(char) = chars.next() {
12125            char
12126        } else {
12127            return false;
12128        };
12129        if chars.next().is_some() {
12130            return false;
12131        }
12132
12133        let buffer = buffer.read(cx);
12134        let scope = buffer.snapshot().language_scope_at(position);
12135        if trigger_in_words && char_kind(&scope, char) == CharKind::Word {
12136            return true;
12137        }
12138
12139        buffer
12140            .completion_triggers()
12141            .iter()
12142            .any(|string| string == text)
12143    }
12144}
12145
12146fn inlay_hint_settings(
12147    location: Anchor,
12148    snapshot: &MultiBufferSnapshot,
12149    cx: &mut ViewContext<'_, Editor>,
12150) -> InlayHintSettings {
12151    let file = snapshot.file_at(location);
12152    let language = snapshot.language_at(location);
12153    let settings = all_language_settings(file, cx);
12154    settings
12155        .language(language.map(|l| l.name()).as_deref())
12156        .inlay_hints
12157}
12158
12159fn consume_contiguous_rows(
12160    contiguous_row_selections: &mut Vec<Selection<Point>>,
12161    selection: &Selection<Point>,
12162    display_map: &DisplaySnapshot,
12163    selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
12164) -> (MultiBufferRow, MultiBufferRow) {
12165    contiguous_row_selections.push(selection.clone());
12166    let start_row = MultiBufferRow(selection.start.row);
12167    let mut end_row = ending_row(selection, display_map);
12168
12169    while let Some(next_selection) = selections.peek() {
12170        if next_selection.start.row <= end_row.0 {
12171            end_row = ending_row(next_selection, display_map);
12172            contiguous_row_selections.push(selections.next().unwrap().clone());
12173        } else {
12174            break;
12175        }
12176    }
12177    (start_row, end_row)
12178}
12179
12180fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
12181    if next_selection.end.column > 0 || next_selection.is_empty() {
12182        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
12183    } else {
12184        MultiBufferRow(next_selection.end.row)
12185    }
12186}
12187
12188impl EditorSnapshot {
12189    pub fn remote_selections_in_range<'a>(
12190        &'a self,
12191        range: &'a Range<Anchor>,
12192        collaboration_hub: &dyn CollaborationHub,
12193        cx: &'a AppContext,
12194    ) -> impl 'a + Iterator<Item = RemoteSelection> {
12195        let participant_names = collaboration_hub.user_names(cx);
12196        let participant_indices = collaboration_hub.user_participant_indices(cx);
12197        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
12198        let collaborators_by_replica_id = collaborators_by_peer_id
12199            .iter()
12200            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
12201            .collect::<HashMap<_, _>>();
12202        self.buffer_snapshot
12203            .selections_in_range(range, false)
12204            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
12205                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
12206                let participant_index = participant_indices.get(&collaborator.user_id).copied();
12207                let user_name = participant_names.get(&collaborator.user_id).cloned();
12208                Some(RemoteSelection {
12209                    replica_id,
12210                    selection,
12211                    cursor_shape,
12212                    line_mode,
12213                    participant_index,
12214                    peer_id: collaborator.peer_id,
12215                    user_name,
12216                })
12217            })
12218    }
12219
12220    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
12221        self.display_snapshot.buffer_snapshot.language_at(position)
12222    }
12223
12224    pub fn is_focused(&self) -> bool {
12225        self.is_focused
12226    }
12227
12228    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
12229        self.placeholder_text.as_ref()
12230    }
12231
12232    pub fn scroll_position(&self) -> gpui::Point<f32> {
12233        self.scroll_anchor.scroll_position(&self.display_snapshot)
12234    }
12235
12236    fn gutter_dimensions(
12237        &self,
12238        font_id: FontId,
12239        font_size: Pixels,
12240        em_width: Pixels,
12241        max_line_number_width: Pixels,
12242        cx: &AppContext,
12243    ) -> GutterDimensions {
12244        if !self.show_gutter {
12245            return GutterDimensions::default();
12246        }
12247        let descent = cx.text_system().descent(font_id, font_size);
12248
12249        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
12250            matches!(
12251                ProjectSettings::get_global(cx).git.git_gutter,
12252                Some(GitGutterSetting::TrackedFiles)
12253            )
12254        });
12255        let gutter_settings = EditorSettings::get_global(cx).gutter;
12256        let show_line_numbers = self
12257            .show_line_numbers
12258            .unwrap_or(gutter_settings.line_numbers);
12259        let line_gutter_width = if show_line_numbers {
12260            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
12261            let min_width_for_number_on_gutter = em_width * 4.0;
12262            max_line_number_width.max(min_width_for_number_on_gutter)
12263        } else {
12264            0.0.into()
12265        };
12266
12267        let show_code_actions = self
12268            .show_code_actions
12269            .unwrap_or(gutter_settings.code_actions);
12270
12271        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
12272
12273        let git_blame_entries_width = self
12274            .render_git_blame_gutter
12275            .then_some(em_width * GIT_BLAME_GUTTER_WIDTH_CHARS);
12276
12277        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
12278        left_padding += if show_code_actions || show_runnables {
12279            em_width * 3.0
12280        } else if show_git_gutter && show_line_numbers {
12281            em_width * 2.0
12282        } else if show_git_gutter || show_line_numbers {
12283            em_width
12284        } else {
12285            px(0.)
12286        };
12287
12288        let right_padding = if gutter_settings.folds && show_line_numbers {
12289            em_width * 4.0
12290        } else if gutter_settings.folds {
12291            em_width * 3.0
12292        } else if show_line_numbers {
12293            em_width
12294        } else {
12295            px(0.)
12296        };
12297
12298        GutterDimensions {
12299            left_padding,
12300            right_padding,
12301            width: line_gutter_width + left_padding + right_padding,
12302            margin: -descent,
12303            git_blame_entries_width,
12304        }
12305    }
12306
12307    pub fn render_fold_toggle(
12308        &self,
12309        buffer_row: MultiBufferRow,
12310        row_contains_cursor: bool,
12311        editor: View<Editor>,
12312        cx: &mut WindowContext,
12313    ) -> Option<AnyElement> {
12314        let folded = self.is_line_folded(buffer_row);
12315
12316        if let Some(crease) = self
12317            .crease_snapshot
12318            .query_row(buffer_row, &self.buffer_snapshot)
12319        {
12320            let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
12321                if folded {
12322                    editor.update(cx, |editor, cx| {
12323                        editor.fold_at(&crate::FoldAt { buffer_row }, cx)
12324                    });
12325                } else {
12326                    editor.update(cx, |editor, cx| {
12327                        editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
12328                    });
12329                }
12330            });
12331
12332            Some((crease.render_toggle)(
12333                buffer_row,
12334                folded,
12335                toggle_callback,
12336                cx,
12337            ))
12338        } else if folded
12339            || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
12340        {
12341            Some(
12342                Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
12343                    .selected(folded)
12344                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
12345                        if folded {
12346                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
12347                        } else {
12348                            this.fold_at(&FoldAt { buffer_row }, cx);
12349                        }
12350                    }))
12351                    .into_any_element(),
12352            )
12353        } else {
12354            None
12355        }
12356    }
12357
12358    pub fn render_crease_trailer(
12359        &self,
12360        buffer_row: MultiBufferRow,
12361        cx: &mut WindowContext,
12362    ) -> Option<AnyElement> {
12363        let folded = self.is_line_folded(buffer_row);
12364        let crease = self
12365            .crease_snapshot
12366            .query_row(buffer_row, &self.buffer_snapshot)?;
12367        Some((crease.render_trailer)(buffer_row, folded, cx))
12368    }
12369}
12370
12371impl Deref for EditorSnapshot {
12372    type Target = DisplaySnapshot;
12373
12374    fn deref(&self) -> &Self::Target {
12375        &self.display_snapshot
12376    }
12377}
12378
12379#[derive(Clone, Debug, PartialEq, Eq)]
12380pub enum EditorEvent {
12381    InputIgnored {
12382        text: Arc<str>,
12383    },
12384    InputHandled {
12385        utf16_range_to_replace: Option<Range<isize>>,
12386        text: Arc<str>,
12387    },
12388    ExcerptsAdded {
12389        buffer: Model<Buffer>,
12390        predecessor: ExcerptId,
12391        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
12392    },
12393    ExcerptsRemoved {
12394        ids: Vec<ExcerptId>,
12395    },
12396    ExcerptsEdited {
12397        ids: Vec<ExcerptId>,
12398    },
12399    ExcerptsExpanded {
12400        ids: Vec<ExcerptId>,
12401    },
12402    BufferEdited,
12403    Edited {
12404        transaction_id: clock::Lamport,
12405    },
12406    Reparsed(BufferId),
12407    Focused,
12408    FocusedIn,
12409    Blurred,
12410    DirtyChanged,
12411    Saved,
12412    TitleChanged,
12413    DiffBaseChanged,
12414    SelectionsChanged {
12415        local: bool,
12416    },
12417    ScrollPositionChanged {
12418        local: bool,
12419        autoscroll: bool,
12420    },
12421    Closed,
12422    TransactionUndone {
12423        transaction_id: clock::Lamport,
12424    },
12425    TransactionBegun {
12426        transaction_id: clock::Lamport,
12427    },
12428}
12429
12430impl EventEmitter<EditorEvent> for Editor {}
12431
12432impl FocusableView for Editor {
12433    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
12434        self.focus_handle.clone()
12435    }
12436}
12437
12438impl Render for Editor {
12439    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
12440        let settings = ThemeSettings::get_global(cx);
12441
12442        let text_style = match self.mode {
12443            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
12444                color: cx.theme().colors().editor_foreground,
12445                font_family: settings.ui_font.family.clone(),
12446                font_features: settings.ui_font.features.clone(),
12447                font_size: rems(0.875).into(),
12448                font_weight: settings.ui_font.weight,
12449                line_height: relative(settings.buffer_line_height.value()),
12450                ..Default::default()
12451            },
12452            EditorMode::Full => TextStyle {
12453                color: cx.theme().colors().editor_foreground,
12454                font_family: settings.buffer_font.family.clone(),
12455                font_features: settings.buffer_font.features.clone(),
12456                font_size: settings.buffer_font_size(cx).into(),
12457                font_weight: settings.buffer_font.weight,
12458                line_height: relative(settings.buffer_line_height.value()),
12459                ..Default::default()
12460            },
12461        };
12462
12463        let background = match self.mode {
12464            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
12465            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
12466            EditorMode::Full => cx.theme().colors().editor_background,
12467        };
12468
12469        EditorElement::new(
12470            cx.view(),
12471            EditorStyle {
12472                background,
12473                local_player: cx.theme().players().local(),
12474                text: text_style,
12475                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
12476                syntax: cx.theme().syntax().clone(),
12477                status: cx.theme().status().clone(),
12478                inlay_hints_style: HighlightStyle {
12479                    color: Some(cx.theme().status().hint),
12480                    ..HighlightStyle::default()
12481                },
12482                suggestions_style: HighlightStyle {
12483                    color: Some(cx.theme().status().predictive),
12484                    ..HighlightStyle::default()
12485                },
12486            },
12487        )
12488    }
12489}
12490
12491impl ViewInputHandler for Editor {
12492    fn text_for_range(
12493        &mut self,
12494        range_utf16: Range<usize>,
12495        cx: &mut ViewContext<Self>,
12496    ) -> Option<String> {
12497        Some(
12498            self.buffer
12499                .read(cx)
12500                .read(cx)
12501                .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
12502                .collect(),
12503        )
12504    }
12505
12506    fn selected_text_range(&mut self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
12507        // Prevent the IME menu from appearing when holding down an alphabetic key
12508        // while input is disabled.
12509        if !self.input_enabled {
12510            return None;
12511        }
12512
12513        let range = self.selections.newest::<OffsetUtf16>(cx).range();
12514        Some(range.start.0..range.end.0)
12515    }
12516
12517    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
12518        let snapshot = self.buffer.read(cx).read(cx);
12519        let range = self.text_highlights::<InputComposition>(cx)?.1.get(0)?;
12520        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
12521    }
12522
12523    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
12524        self.clear_highlights::<InputComposition>(cx);
12525        self.ime_transaction.take();
12526    }
12527
12528    fn replace_text_in_range(
12529        &mut self,
12530        range_utf16: Option<Range<usize>>,
12531        text: &str,
12532        cx: &mut ViewContext<Self>,
12533    ) {
12534        if !self.input_enabled {
12535            cx.emit(EditorEvent::InputIgnored { text: text.into() });
12536            return;
12537        }
12538
12539        self.transact(cx, |this, cx| {
12540            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
12541                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12542                Some(this.selection_replacement_ranges(range_utf16, cx))
12543            } else {
12544                this.marked_text_ranges(cx)
12545            };
12546
12547            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
12548                let newest_selection_id = this.selections.newest_anchor().id;
12549                this.selections
12550                    .all::<OffsetUtf16>(cx)
12551                    .iter()
12552                    .zip(ranges_to_replace.iter())
12553                    .find_map(|(selection, range)| {
12554                        if selection.id == newest_selection_id {
12555                            Some(
12556                                (range.start.0 as isize - selection.head().0 as isize)
12557                                    ..(range.end.0 as isize - selection.head().0 as isize),
12558                            )
12559                        } else {
12560                            None
12561                        }
12562                    })
12563            });
12564
12565            cx.emit(EditorEvent::InputHandled {
12566                utf16_range_to_replace: range_to_replace,
12567                text: text.into(),
12568            });
12569
12570            if let Some(new_selected_ranges) = new_selected_ranges {
12571                this.change_selections(None, cx, |selections| {
12572                    selections.select_ranges(new_selected_ranges)
12573                });
12574                this.backspace(&Default::default(), cx);
12575            }
12576
12577            this.handle_input(text, cx);
12578        });
12579
12580        if let Some(transaction) = self.ime_transaction {
12581            self.buffer.update(cx, |buffer, cx| {
12582                buffer.group_until_transaction(transaction, cx);
12583            });
12584        }
12585
12586        self.unmark_text(cx);
12587    }
12588
12589    fn replace_and_mark_text_in_range(
12590        &mut self,
12591        range_utf16: Option<Range<usize>>,
12592        text: &str,
12593        new_selected_range_utf16: Option<Range<usize>>,
12594        cx: &mut ViewContext<Self>,
12595    ) {
12596        if !self.input_enabled {
12597            return;
12598        }
12599
12600        let transaction = self.transact(cx, |this, cx| {
12601            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
12602                let snapshot = this.buffer.read(cx).read(cx);
12603                if let Some(relative_range_utf16) = range_utf16.as_ref() {
12604                    for marked_range in &mut marked_ranges {
12605                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
12606                        marked_range.start.0 += relative_range_utf16.start;
12607                        marked_range.start =
12608                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
12609                        marked_range.end =
12610                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
12611                    }
12612                }
12613                Some(marked_ranges)
12614            } else if let Some(range_utf16) = range_utf16 {
12615                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12616                Some(this.selection_replacement_ranges(range_utf16, cx))
12617            } else {
12618                None
12619            };
12620
12621            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
12622                let newest_selection_id = this.selections.newest_anchor().id;
12623                this.selections
12624                    .all::<OffsetUtf16>(cx)
12625                    .iter()
12626                    .zip(ranges_to_replace.iter())
12627                    .find_map(|(selection, range)| {
12628                        if selection.id == newest_selection_id {
12629                            Some(
12630                                (range.start.0 as isize - selection.head().0 as isize)
12631                                    ..(range.end.0 as isize - selection.head().0 as isize),
12632                            )
12633                        } else {
12634                            None
12635                        }
12636                    })
12637            });
12638
12639            cx.emit(EditorEvent::InputHandled {
12640                utf16_range_to_replace: range_to_replace,
12641                text: text.into(),
12642            });
12643
12644            if let Some(ranges) = ranges_to_replace {
12645                this.change_selections(None, cx, |s| s.select_ranges(ranges));
12646            }
12647
12648            let marked_ranges = {
12649                let snapshot = this.buffer.read(cx).read(cx);
12650                this.selections
12651                    .disjoint_anchors()
12652                    .iter()
12653                    .map(|selection| {
12654                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
12655                    })
12656                    .collect::<Vec<_>>()
12657            };
12658
12659            if text.is_empty() {
12660                this.unmark_text(cx);
12661            } else {
12662                this.highlight_text::<InputComposition>(
12663                    marked_ranges.clone(),
12664                    HighlightStyle {
12665                        underline: Some(UnderlineStyle {
12666                            thickness: px(1.),
12667                            color: None,
12668                            wavy: false,
12669                        }),
12670                        ..Default::default()
12671                    },
12672                    cx,
12673                );
12674            }
12675
12676            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
12677            let use_autoclose = this.use_autoclose;
12678            let use_auto_surround = this.use_auto_surround;
12679            this.set_use_autoclose(false);
12680            this.set_use_auto_surround(false);
12681            this.handle_input(text, cx);
12682            this.set_use_autoclose(use_autoclose);
12683            this.set_use_auto_surround(use_auto_surround);
12684
12685            if let Some(new_selected_range) = new_selected_range_utf16 {
12686                let snapshot = this.buffer.read(cx).read(cx);
12687                let new_selected_ranges = marked_ranges
12688                    .into_iter()
12689                    .map(|marked_range| {
12690                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
12691                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
12692                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
12693                        snapshot.clip_offset_utf16(new_start, Bias::Left)
12694                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
12695                    })
12696                    .collect::<Vec<_>>();
12697
12698                drop(snapshot);
12699                this.change_selections(None, cx, |selections| {
12700                    selections.select_ranges(new_selected_ranges)
12701                });
12702            }
12703        });
12704
12705        self.ime_transaction = self.ime_transaction.or(transaction);
12706        if let Some(transaction) = self.ime_transaction {
12707            self.buffer.update(cx, |buffer, cx| {
12708                buffer.group_until_transaction(transaction, cx);
12709            });
12710        }
12711
12712        if self.text_highlights::<InputComposition>(cx).is_none() {
12713            self.ime_transaction.take();
12714        }
12715    }
12716
12717    fn bounds_for_range(
12718        &mut self,
12719        range_utf16: Range<usize>,
12720        element_bounds: gpui::Bounds<Pixels>,
12721        cx: &mut ViewContext<Self>,
12722    ) -> Option<gpui::Bounds<Pixels>> {
12723        let text_layout_details = self.text_layout_details(cx);
12724        let style = &text_layout_details.editor_style;
12725        let font_id = cx.text_system().resolve_font(&style.text.font());
12726        let font_size = style.text.font_size.to_pixels(cx.rem_size());
12727        let line_height = style.text.line_height_in_pixels(cx.rem_size());
12728
12729        let em_width = cx
12730            .text_system()
12731            .typographic_bounds(font_id, font_size, 'm')
12732            .unwrap()
12733            .size
12734            .width;
12735
12736        let snapshot = self.snapshot(cx);
12737        let scroll_position = snapshot.scroll_position();
12738        let scroll_left = scroll_position.x * em_width;
12739
12740        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
12741        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
12742            + self.gutter_dimensions.width;
12743        let y = line_height * (start.row().as_f32() - scroll_position.y);
12744
12745        Some(Bounds {
12746            origin: element_bounds.origin + point(x, y),
12747            size: size(em_width, line_height),
12748        })
12749    }
12750}
12751
12752trait SelectionExt {
12753    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
12754    fn spanned_rows(
12755        &self,
12756        include_end_if_at_line_start: bool,
12757        map: &DisplaySnapshot,
12758    ) -> Range<MultiBufferRow>;
12759}
12760
12761impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
12762    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
12763        let start = self
12764            .start
12765            .to_point(&map.buffer_snapshot)
12766            .to_display_point(map);
12767        let end = self
12768            .end
12769            .to_point(&map.buffer_snapshot)
12770            .to_display_point(map);
12771        if self.reversed {
12772            end..start
12773        } else {
12774            start..end
12775        }
12776    }
12777
12778    fn spanned_rows(
12779        &self,
12780        include_end_if_at_line_start: bool,
12781        map: &DisplaySnapshot,
12782    ) -> Range<MultiBufferRow> {
12783        let start = self.start.to_point(&map.buffer_snapshot);
12784        let mut end = self.end.to_point(&map.buffer_snapshot);
12785        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
12786            end.row -= 1;
12787        }
12788
12789        let buffer_start = map.prev_line_boundary(start).0;
12790        let buffer_end = map.next_line_boundary(end).0;
12791        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
12792    }
12793}
12794
12795impl<T: InvalidationRegion> InvalidationStack<T> {
12796    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
12797    where
12798        S: Clone + ToOffset,
12799    {
12800        while let Some(region) = self.last() {
12801            let all_selections_inside_invalidation_ranges =
12802                if selections.len() == region.ranges().len() {
12803                    selections
12804                        .iter()
12805                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
12806                        .all(|(selection, invalidation_range)| {
12807                            let head = selection.head().to_offset(buffer);
12808                            invalidation_range.start <= head && invalidation_range.end >= head
12809                        })
12810                } else {
12811                    false
12812                };
12813
12814            if all_selections_inside_invalidation_ranges {
12815                break;
12816            } else {
12817                self.pop();
12818            }
12819        }
12820    }
12821}
12822
12823impl<T> Default for InvalidationStack<T> {
12824    fn default() -> Self {
12825        Self(Default::default())
12826    }
12827}
12828
12829impl<T> Deref for InvalidationStack<T> {
12830    type Target = Vec<T>;
12831
12832    fn deref(&self) -> &Self::Target {
12833        &self.0
12834    }
12835}
12836
12837impl<T> DerefMut for InvalidationStack<T> {
12838    fn deref_mut(&mut self) -> &mut Self::Target {
12839        &mut self.0
12840    }
12841}
12842
12843impl InvalidationRegion for SnippetState {
12844    fn ranges(&self) -> &[Range<Anchor>] {
12845        &self.ranges[self.active_index]
12846    }
12847}
12848
12849pub fn diagnostic_block_renderer(
12850    diagnostic: Diagnostic,
12851    max_message_rows: Option<u8>,
12852    allow_closing: bool,
12853    _is_valid: bool,
12854) -> RenderBlock {
12855    let (text_without_backticks, code_ranges) =
12856        highlight_diagnostic_message(&diagnostic, max_message_rows);
12857
12858    Box::new(move |cx: &mut BlockContext| {
12859        let group_id: SharedString = cx.block_id.to_string().into();
12860
12861        let mut text_style = cx.text_style().clone();
12862        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
12863        let theme_settings = ThemeSettings::get_global(cx);
12864        text_style.font_family = theme_settings.buffer_font.family.clone();
12865        text_style.font_style = theme_settings.buffer_font.style;
12866        text_style.font_features = theme_settings.buffer_font.features.clone();
12867        text_style.font_weight = theme_settings.buffer_font.weight;
12868
12869        let multi_line_diagnostic = diagnostic.message.contains('\n');
12870
12871        let buttons = |diagnostic: &Diagnostic, block_id: BlockId| {
12872            if multi_line_diagnostic {
12873                v_flex()
12874            } else {
12875                h_flex()
12876            }
12877            .when(allow_closing, |div| {
12878                div.children(diagnostic.is_primary.then(|| {
12879                    IconButton::new(("close-block", EntityId::from(block_id)), IconName::XCircle)
12880                        .icon_color(Color::Muted)
12881                        .size(ButtonSize::Compact)
12882                        .style(ButtonStyle::Transparent)
12883                        .visible_on_hover(group_id.clone())
12884                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
12885                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
12886                }))
12887            })
12888            .child(
12889                IconButton::new(("copy-block", EntityId::from(block_id)), IconName::Copy)
12890                    .icon_color(Color::Muted)
12891                    .size(ButtonSize::Compact)
12892                    .style(ButtonStyle::Transparent)
12893                    .visible_on_hover(group_id.clone())
12894                    .on_click({
12895                        let message = diagnostic.message.clone();
12896                        move |_click, cx| cx.write_to_clipboard(ClipboardItem::new(message.clone()))
12897                    })
12898                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
12899            )
12900        };
12901
12902        let icon_size = buttons(&diagnostic, cx.block_id)
12903            .into_any_element()
12904            .layout_as_root(AvailableSpace::min_size(), cx);
12905
12906        h_flex()
12907            .id(cx.block_id)
12908            .group(group_id.clone())
12909            .relative()
12910            .size_full()
12911            .pl(cx.gutter_dimensions.width)
12912            .w(cx.max_width + cx.gutter_dimensions.width)
12913            .child(
12914                div()
12915                    .flex()
12916                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
12917                    .flex_shrink(),
12918            )
12919            .child(buttons(&diagnostic, cx.block_id))
12920            .child(div().flex().flex_shrink_0().child(
12921                StyledText::new(text_without_backticks.clone()).with_highlights(
12922                    &text_style,
12923                    code_ranges.iter().map(|range| {
12924                        (
12925                            range.clone(),
12926                            HighlightStyle {
12927                                font_weight: Some(FontWeight::BOLD),
12928                                ..Default::default()
12929                            },
12930                        )
12931                    }),
12932                ),
12933            ))
12934            .into_any_element()
12935    })
12936}
12937
12938pub fn highlight_diagnostic_message(
12939    diagnostic: &Diagnostic,
12940    mut max_message_rows: Option<u8>,
12941) -> (SharedString, Vec<Range<usize>>) {
12942    let mut text_without_backticks = String::new();
12943    let mut code_ranges = Vec::new();
12944
12945    if let Some(source) = &diagnostic.source {
12946        text_without_backticks.push_str(&source);
12947        code_ranges.push(0..source.len());
12948        text_without_backticks.push_str(": ");
12949    }
12950
12951    let mut prev_offset = 0;
12952    let mut in_code_block = false;
12953    let has_row_limit = max_message_rows.is_some();
12954    let mut newline_indices = diagnostic
12955        .message
12956        .match_indices('\n')
12957        .filter(|_| has_row_limit)
12958        .map(|(ix, _)| ix)
12959        .fuse()
12960        .peekable();
12961
12962    for (quote_ix, _) in diagnostic
12963        .message
12964        .match_indices('`')
12965        .chain([(diagnostic.message.len(), "")])
12966    {
12967        let mut first_newline_ix = None;
12968        let mut last_newline_ix = None;
12969        while let Some(newline_ix) = newline_indices.peek() {
12970            if *newline_ix < quote_ix {
12971                if first_newline_ix.is_none() {
12972                    first_newline_ix = Some(*newline_ix);
12973                }
12974                last_newline_ix = Some(*newline_ix);
12975
12976                if let Some(rows_left) = &mut max_message_rows {
12977                    if *rows_left == 0 {
12978                        break;
12979                    } else {
12980                        *rows_left -= 1;
12981                    }
12982                }
12983                let _ = newline_indices.next();
12984            } else {
12985                break;
12986            }
12987        }
12988        let prev_len = text_without_backticks.len();
12989        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
12990        text_without_backticks.push_str(new_text);
12991        if in_code_block {
12992            code_ranges.push(prev_len..text_without_backticks.len());
12993        }
12994        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
12995        in_code_block = !in_code_block;
12996        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
12997            text_without_backticks.push_str("...");
12998            break;
12999        }
13000    }
13001
13002    (text_without_backticks.into(), code_ranges)
13003}
13004
13005fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
13006    match severity {
13007        DiagnosticSeverity::ERROR => colors.error,
13008        DiagnosticSeverity::WARNING => colors.warning,
13009        DiagnosticSeverity::INFORMATION => colors.info,
13010        DiagnosticSeverity::HINT => colors.info,
13011        _ => colors.ignored,
13012    }
13013}
13014
13015pub fn styled_runs_for_code_label<'a>(
13016    label: &'a CodeLabel,
13017    syntax_theme: &'a theme::SyntaxTheme,
13018) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
13019    let fade_out = HighlightStyle {
13020        fade_out: Some(0.35),
13021        ..Default::default()
13022    };
13023
13024    let mut prev_end = label.filter_range.end;
13025    label
13026        .runs
13027        .iter()
13028        .enumerate()
13029        .flat_map(move |(ix, (range, highlight_id))| {
13030            let style = if let Some(style) = highlight_id.style(syntax_theme) {
13031                style
13032            } else {
13033                return Default::default();
13034            };
13035            let mut muted_style = style;
13036            muted_style.highlight(fade_out);
13037
13038            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
13039            if range.start >= label.filter_range.end {
13040                if range.start > prev_end {
13041                    runs.push((prev_end..range.start, fade_out));
13042                }
13043                runs.push((range.clone(), muted_style));
13044            } else if range.end <= label.filter_range.end {
13045                runs.push((range.clone(), style));
13046            } else {
13047                runs.push((range.start..label.filter_range.end, style));
13048                runs.push((label.filter_range.end..range.end, muted_style));
13049            }
13050            prev_end = cmp::max(prev_end, range.end);
13051
13052            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
13053                runs.push((prev_end..label.text.len(), fade_out));
13054            }
13055
13056            runs
13057        })
13058}
13059
13060pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
13061    let mut prev_index = 0;
13062    let mut prev_codepoint: Option<char> = None;
13063    text.char_indices()
13064        .chain([(text.len(), '\0')])
13065        .filter_map(move |(index, codepoint)| {
13066            let prev_codepoint = prev_codepoint.replace(codepoint)?;
13067            let is_boundary = index == text.len()
13068                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
13069                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
13070            if is_boundary {
13071                let chunk = &text[prev_index..index];
13072                prev_index = index;
13073                Some(chunk)
13074            } else {
13075                None
13076            }
13077        })
13078}
13079
13080pub trait RangeToAnchorExt: Sized {
13081    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
13082
13083    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
13084        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
13085        anchor_range.start.to_display_point(&snapshot)..anchor_range.end.to_display_point(&snapshot)
13086    }
13087}
13088
13089impl<T: ToOffset> RangeToAnchorExt for Range<T> {
13090    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
13091        let start_offset = self.start.to_offset(snapshot);
13092        let end_offset = self.end.to_offset(snapshot);
13093        if start_offset == end_offset {
13094            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
13095        } else {
13096            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
13097        }
13098    }
13099}
13100
13101pub trait RowExt {
13102    fn as_f32(&self) -> f32;
13103
13104    fn next_row(&self) -> Self;
13105
13106    fn previous_row(&self) -> Self;
13107
13108    fn minus(&self, other: Self) -> u32;
13109}
13110
13111impl RowExt for DisplayRow {
13112    fn as_f32(&self) -> f32 {
13113        self.0 as f32
13114    }
13115
13116    fn next_row(&self) -> Self {
13117        Self(self.0 + 1)
13118    }
13119
13120    fn previous_row(&self) -> Self {
13121        Self(self.0.saturating_sub(1))
13122    }
13123
13124    fn minus(&self, other: Self) -> u32 {
13125        self.0 - other.0
13126    }
13127}
13128
13129impl RowExt for MultiBufferRow {
13130    fn as_f32(&self) -> f32 {
13131        self.0 as f32
13132    }
13133
13134    fn next_row(&self) -> Self {
13135        Self(self.0 + 1)
13136    }
13137
13138    fn previous_row(&self) -> Self {
13139        Self(self.0.saturating_sub(1))
13140    }
13141
13142    fn minus(&self, other: Self) -> u32 {
13143        self.0 - other.0
13144    }
13145}
13146
13147trait RowRangeExt {
13148    type Row;
13149
13150    fn len(&self) -> usize;
13151
13152    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
13153}
13154
13155impl RowRangeExt for Range<MultiBufferRow> {
13156    type Row = MultiBufferRow;
13157
13158    fn len(&self) -> usize {
13159        (self.end.0 - self.start.0) as usize
13160    }
13161
13162    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
13163        (self.start.0..self.end.0).map(MultiBufferRow)
13164    }
13165}
13166
13167impl RowRangeExt for Range<DisplayRow> {
13168    type Row = DisplayRow;
13169
13170    fn len(&self) -> usize {
13171        (self.end.0 - self.start.0) as usize
13172    }
13173
13174    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
13175        (self.start.0..self.end.0).map(DisplayRow)
13176    }
13177}
13178
13179fn hunk_status(hunk: &DiffHunk<MultiBufferRow>) -> DiffHunkStatus {
13180    if hunk.diff_base_byte_range.is_empty() {
13181        DiffHunkStatus::Added
13182    } else if hunk.associated_range.is_empty() {
13183        DiffHunkStatus::Removed
13184    } else {
13185        DiffHunkStatus::Modified
13186    }
13187}