editor.rs

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