editor.rs

   1pub mod display_map;
   2mod element;
   3pub mod items;
   4pub mod movement;
   5mod multi_buffer;
   6
   7#[cfg(test)]
   8mod test;
   9
  10use aho_corasick::AhoCorasick;
  11use anyhow::Result;
  12use clock::ReplicaId;
  13use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
  14pub use display_map::DisplayPoint;
  15use display_map::*;
  16pub use element::*;
  17use fuzzy::{StringMatch, StringMatchCandidate};
  18use gpui::{
  19    action,
  20    color::Color,
  21    elements::*,
  22    executor,
  23    fonts::{self, HighlightStyle, TextStyle},
  24    geometry::vector::{vec2f, Vector2F},
  25    keymap::Binding,
  26    platform::CursorStyle,
  27    text_layout, AppContext, AsyncAppContext, ClipboardItem, Element, ElementBox, Entity,
  28    ModelHandle, MutableAppContext, RenderContext, Task, View, ViewContext, ViewHandle,
  29    WeakViewHandle,
  30};
  31use itertools::Itertools as _;
  32pub use language::{char_kind, CharKind};
  33use language::{
  34    BracketPair, Buffer, CodeAction, CodeLabel, Completion, Diagnostic, DiagnosticSeverity,
  35    Language, OffsetRangeExt, Point, Selection, SelectionGoal, TransactionId,
  36};
  37use multi_buffer::MultiBufferChunks;
  38pub use multi_buffer::{
  39    Anchor, AnchorRangeExt, ExcerptId, MultiBuffer, MultiBufferSnapshot, ToOffset, ToPoint,
  40};
  41use ordered_float::OrderedFloat;
  42use project::{Project, ProjectTransaction};
  43use serde::{Deserialize, Serialize};
  44use settings::Settings;
  45use smallvec::SmallVec;
  46use smol::Timer;
  47use snippet::Snippet;
  48use std::{
  49    any::TypeId,
  50    cmp::{self, Ordering, Reverse},
  51    iter::{self, FromIterator},
  52    mem,
  53    ops::{Deref, DerefMut, Range, RangeInclusive, Sub},
  54    sync::Arc,
  55    time::{Duration, Instant},
  56};
  57pub use sum_tree::Bias;
  58use text::rope::TextDimension;
  59use theme::DiagnosticStyle;
  60use util::{post_inc, ResultExt, TryFutureExt};
  61use workspace::{ItemNavHistory, Workspace};
  62
  63const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  64const MAX_LINE_LEN: usize = 1024;
  65const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  66const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  67const INDENT_SIZE: u32 = 4;
  68
  69action!(Cancel);
  70action!(Backspace);
  71action!(Delete);
  72action!(Input, String);
  73action!(Newline);
  74action!(Tab, Direction);
  75action!(Indent);
  76action!(Outdent);
  77action!(DeleteLine);
  78action!(DeleteToPreviousWordStart);
  79action!(DeleteToPreviousSubwordStart);
  80action!(DeleteToNextWordEnd);
  81action!(DeleteToNextSubwordEnd);
  82action!(DeleteToBeginningOfLine);
  83action!(DeleteToEndOfLine);
  84action!(CutToEndOfLine);
  85action!(DuplicateLine);
  86action!(MoveLineUp);
  87action!(MoveLineDown);
  88action!(Cut);
  89action!(Copy);
  90action!(Paste);
  91action!(Undo);
  92action!(Redo);
  93action!(MoveUp);
  94action!(MoveDown);
  95action!(MoveLeft);
  96action!(MoveRight);
  97action!(MoveToPreviousWordStart);
  98action!(MoveToPreviousSubwordStart);
  99action!(MoveToNextWordEnd);
 100action!(MoveToNextSubwordEnd);
 101action!(MoveToBeginningOfLine);
 102action!(MoveToEndOfLine);
 103action!(MoveToBeginning);
 104action!(MoveToEnd);
 105action!(SelectUp);
 106action!(SelectDown);
 107action!(SelectLeft);
 108action!(SelectRight);
 109action!(SelectToPreviousWordStart);
 110action!(SelectToPreviousSubwordStart);
 111action!(SelectToNextWordEnd);
 112action!(SelectToNextSubwordEnd);
 113action!(SelectToBeginningOfLine, bool);
 114action!(SelectToEndOfLine, bool);
 115action!(SelectToBeginning);
 116action!(SelectToEnd);
 117action!(SelectAll);
 118action!(SelectLine);
 119action!(SplitSelectionIntoLines);
 120action!(AddSelectionAbove);
 121action!(AddSelectionBelow);
 122action!(SelectNext, bool);
 123action!(ToggleComments);
 124action!(SelectLargerSyntaxNode);
 125action!(SelectSmallerSyntaxNode);
 126action!(MoveToEnclosingBracket);
 127action!(UndoSelection);
 128action!(RedoSelection);
 129action!(GoToDiagnostic, Direction);
 130action!(GoToDefinition);
 131action!(FindAllReferences);
 132action!(Rename);
 133action!(ConfirmRename);
 134action!(PageUp);
 135action!(PageDown);
 136action!(Fold);
 137action!(UnfoldLines);
 138action!(FoldSelectedRanges);
 139action!(Scroll, Vector2F);
 140action!(Select, SelectPhase);
 141action!(ShowCompletions);
 142action!(ToggleCodeActions, bool);
 143action!(ConfirmCompletion, Option<usize>);
 144action!(ConfirmCodeAction, Option<usize>);
 145action!(OpenExcerpts);
 146action!(RestartLanguageServer);
 147
 148enum DocumentHighlightRead {}
 149enum DocumentHighlightWrite {}
 150
 151#[derive(Copy, Clone, PartialEq, Eq)]
 152pub enum Direction {
 153    Prev,
 154    Next,
 155}
 156
 157pub fn init(cx: &mut MutableAppContext) {
 158    cx.add_bindings(vec![
 159        Binding::new("escape", Cancel, Some("Editor")),
 160        Binding::new("backspace", Backspace, Some("Editor")),
 161        Binding::new("ctrl-h", Backspace, Some("Editor")),
 162        Binding::new("delete", Delete, Some("Editor")),
 163        Binding::new("ctrl-d", Delete, Some("Editor")),
 164        Binding::new("enter", Newline, Some("Editor && mode == full")),
 165        Binding::new(
 166            "alt-enter",
 167            Input("\n".into()),
 168            Some("Editor && mode == auto_height"),
 169        ),
 170        Binding::new(
 171            "enter",
 172            ConfirmCompletion(None),
 173            Some("Editor && showing_completions"),
 174        ),
 175        Binding::new(
 176            "enter",
 177            ConfirmCodeAction(None),
 178            Some("Editor && showing_code_actions"),
 179        ),
 180        Binding::new("enter", ConfirmRename, Some("Editor && renaming")),
 181        Binding::new("tab", Tab(Direction::Next), Some("Editor")),
 182        Binding::new("shift-tab", Tab(Direction::Prev), Some("Editor")),
 183        Binding::new(
 184            "tab",
 185            ConfirmCompletion(None),
 186            Some("Editor && showing_completions"),
 187        ),
 188        Binding::new("cmd-[", Outdent, Some("Editor")),
 189        Binding::new("cmd-]", Indent, Some("Editor")),
 190        Binding::new("ctrl-shift-K", DeleteLine, Some("Editor")),
 191        Binding::new("alt-backspace", DeleteToPreviousWordStart, Some("Editor")),
 192        Binding::new("alt-h", DeleteToPreviousWordStart, Some("Editor")),
 193        Binding::new(
 194            "ctrl-alt-backspace",
 195            DeleteToPreviousSubwordStart,
 196            Some("Editor"),
 197        ),
 198        Binding::new("ctrl-alt-h", DeleteToPreviousSubwordStart, Some("Editor")),
 199        Binding::new("alt-delete", DeleteToNextWordEnd, Some("Editor")),
 200        Binding::new("alt-d", DeleteToNextWordEnd, Some("Editor")),
 201        Binding::new("ctrl-alt-delete", DeleteToNextSubwordEnd, Some("Editor")),
 202        Binding::new("ctrl-alt-d", DeleteToNextSubwordEnd, Some("Editor")),
 203        Binding::new("cmd-backspace", DeleteToBeginningOfLine, Some("Editor")),
 204        Binding::new("cmd-delete", DeleteToEndOfLine, Some("Editor")),
 205        Binding::new("ctrl-k", CutToEndOfLine, Some("Editor")),
 206        Binding::new("cmd-shift-D", DuplicateLine, Some("Editor")),
 207        Binding::new("ctrl-cmd-up", MoveLineUp, Some("Editor")),
 208        Binding::new("ctrl-cmd-down", MoveLineDown, Some("Editor")),
 209        Binding::new("cmd-x", Cut, Some("Editor")),
 210        Binding::new("cmd-c", Copy, Some("Editor")),
 211        Binding::new("cmd-v", Paste, Some("Editor")),
 212        Binding::new("cmd-z", Undo, Some("Editor")),
 213        Binding::new("cmd-shift-Z", Redo, Some("Editor")),
 214        Binding::new("up", MoveUp, Some("Editor")),
 215        Binding::new("down", MoveDown, Some("Editor")),
 216        Binding::new("left", MoveLeft, Some("Editor")),
 217        Binding::new("right", MoveRight, Some("Editor")),
 218        Binding::new("ctrl-p", MoveUp, Some("Editor")),
 219        Binding::new("ctrl-n", MoveDown, Some("Editor")),
 220        Binding::new("ctrl-b", MoveLeft, Some("Editor")),
 221        Binding::new("ctrl-f", MoveRight, Some("Editor")),
 222        Binding::new("alt-left", MoveToPreviousWordStart, Some("Editor")),
 223        Binding::new("alt-b", MoveToPreviousWordStart, Some("Editor")),
 224        Binding::new("ctrl-alt-left", MoveToPreviousSubwordStart, Some("Editor")),
 225        Binding::new("ctrl-alt-b", MoveToPreviousSubwordStart, Some("Editor")),
 226        Binding::new("alt-right", MoveToNextWordEnd, Some("Editor")),
 227        Binding::new("alt-f", MoveToNextWordEnd, Some("Editor")),
 228        Binding::new("ctrl-alt-right", MoveToNextSubwordEnd, Some("Editor")),
 229        Binding::new("ctrl-alt-f", MoveToNextSubwordEnd, Some("Editor")),
 230        Binding::new("cmd-left", MoveToBeginningOfLine, Some("Editor")),
 231        Binding::new("ctrl-a", MoveToBeginningOfLine, Some("Editor")),
 232        Binding::new("cmd-right", MoveToEndOfLine, Some("Editor")),
 233        Binding::new("ctrl-e", MoveToEndOfLine, Some("Editor")),
 234        Binding::new("cmd-up", MoveToBeginning, Some("Editor")),
 235        Binding::new("cmd-down", MoveToEnd, Some("Editor")),
 236        Binding::new("shift-up", SelectUp, Some("Editor")),
 237        Binding::new("ctrl-shift-P", SelectUp, Some("Editor")),
 238        Binding::new("shift-down", SelectDown, Some("Editor")),
 239        Binding::new("ctrl-shift-N", SelectDown, Some("Editor")),
 240        Binding::new("shift-left", SelectLeft, Some("Editor")),
 241        Binding::new("ctrl-shift-B", SelectLeft, Some("Editor")),
 242        Binding::new("shift-right", SelectRight, Some("Editor")),
 243        Binding::new("ctrl-shift-F", SelectRight, Some("Editor")),
 244        Binding::new("alt-shift-left", SelectToPreviousWordStart, Some("Editor")),
 245        Binding::new("alt-shift-B", SelectToPreviousWordStart, Some("Editor")),
 246        Binding::new(
 247            "ctrl-alt-shift-left",
 248            SelectToPreviousSubwordStart,
 249            Some("Editor"),
 250        ),
 251        Binding::new(
 252            "ctrl-alt-shift-B",
 253            SelectToPreviousSubwordStart,
 254            Some("Editor"),
 255        ),
 256        Binding::new("alt-shift-right", SelectToNextWordEnd, Some("Editor")),
 257        Binding::new("alt-shift-F", SelectToNextWordEnd, Some("Editor")),
 258        Binding::new(
 259            "cmd-shift-left",
 260            SelectToBeginningOfLine(true),
 261            Some("Editor"),
 262        ),
 263        Binding::new(
 264            "ctrl-alt-shift-right",
 265            SelectToNextSubwordEnd,
 266            Some("Editor"),
 267        ),
 268        Binding::new("ctrl-alt-shift-F", SelectToNextSubwordEnd, Some("Editor")),
 269        Binding::new(
 270            "ctrl-shift-A",
 271            SelectToBeginningOfLine(true),
 272            Some("Editor"),
 273        ),
 274        Binding::new("cmd-shift-right", SelectToEndOfLine(true), Some("Editor")),
 275        Binding::new("ctrl-shift-E", SelectToEndOfLine(true), Some("Editor")),
 276        Binding::new("cmd-shift-up", SelectToBeginning, Some("Editor")),
 277        Binding::new("cmd-shift-down", SelectToEnd, Some("Editor")),
 278        Binding::new("cmd-a", SelectAll, Some("Editor")),
 279        Binding::new("cmd-l", SelectLine, Some("Editor")),
 280        Binding::new("cmd-shift-L", SplitSelectionIntoLines, Some("Editor")),
 281        Binding::new("cmd-alt-up", AddSelectionAbove, Some("Editor")),
 282        Binding::new("cmd-ctrl-p", AddSelectionAbove, Some("Editor")),
 283        Binding::new("cmd-alt-down", AddSelectionBelow, Some("Editor")),
 284        Binding::new("cmd-ctrl-n", AddSelectionBelow, Some("Editor")),
 285        Binding::new("cmd-d", SelectNext(false), Some("Editor")),
 286        Binding::new("cmd-k cmd-d", SelectNext(true), Some("Editor")),
 287        Binding::new("cmd-/", ToggleComments, Some("Editor")),
 288        Binding::new("alt-up", SelectLargerSyntaxNode, Some("Editor")),
 289        Binding::new("ctrl-w", SelectLargerSyntaxNode, Some("Editor")),
 290        Binding::new("alt-down", SelectSmallerSyntaxNode, Some("Editor")),
 291        Binding::new("ctrl-shift-W", SelectSmallerSyntaxNode, Some("Editor")),
 292        Binding::new("cmd-u", UndoSelection, Some("Editor")),
 293        Binding::new("cmd-shift-U", RedoSelection, Some("Editor")),
 294        Binding::new("f8", GoToDiagnostic(Direction::Next), Some("Editor")),
 295        Binding::new("shift-f8", GoToDiagnostic(Direction::Prev), Some("Editor")),
 296        Binding::new("f2", Rename, Some("Editor")),
 297        Binding::new("f12", GoToDefinition, Some("Editor")),
 298        Binding::new("alt-shift-f12", FindAllReferences, Some("Editor")),
 299        Binding::new("ctrl-m", MoveToEnclosingBracket, Some("Editor")),
 300        Binding::new("pageup", PageUp, Some("Editor")),
 301        Binding::new("pagedown", PageDown, Some("Editor")),
 302        Binding::new("alt-cmd-[", Fold, Some("Editor")),
 303        Binding::new("alt-cmd-]", UnfoldLines, Some("Editor")),
 304        Binding::new("alt-cmd-f", FoldSelectedRanges, Some("Editor")),
 305        Binding::new("ctrl-space", ShowCompletions, Some("Editor")),
 306        Binding::new("cmd-.", ToggleCodeActions(false), Some("Editor")),
 307        Binding::new("alt-enter", OpenExcerpts, Some("Editor")),
 308        Binding::new("cmd-f10", RestartLanguageServer, Some("Editor")),
 309    ]);
 310
 311    cx.add_action(Editor::open_new);
 312    cx.add_action(|this: &mut Editor, action: &Scroll, cx| this.set_scroll_position(action.0, cx));
 313    cx.add_action(Editor::select);
 314    cx.add_action(Editor::cancel);
 315    cx.add_action(Editor::handle_input);
 316    cx.add_action(Editor::newline);
 317    cx.add_action(Editor::backspace);
 318    cx.add_action(Editor::delete);
 319    cx.add_action(Editor::tab);
 320    cx.add_action(Editor::indent);
 321    cx.add_action(Editor::outdent);
 322    cx.add_action(Editor::delete_line);
 323    cx.add_action(Editor::delete_to_previous_word_start);
 324    cx.add_action(Editor::delete_to_previous_subword_start);
 325    cx.add_action(Editor::delete_to_next_word_end);
 326    cx.add_action(Editor::delete_to_next_subword_end);
 327    cx.add_action(Editor::delete_to_beginning_of_line);
 328    cx.add_action(Editor::delete_to_end_of_line);
 329    cx.add_action(Editor::cut_to_end_of_line);
 330    cx.add_action(Editor::duplicate_line);
 331    cx.add_action(Editor::move_line_up);
 332    cx.add_action(Editor::move_line_down);
 333    cx.add_action(Editor::cut);
 334    cx.add_action(Editor::copy);
 335    cx.add_action(Editor::paste);
 336    cx.add_action(Editor::undo);
 337    cx.add_action(Editor::redo);
 338    cx.add_action(Editor::move_up);
 339    cx.add_action(Editor::move_down);
 340    cx.add_action(Editor::move_left);
 341    cx.add_action(Editor::move_right);
 342    cx.add_action(Editor::move_to_previous_word_start);
 343    cx.add_action(Editor::move_to_previous_subword_start);
 344    cx.add_action(Editor::move_to_next_word_end);
 345    cx.add_action(Editor::move_to_next_subword_end);
 346    cx.add_action(Editor::move_to_beginning_of_line);
 347    cx.add_action(Editor::move_to_end_of_line);
 348    cx.add_action(Editor::move_to_beginning);
 349    cx.add_action(Editor::move_to_end);
 350    cx.add_action(Editor::select_up);
 351    cx.add_action(Editor::select_down);
 352    cx.add_action(Editor::select_left);
 353    cx.add_action(Editor::select_right);
 354    cx.add_action(Editor::select_to_previous_word_start);
 355    cx.add_action(Editor::select_to_previous_subword_start);
 356    cx.add_action(Editor::select_to_next_word_end);
 357    cx.add_action(Editor::select_to_next_subword_end);
 358    cx.add_action(Editor::select_to_beginning_of_line);
 359    cx.add_action(Editor::select_to_end_of_line);
 360    cx.add_action(Editor::select_to_beginning);
 361    cx.add_action(Editor::select_to_end);
 362    cx.add_action(Editor::select_all);
 363    cx.add_action(Editor::select_line);
 364    cx.add_action(Editor::split_selection_into_lines);
 365    cx.add_action(Editor::add_selection_above);
 366    cx.add_action(Editor::add_selection_below);
 367    cx.add_action(Editor::select_next);
 368    cx.add_action(Editor::toggle_comments);
 369    cx.add_action(Editor::select_larger_syntax_node);
 370    cx.add_action(Editor::select_smaller_syntax_node);
 371    cx.add_action(Editor::move_to_enclosing_bracket);
 372    cx.add_action(Editor::undo_selection);
 373    cx.add_action(Editor::redo_selection);
 374    cx.add_action(Editor::go_to_diagnostic);
 375    cx.add_action(Editor::go_to_definition);
 376    cx.add_action(Editor::page_up);
 377    cx.add_action(Editor::page_down);
 378    cx.add_action(Editor::fold);
 379    cx.add_action(Editor::unfold_lines);
 380    cx.add_action(Editor::fold_selected_ranges);
 381    cx.add_action(Editor::show_completions);
 382    cx.add_action(Editor::toggle_code_actions);
 383    cx.add_action(Editor::open_excerpts);
 384    cx.add_action(Editor::restart_language_server);
 385    cx.add_async_action(Editor::confirm_completion);
 386    cx.add_async_action(Editor::confirm_code_action);
 387    cx.add_async_action(Editor::rename);
 388    cx.add_async_action(Editor::confirm_rename);
 389    cx.add_async_action(Editor::find_all_references);
 390
 391    workspace::register_project_item::<Editor>(cx);
 392    workspace::register_followable_item::<Editor>(cx);
 393}
 394
 395trait InvalidationRegion {
 396    fn ranges(&self) -> &[Range<Anchor>];
 397}
 398
 399#[derive(Clone, Debug)]
 400pub enum SelectPhase {
 401    Begin {
 402        position: DisplayPoint,
 403        add: bool,
 404        click_count: usize,
 405    },
 406    BeginColumnar {
 407        position: DisplayPoint,
 408        overshoot: u32,
 409    },
 410    Extend {
 411        position: DisplayPoint,
 412        click_count: usize,
 413    },
 414    Update {
 415        position: DisplayPoint,
 416        overshoot: u32,
 417        scroll_position: Vector2F,
 418    },
 419    End,
 420}
 421
 422#[derive(Clone, Debug)]
 423pub enum SelectMode {
 424    Character,
 425    Word(Range<Anchor>),
 426    Line(Range<Anchor>),
 427    All,
 428}
 429
 430#[derive(PartialEq, Eq)]
 431pub enum Autoscroll {
 432    Fit,
 433    Center,
 434    Newest,
 435}
 436
 437#[derive(Copy, Clone, PartialEq, Eq)]
 438pub enum EditorMode {
 439    SingleLine,
 440    AutoHeight { max_lines: usize },
 441    Full,
 442}
 443
 444#[derive(Clone)]
 445pub enum SoftWrap {
 446    None,
 447    EditorWidth,
 448    Column(u32),
 449}
 450
 451#[derive(Clone)]
 452pub struct EditorStyle {
 453    pub text: TextStyle,
 454    pub placeholder_text: Option<TextStyle>,
 455    pub theme: theme::Editor,
 456}
 457
 458type CompletionId = usize;
 459
 460pub type GetFieldEditorTheme = fn(&theme::Theme) -> theme::FieldEditor;
 461
 462type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
 463
 464pub struct Editor {
 465    handle: WeakViewHandle<Self>,
 466    buffer: ModelHandle<MultiBuffer>,
 467    display_map: ModelHandle<DisplayMap>,
 468    next_selection_id: usize,
 469    selections: Arc<[Selection<Anchor>]>,
 470    pending_selection: Option<PendingSelection>,
 471    columnar_selection_tail: Option<Anchor>,
 472    add_selections_state: Option<AddSelectionsState>,
 473    select_next_state: Option<SelectNextState>,
 474    selection_history: SelectionHistory,
 475    autoclose_stack: InvalidationStack<BracketPairState>,
 476    snippet_stack: InvalidationStack<SnippetState>,
 477    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
 478    active_diagnostics: Option<ActiveDiagnosticGroup>,
 479    scroll_position: Vector2F,
 480    scroll_top_anchor: Anchor,
 481    autoscroll_request: Option<(Autoscroll, bool)>,
 482    soft_wrap_mode_override: Option<settings::SoftWrap>,
 483    get_field_editor_theme: Option<GetFieldEditorTheme>,
 484    override_text_style: Option<Box<OverrideTextStyle>>,
 485    project: Option<ModelHandle<Project>>,
 486    focused: bool,
 487    show_local_cursors: bool,
 488    show_local_selections: bool,
 489    blink_epoch: usize,
 490    blinking_paused: bool,
 491    mode: EditorMode,
 492    vertical_scroll_margin: f32,
 493    placeholder_text: Option<Arc<str>>,
 494    highlighted_rows: Option<Range<u32>>,
 495    background_highlights: BTreeMap<TypeId, (Color, Vec<Range<Anchor>>)>,
 496    nav_history: Option<ItemNavHistory>,
 497    context_menu: Option<ContextMenu>,
 498    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
 499    next_completion_id: CompletionId,
 500    available_code_actions: Option<(ModelHandle<Buffer>, Arc<[CodeAction]>)>,
 501    code_actions_task: Option<Task<()>>,
 502    document_highlights_task: Option<Task<()>>,
 503    pending_rename: Option<RenameState>,
 504    searchable: bool,
 505    cursor_shape: CursorShape,
 506    keymap_context_layers: BTreeMap<TypeId, gpui::keymap::Context>,
 507    input_enabled: bool,
 508    leader_replica_id: Option<u16>,
 509}
 510
 511pub struct EditorSnapshot {
 512    pub mode: EditorMode,
 513    pub display_snapshot: DisplaySnapshot,
 514    pub placeholder_text: Option<Arc<str>>,
 515    is_focused: bool,
 516    scroll_position: Vector2F,
 517    scroll_top_anchor: Anchor,
 518}
 519
 520#[derive(Clone)]
 521pub struct PendingSelection {
 522    selection: Selection<Anchor>,
 523    mode: SelectMode,
 524}
 525
 526#[derive(Clone)]
 527struct SelectionHistoryEntry {
 528    selections: Arc<[Selection<Anchor>]>,
 529    select_next_state: Option<SelectNextState>,
 530    add_selections_state: Option<AddSelectionsState>,
 531}
 532
 533enum SelectionHistoryMode {
 534    Normal,
 535    Undoing,
 536    Redoing,
 537}
 538
 539impl Default for SelectionHistoryMode {
 540    fn default() -> Self {
 541        Self::Normal
 542    }
 543}
 544
 545#[derive(Default)]
 546struct SelectionHistory {
 547    selections_by_transaction:
 548        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
 549    mode: SelectionHistoryMode,
 550    undo_stack: VecDeque<SelectionHistoryEntry>,
 551    redo_stack: VecDeque<SelectionHistoryEntry>,
 552}
 553
 554impl SelectionHistory {
 555    fn insert_transaction(
 556        &mut self,
 557        transaction_id: TransactionId,
 558        selections: Arc<[Selection<Anchor>]>,
 559    ) {
 560        self.selections_by_transaction
 561            .insert(transaction_id, (selections, None));
 562    }
 563
 564    fn transaction(
 565        &self,
 566        transaction_id: TransactionId,
 567    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
 568        self.selections_by_transaction.get(&transaction_id)
 569    }
 570
 571    fn transaction_mut(
 572        &mut self,
 573        transaction_id: TransactionId,
 574    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
 575        self.selections_by_transaction.get_mut(&transaction_id)
 576    }
 577
 578    fn push(&mut self, entry: SelectionHistoryEntry) {
 579        if !entry.selections.is_empty() {
 580            match self.mode {
 581                SelectionHistoryMode::Normal => {
 582                    self.push_undo(entry);
 583                    self.redo_stack.clear();
 584                }
 585                SelectionHistoryMode::Undoing => self.push_redo(entry),
 586                SelectionHistoryMode::Redoing => self.push_undo(entry),
 587            }
 588        }
 589    }
 590
 591    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
 592        if self
 593            .undo_stack
 594            .back()
 595            .map_or(true, |e| e.selections != entry.selections)
 596        {
 597            self.undo_stack.push_back(entry);
 598            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
 599                self.undo_stack.pop_front();
 600            }
 601        }
 602    }
 603
 604    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
 605        if self
 606            .redo_stack
 607            .back()
 608            .map_or(true, |e| e.selections != entry.selections)
 609        {
 610            self.redo_stack.push_back(entry);
 611            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
 612                self.redo_stack.pop_front();
 613            }
 614        }
 615    }
 616}
 617
 618#[derive(Clone)]
 619struct AddSelectionsState {
 620    above: bool,
 621    stack: Vec<usize>,
 622}
 623
 624#[derive(Clone)]
 625struct SelectNextState {
 626    query: AhoCorasick,
 627    wordwise: bool,
 628    done: bool,
 629}
 630
 631struct BracketPairState {
 632    ranges: Vec<Range<Anchor>>,
 633    pair: BracketPair,
 634}
 635
 636struct SnippetState {
 637    ranges: Vec<Vec<Range<Anchor>>>,
 638    active_index: usize,
 639}
 640
 641pub struct RenameState {
 642    pub range: Range<Anchor>,
 643    pub old_name: String,
 644    pub editor: ViewHandle<Editor>,
 645    block_id: BlockId,
 646}
 647
 648struct InvalidationStack<T>(Vec<T>);
 649
 650enum ContextMenu {
 651    Completions(CompletionsMenu),
 652    CodeActions(CodeActionsMenu),
 653}
 654
 655impl ContextMenu {
 656    fn select_prev(&mut self, cx: &mut ViewContext<Editor>) -> bool {
 657        if self.visible() {
 658            match self {
 659                ContextMenu::Completions(menu) => menu.select_prev(cx),
 660                ContextMenu::CodeActions(menu) => menu.select_prev(cx),
 661            }
 662            true
 663        } else {
 664            false
 665        }
 666    }
 667
 668    fn select_next(&mut self, cx: &mut ViewContext<Editor>) -> bool {
 669        if self.visible() {
 670            match self {
 671                ContextMenu::Completions(menu) => menu.select_next(cx),
 672                ContextMenu::CodeActions(menu) => menu.select_next(cx),
 673            }
 674            true
 675        } else {
 676            false
 677        }
 678    }
 679
 680    fn visible(&self) -> bool {
 681        match self {
 682            ContextMenu::Completions(menu) => menu.visible(),
 683            ContextMenu::CodeActions(menu) => menu.visible(),
 684        }
 685    }
 686
 687    fn render(
 688        &self,
 689        cursor_position: DisplayPoint,
 690        style: EditorStyle,
 691        cx: &AppContext,
 692    ) -> (DisplayPoint, ElementBox) {
 693        match self {
 694            ContextMenu::Completions(menu) => (cursor_position, menu.render(style, cx)),
 695            ContextMenu::CodeActions(menu) => menu.render(cursor_position, style),
 696        }
 697    }
 698}
 699
 700struct CompletionsMenu {
 701    id: CompletionId,
 702    initial_position: Anchor,
 703    buffer: ModelHandle<Buffer>,
 704    completions: Arc<[Completion]>,
 705    match_candidates: Vec<StringMatchCandidate>,
 706    matches: Arc<[StringMatch]>,
 707    selected_item: usize,
 708    list: UniformListState,
 709}
 710
 711impl CompletionsMenu {
 712    fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
 713        if self.selected_item > 0 {
 714            self.selected_item -= 1;
 715            self.list.scroll_to(ScrollTarget::Show(self.selected_item));
 716        }
 717        cx.notify();
 718    }
 719
 720    fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
 721        if self.selected_item + 1 < self.matches.len() {
 722            self.selected_item += 1;
 723            self.list.scroll_to(ScrollTarget::Show(self.selected_item));
 724        }
 725        cx.notify();
 726    }
 727
 728    fn visible(&self) -> bool {
 729        !self.matches.is_empty()
 730    }
 731
 732    fn render(&self, style: EditorStyle, _: &AppContext) -> ElementBox {
 733        enum CompletionTag {}
 734
 735        let completions = self.completions.clone();
 736        let matches = self.matches.clone();
 737        let selected_item = self.selected_item;
 738        let container_style = style.autocomplete.container;
 739        UniformList::new(self.list.clone(), matches.len(), move |range, items, cx| {
 740            let start_ix = range.start;
 741            for (ix, mat) in matches[range].iter().enumerate() {
 742                let completion = &completions[mat.candidate_id];
 743                let item_ix = start_ix + ix;
 744                items.push(
 745                    MouseEventHandler::new::<CompletionTag, _, _>(
 746                        mat.candidate_id,
 747                        cx,
 748                        |state, _| {
 749                            let item_style = if item_ix == selected_item {
 750                                style.autocomplete.selected_item
 751                            } else if state.hovered {
 752                                style.autocomplete.hovered_item
 753                            } else {
 754                                style.autocomplete.item
 755                            };
 756
 757                            Text::new(completion.label.text.clone(), style.text.clone())
 758                                .with_soft_wrap(false)
 759                                .with_highlights(combine_syntax_and_fuzzy_match_highlights(
 760                                    &completion.label.text,
 761                                    style.text.color.into(),
 762                                    styled_runs_for_code_label(&completion.label, &style.syntax),
 763                                    &mat.positions,
 764                                ))
 765                                .contained()
 766                                .with_style(item_style)
 767                                .boxed()
 768                        },
 769                    )
 770                    .with_cursor_style(CursorStyle::PointingHand)
 771                    .on_mouse_down(move |cx| {
 772                        cx.dispatch_action(ConfirmCompletion(Some(item_ix)));
 773                    })
 774                    .boxed(),
 775                );
 776            }
 777        })
 778        .with_width_from_item(
 779            self.matches
 780                .iter()
 781                .enumerate()
 782                .max_by_key(|(_, mat)| {
 783                    self.completions[mat.candidate_id]
 784                        .label
 785                        .text
 786                        .chars()
 787                        .count()
 788                })
 789                .map(|(ix, _)| ix),
 790        )
 791        .contained()
 792        .with_style(container_style)
 793        .boxed()
 794    }
 795
 796    pub async fn filter(&mut self, query: Option<&str>, executor: Arc<executor::Background>) {
 797        let mut matches = if let Some(query) = query {
 798            fuzzy::match_strings(
 799                &self.match_candidates,
 800                query,
 801                false,
 802                100,
 803                &Default::default(),
 804                executor,
 805            )
 806            .await
 807        } else {
 808            self.match_candidates
 809                .iter()
 810                .enumerate()
 811                .map(|(candidate_id, candidate)| StringMatch {
 812                    candidate_id,
 813                    score: Default::default(),
 814                    positions: Default::default(),
 815                    string: candidate.string.clone(),
 816                })
 817                .collect()
 818        };
 819        matches.sort_unstable_by_key(|mat| {
 820            (
 821                Reverse(OrderedFloat(mat.score)),
 822                self.completions[mat.candidate_id].sort_key(),
 823            )
 824        });
 825
 826        for mat in &mut matches {
 827            let filter_start = self.completions[mat.candidate_id].label.filter_range.start;
 828            for position in &mut mat.positions {
 829                *position += filter_start;
 830            }
 831        }
 832
 833        self.matches = matches.into();
 834    }
 835}
 836
 837#[derive(Clone)]
 838struct CodeActionsMenu {
 839    actions: Arc<[CodeAction]>,
 840    buffer: ModelHandle<Buffer>,
 841    selected_item: usize,
 842    list: UniformListState,
 843    deployed_from_indicator: bool,
 844}
 845
 846impl CodeActionsMenu {
 847    fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
 848        if self.selected_item > 0 {
 849            self.selected_item -= 1;
 850            cx.notify()
 851        }
 852    }
 853
 854    fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
 855        if self.selected_item + 1 < self.actions.len() {
 856            self.selected_item += 1;
 857            cx.notify()
 858        }
 859    }
 860
 861    fn visible(&self) -> bool {
 862        !self.actions.is_empty()
 863    }
 864
 865    fn render(
 866        &self,
 867        mut cursor_position: DisplayPoint,
 868        style: EditorStyle,
 869    ) -> (DisplayPoint, ElementBox) {
 870        enum ActionTag {}
 871
 872        let container_style = style.autocomplete.container;
 873        let actions = self.actions.clone();
 874        let selected_item = self.selected_item;
 875        let element =
 876            UniformList::new(self.list.clone(), actions.len(), move |range, items, cx| {
 877                let start_ix = range.start;
 878                for (ix, action) in actions[range].iter().enumerate() {
 879                    let item_ix = start_ix + ix;
 880                    items.push(
 881                        MouseEventHandler::new::<ActionTag, _, _>(item_ix, cx, |state, _| {
 882                            let item_style = if item_ix == selected_item {
 883                                style.autocomplete.selected_item
 884                            } else if state.hovered {
 885                                style.autocomplete.hovered_item
 886                            } else {
 887                                style.autocomplete.item
 888                            };
 889
 890                            Text::new(action.lsp_action.title.clone(), style.text.clone())
 891                                .with_soft_wrap(false)
 892                                .contained()
 893                                .with_style(item_style)
 894                                .boxed()
 895                        })
 896                        .with_cursor_style(CursorStyle::PointingHand)
 897                        .on_mouse_down(move |cx| {
 898                            cx.dispatch_action(ConfirmCodeAction(Some(item_ix)));
 899                        })
 900                        .boxed(),
 901                    );
 902                }
 903            })
 904            .with_width_from_item(
 905                self.actions
 906                    .iter()
 907                    .enumerate()
 908                    .max_by_key(|(_, action)| action.lsp_action.title.chars().count())
 909                    .map(|(ix, _)| ix),
 910            )
 911            .contained()
 912            .with_style(container_style)
 913            .boxed();
 914
 915        if self.deployed_from_indicator {
 916            *cursor_position.column_mut() = 0;
 917        }
 918
 919        (cursor_position, element)
 920    }
 921}
 922
 923#[derive(Debug)]
 924struct ActiveDiagnosticGroup {
 925    primary_range: Range<Anchor>,
 926    primary_message: String,
 927    blocks: HashMap<BlockId, Diagnostic>,
 928    is_valid: bool,
 929}
 930
 931#[derive(Serialize, Deserialize)]
 932struct ClipboardSelection {
 933    len: usize,
 934    is_entire_line: bool,
 935}
 936
 937pub struct NavigationData {
 938    anchor: Anchor,
 939    offset: usize,
 940}
 941
 942pub struct EditorCreated(pub ViewHandle<Editor>);
 943
 944impl Editor {
 945    pub fn single_line(
 946        field_editor_style: Option<GetFieldEditorTheme>,
 947        cx: &mut ViewContext<Self>,
 948    ) -> Self {
 949        let buffer = cx.add_model(|cx| Buffer::new(0, String::new(), cx));
 950        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
 951        Self::new(EditorMode::SingleLine, buffer, None, field_editor_style, cx)
 952    }
 953
 954    pub fn auto_height(
 955        max_lines: usize,
 956        field_editor_style: Option<GetFieldEditorTheme>,
 957        cx: &mut ViewContext<Self>,
 958    ) -> Self {
 959        let buffer = cx.add_model(|cx| Buffer::new(0, String::new(), cx));
 960        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
 961        Self::new(
 962            EditorMode::AutoHeight { max_lines },
 963            buffer,
 964            None,
 965            field_editor_style,
 966            cx,
 967        )
 968    }
 969
 970    pub fn for_buffer(
 971        buffer: ModelHandle<Buffer>,
 972        project: Option<ModelHandle<Project>>,
 973        cx: &mut ViewContext<Self>,
 974    ) -> Self {
 975        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
 976        Self::new(EditorMode::Full, buffer, project, None, cx)
 977    }
 978
 979    pub fn for_multibuffer(
 980        buffer: ModelHandle<MultiBuffer>,
 981        project: Option<ModelHandle<Project>>,
 982        cx: &mut ViewContext<Self>,
 983    ) -> Self {
 984        Self::new(EditorMode::Full, buffer, project, None, cx)
 985    }
 986
 987    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 988        let mut clone = Self::new(
 989            self.mode,
 990            self.buffer.clone(),
 991            self.project.clone(),
 992            self.get_field_editor_theme,
 993            cx,
 994        );
 995        clone.scroll_position = self.scroll_position;
 996        clone.scroll_top_anchor = self.scroll_top_anchor.clone();
 997        clone.searchable = self.searchable;
 998        clone
 999    }
1000
1001    fn new(
1002        mode: EditorMode,
1003        buffer: ModelHandle<MultiBuffer>,
1004        project: Option<ModelHandle<Project>>,
1005        get_field_editor_theme: Option<GetFieldEditorTheme>,
1006        cx: &mut ViewContext<Self>,
1007    ) -> Self {
1008        let display_map = cx.add_model(|cx| {
1009            let settings = cx.global::<Settings>();
1010            let style = build_style(&*settings, get_field_editor_theme, None, cx);
1011            DisplayMap::new(
1012                buffer.clone(),
1013                style.text.font_id,
1014                style.text.font_size,
1015                None,
1016                2,
1017                1,
1018                cx,
1019            )
1020        });
1021        cx.observe(&buffer, Self::on_buffer_changed).detach();
1022        cx.subscribe(&buffer, Self::on_buffer_event).detach();
1023        cx.observe(&display_map, Self::on_display_map_changed)
1024            .detach();
1025
1026        let mut this = Self {
1027            handle: cx.weak_handle(),
1028            buffer,
1029            display_map,
1030            selections: Arc::from([]),
1031            pending_selection: Some(PendingSelection {
1032                selection: Selection {
1033                    id: 0,
1034                    start: Anchor::min(),
1035                    end: Anchor::min(),
1036                    reversed: false,
1037                    goal: SelectionGoal::None,
1038                },
1039                mode: SelectMode::Character,
1040            }),
1041            columnar_selection_tail: None,
1042            next_selection_id: 1,
1043            add_selections_state: None,
1044            select_next_state: None,
1045            selection_history: Default::default(),
1046            autoclose_stack: Default::default(),
1047            snippet_stack: Default::default(),
1048            select_larger_syntax_node_stack: Vec::new(),
1049            active_diagnostics: None,
1050            soft_wrap_mode_override: None,
1051            get_field_editor_theme,
1052            project,
1053            scroll_position: Vector2F::zero(),
1054            scroll_top_anchor: Anchor::min(),
1055            autoscroll_request: None,
1056            focused: false,
1057            show_local_cursors: false,
1058            show_local_selections: true,
1059            blink_epoch: 0,
1060            blinking_paused: false,
1061            mode,
1062            vertical_scroll_margin: 3.0,
1063            placeholder_text: None,
1064            highlighted_rows: None,
1065            background_highlights: Default::default(),
1066            nav_history: None,
1067            context_menu: None,
1068            completion_tasks: Default::default(),
1069            next_completion_id: 0,
1070            available_code_actions: Default::default(),
1071            code_actions_task: Default::default(),
1072            document_highlights_task: Default::default(),
1073            pending_rename: Default::default(),
1074            searchable: true,
1075            override_text_style: None,
1076            cursor_shape: Default::default(),
1077            keymap_context_layers: Default::default(),
1078            input_enabled: true,
1079            leader_replica_id: None,
1080        };
1081        this.end_selection(cx);
1082
1083        let editor_created_event = EditorCreated(cx.handle());
1084        cx.emit_global(editor_created_event);
1085
1086        this
1087    }
1088
1089    pub fn open_new(
1090        workspace: &mut Workspace,
1091        _: &workspace::OpenNew,
1092        cx: &mut ViewContext<Workspace>,
1093    ) {
1094        let project = workspace.project().clone();
1095        if project.read(cx).is_remote() {
1096            cx.propagate_action();
1097        } else if let Some(buffer) = project
1098            .update(cx, |project, cx| project.create_buffer(cx))
1099            .log_err()
1100        {
1101            workspace.add_item(
1102                Box::new(cx.add_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx))),
1103                cx,
1104            );
1105        }
1106    }
1107
1108    pub fn replica_id(&self, cx: &AppContext) -> ReplicaId {
1109        self.buffer.read(cx).replica_id()
1110    }
1111
1112    pub fn buffer(&self) -> &ModelHandle<MultiBuffer> {
1113        &self.buffer
1114    }
1115
1116    pub fn title(&self, cx: &AppContext) -> String {
1117        self.buffer().read(cx).title(cx)
1118    }
1119
1120    pub fn snapshot(&mut self, cx: &mut MutableAppContext) -> EditorSnapshot {
1121        EditorSnapshot {
1122            mode: self.mode,
1123            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1124            scroll_position: self.scroll_position,
1125            scroll_top_anchor: self.scroll_top_anchor.clone(),
1126            placeholder_text: self.placeholder_text.clone(),
1127            is_focused: self
1128                .handle
1129                .upgrade(cx)
1130                .map_or(false, |handle| handle.is_focused(cx)),
1131        }
1132    }
1133
1134    pub fn language<'a>(&self, cx: &'a AppContext) -> Option<&'a Arc<Language>> {
1135        self.buffer.read(cx).language(cx)
1136    }
1137
1138    fn style(&self, cx: &AppContext) -> EditorStyle {
1139        build_style(
1140            cx.global::<Settings>(),
1141            self.get_field_editor_theme,
1142            self.override_text_style.as_deref(),
1143            cx,
1144        )
1145    }
1146
1147    pub fn mode(&self) -> EditorMode {
1148        self.mode
1149    }
1150
1151    pub fn set_placeholder_text(
1152        &mut self,
1153        placeholder_text: impl Into<Arc<str>>,
1154        cx: &mut ViewContext<Self>,
1155    ) {
1156        self.placeholder_text = Some(placeholder_text.into());
1157        cx.notify();
1158    }
1159
1160    pub fn set_vertical_scroll_margin(&mut self, margin_rows: usize, cx: &mut ViewContext<Self>) {
1161        self.vertical_scroll_margin = margin_rows as f32;
1162        cx.notify();
1163    }
1164
1165    pub fn set_scroll_position(&mut self, scroll_position: Vector2F, cx: &mut ViewContext<Self>) {
1166        self.set_scroll_position_internal(scroll_position, true, cx);
1167    }
1168
1169    fn set_scroll_position_internal(
1170        &mut self,
1171        scroll_position: Vector2F,
1172        local: bool,
1173        cx: &mut ViewContext<Self>,
1174    ) {
1175        let map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1176
1177        if scroll_position.y() == 0. {
1178            self.scroll_top_anchor = Anchor::min();
1179            self.scroll_position = scroll_position;
1180        } else {
1181            let scroll_top_buffer_offset =
1182                DisplayPoint::new(scroll_position.y() as u32, 0).to_offset(&map, Bias::Right);
1183            let anchor = map
1184                .buffer_snapshot
1185                .anchor_at(scroll_top_buffer_offset, Bias::Right);
1186            self.scroll_position = vec2f(
1187                scroll_position.x(),
1188                scroll_position.y() - anchor.to_display_point(&map).row() as f32,
1189            );
1190            self.scroll_top_anchor = anchor;
1191        }
1192
1193        cx.emit(Event::ScrollPositionChanged { local });
1194        cx.notify();
1195    }
1196
1197    fn set_scroll_top_anchor(
1198        &mut self,
1199        anchor: Anchor,
1200        position: Vector2F,
1201        cx: &mut ViewContext<Self>,
1202    ) {
1203        self.scroll_top_anchor = anchor;
1204        self.scroll_position = position;
1205        cx.emit(Event::ScrollPositionChanged { local: false });
1206        cx.notify();
1207    }
1208
1209    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
1210        self.cursor_shape = cursor_shape;
1211        cx.notify();
1212    }
1213
1214    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
1215        self.display_map
1216            .update(cx, |map, _| map.clip_at_line_ends = clip);
1217    }
1218
1219    pub fn set_keymap_context_layer<Tag: 'static>(&mut self, context: gpui::keymap::Context) {
1220        self.keymap_context_layers
1221            .insert(TypeId::of::<Tag>(), context);
1222    }
1223
1224    pub fn remove_keymap_context_layer<Tag: 'static>(&mut self) {
1225        self.keymap_context_layers.remove(&TypeId::of::<Tag>());
1226    }
1227
1228    pub fn set_input_enabled(&mut self, input_enabled: bool) {
1229        self.input_enabled = input_enabled;
1230    }
1231
1232    pub fn scroll_position(&self, cx: &mut ViewContext<Self>) -> Vector2F {
1233        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1234        compute_scroll_position(&display_map, self.scroll_position, &self.scroll_top_anchor)
1235    }
1236
1237    pub fn clamp_scroll_left(&mut self, max: f32) -> bool {
1238        if max < self.scroll_position.x() {
1239            self.scroll_position.set_x(max);
1240            true
1241        } else {
1242            false
1243        }
1244    }
1245
1246    pub fn autoscroll_vertically(
1247        &mut self,
1248        viewport_height: f32,
1249        line_height: f32,
1250        cx: &mut ViewContext<Self>,
1251    ) -> bool {
1252        let visible_lines = viewport_height / line_height;
1253        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1254        let mut scroll_position =
1255            compute_scroll_position(&display_map, self.scroll_position, &self.scroll_top_anchor);
1256        let max_scroll_top = if matches!(self.mode, EditorMode::AutoHeight { .. }) {
1257            (display_map.max_point().row() as f32 - visible_lines + 1.).max(0.)
1258        } else {
1259            display_map.max_point().row().saturating_sub(1) as f32
1260        };
1261        if scroll_position.y() > max_scroll_top {
1262            scroll_position.set_y(max_scroll_top);
1263            self.set_scroll_position(scroll_position, cx);
1264        }
1265
1266        let (autoscroll, local) = if let Some(autoscroll) = self.autoscroll_request.take() {
1267            autoscroll
1268        } else {
1269            return false;
1270        };
1271
1272        let first_cursor_top;
1273        let last_cursor_bottom;
1274        if let Some(highlighted_rows) = &self.highlighted_rows {
1275            first_cursor_top = highlighted_rows.start as f32;
1276            last_cursor_bottom = first_cursor_top + 1.;
1277        } else if autoscroll == Autoscroll::Newest {
1278            let newest_selection =
1279                self.newest_selection_with_snapshot::<Point>(&display_map.buffer_snapshot);
1280            first_cursor_top = newest_selection.head().to_display_point(&display_map).row() as f32;
1281            last_cursor_bottom = first_cursor_top + 1.;
1282        } else {
1283            let selections = self.local_selections::<Point>(cx);
1284            first_cursor_top = selections
1285                .first()
1286                .unwrap()
1287                .head()
1288                .to_display_point(&display_map)
1289                .row() as f32;
1290            last_cursor_bottom = selections
1291                .last()
1292                .unwrap()
1293                .head()
1294                .to_display_point(&display_map)
1295                .row() as f32
1296                + 1.0;
1297        }
1298
1299        let margin = if matches!(self.mode, EditorMode::AutoHeight { .. }) {
1300            0.
1301        } else {
1302            ((visible_lines - (last_cursor_bottom - first_cursor_top)) / 2.0).floor()
1303        };
1304        if margin < 0.0 {
1305            return false;
1306        }
1307
1308        match autoscroll {
1309            Autoscroll::Fit | Autoscroll::Newest => {
1310                let margin = margin.min(self.vertical_scroll_margin);
1311                let target_top = (first_cursor_top - margin).max(0.0);
1312                let target_bottom = last_cursor_bottom + margin;
1313                let start_row = scroll_position.y();
1314                let end_row = start_row + visible_lines;
1315
1316                if target_top < start_row {
1317                    scroll_position.set_y(target_top);
1318                    self.set_scroll_position_internal(scroll_position, local, cx);
1319                } else if target_bottom >= end_row {
1320                    scroll_position.set_y(target_bottom - visible_lines);
1321                    self.set_scroll_position_internal(scroll_position, local, cx);
1322                }
1323            }
1324            Autoscroll::Center => {
1325                scroll_position.set_y((first_cursor_top - margin).max(0.0));
1326                self.set_scroll_position_internal(scroll_position, local, cx);
1327            }
1328        }
1329
1330        true
1331    }
1332
1333    pub fn autoscroll_horizontally(
1334        &mut self,
1335        start_row: u32,
1336        viewport_width: f32,
1337        scroll_width: f32,
1338        max_glyph_width: f32,
1339        layouts: &[text_layout::Line],
1340        cx: &mut ViewContext<Self>,
1341    ) -> bool {
1342        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1343        let selections = self.local_selections::<Point>(cx);
1344
1345        let mut target_left;
1346        let mut target_right;
1347
1348        if self.highlighted_rows.is_some() {
1349            target_left = 0.0_f32;
1350            target_right = 0.0_f32;
1351        } else {
1352            target_left = std::f32::INFINITY;
1353            target_right = 0.0_f32;
1354            for selection in selections {
1355                let head = selection.head().to_display_point(&display_map);
1356                if head.row() >= start_row && head.row() < start_row + layouts.len() as u32 {
1357                    let start_column = head.column().saturating_sub(3);
1358                    let end_column = cmp::min(display_map.line_len(head.row()), head.column() + 3);
1359                    target_left = target_left.min(
1360                        layouts[(head.row() - start_row) as usize]
1361                            .x_for_index(start_column as usize),
1362                    );
1363                    target_right = target_right.max(
1364                        layouts[(head.row() - start_row) as usize].x_for_index(end_column as usize)
1365                            + max_glyph_width,
1366                    );
1367                }
1368            }
1369        }
1370
1371        target_right = target_right.min(scroll_width);
1372
1373        if target_right - target_left > viewport_width {
1374            return false;
1375        }
1376
1377        let scroll_left = self.scroll_position.x() * max_glyph_width;
1378        let scroll_right = scroll_left + viewport_width;
1379
1380        if target_left < scroll_left {
1381            self.scroll_position.set_x(target_left / max_glyph_width);
1382            true
1383        } else if target_right > scroll_right {
1384            self.scroll_position
1385                .set_x((target_right - viewport_width) / max_glyph_width);
1386            true
1387        } else {
1388            false
1389        }
1390    }
1391
1392    pub fn replace_selections_with(
1393        &mut self,
1394        cx: &mut ViewContext<Self>,
1395        find_replacement: impl Fn(&DisplaySnapshot) -> DisplayPoint,
1396    ) {
1397        let display_map = self.snapshot(cx);
1398        let cursor = find_replacement(&display_map);
1399        let selection = Selection {
1400            id: post_inc(&mut self.next_selection_id),
1401            start: cursor,
1402            end: cursor,
1403            reversed: false,
1404            goal: SelectionGoal::None,
1405        }
1406        .map(|display_point| display_point.to_point(&display_map));
1407        self.update_selections(vec![selection], None, cx);
1408    }
1409
1410    pub fn move_selections(
1411        &mut self,
1412        cx: &mut ViewContext<Self>,
1413        move_selection: impl Fn(&DisplaySnapshot, &mut Selection<DisplayPoint>),
1414    ) {
1415        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1416        let selections = self
1417            .local_selections::<Point>(cx)
1418            .into_iter()
1419            .map(|selection| {
1420                let mut selection = selection.map(|point| point.to_display_point(&display_map));
1421                move_selection(&display_map, &mut selection);
1422                selection.map(|display_point| display_point.to_point(&display_map))
1423            })
1424            .collect();
1425        self.update_selections(selections, Some(Autoscroll::Fit), cx);
1426    }
1427
1428    pub fn move_selection_heads(
1429        &mut self,
1430        cx: &mut ViewContext<Self>,
1431        update_head: impl Fn(
1432            &DisplaySnapshot,
1433            DisplayPoint,
1434            SelectionGoal,
1435        ) -> (DisplayPoint, SelectionGoal),
1436    ) {
1437        self.move_selections(cx, |map, selection| {
1438            let (new_head, new_goal) = update_head(map, selection.head(), selection.goal);
1439            selection.set_head(new_head, new_goal);
1440        });
1441    }
1442
1443    pub fn move_cursors(
1444        &mut self,
1445        cx: &mut ViewContext<Self>,
1446        update_cursor_position: impl Fn(
1447            &DisplaySnapshot,
1448            DisplayPoint,
1449            SelectionGoal,
1450        ) -> (DisplayPoint, SelectionGoal),
1451    ) {
1452        self.move_selections(cx, |map, selection| {
1453            let (cursor, new_goal) = update_cursor_position(map, selection.head(), selection.goal);
1454            selection.collapse_to(cursor, new_goal)
1455        });
1456    }
1457
1458    fn select(&mut self, Select(phase): &Select, cx: &mut ViewContext<Self>) {
1459        self.hide_context_menu(cx);
1460
1461        match phase {
1462            SelectPhase::Begin {
1463                position,
1464                add,
1465                click_count,
1466            } => self.begin_selection(*position, *add, *click_count, cx),
1467            SelectPhase::BeginColumnar {
1468                position,
1469                overshoot,
1470            } => self.begin_columnar_selection(*position, *overshoot, cx),
1471            SelectPhase::Extend {
1472                position,
1473                click_count,
1474            } => self.extend_selection(*position, *click_count, cx),
1475            SelectPhase::Update {
1476                position,
1477                overshoot,
1478                scroll_position,
1479            } => self.update_selection(*position, *overshoot, *scroll_position, cx),
1480            SelectPhase::End => self.end_selection(cx),
1481        }
1482    }
1483
1484    fn extend_selection(
1485        &mut self,
1486        position: DisplayPoint,
1487        click_count: usize,
1488        cx: &mut ViewContext<Self>,
1489    ) {
1490        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1491        let tail = self
1492            .newest_selection_with_snapshot::<usize>(&display_map.buffer_snapshot)
1493            .tail();
1494        self.begin_selection(position, false, click_count, cx);
1495
1496        let position = position.to_offset(&display_map, Bias::Left);
1497        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
1498        let mut pending = self.pending_selection.clone().unwrap();
1499
1500        if position >= tail {
1501            pending.selection.start = tail_anchor.clone();
1502        } else {
1503            pending.selection.end = tail_anchor.clone();
1504            pending.selection.reversed = true;
1505        }
1506
1507        match &mut pending.mode {
1508            SelectMode::Word(range) | SelectMode::Line(range) => {
1509                *range = tail_anchor.clone()..tail_anchor
1510            }
1511            _ => {}
1512        }
1513
1514        self.set_selections(self.selections.clone(), Some(pending), true, cx);
1515    }
1516
1517    fn begin_selection(
1518        &mut self,
1519        position: DisplayPoint,
1520        add: bool,
1521        click_count: usize,
1522        cx: &mut ViewContext<Self>,
1523    ) {
1524        if !self.focused {
1525            cx.focus_self();
1526            cx.emit(Event::Activate);
1527        }
1528
1529        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1530        let buffer = &display_map.buffer_snapshot;
1531        let newest_selection = self.newest_anchor_selection().clone();
1532
1533        let start;
1534        let end;
1535        let mode;
1536        match click_count {
1537            1 => {
1538                start = buffer.anchor_before(position.to_point(&display_map));
1539                end = start.clone();
1540                mode = SelectMode::Character;
1541            }
1542            2 => {
1543                let range = movement::surrounding_word(&display_map, position);
1544                start = buffer.anchor_before(range.start.to_point(&display_map));
1545                end = buffer.anchor_before(range.end.to_point(&display_map));
1546                mode = SelectMode::Word(start.clone()..end.clone());
1547            }
1548            3 => {
1549                let position = display_map
1550                    .clip_point(position, Bias::Left)
1551                    .to_point(&display_map);
1552                let line_start = display_map.prev_line_boundary(position).0;
1553                let next_line_start = buffer.clip_point(
1554                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
1555                    Bias::Left,
1556                );
1557                start = buffer.anchor_before(line_start);
1558                end = buffer.anchor_before(next_line_start);
1559                mode = SelectMode::Line(start.clone()..end.clone());
1560            }
1561            _ => {
1562                start = buffer.anchor_before(0);
1563                end = buffer.anchor_before(buffer.len());
1564                mode = SelectMode::All;
1565            }
1566        }
1567
1568        let selection = Selection {
1569            id: post_inc(&mut self.next_selection_id),
1570            start,
1571            end,
1572            reversed: false,
1573            goal: SelectionGoal::None,
1574        };
1575
1576        let mut selections;
1577        if add {
1578            selections = self.selections.clone();
1579            // Remove the newest selection if it was added due to a previous mouse up
1580            // within this multi-click.
1581            if click_count > 1 {
1582                selections = self
1583                    .selections
1584                    .iter()
1585                    .filter(|selection| selection.id != newest_selection.id)
1586                    .cloned()
1587                    .collect();
1588            }
1589        } else {
1590            selections = Arc::from([]);
1591        }
1592        self.set_selections(
1593            selections,
1594            Some(PendingSelection { selection, mode }),
1595            true,
1596            cx,
1597        );
1598
1599        cx.notify();
1600    }
1601
1602    fn begin_columnar_selection(
1603        &mut self,
1604        position: DisplayPoint,
1605        overshoot: u32,
1606        cx: &mut ViewContext<Self>,
1607    ) {
1608        if !self.focused {
1609            cx.focus_self();
1610            cx.emit(Event::Activate);
1611        }
1612
1613        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1614        let tail = self
1615            .newest_selection_with_snapshot::<Point>(&display_map.buffer_snapshot)
1616            .tail();
1617        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
1618
1619        self.select_columns(
1620            tail.to_display_point(&display_map),
1621            position,
1622            overshoot,
1623            &display_map,
1624            cx,
1625        );
1626    }
1627
1628    fn update_selection(
1629        &mut self,
1630        position: DisplayPoint,
1631        overshoot: u32,
1632        scroll_position: Vector2F,
1633        cx: &mut ViewContext<Self>,
1634    ) {
1635        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1636
1637        if let Some(tail) = self.columnar_selection_tail.as_ref() {
1638            let tail = tail.to_display_point(&display_map);
1639            self.select_columns(tail, position, overshoot, &display_map, cx);
1640        } else if let Some(mut pending) = self.pending_selection.clone() {
1641            let buffer = self.buffer.read(cx).snapshot(cx);
1642            let head;
1643            let tail;
1644            match &pending.mode {
1645                SelectMode::Character => {
1646                    head = position.to_point(&display_map);
1647                    tail = pending.selection.tail().to_point(&buffer);
1648                }
1649                SelectMode::Word(original_range) => {
1650                    let original_display_range = original_range.start.to_display_point(&display_map)
1651                        ..original_range.end.to_display_point(&display_map);
1652                    let original_buffer_range = original_display_range.start.to_point(&display_map)
1653                        ..original_display_range.end.to_point(&display_map);
1654                    if movement::is_inside_word(&display_map, position)
1655                        || original_display_range.contains(&position)
1656                    {
1657                        let word_range = movement::surrounding_word(&display_map, position);
1658                        if word_range.start < original_display_range.start {
1659                            head = word_range.start.to_point(&display_map);
1660                        } else {
1661                            head = word_range.end.to_point(&display_map);
1662                        }
1663                    } else {
1664                        head = position.to_point(&display_map);
1665                    }
1666
1667                    if head <= original_buffer_range.start {
1668                        tail = original_buffer_range.end;
1669                    } else {
1670                        tail = original_buffer_range.start;
1671                    }
1672                }
1673                SelectMode::Line(original_range) => {
1674                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
1675
1676                    let position = display_map
1677                        .clip_point(position, Bias::Left)
1678                        .to_point(&display_map);
1679                    let line_start = display_map.prev_line_boundary(position).0;
1680                    let next_line_start = buffer.clip_point(
1681                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
1682                        Bias::Left,
1683                    );
1684
1685                    if line_start < original_range.start {
1686                        head = line_start
1687                    } else {
1688                        head = next_line_start
1689                    }
1690
1691                    if head <= original_range.start {
1692                        tail = original_range.end;
1693                    } else {
1694                        tail = original_range.start;
1695                    }
1696                }
1697                SelectMode::All => {
1698                    return;
1699                }
1700            };
1701
1702            if head < tail {
1703                pending.selection.start = buffer.anchor_before(head);
1704                pending.selection.end = buffer.anchor_before(tail);
1705                pending.selection.reversed = true;
1706            } else {
1707                pending.selection.start = buffer.anchor_before(tail);
1708                pending.selection.end = buffer.anchor_before(head);
1709                pending.selection.reversed = false;
1710            }
1711            self.set_selections(self.selections.clone(), Some(pending), true, cx);
1712        } else {
1713            log::error!("update_selection dispatched with no pending selection");
1714            return;
1715        }
1716
1717        self.set_scroll_position(scroll_position, cx);
1718        cx.notify();
1719    }
1720
1721    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
1722        self.columnar_selection_tail.take();
1723        if self.pending_selection.is_some() {
1724            let selections = self.local_selections::<usize>(cx);
1725            self.update_selections(selections, None, cx);
1726        }
1727    }
1728
1729    fn select_columns(
1730        &mut self,
1731        tail: DisplayPoint,
1732        head: DisplayPoint,
1733        overshoot: u32,
1734        display_map: &DisplaySnapshot,
1735        cx: &mut ViewContext<Self>,
1736    ) {
1737        let start_row = cmp::min(tail.row(), head.row());
1738        let end_row = cmp::max(tail.row(), head.row());
1739        let start_column = cmp::min(tail.column(), head.column() + overshoot);
1740        let end_column = cmp::max(tail.column(), head.column() + overshoot);
1741        let reversed = start_column < tail.column();
1742
1743        let selections = (start_row..=end_row)
1744            .filter_map(|row| {
1745                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
1746                    let start = display_map
1747                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
1748                        .to_point(&display_map);
1749                    let end = display_map
1750                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
1751                        .to_point(&display_map);
1752                    Some(Selection {
1753                        id: post_inc(&mut self.next_selection_id),
1754                        start,
1755                        end,
1756                        reversed,
1757                        goal: SelectionGoal::None,
1758                    })
1759                } else {
1760                    None
1761                }
1762            })
1763            .collect::<Vec<_>>();
1764
1765        self.update_selections(selections, None, cx);
1766        cx.notify();
1767    }
1768
1769    pub fn is_selecting(&self) -> bool {
1770        self.pending_selection.is_some() || self.columnar_selection_tail.is_some()
1771    }
1772
1773    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
1774        if self.take_rename(false, cx).is_some() {
1775            return;
1776        }
1777
1778        if self.hide_context_menu(cx).is_some() {
1779            return;
1780        }
1781
1782        if self.snippet_stack.pop().is_some() {
1783            return;
1784        }
1785
1786        if self.mode != EditorMode::Full {
1787            cx.propagate_action();
1788            return;
1789        }
1790
1791        if self.active_diagnostics.is_some() {
1792            self.dismiss_diagnostics(cx);
1793        } else if let Some(pending) = self.pending_selection.clone() {
1794            let mut selections = self.selections.clone();
1795            if selections.is_empty() {
1796                selections = Arc::from([pending.selection]);
1797            }
1798            self.set_selections(selections, None, true, cx);
1799            self.request_autoscroll(Autoscroll::Fit, cx);
1800        } else {
1801            let mut oldest_selection = self.oldest_selection::<usize>(&cx);
1802            if self.selection_count() == 1 {
1803                if oldest_selection.is_empty() {
1804                    cx.propagate_action();
1805                    return;
1806                }
1807
1808                oldest_selection.start = oldest_selection.head().clone();
1809                oldest_selection.end = oldest_selection.head().clone();
1810            }
1811            self.update_selections(vec![oldest_selection], Some(Autoscroll::Fit), cx);
1812        }
1813    }
1814
1815    #[cfg(any(test, feature = "test-support"))]
1816    pub fn selected_ranges<D: TextDimension + Ord + Sub<D, Output = D>>(
1817        &self,
1818        cx: &AppContext,
1819    ) -> Vec<Range<D>> {
1820        self.local_selections::<D>(cx)
1821            .iter()
1822            .map(|s| {
1823                if s.reversed {
1824                    s.end.clone()..s.start.clone()
1825                } else {
1826                    s.start.clone()..s.end.clone()
1827                }
1828            })
1829            .collect()
1830    }
1831
1832    #[cfg(any(test, feature = "test-support"))]
1833    pub fn selected_display_ranges(&self, cx: &mut MutableAppContext) -> Vec<Range<DisplayPoint>> {
1834        let display_map = self
1835            .display_map
1836            .update(cx, |display_map, cx| display_map.snapshot(cx));
1837        self.selections
1838            .iter()
1839            .chain(
1840                self.pending_selection
1841                    .as_ref()
1842                    .map(|pending| &pending.selection),
1843            )
1844            .map(|s| {
1845                if s.reversed {
1846                    s.end.to_display_point(&display_map)..s.start.to_display_point(&display_map)
1847                } else {
1848                    s.start.to_display_point(&display_map)..s.end.to_display_point(&display_map)
1849                }
1850            })
1851            .collect()
1852    }
1853
1854    pub fn select_ranges<I, T>(
1855        &mut self,
1856        ranges: I,
1857        autoscroll: Option<Autoscroll>,
1858        cx: &mut ViewContext<Self>,
1859    ) where
1860        I: IntoIterator<Item = Range<T>>,
1861        T: ToOffset,
1862    {
1863        let buffer = self.buffer.read(cx).snapshot(cx);
1864        let selections = ranges
1865            .into_iter()
1866            .map(|range| {
1867                let mut start = range.start.to_offset(&buffer);
1868                let mut end = range.end.to_offset(&buffer);
1869                let reversed = if start > end {
1870                    mem::swap(&mut start, &mut end);
1871                    true
1872                } else {
1873                    false
1874                };
1875                Selection {
1876                    id: post_inc(&mut self.next_selection_id),
1877                    start,
1878                    end,
1879                    reversed,
1880                    goal: SelectionGoal::None,
1881                }
1882            })
1883            .collect::<Vec<_>>();
1884        self.update_selections(selections, autoscroll, cx);
1885    }
1886
1887    #[cfg(any(test, feature = "test-support"))]
1888    pub fn select_display_ranges<'a, T>(&mut self, ranges: T, cx: &mut ViewContext<Self>)
1889    where
1890        T: IntoIterator<Item = &'a Range<DisplayPoint>>,
1891    {
1892        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1893        let selections = ranges
1894            .into_iter()
1895            .map(|range| {
1896                let mut start = range.start;
1897                let mut end = range.end;
1898                let reversed = if start > end {
1899                    mem::swap(&mut start, &mut end);
1900                    true
1901                } else {
1902                    false
1903                };
1904                Selection {
1905                    id: post_inc(&mut self.next_selection_id),
1906                    start: start.to_point(&display_map),
1907                    end: end.to_point(&display_map),
1908                    reversed,
1909                    goal: SelectionGoal::None,
1910                }
1911            })
1912            .collect();
1913        self.update_selections(selections, None, cx);
1914    }
1915
1916    pub fn handle_input(&mut self, action: &Input, cx: &mut ViewContext<Self>) {
1917        if !self.input_enabled {
1918            cx.propagate_action();
1919            return;
1920        }
1921
1922        let text = action.0.as_ref();
1923        if !self.skip_autoclose_end(text, cx) {
1924            self.transact(cx, |this, cx| {
1925                if !this.surround_with_bracket_pair(text, cx) {
1926                    this.insert(text, cx);
1927                    this.autoclose_bracket_pairs(cx);
1928                }
1929            });
1930            self.trigger_completion_on_input(text, cx);
1931        }
1932    }
1933
1934    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
1935        self.transact(cx, |this, cx| {
1936            let mut old_selections = SmallVec::<[_; 32]>::new();
1937            {
1938                let selections = this.local_selections::<usize>(cx);
1939                let buffer = this.buffer.read(cx).snapshot(cx);
1940                for selection in selections.iter() {
1941                    let start_point = selection.start.to_point(&buffer);
1942                    let indent = buffer
1943                        .indent_column_for_line(start_point.row)
1944                        .min(start_point.column);
1945                    let start = selection.start;
1946                    let end = selection.end;
1947
1948                    let mut insert_extra_newline = false;
1949                    if let Some(language) = buffer.language() {
1950                        let leading_whitespace_len = buffer
1951                            .reversed_chars_at(start)
1952                            .take_while(|c| c.is_whitespace() && *c != '\n')
1953                            .map(|c| c.len_utf8())
1954                            .sum::<usize>();
1955
1956                        let trailing_whitespace_len = buffer
1957                            .chars_at(end)
1958                            .take_while(|c| c.is_whitespace() && *c != '\n')
1959                            .map(|c| c.len_utf8())
1960                            .sum::<usize>();
1961
1962                        insert_extra_newline = language.brackets().iter().any(|pair| {
1963                            let pair_start = pair.start.trim_end();
1964                            let pair_end = pair.end.trim_start();
1965
1966                            pair.newline
1967                                && buffer.contains_str_at(end + trailing_whitespace_len, pair_end)
1968                                && buffer.contains_str_at(
1969                                    (start - leading_whitespace_len)
1970                                        .saturating_sub(pair_start.len()),
1971                                    pair_start,
1972                                )
1973                        });
1974                    }
1975
1976                    old_selections.push((
1977                        selection.id,
1978                        buffer.anchor_after(end),
1979                        start..end,
1980                        indent,
1981                        insert_extra_newline,
1982                    ));
1983                }
1984            }
1985
1986            this.buffer.update(cx, |buffer, cx| {
1987                let mut delta = 0_isize;
1988                let mut pending_edit: Option<PendingEdit> = None;
1989                for (_, _, range, indent, insert_extra_newline) in &old_selections {
1990                    if pending_edit.as_ref().map_or(false, |pending| {
1991                        pending.indent != *indent
1992                            || pending.insert_extra_newline != *insert_extra_newline
1993                    }) {
1994                        let pending = pending_edit.take().unwrap();
1995                        let mut new_text = String::with_capacity(1 + pending.indent as usize);
1996                        new_text.push('\n');
1997                        new_text.extend(iter::repeat(' ').take(pending.indent as usize));
1998                        if pending.insert_extra_newline {
1999                            new_text = new_text.repeat(2);
2000                        }
2001                        buffer.edit_with_autoindent(pending.ranges, new_text, cx);
2002                        delta += pending.delta;
2003                    }
2004
2005                    let start = (range.start as isize + delta) as usize;
2006                    let end = (range.end as isize + delta) as usize;
2007                    let mut text_len = *indent as usize + 1;
2008                    if *insert_extra_newline {
2009                        text_len *= 2;
2010                    }
2011
2012                    let pending = pending_edit.get_or_insert_with(Default::default);
2013                    pending.delta += text_len as isize - (end - start) as isize;
2014                    pending.indent = *indent;
2015                    pending.insert_extra_newline = *insert_extra_newline;
2016                    pending.ranges.push(start..end);
2017                }
2018
2019                let pending = pending_edit.unwrap();
2020                let mut new_text = String::with_capacity(1 + pending.indent as usize);
2021                new_text.push('\n');
2022                new_text.extend(iter::repeat(' ').take(pending.indent as usize));
2023                if pending.insert_extra_newline {
2024                    new_text = new_text.repeat(2);
2025                }
2026                buffer.edit_with_autoindent(pending.ranges, new_text, cx);
2027
2028                let buffer = buffer.read(cx);
2029                this.selections = this
2030                    .selections
2031                    .iter()
2032                    .cloned()
2033                    .zip(old_selections)
2034                    .map(
2035                        |(mut new_selection, (_, end_anchor, _, _, insert_extra_newline))| {
2036                            let mut cursor = end_anchor.to_point(&buffer);
2037                            if insert_extra_newline {
2038                                cursor.row -= 1;
2039                                cursor.column = buffer.line_len(cursor.row);
2040                            }
2041                            let anchor = buffer.anchor_after(cursor);
2042                            new_selection.start = anchor.clone();
2043                            new_selection.end = anchor;
2044                            new_selection
2045                        },
2046                    )
2047                    .collect();
2048            });
2049
2050            this.request_autoscroll(Autoscroll::Fit, cx);
2051        });
2052
2053        #[derive(Default)]
2054        struct PendingEdit {
2055            indent: u32,
2056            insert_extra_newline: bool,
2057            delta: isize,
2058            ranges: SmallVec<[Range<usize>; 32]>,
2059        }
2060    }
2061
2062    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
2063        self.transact(cx, |this, cx| {
2064            let old_selections = this.local_selections::<usize>(cx);
2065            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
2066                let anchors = {
2067                    let snapshot = buffer.read(cx);
2068                    old_selections
2069                        .iter()
2070                        .map(|s| (s.id, s.goal, snapshot.anchor_after(s.end)))
2071                        .collect::<Vec<_>>()
2072                };
2073                let edit_ranges = old_selections.iter().map(|s| s.start..s.end);
2074                buffer.edit_with_autoindent(edit_ranges, text, cx);
2075                anchors
2076            });
2077
2078            let selections = {
2079                let snapshot = this.buffer.read(cx).read(cx);
2080                selection_anchors
2081                    .into_iter()
2082                    .map(|(id, goal, position)| {
2083                        let position = position.to_offset(&snapshot);
2084                        Selection {
2085                            id,
2086                            start: position,
2087                            end: position,
2088                            goal,
2089                            reversed: false,
2090                        }
2091                    })
2092                    .collect()
2093            };
2094            this.update_selections(selections, Some(Autoscroll::Fit), cx);
2095        });
2096    }
2097
2098    fn trigger_completion_on_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
2099        let selection = self.newest_anchor_selection();
2100        if self
2101            .buffer
2102            .read(cx)
2103            .is_completion_trigger(selection.head(), text, cx)
2104        {
2105            self.show_completions(&ShowCompletions, cx);
2106        } else {
2107            self.hide_context_menu(cx);
2108        }
2109    }
2110
2111    fn surround_with_bracket_pair(&mut self, text: &str, cx: &mut ViewContext<Self>) -> bool {
2112        let snapshot = self.buffer.read(cx).snapshot(cx);
2113        if let Some(pair) = snapshot
2114            .language()
2115            .and_then(|language| language.brackets().iter().find(|b| b.start == text))
2116            .cloned()
2117        {
2118            if self
2119                .local_selections::<usize>(cx)
2120                .iter()
2121                .any(|selection| selection.is_empty())
2122            {
2123                false
2124            } else {
2125                let mut selections = self.selections.to_vec();
2126                for selection in &mut selections {
2127                    selection.end = selection.end.bias_left(&snapshot);
2128                }
2129                drop(snapshot);
2130
2131                self.buffer.update(cx, |buffer, cx| {
2132                    buffer.edit(
2133                        selections.iter().map(|s| s.start.clone()..s.start.clone()),
2134                        &pair.start,
2135                        cx,
2136                    );
2137                    buffer.edit(
2138                        selections.iter().map(|s| s.end.clone()..s.end.clone()),
2139                        &pair.end,
2140                        cx,
2141                    );
2142                });
2143
2144                let snapshot = self.buffer.read(cx).read(cx);
2145                for selection in &mut selections {
2146                    selection.end = selection.end.bias_right(&snapshot);
2147                }
2148                drop(snapshot);
2149
2150                self.set_selections(selections.into(), None, true, cx);
2151                true
2152            }
2153        } else {
2154            false
2155        }
2156    }
2157
2158    fn autoclose_bracket_pairs(&mut self, cx: &mut ViewContext<Self>) {
2159        let selections = self.local_selections::<usize>(cx);
2160        let mut bracket_pair_state = None;
2161        let mut new_selections = None;
2162        self.buffer.update(cx, |buffer, cx| {
2163            let mut snapshot = buffer.snapshot(cx);
2164            let left_biased_selections = selections
2165                .iter()
2166                .map(|selection| Selection {
2167                    id: selection.id,
2168                    start: snapshot.anchor_before(selection.start),
2169                    end: snapshot.anchor_before(selection.end),
2170                    reversed: selection.reversed,
2171                    goal: selection.goal,
2172                })
2173                .collect::<Vec<_>>();
2174
2175            let autoclose_pair = snapshot.language().and_then(|language| {
2176                let first_selection_start = selections.first().unwrap().start;
2177                let pair = language.brackets().iter().find(|pair| {
2178                    snapshot.contains_str_at(
2179                        first_selection_start.saturating_sub(pair.start.len()),
2180                        &pair.start,
2181                    )
2182                });
2183                pair.and_then(|pair| {
2184                    let should_autoclose = selections.iter().all(|selection| {
2185                        // Ensure all selections are parked at the end of a pair start.
2186                        if snapshot.contains_str_at(
2187                            selection.start.saturating_sub(pair.start.len()),
2188                            &pair.start,
2189                        ) {
2190                            snapshot
2191                                .chars_at(selection.start)
2192                                .next()
2193                                .map_or(true, |c| language.should_autoclose_before(c))
2194                        } else {
2195                            false
2196                        }
2197                    });
2198
2199                    if should_autoclose {
2200                        Some(pair.clone())
2201                    } else {
2202                        None
2203                    }
2204                })
2205            });
2206
2207            if let Some(pair) = autoclose_pair {
2208                let selection_ranges = selections
2209                    .iter()
2210                    .map(|selection| {
2211                        let start = selection.start.to_offset(&snapshot);
2212                        start..start
2213                    })
2214                    .collect::<SmallVec<[_; 32]>>();
2215
2216                buffer.edit(selection_ranges, &pair.end, cx);
2217                snapshot = buffer.snapshot(cx);
2218
2219                new_selections = Some(
2220                    self.resolve_selections::<usize, _>(left_biased_selections.iter(), &snapshot)
2221                        .collect::<Vec<_>>(),
2222                );
2223
2224                if pair.end.len() == 1 {
2225                    let mut delta = 0;
2226                    bracket_pair_state = Some(BracketPairState {
2227                        ranges: selections
2228                            .iter()
2229                            .map(move |selection| {
2230                                let offset = selection.start + delta;
2231                                delta += 1;
2232                                snapshot.anchor_before(offset)..snapshot.anchor_after(offset)
2233                            })
2234                            .collect(),
2235                        pair,
2236                    });
2237                }
2238            }
2239        });
2240
2241        if let Some(new_selections) = new_selections {
2242            self.update_selections(new_selections, None, cx);
2243        }
2244        if let Some(bracket_pair_state) = bracket_pair_state {
2245            self.autoclose_stack.push(bracket_pair_state);
2246        }
2247    }
2248
2249    fn skip_autoclose_end(&mut self, text: &str, cx: &mut ViewContext<Self>) -> bool {
2250        let old_selections = self.local_selections::<usize>(cx);
2251        let autoclose_pair = if let Some(autoclose_pair) = self.autoclose_stack.last() {
2252            autoclose_pair
2253        } else {
2254            return false;
2255        };
2256        if text != autoclose_pair.pair.end {
2257            return false;
2258        }
2259
2260        debug_assert_eq!(old_selections.len(), autoclose_pair.ranges.len());
2261
2262        let buffer = self.buffer.read(cx).snapshot(cx);
2263        if old_selections
2264            .iter()
2265            .zip(autoclose_pair.ranges.iter().map(|r| r.to_offset(&buffer)))
2266            .all(|(selection, autoclose_range)| {
2267                let autoclose_range_end = autoclose_range.end.to_offset(&buffer);
2268                selection.is_empty() && selection.start == autoclose_range_end
2269            })
2270        {
2271            let new_selections = old_selections
2272                .into_iter()
2273                .map(|selection| {
2274                    let cursor = selection.start + 1;
2275                    Selection {
2276                        id: selection.id,
2277                        start: cursor,
2278                        end: cursor,
2279                        reversed: false,
2280                        goal: SelectionGoal::None,
2281                    }
2282                })
2283                .collect();
2284            self.autoclose_stack.pop();
2285            self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
2286            true
2287        } else {
2288            false
2289        }
2290    }
2291
2292    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
2293        let offset = position.to_offset(buffer);
2294        let (word_range, kind) = buffer.surrounding_word(offset);
2295        if offset > word_range.start && kind == Some(CharKind::Word) {
2296            Some(
2297                buffer
2298                    .text_for_range(word_range.start..offset)
2299                    .collect::<String>(),
2300            )
2301        } else {
2302            None
2303        }
2304    }
2305
2306    fn show_completions(&mut self, _: &ShowCompletions, cx: &mut ViewContext<Self>) {
2307        if self.pending_rename.is_some() {
2308            return;
2309        }
2310
2311        let project = if let Some(project) = self.project.clone() {
2312            project
2313        } else {
2314            return;
2315        };
2316
2317        let position = self.newest_anchor_selection().head();
2318        let (buffer, buffer_position) = if let Some(output) = self
2319            .buffer
2320            .read(cx)
2321            .text_anchor_for_position(position.clone(), cx)
2322        {
2323            output
2324        } else {
2325            return;
2326        };
2327
2328        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position.clone());
2329        let completions = project.update(cx, |project, cx| {
2330            project.completions(&buffer, buffer_position.clone(), cx)
2331        });
2332
2333        let id = post_inc(&mut self.next_completion_id);
2334        let task = cx.spawn_weak(|this, mut cx| {
2335            async move {
2336                let completions = completions.await?;
2337                if completions.is_empty() {
2338                    return Ok(());
2339                }
2340
2341                let mut menu = CompletionsMenu {
2342                    id,
2343                    initial_position: position,
2344                    match_candidates: completions
2345                        .iter()
2346                        .enumerate()
2347                        .map(|(id, completion)| {
2348                            StringMatchCandidate::new(
2349                                id,
2350                                completion.label.text[completion.label.filter_range.clone()].into(),
2351                            )
2352                        })
2353                        .collect(),
2354                    buffer,
2355                    completions: completions.into(),
2356                    matches: Vec::new().into(),
2357                    selected_item: 0,
2358                    list: Default::default(),
2359                };
2360
2361                menu.filter(query.as_deref(), cx.background()).await;
2362
2363                if let Some(this) = this.upgrade(&cx) {
2364                    this.update(&mut cx, |this, cx| {
2365                        match this.context_menu.as_ref() {
2366                            None => {}
2367                            Some(ContextMenu::Completions(prev_menu)) => {
2368                                if prev_menu.id > menu.id {
2369                                    return;
2370                                }
2371                            }
2372                            _ => return,
2373                        }
2374
2375                        this.completion_tasks.retain(|(id, _)| *id > menu.id);
2376                        if this.focused {
2377                            this.show_context_menu(ContextMenu::Completions(menu), cx);
2378                        }
2379
2380                        cx.notify();
2381                    });
2382                }
2383                Ok::<_, anyhow::Error>(())
2384            }
2385            .log_err()
2386        });
2387        self.completion_tasks.push((id, task));
2388    }
2389
2390    pub fn confirm_completion(
2391        &mut self,
2392        ConfirmCompletion(completion_ix): &ConfirmCompletion,
2393        cx: &mut ViewContext<Self>,
2394    ) -> Option<Task<Result<()>>> {
2395        use language::ToOffset as _;
2396
2397        let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
2398            menu
2399        } else {
2400            return None;
2401        };
2402
2403        let mat = completions_menu
2404            .matches
2405            .get(completion_ix.unwrap_or(completions_menu.selected_item))?;
2406        let buffer_handle = completions_menu.buffer;
2407        let completion = completions_menu.completions.get(mat.candidate_id)?;
2408
2409        let snippet;
2410        let text;
2411        if completion.is_snippet() {
2412            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
2413            text = snippet.as_ref().unwrap().text.clone();
2414        } else {
2415            snippet = None;
2416            text = completion.new_text.clone();
2417        };
2418        let buffer = buffer_handle.read(cx);
2419        let old_range = completion.old_range.to_offset(&buffer);
2420        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
2421
2422        let selections = self.local_selections::<usize>(cx);
2423        let newest_selection = self.newest_anchor_selection();
2424        if newest_selection.start.buffer_id != Some(buffer_handle.id()) {
2425            return None;
2426        }
2427
2428        let lookbehind = newest_selection
2429            .start
2430            .text_anchor
2431            .to_offset(buffer)
2432            .saturating_sub(old_range.start);
2433        let lookahead = old_range
2434            .end
2435            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
2436        let mut common_prefix_len = old_text
2437            .bytes()
2438            .zip(text.bytes())
2439            .take_while(|(a, b)| a == b)
2440            .count();
2441
2442        let snapshot = self.buffer.read(cx).snapshot(cx);
2443        let mut ranges = Vec::new();
2444        for selection in &selections {
2445            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
2446                let start = selection.start.saturating_sub(lookbehind);
2447                let end = selection.end + lookahead;
2448                ranges.push(start + common_prefix_len..end);
2449            } else {
2450                common_prefix_len = 0;
2451                ranges.clear();
2452                ranges.extend(selections.iter().map(|s| {
2453                    if s.id == newest_selection.id {
2454                        old_range.clone()
2455                    } else {
2456                        s.start..s.end
2457                    }
2458                }));
2459                break;
2460            }
2461        }
2462        let text = &text[common_prefix_len..];
2463
2464        self.transact(cx, |this, cx| {
2465            if let Some(mut snippet) = snippet {
2466                snippet.text = text.to_string();
2467                for tabstop in snippet.tabstops.iter_mut().flatten() {
2468                    tabstop.start -= common_prefix_len as isize;
2469                    tabstop.end -= common_prefix_len as isize;
2470                }
2471
2472                this.insert_snippet(&ranges, snippet, cx).log_err();
2473            } else {
2474                this.buffer.update(cx, |buffer, cx| {
2475                    buffer.edit_with_autoindent(ranges, text, cx);
2476                });
2477            }
2478        });
2479
2480        let project = self.project.clone()?;
2481        let apply_edits = project.update(cx, |project, cx| {
2482            project.apply_additional_edits_for_completion(
2483                buffer_handle,
2484                completion.clone(),
2485                true,
2486                cx,
2487            )
2488        });
2489        Some(cx.foreground().spawn(async move {
2490            apply_edits.await?;
2491            Ok(())
2492        }))
2493    }
2494
2495    pub fn toggle_code_actions(
2496        &mut self,
2497        &ToggleCodeActions(deployed_from_indicator): &ToggleCodeActions,
2498        cx: &mut ViewContext<Self>,
2499    ) {
2500        if matches!(
2501            self.context_menu.as_ref(),
2502            Some(ContextMenu::CodeActions(_))
2503        ) {
2504            self.context_menu.take();
2505            cx.notify();
2506            return;
2507        }
2508
2509        let mut task = self.code_actions_task.take();
2510        cx.spawn_weak(|this, mut cx| async move {
2511            while let Some(prev_task) = task {
2512                prev_task.await;
2513                task = this
2514                    .upgrade(&cx)
2515                    .and_then(|this| this.update(&mut cx, |this, _| this.code_actions_task.take()));
2516            }
2517
2518            if let Some(this) = this.upgrade(&cx) {
2519                this.update(&mut cx, |this, cx| {
2520                    if this.focused {
2521                        if let Some((buffer, actions)) = this.available_code_actions.clone() {
2522                            this.show_context_menu(
2523                                ContextMenu::CodeActions(CodeActionsMenu {
2524                                    buffer,
2525                                    actions,
2526                                    selected_item: Default::default(),
2527                                    list: Default::default(),
2528                                    deployed_from_indicator,
2529                                }),
2530                                cx,
2531                            );
2532                        }
2533                    }
2534                })
2535            }
2536            Ok::<_, anyhow::Error>(())
2537        })
2538        .detach_and_log_err(cx);
2539    }
2540
2541    pub fn confirm_code_action(
2542        workspace: &mut Workspace,
2543        ConfirmCodeAction(action_ix): &ConfirmCodeAction,
2544        cx: &mut ViewContext<Workspace>,
2545    ) -> Option<Task<Result<()>>> {
2546        let editor = workspace.active_item(cx)?.act_as::<Editor>(cx)?;
2547        let actions_menu = if let ContextMenu::CodeActions(menu) =
2548            editor.update(cx, |editor, cx| editor.hide_context_menu(cx))?
2549        {
2550            menu
2551        } else {
2552            return None;
2553        };
2554        let action_ix = action_ix.unwrap_or(actions_menu.selected_item);
2555        let action = actions_menu.actions.get(action_ix)?.clone();
2556        let title = action.lsp_action.title.clone();
2557        let buffer = actions_menu.buffer;
2558
2559        let apply_code_actions = workspace.project().clone().update(cx, |project, cx| {
2560            project.apply_code_action(buffer, action, true, cx)
2561        });
2562        Some(cx.spawn(|workspace, cx| async move {
2563            let project_transaction = apply_code_actions.await?;
2564            Self::open_project_transaction(editor, workspace, project_transaction, title, cx).await
2565        }))
2566    }
2567
2568    async fn open_project_transaction(
2569        this: ViewHandle<Editor>,
2570        workspace: ViewHandle<Workspace>,
2571        transaction: ProjectTransaction,
2572        title: String,
2573        mut cx: AsyncAppContext,
2574    ) -> Result<()> {
2575        let replica_id = this.read_with(&cx, |this, cx| this.replica_id(cx));
2576
2577        // If the project transaction's edits are all contained within this editor, then
2578        // avoid opening a new editor to display them.
2579        let mut entries = transaction.0.iter();
2580        if let Some((buffer, transaction)) = entries.next() {
2581            if entries.next().is_none() {
2582                let excerpt = this.read_with(&cx, |editor, cx| {
2583                    editor
2584                        .buffer()
2585                        .read(cx)
2586                        .excerpt_containing(editor.newest_anchor_selection().head(), cx)
2587                });
2588                if let Some((excerpted_buffer, excerpt_range)) = excerpt {
2589                    if excerpted_buffer == *buffer {
2590                        let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
2591                        let excerpt_range = excerpt_range.to_offset(&snapshot);
2592                        if snapshot
2593                            .edited_ranges_for_transaction(transaction)
2594                            .all(|range| {
2595                                excerpt_range.start <= range.start && excerpt_range.end >= range.end
2596                            })
2597                        {
2598                            return Ok(());
2599                        }
2600                    }
2601                }
2602            }
2603        } else {
2604            return Ok(());
2605        }
2606
2607        let mut ranges_to_highlight = Vec::new();
2608        let excerpt_buffer = cx.add_model(|cx| {
2609            let mut multibuffer = MultiBuffer::new(replica_id).with_title(title);
2610            for (buffer, transaction) in &transaction.0 {
2611                let snapshot = buffer.read(cx).snapshot();
2612                ranges_to_highlight.extend(
2613                    multibuffer.push_excerpts_with_context_lines(
2614                        buffer.clone(),
2615                        snapshot
2616                            .edited_ranges_for_transaction::<usize>(transaction)
2617                            .collect(),
2618                        1,
2619                        cx,
2620                    ),
2621                );
2622            }
2623            multibuffer.push_transaction(&transaction.0);
2624            multibuffer
2625        });
2626
2627        workspace.update(&mut cx, |workspace, cx| {
2628            let project = workspace.project().clone();
2629            let editor =
2630                cx.add_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), cx));
2631            workspace.add_item(Box::new(editor.clone()), cx);
2632            editor.update(cx, |editor, cx| {
2633                let color = editor.style(cx).highlighted_line_background;
2634                editor.highlight_background::<Self>(ranges_to_highlight, color, cx);
2635            });
2636        });
2637
2638        Ok(())
2639    }
2640
2641    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
2642        let project = self.project.as_ref()?;
2643        let buffer = self.buffer.read(cx);
2644        let newest_selection = self.newest_anchor_selection().clone();
2645        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
2646        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
2647        if start_buffer != end_buffer {
2648            return None;
2649        }
2650
2651        let actions = project.update(cx, |project, cx| {
2652            project.code_actions(&start_buffer, start..end, cx)
2653        });
2654        self.code_actions_task = Some(cx.spawn_weak(|this, mut cx| async move {
2655            let actions = actions.await;
2656            if let Some(this) = this.upgrade(&cx) {
2657                this.update(&mut cx, |this, cx| {
2658                    this.available_code_actions = actions.log_err().and_then(|actions| {
2659                        if actions.is_empty() {
2660                            None
2661                        } else {
2662                            Some((start_buffer, actions.into()))
2663                        }
2664                    });
2665                    cx.notify();
2666                })
2667            }
2668        }));
2669        None
2670    }
2671
2672    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
2673        if self.pending_rename.is_some() {
2674            return None;
2675        }
2676
2677        let project = self.project.as_ref()?;
2678        let buffer = self.buffer.read(cx);
2679        let newest_selection = self.newest_anchor_selection().clone();
2680        let cursor_position = newest_selection.head();
2681        let (cursor_buffer, cursor_buffer_position) =
2682            buffer.text_anchor_for_position(cursor_position.clone(), cx)?;
2683        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
2684        if cursor_buffer != tail_buffer {
2685            return None;
2686        }
2687
2688        let highlights = project.update(cx, |project, cx| {
2689            project.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
2690        });
2691
2692        self.document_highlights_task = Some(cx.spawn_weak(|this, mut cx| async move {
2693            let highlights = highlights.log_err().await;
2694            if let Some((this, highlights)) = this.upgrade(&cx).zip(highlights) {
2695                this.update(&mut cx, |this, cx| {
2696                    if this.pending_rename.is_some() {
2697                        return;
2698                    }
2699
2700                    let buffer_id = cursor_position.buffer_id;
2701                    let style = this.style(cx);
2702                    let read_background = style.document_highlight_read_background;
2703                    let write_background = style.document_highlight_write_background;
2704                    let buffer = this.buffer.read(cx);
2705                    if !buffer
2706                        .text_anchor_for_position(cursor_position, cx)
2707                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
2708                    {
2709                        return;
2710                    }
2711
2712                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
2713                    let mut write_ranges = Vec::new();
2714                    let mut read_ranges = Vec::new();
2715                    for highlight in highlights {
2716                        for (excerpt_id, excerpt_range) in
2717                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
2718                        {
2719                            let start = highlight
2720                                .range
2721                                .start
2722                                .max(&excerpt_range.start, cursor_buffer_snapshot);
2723                            let end = highlight
2724                                .range
2725                                .end
2726                                .min(&excerpt_range.end, cursor_buffer_snapshot);
2727                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
2728                                continue;
2729                            }
2730
2731                            let range = Anchor {
2732                                buffer_id,
2733                                excerpt_id: excerpt_id.clone(),
2734                                text_anchor: start,
2735                            }..Anchor {
2736                                buffer_id,
2737                                excerpt_id,
2738                                text_anchor: end,
2739                            };
2740                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
2741                                write_ranges.push(range);
2742                            } else {
2743                                read_ranges.push(range);
2744                            }
2745                        }
2746                    }
2747
2748                    this.highlight_background::<DocumentHighlightRead>(
2749                        read_ranges,
2750                        read_background,
2751                        cx,
2752                    );
2753                    this.highlight_background::<DocumentHighlightWrite>(
2754                        write_ranges,
2755                        write_background,
2756                        cx,
2757                    );
2758                    cx.notify();
2759                });
2760            }
2761        }));
2762        None
2763    }
2764
2765    pub fn render_code_actions_indicator(
2766        &self,
2767        style: &EditorStyle,
2768        cx: &mut ViewContext<Self>,
2769    ) -> Option<ElementBox> {
2770        if self.available_code_actions.is_some() {
2771            enum Tag {}
2772            Some(
2773                MouseEventHandler::new::<Tag, _, _>(0, cx, |_, _| {
2774                    Svg::new("icons/zap.svg")
2775                        .with_color(style.code_actions_indicator)
2776                        .boxed()
2777                })
2778                .with_cursor_style(CursorStyle::PointingHand)
2779                .with_padding(Padding::uniform(3.))
2780                .on_mouse_down(|cx| {
2781                    cx.dispatch_action(ToggleCodeActions(true));
2782                })
2783                .boxed(),
2784            )
2785        } else {
2786            None
2787        }
2788    }
2789
2790    pub fn context_menu_visible(&self) -> bool {
2791        self.context_menu
2792            .as_ref()
2793            .map_or(false, |menu| menu.visible())
2794    }
2795
2796    pub fn render_context_menu(
2797        &self,
2798        cursor_position: DisplayPoint,
2799        style: EditorStyle,
2800        cx: &AppContext,
2801    ) -> Option<(DisplayPoint, ElementBox)> {
2802        self.context_menu
2803            .as_ref()
2804            .map(|menu| menu.render(cursor_position, style, cx))
2805    }
2806
2807    fn show_context_menu(&mut self, menu: ContextMenu, cx: &mut ViewContext<Self>) {
2808        if !matches!(menu, ContextMenu::Completions(_)) {
2809            self.completion_tasks.clear();
2810        }
2811        self.context_menu = Some(menu);
2812        cx.notify();
2813    }
2814
2815    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
2816        cx.notify();
2817        self.completion_tasks.clear();
2818        self.context_menu.take()
2819    }
2820
2821    pub fn insert_snippet(
2822        &mut self,
2823        insertion_ranges: &[Range<usize>],
2824        snippet: Snippet,
2825        cx: &mut ViewContext<Self>,
2826    ) -> Result<()> {
2827        let tabstops = self.buffer.update(cx, |buffer, cx| {
2828            buffer.edit_with_autoindent(insertion_ranges.iter().cloned(), &snippet.text, cx);
2829
2830            let snapshot = &*buffer.read(cx);
2831            let snippet = &snippet;
2832            snippet
2833                .tabstops
2834                .iter()
2835                .map(|tabstop| {
2836                    let mut tabstop_ranges = tabstop
2837                        .iter()
2838                        .flat_map(|tabstop_range| {
2839                            let mut delta = 0 as isize;
2840                            insertion_ranges.iter().map(move |insertion_range| {
2841                                let insertion_start = insertion_range.start as isize + delta;
2842                                delta +=
2843                                    snippet.text.len() as isize - insertion_range.len() as isize;
2844
2845                                let start = snapshot.anchor_before(
2846                                    (insertion_start + tabstop_range.start) as usize,
2847                                );
2848                                let end = snapshot
2849                                    .anchor_after((insertion_start + tabstop_range.end) as usize);
2850                                start..end
2851                            })
2852                        })
2853                        .collect::<Vec<_>>();
2854                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
2855                    tabstop_ranges
2856                })
2857                .collect::<Vec<_>>()
2858        });
2859
2860        if let Some(tabstop) = tabstops.first() {
2861            self.select_ranges(tabstop.iter().cloned(), Some(Autoscroll::Fit), cx);
2862            self.snippet_stack.push(SnippetState {
2863                active_index: 0,
2864                ranges: tabstops,
2865            });
2866        }
2867
2868        Ok(())
2869    }
2870
2871    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
2872        self.move_to_snippet_tabstop(Bias::Right, cx)
2873    }
2874
2875    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) {
2876        self.move_to_snippet_tabstop(Bias::Left, cx);
2877    }
2878
2879    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
2880        let buffer = self.buffer.read(cx).snapshot(cx);
2881
2882        if let Some(snippet) = self.snippet_stack.last_mut() {
2883            match bias {
2884                Bias::Left => {
2885                    if snippet.active_index > 0 {
2886                        snippet.active_index -= 1;
2887                    } else {
2888                        return false;
2889                    }
2890                }
2891                Bias::Right => {
2892                    if snippet.active_index + 1 < snippet.ranges.len() {
2893                        snippet.active_index += 1;
2894                    } else {
2895                        return false;
2896                    }
2897                }
2898            }
2899            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
2900                let new_selections = current_ranges
2901                    .iter()
2902                    .map(|new_range| {
2903                        let new_range = new_range.to_offset(&buffer);
2904                        Selection {
2905                            id: post_inc(&mut self.next_selection_id),
2906                            start: new_range.start,
2907                            end: new_range.end,
2908                            reversed: false,
2909                            goal: SelectionGoal::None,
2910                        }
2911                    })
2912                    .collect();
2913
2914                // Remove the snippet state when moving to the last tabstop.
2915                if snippet.active_index + 1 == snippet.ranges.len() {
2916                    self.snippet_stack.pop();
2917                }
2918
2919                self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
2920                return true;
2921            }
2922            self.snippet_stack.pop();
2923        }
2924
2925        false
2926    }
2927
2928    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
2929        self.transact(cx, |this, cx| {
2930            this.select_all(&SelectAll, cx);
2931            this.insert("", cx);
2932        });
2933    }
2934
2935    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
2936        let mut selections = self.local_selections::<Point>(cx);
2937        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2938        for selection in &mut selections {
2939            if selection.is_empty() {
2940                let old_head = selection.head();
2941                let mut new_head =
2942                    movement::left(&display_map, old_head.to_display_point(&display_map))
2943                        .to_point(&display_map);
2944                if let Some((buffer, line_buffer_range)) = display_map
2945                    .buffer_snapshot
2946                    .buffer_line_for_row(old_head.row)
2947                {
2948                    let indent_column = buffer.indent_column_for_line(line_buffer_range.start.row);
2949                    if old_head.column <= indent_column && old_head.column > 0 {
2950                        let indent = INDENT_SIZE;
2951                        new_head = cmp::min(
2952                            new_head,
2953                            Point::new(old_head.row, ((old_head.column - 1) / indent) * indent),
2954                        );
2955                    }
2956                }
2957
2958                selection.set_head(new_head, SelectionGoal::None);
2959            }
2960        }
2961
2962        self.transact(cx, |this, cx| {
2963            this.update_selections(selections, Some(Autoscroll::Fit), cx);
2964            this.insert("", cx);
2965        });
2966    }
2967
2968    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
2969        self.transact(cx, |this, cx| {
2970            this.move_selections(cx, |map, selection| {
2971                if selection.is_empty() {
2972                    let cursor = movement::right(map, selection.head());
2973                    selection.set_head(cursor, SelectionGoal::None);
2974                }
2975            });
2976            this.insert(&"", cx);
2977        });
2978    }
2979
2980    pub fn tab(&mut self, &Tab(direction): &Tab, cx: &mut ViewContext<Self>) {
2981        match direction {
2982            Direction::Prev => {
2983                if !self.snippet_stack.is_empty() {
2984                    self.move_to_prev_snippet_tabstop(cx);
2985                    return;
2986                }
2987
2988                self.outdent(&Outdent, cx);
2989            }
2990            Direction::Next => {
2991                if self.move_to_next_snippet_tabstop(cx) {
2992                    return;
2993                }
2994
2995                let tab_size = cx.global::<Settings>().tab_size;
2996                let mut selections = self.local_selections::<Point>(cx);
2997                if selections.iter().all(|s| s.is_empty()) {
2998                    self.transact(cx, |this, cx| {
2999                        this.buffer.update(cx, |buffer, cx| {
3000                            for selection in &mut selections {
3001                                let char_column = buffer
3002                                    .read(cx)
3003                                    .text_for_range(
3004                                        Point::new(selection.start.row, 0)..selection.start,
3005                                    )
3006                                    .flat_map(str::chars)
3007                                    .count();
3008                                let chars_to_next_tab_stop =
3009                                    tab_size - (char_column as u32 % tab_size);
3010                                buffer.edit(
3011                                    [selection.start..selection.start],
3012                                    " ".repeat(chars_to_next_tab_stop as usize),
3013                                    cx,
3014                                );
3015                                selection.start.column += chars_to_next_tab_stop;
3016                                selection.end = selection.start;
3017                            }
3018                        });
3019                        this.update_selections(selections, Some(Autoscroll::Fit), cx);
3020                    });
3021                } else {
3022                    self.indent(&Indent, cx);
3023                }
3024            }
3025        }
3026    }
3027
3028    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
3029        let tab_size = cx.global::<Settings>().tab_size;
3030        let mut selections = self.local_selections::<Point>(cx);
3031        self.transact(cx, |this, cx| {
3032            let mut last_indent = None;
3033            this.buffer.update(cx, |buffer, cx| {
3034                for selection in &mut selections {
3035                    let mut start_row = selection.start.row;
3036                    let mut end_row = selection.end.row + 1;
3037
3038                    // If a selection ends at the beginning of a line, don't indent
3039                    // that last line.
3040                    if selection.end.column == 0 {
3041                        end_row -= 1;
3042                    }
3043
3044                    // Avoid re-indenting a row that has already been indented by a
3045                    // previous selection, but still update this selection's column
3046                    // to reflect that indentation.
3047                    if let Some((last_indent_row, last_indent_len)) = last_indent {
3048                        if last_indent_row == selection.start.row {
3049                            selection.start.column += last_indent_len;
3050                            start_row += 1;
3051                        }
3052                        if last_indent_row == selection.end.row {
3053                            selection.end.column += last_indent_len;
3054                        }
3055                    }
3056
3057                    for row in start_row..end_row {
3058                        let indent_column = buffer.read(cx).indent_column_for_line(row);
3059                        let columns_to_next_tab_stop = tab_size - (indent_column % tab_size);
3060                        let row_start = Point::new(row, 0);
3061                        buffer.edit(
3062                            [row_start..row_start],
3063                            " ".repeat(columns_to_next_tab_stop as usize),
3064                            cx,
3065                        );
3066
3067                        // Update this selection's endpoints to reflect the indentation.
3068                        if row == selection.start.row {
3069                            selection.start.column += columns_to_next_tab_stop as u32;
3070                        }
3071                        if row == selection.end.row {
3072                            selection.end.column += columns_to_next_tab_stop as u32;
3073                        }
3074
3075                        last_indent = Some((row, columns_to_next_tab_stop as u32));
3076                    }
3077                }
3078            });
3079
3080            this.update_selections(selections, Some(Autoscroll::Fit), cx);
3081        });
3082    }
3083
3084    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
3085        let tab_size = cx.global::<Settings>().tab_size;
3086        let selections = self.local_selections::<Point>(cx);
3087        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3088        let mut deletion_ranges = Vec::new();
3089        let mut last_outdent = None;
3090        {
3091            let buffer = self.buffer.read(cx).read(cx);
3092            for selection in &selections {
3093                let mut rows = selection.spanned_rows(false, &display_map);
3094
3095                // Avoid re-outdenting a row that has already been outdented by a
3096                // previous selection.
3097                if let Some(last_row) = last_outdent {
3098                    if last_row == rows.start {
3099                        rows.start += 1;
3100                    }
3101                }
3102
3103                for row in rows {
3104                    let column = buffer.indent_column_for_line(row);
3105                    if column > 0 {
3106                        let mut deletion_len = column % tab_size;
3107                        if deletion_len == 0 {
3108                            deletion_len = tab_size;
3109                        }
3110                        deletion_ranges.push(Point::new(row, 0)..Point::new(row, deletion_len));
3111                        last_outdent = Some(row);
3112                    }
3113                }
3114            }
3115        }
3116
3117        self.transact(cx, |this, cx| {
3118            this.buffer.update(cx, |buffer, cx| {
3119                buffer.edit(deletion_ranges, "", cx);
3120            });
3121            this.update_selections(
3122                this.local_selections::<usize>(cx),
3123                Some(Autoscroll::Fit),
3124                cx,
3125            );
3126        });
3127    }
3128
3129    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
3130        let selections = self.local_selections::<Point>(cx);
3131        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3132        let buffer = self.buffer.read(cx).snapshot(cx);
3133
3134        let mut new_cursors = Vec::new();
3135        let mut edit_ranges = Vec::new();
3136        let mut selections = selections.iter().peekable();
3137        while let Some(selection) = selections.next() {
3138            let mut rows = selection.spanned_rows(false, &display_map);
3139            let goal_display_column = selection.head().to_display_point(&display_map).column();
3140
3141            // Accumulate contiguous regions of rows that we want to delete.
3142            while let Some(next_selection) = selections.peek() {
3143                let next_rows = next_selection.spanned_rows(false, &display_map);
3144                if next_rows.start <= rows.end {
3145                    rows.end = next_rows.end;
3146                    selections.next().unwrap();
3147                } else {
3148                    break;
3149                }
3150            }
3151
3152            let mut edit_start = Point::new(rows.start, 0).to_offset(&buffer);
3153            let edit_end;
3154            let cursor_buffer_row;
3155            if buffer.max_point().row >= rows.end {
3156                // If there's a line after the range, delete the \n from the end of the row range
3157                // and position the cursor on the next line.
3158                edit_end = Point::new(rows.end, 0).to_offset(&buffer);
3159                cursor_buffer_row = rows.end;
3160            } else {
3161                // If there isn't a line after the range, delete the \n from the line before the
3162                // start of the row range and position the cursor there.
3163                edit_start = edit_start.saturating_sub(1);
3164                edit_end = buffer.len();
3165                cursor_buffer_row = rows.start.saturating_sub(1);
3166            }
3167
3168            let mut cursor = Point::new(cursor_buffer_row, 0).to_display_point(&display_map);
3169            *cursor.column_mut() =
3170                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
3171
3172            new_cursors.push((
3173                selection.id,
3174                buffer.anchor_after(cursor.to_point(&display_map)),
3175            ));
3176            edit_ranges.push(edit_start..edit_end);
3177        }
3178
3179        self.transact(cx, |this, cx| {
3180            let buffer = this.buffer.update(cx, |buffer, cx| {
3181                buffer.edit(edit_ranges, "", cx);
3182                buffer.snapshot(cx)
3183            });
3184            let new_selections = new_cursors
3185                .into_iter()
3186                .map(|(id, cursor)| {
3187                    let cursor = cursor.to_point(&buffer);
3188                    Selection {
3189                        id,
3190                        start: cursor,
3191                        end: cursor,
3192                        reversed: false,
3193                        goal: SelectionGoal::None,
3194                    }
3195                })
3196                .collect();
3197            this.update_selections(new_selections, Some(Autoscroll::Fit), cx);
3198        });
3199    }
3200
3201    pub fn duplicate_line(&mut self, _: &DuplicateLine, cx: &mut ViewContext<Self>) {
3202        let selections = self.local_selections::<Point>(cx);
3203        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3204        let buffer = &display_map.buffer_snapshot;
3205
3206        let mut edits = Vec::new();
3207        let mut selections_iter = selections.iter().peekable();
3208        while let Some(selection) = selections_iter.next() {
3209            // Avoid duplicating the same lines twice.
3210            let mut rows = selection.spanned_rows(false, &display_map);
3211
3212            while let Some(next_selection) = selections_iter.peek() {
3213                let next_rows = next_selection.spanned_rows(false, &display_map);
3214                if next_rows.start <= rows.end - 1 {
3215                    rows.end = next_rows.end;
3216                    selections_iter.next().unwrap();
3217                } else {
3218                    break;
3219                }
3220            }
3221
3222            // Copy the text from the selected row region and splice it at the start of the region.
3223            let start = Point::new(rows.start, 0);
3224            let end = Point::new(rows.end - 1, buffer.line_len(rows.end - 1));
3225            let text = buffer
3226                .text_for_range(start..end)
3227                .chain(Some("\n"))
3228                .collect::<String>();
3229            edits.push((start, text, rows.len() as u32));
3230        }
3231
3232        self.transact(cx, |this, cx| {
3233            this.buffer.update(cx, |buffer, cx| {
3234                for (point, text, _) in edits.into_iter().rev() {
3235                    buffer.edit(Some(point..point), text, cx);
3236                }
3237            });
3238
3239            this.request_autoscroll(Autoscroll::Fit, cx);
3240        });
3241    }
3242
3243    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
3244        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3245        let buffer = self.buffer.read(cx).snapshot(cx);
3246
3247        let mut edits = Vec::new();
3248        let mut unfold_ranges = Vec::new();
3249        let mut refold_ranges = Vec::new();
3250
3251        let selections = self.local_selections::<Point>(cx);
3252        let mut selections = selections.iter().peekable();
3253        let mut contiguous_row_selections = Vec::new();
3254        let mut new_selections = Vec::new();
3255
3256        while let Some(selection) = selections.next() {
3257            // Find all the selections that span a contiguous row range
3258            contiguous_row_selections.push(selection.clone());
3259            let start_row = selection.start.row;
3260            let mut end_row = if selection.end.column > 0 || selection.is_empty() {
3261                display_map.next_line_boundary(selection.end).0.row + 1
3262            } else {
3263                selection.end.row
3264            };
3265
3266            while let Some(next_selection) = selections.peek() {
3267                if next_selection.start.row <= end_row {
3268                    end_row = if next_selection.end.column > 0 || next_selection.is_empty() {
3269                        display_map.next_line_boundary(next_selection.end).0.row + 1
3270                    } else {
3271                        next_selection.end.row
3272                    };
3273                    contiguous_row_selections.push(selections.next().unwrap().clone());
3274                } else {
3275                    break;
3276                }
3277            }
3278
3279            // Move the text spanned by the row range to be before the line preceding the row range
3280            if start_row > 0 {
3281                let range_to_move = Point::new(start_row - 1, buffer.line_len(start_row - 1))
3282                    ..Point::new(end_row - 1, buffer.line_len(end_row - 1));
3283                let insertion_point = display_map
3284                    .prev_line_boundary(Point::new(start_row - 1, 0))
3285                    .0;
3286
3287                // Don't move lines across excerpts
3288                if buffer
3289                    .excerpt_boundaries_in_range((
3290                        Bound::Excluded(insertion_point),
3291                        Bound::Included(range_to_move.end),
3292                    ))
3293                    .next()
3294                    .is_none()
3295                {
3296                    let text = buffer
3297                        .text_for_range(range_to_move.clone())
3298                        .flat_map(|s| s.chars())
3299                        .skip(1)
3300                        .chain(['\n'])
3301                        .collect::<String>();
3302
3303                    edits.push((
3304                        buffer.anchor_after(range_to_move.start)
3305                            ..buffer.anchor_before(range_to_move.end),
3306                        String::new(),
3307                    ));
3308                    let insertion_anchor = buffer.anchor_after(insertion_point);
3309                    edits.push((insertion_anchor.clone()..insertion_anchor, text));
3310
3311                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
3312
3313                    // Move selections up
3314                    new_selections.extend(contiguous_row_selections.drain(..).map(
3315                        |mut selection| {
3316                            selection.start.row -= row_delta;
3317                            selection.end.row -= row_delta;
3318                            selection
3319                        },
3320                    ));
3321
3322                    // Move folds up
3323                    unfold_ranges.push(range_to_move.clone());
3324                    for fold in display_map.folds_in_range(
3325                        buffer.anchor_before(range_to_move.start)
3326                            ..buffer.anchor_after(range_to_move.end),
3327                    ) {
3328                        let mut start = fold.start.to_point(&buffer);
3329                        let mut end = fold.end.to_point(&buffer);
3330                        start.row -= row_delta;
3331                        end.row -= row_delta;
3332                        refold_ranges.push(start..end);
3333                    }
3334                }
3335            }
3336
3337            // If we didn't move line(s), preserve the existing selections
3338            new_selections.extend(contiguous_row_selections.drain(..));
3339        }
3340
3341        self.transact(cx, |this, cx| {
3342            this.unfold_ranges(unfold_ranges, true, cx);
3343            this.buffer.update(cx, |buffer, cx| {
3344                for (range, text) in edits {
3345                    buffer.edit([range], text, cx);
3346                }
3347            });
3348            this.fold_ranges(refold_ranges, cx);
3349            this.update_selections(new_selections, Some(Autoscroll::Fit), cx);
3350        });
3351    }
3352
3353    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
3354        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3355        let buffer = self.buffer.read(cx).snapshot(cx);
3356
3357        let mut edits = Vec::new();
3358        let mut unfold_ranges = Vec::new();
3359        let mut refold_ranges = Vec::new();
3360
3361        let selections = self.local_selections::<Point>(cx);
3362        let mut selections = selections.iter().peekable();
3363        let mut contiguous_row_selections = Vec::new();
3364        let mut new_selections = Vec::new();
3365
3366        while let Some(selection) = selections.next() {
3367            // Find all the selections that span a contiguous row range
3368            contiguous_row_selections.push(selection.clone());
3369            let start_row = selection.start.row;
3370            let mut end_row = if selection.end.column > 0 || selection.is_empty() {
3371                display_map.next_line_boundary(selection.end).0.row + 1
3372            } else {
3373                selection.end.row
3374            };
3375
3376            while let Some(next_selection) = selections.peek() {
3377                if next_selection.start.row <= end_row {
3378                    end_row = if next_selection.end.column > 0 || next_selection.is_empty() {
3379                        display_map.next_line_boundary(next_selection.end).0.row + 1
3380                    } else {
3381                        next_selection.end.row
3382                    };
3383                    contiguous_row_selections.push(selections.next().unwrap().clone());
3384                } else {
3385                    break;
3386                }
3387            }
3388
3389            // Move the text spanned by the row range to be after the last line of the row range
3390            if end_row <= buffer.max_point().row {
3391                let range_to_move = Point::new(start_row, 0)..Point::new(end_row, 0);
3392                let insertion_point = display_map.next_line_boundary(Point::new(end_row, 0)).0;
3393
3394                // Don't move lines across excerpt boundaries
3395                if buffer
3396                    .excerpt_boundaries_in_range((
3397                        Bound::Excluded(range_to_move.start),
3398                        Bound::Included(insertion_point),
3399                    ))
3400                    .next()
3401                    .is_none()
3402                {
3403                    let mut text = String::from("\n");
3404                    text.extend(buffer.text_for_range(range_to_move.clone()));
3405                    text.pop(); // Drop trailing newline
3406                    edits.push((
3407                        buffer.anchor_after(range_to_move.start)
3408                            ..buffer.anchor_before(range_to_move.end),
3409                        String::new(),
3410                    ));
3411                    let insertion_anchor = buffer.anchor_after(insertion_point);
3412                    edits.push((insertion_anchor.clone()..insertion_anchor, text));
3413
3414                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
3415
3416                    // Move selections down
3417                    new_selections.extend(contiguous_row_selections.drain(..).map(
3418                        |mut selection| {
3419                            selection.start.row += row_delta;
3420                            selection.end.row += row_delta;
3421                            selection
3422                        },
3423                    ));
3424
3425                    // Move folds down
3426                    unfold_ranges.push(range_to_move.clone());
3427                    for fold in display_map.folds_in_range(
3428                        buffer.anchor_before(range_to_move.start)
3429                            ..buffer.anchor_after(range_to_move.end),
3430                    ) {
3431                        let mut start = fold.start.to_point(&buffer);
3432                        let mut end = fold.end.to_point(&buffer);
3433                        start.row += row_delta;
3434                        end.row += row_delta;
3435                        refold_ranges.push(start..end);
3436                    }
3437                }
3438            }
3439
3440            // If we didn't move line(s), preserve the existing selections
3441            new_selections.extend(contiguous_row_selections.drain(..));
3442        }
3443
3444        self.transact(cx, |this, cx| {
3445            this.unfold_ranges(unfold_ranges, true, cx);
3446            this.buffer.update(cx, |buffer, cx| {
3447                for (range, text) in edits {
3448                    buffer.edit([range], text, cx);
3449                }
3450            });
3451            this.fold_ranges(refold_ranges, cx);
3452            this.update_selections(new_selections, Some(Autoscroll::Fit), cx);
3453        });
3454    }
3455
3456    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
3457        let mut text = String::new();
3458        let mut selections = self.local_selections::<Point>(cx);
3459        let mut clipboard_selections = Vec::with_capacity(selections.len());
3460        {
3461            let buffer = self.buffer.read(cx).read(cx);
3462            let max_point = buffer.max_point();
3463            for selection in &mut selections {
3464                let is_entire_line = selection.is_empty();
3465                if is_entire_line {
3466                    selection.start = Point::new(selection.start.row, 0);
3467                    selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
3468                    selection.goal = SelectionGoal::None;
3469                }
3470                let mut len = 0;
3471                for chunk in buffer.text_for_range(selection.start..selection.end) {
3472                    text.push_str(chunk);
3473                    len += chunk.len();
3474                }
3475                clipboard_selections.push(ClipboardSelection {
3476                    len,
3477                    is_entire_line,
3478                });
3479            }
3480        }
3481
3482        self.transact(cx, |this, cx| {
3483            this.update_selections(selections, Some(Autoscroll::Fit), cx);
3484            this.insert("", cx);
3485            cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
3486        });
3487    }
3488
3489    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
3490        let selections = self.local_selections::<Point>(cx);
3491        let mut text = String::new();
3492        let mut clipboard_selections = Vec::with_capacity(selections.len());
3493        {
3494            let buffer = self.buffer.read(cx).read(cx);
3495            let max_point = buffer.max_point();
3496            for selection in selections.iter() {
3497                let mut start = selection.start;
3498                let mut end = selection.end;
3499                let is_entire_line = selection.is_empty();
3500                if is_entire_line {
3501                    start = Point::new(start.row, 0);
3502                    end = cmp::min(max_point, Point::new(start.row + 1, 0));
3503                }
3504                let mut len = 0;
3505                for chunk in buffer.text_for_range(start..end) {
3506                    text.push_str(chunk);
3507                    len += chunk.len();
3508                }
3509                clipboard_selections.push(ClipboardSelection {
3510                    len,
3511                    is_entire_line,
3512                });
3513            }
3514        }
3515
3516        cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
3517    }
3518
3519    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
3520        self.transact(cx, |this, cx| {
3521            if let Some(item) = cx.as_mut().read_from_clipboard() {
3522                let clipboard_text = item.text();
3523                if let Some(mut clipboard_selections) = item.metadata::<Vec<ClipboardSelection>>() {
3524                    let mut selections = this.local_selections::<usize>(cx);
3525                    let all_selections_were_entire_line =
3526                        clipboard_selections.iter().all(|s| s.is_entire_line);
3527                    if clipboard_selections.len() != selections.len() {
3528                        clipboard_selections.clear();
3529                    }
3530
3531                    let mut delta = 0_isize;
3532                    let mut start_offset = 0;
3533                    for (i, selection) in selections.iter_mut().enumerate() {
3534                        let to_insert;
3535                        let entire_line;
3536                        if let Some(clipboard_selection) = clipboard_selections.get(i) {
3537                            let end_offset = start_offset + clipboard_selection.len;
3538                            to_insert = &clipboard_text[start_offset..end_offset];
3539                            entire_line = clipboard_selection.is_entire_line;
3540                            start_offset = end_offset
3541                        } else {
3542                            to_insert = clipboard_text.as_str();
3543                            entire_line = all_selections_were_entire_line;
3544                        }
3545
3546                        selection.start = (selection.start as isize + delta) as usize;
3547                        selection.end = (selection.end as isize + delta) as usize;
3548
3549                        this.buffer.update(cx, |buffer, cx| {
3550                            // If the corresponding selection was empty when this slice of the
3551                            // clipboard text was written, then the entire line containing the
3552                            // selection was copied. If this selection is also currently empty,
3553                            // then paste the line before the current line of the buffer.
3554                            let range = if selection.is_empty() && entire_line {
3555                                let column =
3556                                    selection.start.to_point(&buffer.read(cx)).column as usize;
3557                                let line_start = selection.start - column;
3558                                line_start..line_start
3559                            } else {
3560                                selection.start..selection.end
3561                            };
3562
3563                            delta += to_insert.len() as isize - range.len() as isize;
3564                            buffer.edit([range], to_insert, cx);
3565                            selection.start += to_insert.len();
3566                            selection.end = selection.start;
3567                        });
3568                    }
3569                    this.update_selections(selections, Some(Autoscroll::Fit), cx);
3570                } else {
3571                    this.insert(clipboard_text, cx);
3572                }
3573            }
3574        });
3575    }
3576
3577    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
3578        if let Some(tx_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
3579            if let Some((selections, _)) = self.selection_history.transaction(tx_id).cloned() {
3580                self.set_selections(selections, None, true, cx);
3581            }
3582            self.request_autoscroll(Autoscroll::Fit, cx);
3583            cx.emit(Event::Edited);
3584        }
3585    }
3586
3587    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
3588        if let Some(tx_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
3589            if let Some((_, Some(selections))) = self.selection_history.transaction(tx_id).cloned()
3590            {
3591                self.set_selections(selections, None, true, cx);
3592            }
3593            self.request_autoscroll(Autoscroll::Fit, cx);
3594            cx.emit(Event::Edited);
3595        }
3596    }
3597
3598    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
3599        self.buffer
3600            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
3601    }
3602
3603    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
3604        self.move_selections(cx, |map, selection| {
3605            let cursor = if selection.is_empty() {
3606                movement::left(map, selection.start)
3607            } else {
3608                selection.start
3609            };
3610            selection.collapse_to(cursor, SelectionGoal::None);
3611        });
3612    }
3613
3614    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
3615        self.move_selection_heads(cx, |map, head, _| {
3616            (movement::left(map, head), SelectionGoal::None)
3617        });
3618    }
3619
3620    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
3621        self.move_selections(cx, |map, selection| {
3622            let cursor = if selection.is_empty() {
3623                movement::right(map, selection.end)
3624            } else {
3625                selection.end
3626            };
3627            selection.collapse_to(cursor, SelectionGoal::None)
3628        });
3629    }
3630
3631    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
3632        self.move_selection_heads(cx, |map, head, _| {
3633            (movement::right(map, head), SelectionGoal::None)
3634        });
3635    }
3636
3637    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
3638        if self.take_rename(true, cx).is_some() {
3639            return;
3640        }
3641
3642        if let Some(context_menu) = self.context_menu.as_mut() {
3643            if context_menu.select_prev(cx) {
3644                return;
3645            }
3646        }
3647
3648        if matches!(self.mode, EditorMode::SingleLine) {
3649            cx.propagate_action();
3650            return;
3651        }
3652
3653        self.move_selections(cx, |map, selection| {
3654            if !selection.is_empty() {
3655                selection.goal = SelectionGoal::None;
3656            }
3657            let (cursor, goal) = movement::up(&map, selection.start, selection.goal);
3658            selection.collapse_to(cursor, goal);
3659        });
3660    }
3661
3662    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
3663        self.move_selection_heads(cx, movement::up)
3664    }
3665
3666    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
3667        self.take_rename(true, cx);
3668
3669        if let Some(context_menu) = self.context_menu.as_mut() {
3670            if context_menu.select_next(cx) {
3671                return;
3672            }
3673        }
3674
3675        if matches!(self.mode, EditorMode::SingleLine) {
3676            cx.propagate_action();
3677            return;
3678        }
3679
3680        self.move_selections(cx, |map, selection| {
3681            if !selection.is_empty() {
3682                selection.goal = SelectionGoal::None;
3683            }
3684            let (cursor, goal) = movement::down(&map, selection.end, selection.goal);
3685            selection.collapse_to(cursor, goal);
3686        });
3687    }
3688
3689    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
3690        self.move_selection_heads(cx, movement::down)
3691    }
3692
3693    pub fn move_to_previous_word_start(
3694        &mut self,
3695        _: &MoveToPreviousWordStart,
3696        cx: &mut ViewContext<Self>,
3697    ) {
3698        self.move_cursors(cx, |map, head, _| {
3699            (
3700                movement::previous_word_start(map, head),
3701                SelectionGoal::None,
3702            )
3703        });
3704    }
3705
3706    pub fn move_to_previous_subword_start(
3707        &mut self,
3708        _: &MoveToPreviousSubwordStart,
3709        cx: &mut ViewContext<Self>,
3710    ) {
3711        self.move_cursors(cx, |map, head, _| {
3712            (
3713                movement::previous_subword_start(map, head),
3714                SelectionGoal::None,
3715            )
3716        });
3717    }
3718
3719    pub fn select_to_previous_word_start(
3720        &mut self,
3721        _: &SelectToPreviousWordStart,
3722        cx: &mut ViewContext<Self>,
3723    ) {
3724        self.move_selection_heads(cx, |map, head, _| {
3725            (
3726                movement::previous_word_start(map, head),
3727                SelectionGoal::None,
3728            )
3729        });
3730    }
3731
3732    pub fn select_to_previous_subword_start(
3733        &mut self,
3734        _: &SelectToPreviousSubwordStart,
3735        cx: &mut ViewContext<Self>,
3736    ) {
3737        self.move_selection_heads(cx, |map, head, _| {
3738            (
3739                movement::previous_subword_start(map, head),
3740                SelectionGoal::None,
3741            )
3742        });
3743    }
3744
3745    pub fn delete_to_previous_word_start(
3746        &mut self,
3747        _: &DeleteToPreviousWordStart,
3748        cx: &mut ViewContext<Self>,
3749    ) {
3750        self.transact(cx, |this, cx| {
3751            this.move_selections(cx, |map, selection| {
3752                if selection.is_empty() {
3753                    let cursor = movement::previous_word_start(map, selection.head());
3754                    selection.set_head(cursor, SelectionGoal::None);
3755                }
3756            });
3757            this.insert("", cx);
3758        });
3759    }
3760
3761    pub fn delete_to_previous_subword_start(
3762        &mut self,
3763        _: &DeleteToPreviousSubwordStart,
3764        cx: &mut ViewContext<Self>,
3765    ) {
3766        self.transact(cx, |this, cx| {
3767            this.move_selections(cx, |map, selection| {
3768                if selection.is_empty() {
3769                    let cursor = movement::previous_subword_start(map, selection.head());
3770                    selection.set_head(cursor, SelectionGoal::None);
3771                }
3772            });
3773            this.insert("", cx);
3774        });
3775    }
3776
3777    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
3778        self.move_cursors(cx, |map, head, _| {
3779            (movement::next_word_end(map, head), SelectionGoal::None)
3780        });
3781    }
3782
3783    pub fn move_to_next_subword_end(
3784        &mut self,
3785        _: &MoveToNextSubwordEnd,
3786        cx: &mut ViewContext<Self>,
3787    ) {
3788        self.move_cursors(cx, |map, head, _| {
3789            (movement::next_subword_end(map, head), SelectionGoal::None)
3790        });
3791    }
3792
3793    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
3794        self.move_selection_heads(cx, |map, head, _| {
3795            (movement::next_word_end(map, head), SelectionGoal::None)
3796        });
3797    }
3798
3799    pub fn select_to_next_subword_end(
3800        &mut self,
3801        _: &SelectToNextSubwordEnd,
3802        cx: &mut ViewContext<Self>,
3803    ) {
3804        self.move_selection_heads(cx, |map, head, _| {
3805            (movement::next_subword_end(map, head), SelectionGoal::None)
3806        });
3807    }
3808
3809    pub fn delete_to_next_word_end(&mut self, _: &DeleteToNextWordEnd, cx: &mut ViewContext<Self>) {
3810        self.transact(cx, |this, cx| {
3811            this.move_selections(cx, |map, selection| {
3812                if selection.is_empty() {
3813                    let cursor = movement::next_word_end(map, selection.head());
3814                    selection.set_head(cursor, SelectionGoal::None);
3815                }
3816            });
3817            this.insert("", cx);
3818        });
3819    }
3820
3821    pub fn delete_to_next_subword_end(
3822        &mut self,
3823        _: &DeleteToNextSubwordEnd,
3824        cx: &mut ViewContext<Self>,
3825    ) {
3826        self.transact(cx, |this, cx| {
3827            this.move_selections(cx, |map, selection| {
3828                if selection.is_empty() {
3829                    let cursor = movement::next_subword_end(map, selection.head());
3830                    selection.set_head(cursor, SelectionGoal::None);
3831                }
3832            });
3833            this.insert("", cx);
3834        });
3835    }
3836
3837    pub fn move_to_beginning_of_line(
3838        &mut self,
3839        _: &MoveToBeginningOfLine,
3840        cx: &mut ViewContext<Self>,
3841    ) {
3842        self.move_cursors(cx, |map, head, _| {
3843            (
3844                movement::line_beginning(map, head, true),
3845                SelectionGoal::None,
3846            )
3847        });
3848    }
3849
3850    pub fn select_to_beginning_of_line(
3851        &mut self,
3852        SelectToBeginningOfLine(stop_at_soft_boundaries): &SelectToBeginningOfLine,
3853        cx: &mut ViewContext<Self>,
3854    ) {
3855        self.move_selection_heads(cx, |map, head, _| {
3856            (
3857                movement::line_beginning(map, head, *stop_at_soft_boundaries),
3858                SelectionGoal::None,
3859            )
3860        });
3861    }
3862
3863    pub fn delete_to_beginning_of_line(
3864        &mut self,
3865        _: &DeleteToBeginningOfLine,
3866        cx: &mut ViewContext<Self>,
3867    ) {
3868        self.transact(cx, |this, cx| {
3869            this.select_to_beginning_of_line(&SelectToBeginningOfLine(false), cx);
3870            this.backspace(&Backspace, cx);
3871        });
3872    }
3873
3874    pub fn move_to_end_of_line(&mut self, _: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
3875        self.move_cursors(cx, |map, head, _| {
3876            (movement::line_end(map, head, true), SelectionGoal::None)
3877        });
3878    }
3879
3880    pub fn select_to_end_of_line(
3881        &mut self,
3882        SelectToEndOfLine(stop_at_soft_boundaries): &SelectToEndOfLine,
3883        cx: &mut ViewContext<Self>,
3884    ) {
3885        self.move_selection_heads(cx, |map, head, _| {
3886            (
3887                movement::line_end(map, head, *stop_at_soft_boundaries),
3888                SelectionGoal::None,
3889            )
3890        });
3891    }
3892
3893    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
3894        self.transact(cx, |this, cx| {
3895            this.select_to_end_of_line(&SelectToEndOfLine(false), cx);
3896            this.delete(&Delete, cx);
3897        });
3898    }
3899
3900    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
3901        self.transact(cx, |this, cx| {
3902            this.select_to_end_of_line(&SelectToEndOfLine(false), cx);
3903            this.cut(&Cut, cx);
3904        });
3905    }
3906
3907    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
3908        if matches!(self.mode, EditorMode::SingleLine) {
3909            cx.propagate_action();
3910            return;
3911        }
3912
3913        let selection = Selection {
3914            id: post_inc(&mut self.next_selection_id),
3915            start: 0,
3916            end: 0,
3917            reversed: false,
3918            goal: SelectionGoal::None,
3919        };
3920        self.update_selections(vec![selection], Some(Autoscroll::Fit), cx);
3921    }
3922
3923    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
3924        let mut selection = self.local_selections::<Point>(cx).last().unwrap().clone();
3925        selection.set_head(Point::zero(), SelectionGoal::None);
3926        self.update_selections(vec![selection], Some(Autoscroll::Fit), cx);
3927    }
3928
3929    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
3930        if matches!(self.mode, EditorMode::SingleLine) {
3931            cx.propagate_action();
3932            return;
3933        }
3934
3935        let cursor = self.buffer.read(cx).read(cx).len();
3936        let selection = Selection {
3937            id: post_inc(&mut self.next_selection_id),
3938            start: cursor,
3939            end: cursor,
3940            reversed: false,
3941            goal: SelectionGoal::None,
3942        };
3943        self.update_selections(vec![selection], Some(Autoscroll::Fit), cx);
3944    }
3945
3946    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
3947        self.nav_history = nav_history;
3948    }
3949
3950    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
3951        self.nav_history.as_ref()
3952    }
3953
3954    fn push_to_nav_history(
3955        &self,
3956        position: Anchor,
3957        new_position: Option<Point>,
3958        cx: &mut ViewContext<Self>,
3959    ) {
3960        if let Some(nav_history) = &self.nav_history {
3961            let buffer = self.buffer.read(cx).read(cx);
3962            let offset = position.to_offset(&buffer);
3963            let point = position.to_point(&buffer);
3964            drop(buffer);
3965
3966            if let Some(new_position) = new_position {
3967                let row_delta = (new_position.row as i64 - point.row as i64).abs();
3968                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
3969                    return;
3970                }
3971            }
3972
3973            nav_history.push(Some(NavigationData {
3974                anchor: position,
3975                offset,
3976            }));
3977        }
3978    }
3979
3980    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
3981        let mut selection = self.local_selections::<usize>(cx).first().unwrap().clone();
3982        selection.set_head(self.buffer.read(cx).read(cx).len(), SelectionGoal::None);
3983        self.update_selections(vec![selection], Some(Autoscroll::Fit), cx);
3984    }
3985
3986    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
3987        let selection = Selection {
3988            id: post_inc(&mut self.next_selection_id),
3989            start: 0,
3990            end: self.buffer.read(cx).read(cx).len(),
3991            reversed: false,
3992            goal: SelectionGoal::None,
3993        };
3994        self.update_selections(vec![selection], None, cx);
3995    }
3996
3997    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
3998        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3999        let mut selections = self.local_selections::<Point>(cx);
4000        let max_point = display_map.buffer_snapshot.max_point();
4001        for selection in &mut selections {
4002            let rows = selection.spanned_rows(true, &display_map);
4003            selection.start = Point::new(rows.start, 0);
4004            selection.end = cmp::min(max_point, Point::new(rows.end, 0));
4005            selection.reversed = false;
4006        }
4007        self.update_selections(selections, Some(Autoscroll::Fit), cx);
4008    }
4009
4010    pub fn split_selection_into_lines(
4011        &mut self,
4012        _: &SplitSelectionIntoLines,
4013        cx: &mut ViewContext<Self>,
4014    ) {
4015        let mut to_unfold = Vec::new();
4016        let mut new_selections = Vec::new();
4017        {
4018            let selections = self.local_selections::<Point>(cx);
4019            let buffer = self.buffer.read(cx).read(cx);
4020            for selection in selections {
4021                for row in selection.start.row..selection.end.row {
4022                    let cursor = Point::new(row, buffer.line_len(row));
4023                    new_selections.push(Selection {
4024                        id: post_inc(&mut self.next_selection_id),
4025                        start: cursor,
4026                        end: cursor,
4027                        reversed: false,
4028                        goal: SelectionGoal::None,
4029                    });
4030                }
4031                new_selections.push(Selection {
4032                    id: selection.id,
4033                    start: selection.end,
4034                    end: selection.end,
4035                    reversed: false,
4036                    goal: SelectionGoal::None,
4037                });
4038                to_unfold.push(selection.start..selection.end);
4039            }
4040        }
4041        self.unfold_ranges(to_unfold, true, cx);
4042        self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
4043    }
4044
4045    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
4046        self.add_selection(true, cx);
4047    }
4048
4049    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
4050        self.add_selection(false, cx);
4051    }
4052
4053    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
4054        self.push_to_selection_history();
4055        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
4056        let mut selections = self.local_selections::<Point>(cx);
4057        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
4058            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
4059            let range = oldest_selection.display_range(&display_map).sorted();
4060            let columns = cmp::min(range.start.column(), range.end.column())
4061                ..cmp::max(range.start.column(), range.end.column());
4062
4063            selections.clear();
4064            let mut stack = Vec::new();
4065            for row in range.start.row()..=range.end.row() {
4066                if let Some(selection) = self.build_columnar_selection(
4067                    &display_map,
4068                    row,
4069                    &columns,
4070                    oldest_selection.reversed,
4071                ) {
4072                    stack.push(selection.id);
4073                    selections.push(selection);
4074                }
4075            }
4076
4077            if above {
4078                stack.reverse();
4079            }
4080
4081            AddSelectionsState { above, stack }
4082        });
4083
4084        let last_added_selection = *state.stack.last().unwrap();
4085        let mut new_selections = Vec::new();
4086        if above == state.above {
4087            let end_row = if above {
4088                0
4089            } else {
4090                display_map.max_point().row()
4091            };
4092
4093            'outer: for selection in selections {
4094                if selection.id == last_added_selection {
4095                    let range = selection.display_range(&display_map).sorted();
4096                    debug_assert_eq!(range.start.row(), range.end.row());
4097                    let mut row = range.start.row();
4098                    let columns = if let SelectionGoal::ColumnRange { start, end } = selection.goal
4099                    {
4100                        start..end
4101                    } else {
4102                        cmp::min(range.start.column(), range.end.column())
4103                            ..cmp::max(range.start.column(), range.end.column())
4104                    };
4105
4106                    while row != end_row {
4107                        if above {
4108                            row -= 1;
4109                        } else {
4110                            row += 1;
4111                        }
4112
4113                        if let Some(new_selection) = self.build_columnar_selection(
4114                            &display_map,
4115                            row,
4116                            &columns,
4117                            selection.reversed,
4118                        ) {
4119                            state.stack.push(new_selection.id);
4120                            if above {
4121                                new_selections.push(new_selection);
4122                                new_selections.push(selection);
4123                            } else {
4124                                new_selections.push(selection);
4125                                new_selections.push(new_selection);
4126                            }
4127
4128                            continue 'outer;
4129                        }
4130                    }
4131                }
4132
4133                new_selections.push(selection);
4134            }
4135        } else {
4136            new_selections = selections;
4137            new_selections.retain(|s| s.id != last_added_selection);
4138            state.stack.pop();
4139        }
4140
4141        self.update_selections(new_selections, Some(Autoscroll::Newest), cx);
4142        if state.stack.len() > 1 {
4143            self.add_selections_state = Some(state);
4144        }
4145    }
4146
4147    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) {
4148        self.push_to_selection_history();
4149        let replace_newest = action.0;
4150        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
4151        let buffer = &display_map.buffer_snapshot;
4152        let mut selections = self.local_selections::<usize>(cx);
4153        if let Some(mut select_next_state) = self.select_next_state.take() {
4154            let query = &select_next_state.query;
4155            if !select_next_state.done {
4156                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
4157                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
4158                let mut next_selected_range = None;
4159
4160                let bytes_after_last_selection =
4161                    buffer.bytes_in_range(last_selection.end..buffer.len());
4162                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
4163                let query_matches = query
4164                    .stream_find_iter(bytes_after_last_selection)
4165                    .map(|result| (last_selection.end, result))
4166                    .chain(
4167                        query
4168                            .stream_find_iter(bytes_before_first_selection)
4169                            .map(|result| (0, result)),
4170                    );
4171                for (start_offset, query_match) in query_matches {
4172                    let query_match = query_match.unwrap(); // can only fail due to I/O
4173                    let offset_range =
4174                        start_offset + query_match.start()..start_offset + query_match.end();
4175                    let display_range = offset_range.start.to_display_point(&display_map)
4176                        ..offset_range.end.to_display_point(&display_map);
4177
4178                    if !select_next_state.wordwise
4179                        || (!movement::is_inside_word(&display_map, display_range.start)
4180                            && !movement::is_inside_word(&display_map, display_range.end))
4181                    {
4182                        next_selected_range = Some(offset_range);
4183                        break;
4184                    }
4185                }
4186
4187                if let Some(next_selected_range) = next_selected_range {
4188                    if replace_newest {
4189                        if let Some(newest_id) =
4190                            selections.iter().max_by_key(|s| s.id).map(|s| s.id)
4191                        {
4192                            selections.retain(|s| s.id != newest_id);
4193                        }
4194                    }
4195                    selections.push(Selection {
4196                        id: post_inc(&mut self.next_selection_id),
4197                        start: next_selected_range.start,
4198                        end: next_selected_range.end,
4199                        reversed: false,
4200                        goal: SelectionGoal::None,
4201                    });
4202                    self.unfold_ranges([next_selected_range], false, cx);
4203                    self.update_selections(selections, Some(Autoscroll::Newest), cx);
4204                } else {
4205                    select_next_state.done = true;
4206                }
4207            }
4208
4209            self.select_next_state = Some(select_next_state);
4210        } else if selections.len() == 1 {
4211            let selection = selections.last_mut().unwrap();
4212            if selection.start == selection.end {
4213                let word_range = movement::surrounding_word(
4214                    &display_map,
4215                    selection.start.to_display_point(&display_map),
4216                );
4217                selection.start = word_range.start.to_offset(&display_map, Bias::Left);
4218                selection.end = word_range.end.to_offset(&display_map, Bias::Left);
4219                selection.goal = SelectionGoal::None;
4220                selection.reversed = false;
4221
4222                let query = buffer
4223                    .text_for_range(selection.start..selection.end)
4224                    .collect::<String>();
4225                let select_state = SelectNextState {
4226                    query: AhoCorasick::new_auto_configured(&[query]),
4227                    wordwise: true,
4228                    done: false,
4229                };
4230                self.unfold_ranges([selection.start..selection.end], false, cx);
4231                self.update_selections(selections, Some(Autoscroll::Newest), cx);
4232                self.select_next_state = Some(select_state);
4233            } else {
4234                let query = buffer
4235                    .text_for_range(selection.start..selection.end)
4236                    .collect::<String>();
4237                self.select_next_state = Some(SelectNextState {
4238                    query: AhoCorasick::new_auto_configured(&[query]),
4239                    wordwise: false,
4240                    done: false,
4241                });
4242                self.select_next(action, cx);
4243            }
4244        }
4245    }
4246
4247    pub fn toggle_comments(&mut self, _: &ToggleComments, cx: &mut ViewContext<Self>) {
4248        // Get the line comment prefix. Split its trailing whitespace into a separate string,
4249        // as that portion won't be used for detecting if a line is a comment.
4250        let full_comment_prefix =
4251            if let Some(prefix) = self.language(cx).and_then(|l| l.line_comment_prefix()) {
4252                prefix.to_string()
4253            } else {
4254                return;
4255            };
4256        let comment_prefix = full_comment_prefix.trim_end_matches(' ');
4257        let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
4258
4259        self.transact(cx, |this, cx| {
4260            let mut selections = this.local_selections::<Point>(cx);
4261            let mut all_selection_lines_are_comments = true;
4262            let mut edit_ranges = Vec::new();
4263            let mut last_toggled_row = None;
4264            this.buffer.update(cx, |buffer, cx| {
4265                for selection in &mut selections {
4266                    edit_ranges.clear();
4267                    let snapshot = buffer.snapshot(cx);
4268
4269                    let end_row =
4270                        if selection.end.row > selection.start.row && selection.end.column == 0 {
4271                            selection.end.row
4272                        } else {
4273                            selection.end.row + 1
4274                        };
4275
4276                    for row in selection.start.row..end_row {
4277                        // If multiple selections contain a given row, avoid processing that
4278                        // row more than once.
4279                        if last_toggled_row == Some(row) {
4280                            continue;
4281                        } else {
4282                            last_toggled_row = Some(row);
4283                        }
4284
4285                        if snapshot.is_line_blank(row) {
4286                            continue;
4287                        }
4288
4289                        let start = Point::new(row, snapshot.indent_column_for_line(row));
4290                        let mut line_bytes = snapshot
4291                            .bytes_in_range(start..snapshot.max_point())
4292                            .flatten()
4293                            .copied();
4294
4295                        // If this line currently begins with the line comment prefix, then record
4296                        // the range containing the prefix.
4297                        if all_selection_lines_are_comments
4298                            && line_bytes
4299                                .by_ref()
4300                                .take(comment_prefix.len())
4301                                .eq(comment_prefix.bytes())
4302                        {
4303                            // Include any whitespace that matches the comment prefix.
4304                            let matching_whitespace_len = line_bytes
4305                                .zip(comment_prefix_whitespace.bytes())
4306                                .take_while(|(a, b)| a == b)
4307                                .count()
4308                                as u32;
4309                            let end = Point::new(
4310                                row,
4311                                start.column
4312                                    + comment_prefix.len() as u32
4313                                    + matching_whitespace_len,
4314                            );
4315                            edit_ranges.push(start..end);
4316                        }
4317                        // If this line does not begin with the line comment prefix, then record
4318                        // the position where the prefix should be inserted.
4319                        else {
4320                            all_selection_lines_are_comments = false;
4321                            edit_ranges.push(start..start);
4322                        }
4323                    }
4324
4325                    if !edit_ranges.is_empty() {
4326                        if all_selection_lines_are_comments {
4327                            buffer.edit(edit_ranges.iter().cloned(), "", cx);
4328                        } else {
4329                            let min_column =
4330                                edit_ranges.iter().map(|r| r.start.column).min().unwrap();
4331                            let edit_ranges = edit_ranges.iter().map(|range| {
4332                                let position = Point::new(range.start.row, min_column);
4333                                position..position
4334                            });
4335                            buffer.edit(edit_ranges, &full_comment_prefix, cx);
4336                        }
4337                    }
4338                }
4339            });
4340
4341            this.update_selections(
4342                this.local_selections::<usize>(cx),
4343                Some(Autoscroll::Fit),
4344                cx,
4345            );
4346        });
4347    }
4348
4349    pub fn select_larger_syntax_node(
4350        &mut self,
4351        _: &SelectLargerSyntaxNode,
4352        cx: &mut ViewContext<Self>,
4353    ) {
4354        let old_selections = self.local_selections::<usize>(cx).into_boxed_slice();
4355        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
4356        let buffer = self.buffer.read(cx).snapshot(cx);
4357
4358        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
4359        let mut selected_larger_node = false;
4360        let new_selections = old_selections
4361            .iter()
4362            .map(|selection| {
4363                let old_range = selection.start..selection.end;
4364                let mut new_range = old_range.clone();
4365                while let Some(containing_range) =
4366                    buffer.range_for_syntax_ancestor(new_range.clone())
4367                {
4368                    new_range = containing_range;
4369                    if !display_map.intersects_fold(new_range.start)
4370                        && !display_map.intersects_fold(new_range.end)
4371                    {
4372                        break;
4373                    }
4374                }
4375
4376                selected_larger_node |= new_range != old_range;
4377                Selection {
4378                    id: selection.id,
4379                    start: new_range.start,
4380                    end: new_range.end,
4381                    goal: SelectionGoal::None,
4382                    reversed: selection.reversed,
4383                }
4384            })
4385            .collect::<Vec<_>>();
4386
4387        if selected_larger_node {
4388            stack.push(old_selections);
4389            self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
4390        }
4391        self.select_larger_syntax_node_stack = stack;
4392    }
4393
4394    pub fn select_smaller_syntax_node(
4395        &mut self,
4396        _: &SelectSmallerSyntaxNode,
4397        cx: &mut ViewContext<Self>,
4398    ) {
4399        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
4400        if let Some(selections) = stack.pop() {
4401            self.update_selections(selections.to_vec(), Some(Autoscroll::Fit), cx);
4402        }
4403        self.select_larger_syntax_node_stack = stack;
4404    }
4405
4406    pub fn move_to_enclosing_bracket(
4407        &mut self,
4408        _: &MoveToEnclosingBracket,
4409        cx: &mut ViewContext<Self>,
4410    ) {
4411        let mut selections = self.local_selections::<usize>(cx);
4412        let buffer = self.buffer.read(cx).snapshot(cx);
4413        for selection in &mut selections {
4414            if let Some((open_range, close_range)) =
4415                buffer.enclosing_bracket_ranges(selection.start..selection.end)
4416            {
4417                let close_range = close_range.to_inclusive();
4418                let destination = if close_range.contains(&selection.start)
4419                    && close_range.contains(&selection.end)
4420                {
4421                    open_range.end
4422                } else {
4423                    *close_range.start()
4424                };
4425                selection.start = destination;
4426                selection.end = destination;
4427            }
4428        }
4429
4430        self.update_selections(selections, Some(Autoscroll::Fit), cx);
4431    }
4432
4433    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
4434        self.end_selection(cx);
4435        self.selection_history.mode = SelectionHistoryMode::Undoing;
4436        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
4437            self.set_selections(entry.selections, None, true, cx);
4438            self.select_next_state = entry.select_next_state;
4439            self.add_selections_state = entry.add_selections_state;
4440            self.request_autoscroll(Autoscroll::Newest, cx);
4441        }
4442        self.selection_history.mode = SelectionHistoryMode::Normal;
4443    }
4444
4445    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
4446        self.end_selection(cx);
4447        self.selection_history.mode = SelectionHistoryMode::Redoing;
4448        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
4449            self.set_selections(entry.selections, None, true, cx);
4450            self.select_next_state = entry.select_next_state;
4451            self.add_selections_state = entry.add_selections_state;
4452            self.request_autoscroll(Autoscroll::Newest, cx);
4453        }
4454        self.selection_history.mode = SelectionHistoryMode::Normal;
4455    }
4456
4457    pub fn go_to_diagnostic(
4458        &mut self,
4459        &GoToDiagnostic(direction): &GoToDiagnostic,
4460        cx: &mut ViewContext<Self>,
4461    ) {
4462        let buffer = self.buffer.read(cx).snapshot(cx);
4463        let selection = self.newest_selection_with_snapshot::<usize>(&buffer);
4464        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
4465            active_diagnostics
4466                .primary_range
4467                .to_offset(&buffer)
4468                .to_inclusive()
4469        });
4470        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
4471            if active_primary_range.contains(&selection.head()) {
4472                *active_primary_range.end()
4473            } else {
4474                selection.head()
4475            }
4476        } else {
4477            selection.head()
4478        };
4479
4480        loop {
4481            let mut diagnostics = if direction == Direction::Prev {
4482                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
4483            } else {
4484                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
4485            };
4486            let group = diagnostics.find_map(|entry| {
4487                if entry.diagnostic.is_primary
4488                    && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
4489                    && !entry.range.is_empty()
4490                    && Some(entry.range.end) != active_primary_range.as_ref().map(|r| *r.end())
4491                {
4492                    Some((entry.range, entry.diagnostic.group_id))
4493                } else {
4494                    None
4495                }
4496            });
4497
4498            if let Some((primary_range, group_id)) = group {
4499                self.activate_diagnostics(group_id, cx);
4500                self.update_selections(
4501                    vec![Selection {
4502                        id: selection.id,
4503                        start: primary_range.start,
4504                        end: primary_range.start,
4505                        reversed: false,
4506                        goal: SelectionGoal::None,
4507                    }],
4508                    Some(Autoscroll::Center),
4509                    cx,
4510                );
4511                break;
4512            } else {
4513                // Cycle around to the start of the buffer, potentially moving back to the start of
4514                // the currently active diagnostic.
4515                active_primary_range.take();
4516                if direction == Direction::Prev {
4517                    if search_start == buffer.len() {
4518                        break;
4519                    } else {
4520                        search_start = buffer.len();
4521                    }
4522                } else {
4523                    if search_start == 0 {
4524                        break;
4525                    } else {
4526                        search_start = 0;
4527                    }
4528                }
4529            }
4530        }
4531    }
4532
4533    pub fn go_to_definition(
4534        workspace: &mut Workspace,
4535        _: &GoToDefinition,
4536        cx: &mut ViewContext<Workspace>,
4537    ) {
4538        let active_item = workspace.active_item(cx);
4539        let editor_handle = if let Some(editor) = active_item
4540            .as_ref()
4541            .and_then(|item| item.act_as::<Self>(cx))
4542        {
4543            editor
4544        } else {
4545            return;
4546        };
4547
4548        let editor = editor_handle.read(cx);
4549        let head = editor.newest_selection::<usize>(cx).head();
4550        let (buffer, head) =
4551            if let Some(text_anchor) = editor.buffer.read(cx).text_anchor_for_position(head, cx) {
4552                text_anchor
4553            } else {
4554                return;
4555            };
4556
4557        let project = workspace.project().clone();
4558        let definitions = project.update(cx, |project, cx| project.definition(&buffer, head, cx));
4559        cx.spawn(|workspace, mut cx| async move {
4560            let definitions = definitions.await?;
4561            workspace.update(&mut cx, |workspace, cx| {
4562                let nav_history = workspace.active_pane().read(cx).nav_history().clone();
4563                for definition in definitions {
4564                    let range = definition.range.to_offset(definition.buffer.read(cx));
4565
4566                    let target_editor_handle = workspace.open_project_item(definition.buffer, cx);
4567                    target_editor_handle.update(cx, |target_editor, cx| {
4568                        // When selecting a definition in a different buffer, disable the nav history
4569                        // to avoid creating a history entry at the previous cursor location.
4570                        if editor_handle != target_editor_handle {
4571                            nav_history.borrow_mut().disable();
4572                        }
4573                        target_editor.select_ranges([range], Some(Autoscroll::Center), cx);
4574                        nav_history.borrow_mut().enable();
4575                    });
4576                }
4577            });
4578
4579            Ok::<(), anyhow::Error>(())
4580        })
4581        .detach_and_log_err(cx);
4582    }
4583
4584    pub fn find_all_references(
4585        workspace: &mut Workspace,
4586        _: &FindAllReferences,
4587        cx: &mut ViewContext<Workspace>,
4588    ) -> Option<Task<Result<()>>> {
4589        let active_item = workspace.active_item(cx)?;
4590        let editor_handle = active_item.act_as::<Self>(cx)?;
4591
4592        let editor = editor_handle.read(cx);
4593        let head = editor.newest_selection::<usize>(cx).head();
4594        let (buffer, head) = editor.buffer.read(cx).text_anchor_for_position(head, cx)?;
4595        let replica_id = editor.replica_id(cx);
4596
4597        let project = workspace.project().clone();
4598        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
4599        Some(cx.spawn(|workspace, mut cx| async move {
4600            let mut locations = references.await?;
4601            if locations.is_empty() {
4602                return Ok(());
4603            }
4604
4605            locations.sort_by_key(|location| location.buffer.id());
4606            let mut locations = locations.into_iter().peekable();
4607            let mut ranges_to_highlight = Vec::new();
4608
4609            let excerpt_buffer = cx.add_model(|cx| {
4610                let mut symbol_name = None;
4611                let mut multibuffer = MultiBuffer::new(replica_id);
4612                while let Some(location) = locations.next() {
4613                    let buffer = location.buffer.read(cx);
4614                    let mut ranges_for_buffer = Vec::new();
4615                    let range = location.range.to_offset(buffer);
4616                    ranges_for_buffer.push(range.clone());
4617                    if symbol_name.is_none() {
4618                        symbol_name = Some(buffer.text_for_range(range).collect::<String>());
4619                    }
4620
4621                    while let Some(next_location) = locations.peek() {
4622                        if next_location.buffer == location.buffer {
4623                            ranges_for_buffer.push(next_location.range.to_offset(buffer));
4624                            locations.next();
4625                        } else {
4626                            break;
4627                        }
4628                    }
4629
4630                    ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
4631                    ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
4632                        location.buffer.clone(),
4633                        ranges_for_buffer,
4634                        1,
4635                        cx,
4636                    ));
4637                }
4638                multibuffer.with_title(format!("References to `{}`", symbol_name.unwrap()))
4639            });
4640
4641            workspace.update(&mut cx, |workspace, cx| {
4642                let editor =
4643                    cx.add_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), cx));
4644                editor.update(cx, |editor, cx| {
4645                    let color = editor.style(cx).highlighted_line_background;
4646                    editor.highlight_background::<Self>(ranges_to_highlight, color, cx);
4647                });
4648                workspace.add_item(Box::new(editor), cx);
4649            });
4650
4651            Ok(())
4652        }))
4653    }
4654
4655    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
4656        use language::ToOffset as _;
4657
4658        let project = self.project.clone()?;
4659        let selection = self.newest_anchor_selection().clone();
4660        let (cursor_buffer, cursor_buffer_position) = self
4661            .buffer
4662            .read(cx)
4663            .text_anchor_for_position(selection.head(), cx)?;
4664        let (tail_buffer, _) = self
4665            .buffer
4666            .read(cx)
4667            .text_anchor_for_position(selection.tail(), cx)?;
4668        if tail_buffer != cursor_buffer {
4669            return None;
4670        }
4671
4672        let snapshot = cursor_buffer.read(cx).snapshot();
4673        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
4674        let prepare_rename = project.update(cx, |project, cx| {
4675            project.prepare_rename(cursor_buffer, cursor_buffer_offset, cx)
4676        });
4677
4678        Some(cx.spawn(|this, mut cx| async move {
4679            if let Some(rename_range) = prepare_rename.await? {
4680                let rename_buffer_range = rename_range.to_offset(&snapshot);
4681                let cursor_offset_in_rename_range =
4682                    cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
4683
4684                this.update(&mut cx, |this, cx| {
4685                    this.take_rename(false, cx);
4686                    let style = this.style(cx);
4687                    let buffer = this.buffer.read(cx).read(cx);
4688                    let cursor_offset = selection.head().to_offset(&buffer);
4689                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
4690                    let rename_end = rename_start + rename_buffer_range.len();
4691                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
4692                    let mut old_highlight_id = None;
4693                    let old_name = buffer
4694                        .chunks(rename_start..rename_end, true)
4695                        .map(|chunk| {
4696                            if old_highlight_id.is_none() {
4697                                old_highlight_id = chunk.syntax_highlight_id;
4698                            }
4699                            chunk.text
4700                        })
4701                        .collect();
4702
4703                    drop(buffer);
4704
4705                    // Position the selection in the rename editor so that it matches the current selection.
4706                    this.show_local_selections = false;
4707                    let rename_editor = cx.add_view(|cx| {
4708                        let mut editor = Editor::single_line(None, cx);
4709                        if let Some(old_highlight_id) = old_highlight_id {
4710                            editor.override_text_style =
4711                                Some(Box::new(move |style| old_highlight_id.style(&style.syntax)));
4712                        }
4713                        editor
4714                            .buffer
4715                            .update(cx, |buffer, cx| buffer.edit([0..0], &old_name, cx));
4716                        editor.select_all(&SelectAll, cx);
4717                        editor
4718                    });
4719
4720                    let ranges = this
4721                        .clear_background_highlights::<DocumentHighlightWrite>(cx)
4722                        .into_iter()
4723                        .flat_map(|(_, ranges)| ranges)
4724                        .chain(
4725                            this.clear_background_highlights::<DocumentHighlightRead>(cx)
4726                                .into_iter()
4727                                .flat_map(|(_, ranges)| ranges),
4728                        )
4729                        .collect();
4730
4731                    this.highlight_text::<Rename>(
4732                        ranges,
4733                        HighlightStyle {
4734                            fade_out: Some(style.rename_fade),
4735                            ..Default::default()
4736                        },
4737                        cx,
4738                    );
4739                    cx.focus(&rename_editor);
4740                    let block_id = this.insert_blocks(
4741                        [BlockProperties {
4742                            position: range.start.clone(),
4743                            height: 1,
4744                            render: Arc::new({
4745                                let editor = rename_editor.clone();
4746                                move |cx: &BlockContext| {
4747                                    ChildView::new(editor.clone())
4748                                        .contained()
4749                                        .with_padding_left(cx.anchor_x)
4750                                        .boxed()
4751                                }
4752                            }),
4753                            disposition: BlockDisposition::Below,
4754                        }],
4755                        cx,
4756                    )[0];
4757                    this.pending_rename = Some(RenameState {
4758                        range,
4759                        old_name,
4760                        editor: rename_editor,
4761                        block_id,
4762                    });
4763                });
4764            }
4765
4766            Ok(())
4767        }))
4768    }
4769
4770    pub fn confirm_rename(
4771        workspace: &mut Workspace,
4772        _: &ConfirmRename,
4773        cx: &mut ViewContext<Workspace>,
4774    ) -> Option<Task<Result<()>>> {
4775        let editor = workspace.active_item(cx)?.act_as::<Editor>(cx)?;
4776
4777        let (buffer, range, old_name, new_name) = editor.update(cx, |editor, cx| {
4778            let rename = editor.take_rename(false, cx)?;
4779            let buffer = editor.buffer.read(cx);
4780            let (start_buffer, start) =
4781                buffer.text_anchor_for_position(rename.range.start.clone(), cx)?;
4782            let (end_buffer, end) =
4783                buffer.text_anchor_for_position(rename.range.end.clone(), cx)?;
4784            if start_buffer == end_buffer {
4785                let new_name = rename.editor.read(cx).text(cx);
4786                Some((start_buffer, start..end, rename.old_name, new_name))
4787            } else {
4788                None
4789            }
4790        })?;
4791
4792        let rename = workspace.project().clone().update(cx, |project, cx| {
4793            project.perform_rename(
4794                buffer.clone(),
4795                range.start.clone(),
4796                new_name.clone(),
4797                true,
4798                cx,
4799            )
4800        });
4801
4802        Some(cx.spawn(|workspace, mut cx| async move {
4803            let project_transaction = rename.await?;
4804            Self::open_project_transaction(
4805                editor.clone(),
4806                workspace,
4807                project_transaction,
4808                format!("Rename: {}{}", old_name, new_name),
4809                cx.clone(),
4810            )
4811            .await?;
4812
4813            editor.update(&mut cx, |editor, cx| {
4814                editor.refresh_document_highlights(cx);
4815            });
4816            Ok(())
4817        }))
4818    }
4819
4820    fn take_rename(
4821        &mut self,
4822        moving_cursor: bool,
4823        cx: &mut ViewContext<Self>,
4824    ) -> Option<RenameState> {
4825        let rename = self.pending_rename.take()?;
4826        self.remove_blocks([rename.block_id].into_iter().collect(), cx);
4827        self.clear_text_highlights::<Rename>(cx);
4828        self.show_local_selections = true;
4829
4830        if moving_cursor {
4831            let cursor_in_rename_editor =
4832                rename.editor.read(cx).newest_selection::<usize>(cx).head();
4833
4834            // Update the selection to match the position of the selection inside
4835            // the rename editor.
4836            let snapshot = self.buffer.read(cx).read(cx);
4837            let rename_range = rename.range.to_offset(&snapshot);
4838            let cursor_in_editor = snapshot
4839                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
4840                .min(rename_range.end);
4841            drop(snapshot);
4842
4843            self.update_selections(
4844                vec![Selection {
4845                    id: self.newest_anchor_selection().id,
4846                    start: cursor_in_editor,
4847                    end: cursor_in_editor,
4848                    reversed: false,
4849                    goal: SelectionGoal::None,
4850                }],
4851                None,
4852                cx,
4853            );
4854        }
4855
4856        Some(rename)
4857    }
4858
4859    fn invalidate_rename_range(
4860        &mut self,
4861        buffer: &MultiBufferSnapshot,
4862        cx: &mut ViewContext<Self>,
4863    ) {
4864        if let Some(rename) = self.pending_rename.as_ref() {
4865            if self.selections.len() == 1 {
4866                let head = self.selections[0].head().to_offset(buffer);
4867                let range = rename.range.to_offset(buffer).to_inclusive();
4868                if range.contains(&head) {
4869                    return;
4870                }
4871            }
4872            let rename = self.pending_rename.take().unwrap();
4873            self.remove_blocks([rename.block_id].into_iter().collect(), cx);
4874            self.clear_background_highlights::<Rename>(cx);
4875        }
4876    }
4877
4878    #[cfg(any(test, feature = "test-support"))]
4879    pub fn pending_rename(&self) -> Option<&RenameState> {
4880        self.pending_rename.as_ref()
4881    }
4882
4883    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
4884        if let Some(project) = self.project.clone() {
4885            self.buffer.update(cx, |multi_buffer, cx| {
4886                project.update(cx, |project, cx| {
4887                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
4888                });
4889            })
4890        }
4891    }
4892
4893    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
4894        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
4895            let buffer = self.buffer.read(cx).snapshot(cx);
4896            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
4897            let is_valid = buffer
4898                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
4899                .any(|entry| {
4900                    entry.diagnostic.is_primary
4901                        && !entry.range.is_empty()
4902                        && entry.range.start == primary_range_start
4903                        && entry.diagnostic.message == active_diagnostics.primary_message
4904                });
4905
4906            if is_valid != active_diagnostics.is_valid {
4907                active_diagnostics.is_valid = is_valid;
4908                let mut new_styles = HashMap::default();
4909                for (block_id, diagnostic) in &active_diagnostics.blocks {
4910                    new_styles.insert(
4911                        *block_id,
4912                        diagnostic_block_renderer(diagnostic.clone(), is_valid),
4913                    );
4914                }
4915                self.display_map
4916                    .update(cx, |display_map, _| display_map.replace_blocks(new_styles));
4917            }
4918        }
4919    }
4920
4921    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) {
4922        self.dismiss_diagnostics(cx);
4923        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
4924            let buffer = self.buffer.read(cx).snapshot(cx);
4925
4926            let mut primary_range = None;
4927            let mut primary_message = None;
4928            let mut group_end = Point::zero();
4929            let diagnostic_group = buffer
4930                .diagnostic_group::<Point>(group_id)
4931                .map(|entry| {
4932                    if entry.range.end > group_end {
4933                        group_end = entry.range.end;
4934                    }
4935                    if entry.diagnostic.is_primary {
4936                        primary_range = Some(entry.range.clone());
4937                        primary_message = Some(entry.diagnostic.message.clone());
4938                    }
4939                    entry
4940                })
4941                .collect::<Vec<_>>();
4942            let primary_range = primary_range.unwrap();
4943            let primary_message = primary_message.unwrap();
4944            let primary_range =
4945                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
4946
4947            let blocks = display_map
4948                .insert_blocks(
4949                    diagnostic_group.iter().map(|entry| {
4950                        let diagnostic = entry.diagnostic.clone();
4951                        let message_height = diagnostic.message.lines().count() as u8;
4952                        BlockProperties {
4953                            position: buffer.anchor_after(entry.range.start),
4954                            height: message_height,
4955                            render: diagnostic_block_renderer(diagnostic, true),
4956                            disposition: BlockDisposition::Below,
4957                        }
4958                    }),
4959                    cx,
4960                )
4961                .into_iter()
4962                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
4963                .collect();
4964
4965            Some(ActiveDiagnosticGroup {
4966                primary_range,
4967                primary_message,
4968                blocks,
4969                is_valid: true,
4970            })
4971        });
4972    }
4973
4974    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
4975        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
4976            self.display_map.update(cx, |display_map, cx| {
4977                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
4978            });
4979            cx.notify();
4980        }
4981    }
4982
4983    fn build_columnar_selection(
4984        &mut self,
4985        display_map: &DisplaySnapshot,
4986        row: u32,
4987        columns: &Range<u32>,
4988        reversed: bool,
4989    ) -> Option<Selection<Point>> {
4990        let is_empty = columns.start == columns.end;
4991        let line_len = display_map.line_len(row);
4992        if columns.start < line_len || (is_empty && columns.start == line_len) {
4993            let start = DisplayPoint::new(row, columns.start);
4994            let end = DisplayPoint::new(row, cmp::min(columns.end, line_len));
4995            Some(Selection {
4996                id: post_inc(&mut self.next_selection_id),
4997                start: start.to_point(display_map),
4998                end: end.to_point(display_map),
4999                reversed,
5000                goal: SelectionGoal::ColumnRange {
5001                    start: columns.start,
5002                    end: columns.end,
5003                },
5004            })
5005        } else {
5006            None
5007        }
5008    }
5009
5010    pub fn local_selections_in_range(
5011        &self,
5012        range: Range<Anchor>,
5013        display_map: &DisplaySnapshot,
5014    ) -> Vec<Selection<Point>> {
5015        let buffer = &display_map.buffer_snapshot;
5016
5017        let start_ix = match self
5018            .selections
5019            .binary_search_by(|probe| probe.end.cmp(&range.start, &buffer))
5020        {
5021            Ok(ix) | Err(ix) => ix,
5022        };
5023        let end_ix = match self
5024            .selections
5025            .binary_search_by(|probe| probe.start.cmp(&range.end, &buffer))
5026        {
5027            Ok(ix) => ix + 1,
5028            Err(ix) => ix,
5029        };
5030
5031        fn point_selection(
5032            selection: &Selection<Anchor>,
5033            buffer: &MultiBufferSnapshot,
5034        ) -> Selection<Point> {
5035            let start = selection.start.to_point(&buffer);
5036            let end = selection.end.to_point(&buffer);
5037            Selection {
5038                id: selection.id,
5039                start,
5040                end,
5041                reversed: selection.reversed,
5042                goal: selection.goal,
5043            }
5044        }
5045
5046        self.selections[start_ix..end_ix]
5047            .iter()
5048            .chain(
5049                self.pending_selection
5050                    .as_ref()
5051                    .map(|pending| &pending.selection),
5052            )
5053            .map(|s| point_selection(s, &buffer))
5054            .collect()
5055    }
5056
5057    pub fn local_selections<'a, D>(&self, cx: &'a AppContext) -> Vec<Selection<D>>
5058    where
5059        D: 'a + TextDimension + Ord + Sub<D, Output = D>,
5060    {
5061        let buffer = self.buffer.read(cx).snapshot(cx);
5062        let mut selections = self
5063            .resolve_selections::<D, _>(self.selections.iter(), &buffer)
5064            .peekable();
5065
5066        let mut pending_selection = self.pending_selection::<D>(&buffer);
5067
5068        iter::from_fn(move || {
5069            if let Some(pending) = pending_selection.as_mut() {
5070                while let Some(next_selection) = selections.peek() {
5071                    if pending.start <= next_selection.end && pending.end >= next_selection.start {
5072                        let next_selection = selections.next().unwrap();
5073                        if next_selection.start < pending.start {
5074                            pending.start = next_selection.start;
5075                        }
5076                        if next_selection.end > pending.end {
5077                            pending.end = next_selection.end;
5078                        }
5079                    } else if next_selection.end < pending.start {
5080                        return selections.next();
5081                    } else {
5082                        break;
5083                    }
5084                }
5085
5086                pending_selection.take()
5087            } else {
5088                selections.next()
5089            }
5090        })
5091        .collect()
5092    }
5093
5094    fn resolve_selections<'a, D, I>(
5095        &self,
5096        selections: I,
5097        snapshot: &MultiBufferSnapshot,
5098    ) -> impl 'a + Iterator<Item = Selection<D>>
5099    where
5100        D: TextDimension + Ord + Sub<D, Output = D>,
5101        I: 'a + IntoIterator<Item = &'a Selection<Anchor>>,
5102    {
5103        let (to_summarize, selections) = selections.into_iter().tee();
5104        let mut summaries = snapshot
5105            .summaries_for_anchors::<D, _>(to_summarize.flat_map(|s| [&s.start, &s.end]))
5106            .into_iter();
5107        selections.map(move |s| Selection {
5108            id: s.id,
5109            start: summaries.next().unwrap(),
5110            end: summaries.next().unwrap(),
5111            reversed: s.reversed,
5112            goal: s.goal,
5113        })
5114    }
5115
5116    fn pending_selection<D: TextDimension + Ord + Sub<D, Output = D>>(
5117        &self,
5118        snapshot: &MultiBufferSnapshot,
5119    ) -> Option<Selection<D>> {
5120        self.pending_selection
5121            .as_ref()
5122            .map(|pending| self.resolve_selection(&pending.selection, &snapshot))
5123    }
5124
5125    fn resolve_selection<D: TextDimension + Ord + Sub<D, Output = D>>(
5126        &self,
5127        selection: &Selection<Anchor>,
5128        buffer: &MultiBufferSnapshot,
5129    ) -> Selection<D> {
5130        Selection {
5131            id: selection.id,
5132            start: selection.start.summary::<D>(&buffer),
5133            end: selection.end.summary::<D>(&buffer),
5134            reversed: selection.reversed,
5135            goal: selection.goal,
5136        }
5137    }
5138
5139    fn selection_count<'a>(&self) -> usize {
5140        let mut count = self.selections.len();
5141        if self.pending_selection.is_some() {
5142            count += 1;
5143        }
5144        count
5145    }
5146
5147    pub fn oldest_selection<D: TextDimension + Ord + Sub<D, Output = D>>(
5148        &self,
5149        cx: &AppContext,
5150    ) -> Selection<D> {
5151        let snapshot = self.buffer.read(cx).read(cx);
5152        self.selections
5153            .iter()
5154            .min_by_key(|s| s.id)
5155            .map(|selection| self.resolve_selection(selection, &snapshot))
5156            .or_else(|| self.pending_selection(&snapshot))
5157            .unwrap()
5158    }
5159
5160    pub fn newest_selection<D: TextDimension + Ord + Sub<D, Output = D>>(
5161        &self,
5162        cx: &AppContext,
5163    ) -> Selection<D> {
5164        self.resolve_selection(
5165            self.newest_anchor_selection(),
5166            &self.buffer.read(cx).read(cx),
5167        )
5168    }
5169
5170    pub fn newest_selection_with_snapshot<D: TextDimension + Ord + Sub<D, Output = D>>(
5171        &self,
5172        snapshot: &MultiBufferSnapshot,
5173    ) -> Selection<D> {
5174        self.resolve_selection(self.newest_anchor_selection(), snapshot)
5175    }
5176
5177    pub fn newest_anchor_selection(&self) -> &Selection<Anchor> {
5178        self.pending_selection
5179            .as_ref()
5180            .map(|s| &s.selection)
5181            .or_else(|| self.selections.iter().max_by_key(|s| s.id))
5182            .unwrap()
5183    }
5184
5185    pub fn update_selections<T>(
5186        &mut self,
5187        mut selections: Vec<Selection<T>>,
5188        autoscroll: Option<Autoscroll>,
5189        cx: &mut ViewContext<Self>,
5190    ) where
5191        T: ToOffset + ToPoint + Ord + std::marker::Copy + std::fmt::Debug,
5192    {
5193        let buffer = self.buffer.read(cx).snapshot(cx);
5194        selections.sort_unstable_by_key(|s| s.start);
5195
5196        // Merge overlapping selections.
5197        let mut i = 1;
5198        while i < selections.len() {
5199            if selections[i - 1].end >= selections[i].start {
5200                let removed = selections.remove(i);
5201                if removed.start < selections[i - 1].start {
5202                    selections[i - 1].start = removed.start;
5203                }
5204                if removed.end > selections[i - 1].end {
5205                    selections[i - 1].end = removed.end;
5206                }
5207            } else {
5208                i += 1;
5209            }
5210        }
5211
5212        if let Some(autoscroll) = autoscroll {
5213            self.request_autoscroll(autoscroll, cx);
5214        }
5215
5216        self.set_selections(
5217            Arc::from_iter(selections.into_iter().map(|selection| {
5218                let end_bias = if selection.end > selection.start {
5219                    Bias::Left
5220                } else {
5221                    Bias::Right
5222                };
5223                Selection {
5224                    id: selection.id,
5225                    start: buffer.anchor_after(selection.start),
5226                    end: buffer.anchor_at(selection.end, end_bias),
5227                    reversed: selection.reversed,
5228                    goal: selection.goal,
5229                }
5230            })),
5231            None,
5232            true,
5233            cx,
5234        );
5235    }
5236
5237    pub fn set_selections_from_remote(
5238        &mut self,
5239        mut selections: Vec<Selection<Anchor>>,
5240        cx: &mut ViewContext<Self>,
5241    ) {
5242        let buffer = self.buffer.read(cx);
5243        let buffer = buffer.read(cx);
5244        selections.sort_by(|a, b| {
5245            a.start
5246                .cmp(&b.start, &*buffer)
5247                .then_with(|| b.end.cmp(&a.end, &*buffer))
5248        });
5249
5250        // Merge overlapping selections
5251        let mut i = 1;
5252        while i < selections.len() {
5253            if selections[i - 1]
5254                .end
5255                .cmp(&selections[i].start, &*buffer)
5256                .is_ge()
5257            {
5258                let removed = selections.remove(i);
5259                if removed
5260                    .start
5261                    .cmp(&selections[i - 1].start, &*buffer)
5262                    .is_lt()
5263                {
5264                    selections[i - 1].start = removed.start;
5265                }
5266                if removed.end.cmp(&selections[i - 1].end, &*buffer).is_gt() {
5267                    selections[i - 1].end = removed.end;
5268                }
5269            } else {
5270                i += 1;
5271            }
5272        }
5273
5274        drop(buffer);
5275        self.set_selections(selections.into(), None, false, cx);
5276    }
5277
5278    /// Compute new ranges for any selections that were located in excerpts that have
5279    /// since been removed.
5280    ///
5281    /// Returns a `HashMap` indicating which selections whose former head position
5282    /// was no longer present. The keys of the map are selection ids. The values are
5283    /// the id of the new excerpt where the head of the selection has been moved.
5284    pub fn refresh_selections(&mut self, cx: &mut ViewContext<Self>) -> HashMap<usize, ExcerptId> {
5285        let snapshot = self.buffer.read(cx).read(cx);
5286        let mut selections_with_lost_position = HashMap::default();
5287
5288        let mut pending_selection = self.pending_selection.take();
5289        if let Some(pending) = pending_selection.as_mut() {
5290            let anchors =
5291                snapshot.refresh_anchors([&pending.selection.start, &pending.selection.end]);
5292            let (_, start, kept_start) = anchors[0].clone();
5293            let (_, end, kept_end) = anchors[1].clone();
5294            let kept_head = if pending.selection.reversed {
5295                kept_start
5296            } else {
5297                kept_end
5298            };
5299            if !kept_head {
5300                selections_with_lost_position.insert(
5301                    pending.selection.id,
5302                    pending.selection.head().excerpt_id.clone(),
5303                );
5304            }
5305
5306            pending.selection.start = start;
5307            pending.selection.end = end;
5308        }
5309
5310        let anchors_with_status = snapshot.refresh_anchors(
5311            self.selections
5312                .iter()
5313                .flat_map(|selection| [&selection.start, &selection.end]),
5314        );
5315        self.selections = anchors_with_status
5316            .chunks(2)
5317            .map(|selection_anchors| {
5318                let (anchor_ix, start, kept_start) = selection_anchors[0].clone();
5319                let (_, end, kept_end) = selection_anchors[1].clone();
5320                let selection = &self.selections[anchor_ix / 2];
5321                let kept_head = if selection.reversed {
5322                    kept_start
5323                } else {
5324                    kept_end
5325                };
5326                if !kept_head {
5327                    selections_with_lost_position
5328                        .insert(selection.id, selection.head().excerpt_id.clone());
5329                }
5330
5331                Selection {
5332                    id: selection.id,
5333                    start,
5334                    end,
5335                    reversed: selection.reversed,
5336                    goal: selection.goal,
5337                }
5338            })
5339            .collect();
5340        drop(snapshot);
5341
5342        let new_selections = self.local_selections::<usize>(cx);
5343        if !new_selections.is_empty() {
5344            self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
5345        }
5346        self.pending_selection = pending_selection;
5347
5348        selections_with_lost_position
5349    }
5350
5351    fn set_selections(
5352        &mut self,
5353        selections: Arc<[Selection<Anchor>]>,
5354        pending_selection: Option<PendingSelection>,
5355        local: bool,
5356        cx: &mut ViewContext<Self>,
5357    ) {
5358        assert!(
5359            !selections.is_empty() || pending_selection.is_some(),
5360            "must have at least one selection"
5361        );
5362
5363        let old_cursor_position = self.newest_anchor_selection().head();
5364
5365        self.push_to_selection_history();
5366        self.selections = selections;
5367        self.pending_selection = pending_selection;
5368        if self.focused && self.leader_replica_id.is_none() {
5369            self.buffer.update(cx, |buffer, cx| {
5370                buffer.set_active_selections(&self.selections, cx)
5371            });
5372        }
5373
5374        let display_map = self
5375            .display_map
5376            .update(cx, |display_map, cx| display_map.snapshot(cx));
5377        let buffer = &display_map.buffer_snapshot;
5378        self.add_selections_state = None;
5379        self.select_next_state = None;
5380        self.select_larger_syntax_node_stack.clear();
5381        self.autoclose_stack.invalidate(&self.selections, &buffer);
5382        self.snippet_stack.invalidate(&self.selections, &buffer);
5383        self.invalidate_rename_range(&buffer, cx);
5384
5385        let new_cursor_position = self.newest_anchor_selection().head();
5386
5387        self.push_to_nav_history(
5388            old_cursor_position.clone(),
5389            Some(new_cursor_position.to_point(&buffer)),
5390            cx,
5391        );
5392
5393        if local {
5394            let completion_menu = match self.context_menu.as_mut() {
5395                Some(ContextMenu::Completions(menu)) => Some(menu),
5396                _ => {
5397                    self.context_menu.take();
5398                    None
5399                }
5400            };
5401
5402            if let Some(completion_menu) = completion_menu {
5403                let cursor_position = new_cursor_position.to_offset(&buffer);
5404                let (word_range, kind) =
5405                    buffer.surrounding_word(completion_menu.initial_position.clone());
5406                if kind == Some(CharKind::Word)
5407                    && word_range.to_inclusive().contains(&cursor_position)
5408                {
5409                    let query = Self::completion_query(&buffer, cursor_position);
5410                    cx.background()
5411                        .block(completion_menu.filter(query.as_deref(), cx.background().clone()));
5412                    self.show_completions(&ShowCompletions, cx);
5413                } else {
5414                    self.hide_context_menu(cx);
5415                }
5416            }
5417
5418            if old_cursor_position.to_display_point(&display_map).row()
5419                != new_cursor_position.to_display_point(&display_map).row()
5420            {
5421                self.available_code_actions.take();
5422            }
5423            self.refresh_code_actions(cx);
5424            self.refresh_document_highlights(cx);
5425        }
5426
5427        self.pause_cursor_blinking(cx);
5428        cx.emit(Event::SelectionsChanged { local });
5429    }
5430
5431    fn push_to_selection_history(&mut self) {
5432        self.selection_history.push(SelectionHistoryEntry {
5433            selections: self.selections.clone(),
5434            select_next_state: self.select_next_state.clone(),
5435            add_selections_state: self.add_selections_state.clone(),
5436        });
5437    }
5438
5439    pub fn request_autoscroll(&mut self, autoscroll: Autoscroll, cx: &mut ViewContext<Self>) {
5440        self.autoscroll_request = Some((autoscroll, true));
5441        cx.notify();
5442    }
5443
5444    fn request_autoscroll_remotely(&mut self, autoscroll: Autoscroll, cx: &mut ViewContext<Self>) {
5445        self.autoscroll_request = Some((autoscroll, false));
5446        cx.notify();
5447    }
5448
5449    pub fn transact(
5450        &mut self,
5451        cx: &mut ViewContext<Self>,
5452        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
5453    ) {
5454        self.start_transaction_at(Instant::now(), cx);
5455        update(self, cx);
5456        self.end_transaction_at(Instant::now(), cx);
5457    }
5458
5459    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
5460        self.end_selection(cx);
5461        if let Some(tx_id) = self
5462            .buffer
5463            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
5464        {
5465            self.selection_history
5466                .insert_transaction(tx_id, self.selections.clone());
5467        }
5468    }
5469
5470    fn end_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
5471        if let Some(tx_id) = self
5472            .buffer
5473            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
5474        {
5475            if let Some((_, end_selections)) = self.selection_history.transaction_mut(tx_id) {
5476                *end_selections = Some(self.selections.clone());
5477            } else {
5478                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
5479            }
5480
5481            cx.emit(Event::Edited);
5482        }
5483    }
5484
5485    pub fn page_up(&mut self, _: &PageUp, _: &mut ViewContext<Self>) {
5486        log::info!("Editor::page_up");
5487    }
5488
5489    pub fn page_down(&mut self, _: &PageDown, _: &mut ViewContext<Self>) {
5490        log::info!("Editor::page_down");
5491    }
5492
5493    pub fn fold(&mut self, _: &Fold, cx: &mut ViewContext<Self>) {
5494        let mut fold_ranges = Vec::new();
5495
5496        let selections = self.local_selections::<Point>(cx);
5497        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5498        for selection in selections {
5499            let range = selection.display_range(&display_map).sorted();
5500            let buffer_start_row = range.start.to_point(&display_map).row;
5501
5502            for row in (0..=range.end.row()).rev() {
5503                if self.is_line_foldable(&display_map, row) && !display_map.is_line_folded(row) {
5504                    let fold_range = self.foldable_range_for_line(&display_map, row);
5505                    if fold_range.end.row >= buffer_start_row {
5506                        fold_ranges.push(fold_range);
5507                        if row <= range.start.row() {
5508                            break;
5509                        }
5510                    }
5511                }
5512            }
5513        }
5514
5515        self.fold_ranges(fold_ranges, cx);
5516    }
5517
5518    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
5519        let selections = self.local_selections::<Point>(cx);
5520        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5521        let buffer = &display_map.buffer_snapshot;
5522        let ranges = selections
5523            .iter()
5524            .map(|s| {
5525                let range = s.display_range(&display_map).sorted();
5526                let mut start = range.start.to_point(&display_map);
5527                let mut end = range.end.to_point(&display_map);
5528                start.column = 0;
5529                end.column = buffer.line_len(end.row);
5530                start..end
5531            })
5532            .collect::<Vec<_>>();
5533        self.unfold_ranges(ranges, true, cx);
5534    }
5535
5536    fn is_line_foldable(&self, display_map: &DisplaySnapshot, display_row: u32) -> bool {
5537        let max_point = display_map.max_point();
5538        if display_row >= max_point.row() {
5539            false
5540        } else {
5541            let (start_indent, is_blank) = display_map.line_indent(display_row);
5542            if is_blank {
5543                false
5544            } else {
5545                for display_row in display_row + 1..=max_point.row() {
5546                    let (indent, is_blank) = display_map.line_indent(display_row);
5547                    if !is_blank {
5548                        return indent > start_indent;
5549                    }
5550                }
5551                false
5552            }
5553        }
5554    }
5555
5556    fn foldable_range_for_line(
5557        &self,
5558        display_map: &DisplaySnapshot,
5559        start_row: u32,
5560    ) -> Range<Point> {
5561        let max_point = display_map.max_point();
5562
5563        let (start_indent, _) = display_map.line_indent(start_row);
5564        let start = DisplayPoint::new(start_row, display_map.line_len(start_row));
5565        let mut end = None;
5566        for row in start_row + 1..=max_point.row() {
5567            let (indent, is_blank) = display_map.line_indent(row);
5568            if !is_blank && indent <= start_indent {
5569                end = Some(DisplayPoint::new(row - 1, display_map.line_len(row - 1)));
5570                break;
5571            }
5572        }
5573
5574        let end = end.unwrap_or(max_point);
5575        return start.to_point(display_map)..end.to_point(display_map);
5576    }
5577
5578    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
5579        let selections = self.local_selections::<Point>(cx);
5580        let ranges = selections.into_iter().map(|s| s.start..s.end);
5581        self.fold_ranges(ranges, cx);
5582    }
5583
5584    pub fn fold_ranges<T: ToOffset>(
5585        &mut self,
5586        ranges: impl IntoIterator<Item = Range<T>>,
5587        cx: &mut ViewContext<Self>,
5588    ) {
5589        let mut ranges = ranges.into_iter().peekable();
5590        if ranges.peek().is_some() {
5591            self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
5592            self.request_autoscroll(Autoscroll::Fit, cx);
5593            cx.notify();
5594        }
5595    }
5596
5597    pub fn unfold_ranges<T: ToOffset>(
5598        &mut self,
5599        ranges: impl IntoIterator<Item = Range<T>>,
5600        inclusive: bool,
5601        cx: &mut ViewContext<Self>,
5602    ) {
5603        let mut ranges = ranges.into_iter().peekable();
5604        if ranges.peek().is_some() {
5605            self.display_map
5606                .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
5607            self.request_autoscroll(Autoscroll::Fit, cx);
5608            cx.notify();
5609        }
5610    }
5611
5612    pub fn insert_blocks(
5613        &mut self,
5614        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
5615        cx: &mut ViewContext<Self>,
5616    ) -> Vec<BlockId> {
5617        let blocks = self
5618            .display_map
5619            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
5620        self.request_autoscroll(Autoscroll::Fit, cx);
5621        blocks
5622    }
5623
5624    pub fn replace_blocks(
5625        &mut self,
5626        blocks: HashMap<BlockId, RenderBlock>,
5627        cx: &mut ViewContext<Self>,
5628    ) {
5629        self.display_map
5630            .update(cx, |display_map, _| display_map.replace_blocks(blocks));
5631        self.request_autoscroll(Autoscroll::Fit, cx);
5632    }
5633
5634    pub fn remove_blocks(&mut self, block_ids: HashSet<BlockId>, cx: &mut ViewContext<Self>) {
5635        self.display_map.update(cx, |display_map, cx| {
5636            display_map.remove_blocks(block_ids, cx)
5637        });
5638    }
5639
5640    pub fn longest_row(&self, cx: &mut MutableAppContext) -> u32 {
5641        self.display_map
5642            .update(cx, |map, cx| map.snapshot(cx))
5643            .longest_row()
5644    }
5645
5646    pub fn max_point(&self, cx: &mut MutableAppContext) -> DisplayPoint {
5647        self.display_map
5648            .update(cx, |map, cx| map.snapshot(cx))
5649            .max_point()
5650    }
5651
5652    pub fn text(&self, cx: &AppContext) -> String {
5653        self.buffer.read(cx).read(cx).text()
5654    }
5655
5656    pub fn set_text(&mut self, text: impl Into<String>, cx: &mut ViewContext<Self>) {
5657        self.transact(cx, |this, cx| {
5658            this.buffer
5659                .read(cx)
5660                .as_singleton()
5661                .expect("you can only call set_text on editors for singleton buffers")
5662                .update(cx, |buffer, cx| buffer.set_text(text, cx));
5663        });
5664    }
5665
5666    pub fn display_text(&self, cx: &mut MutableAppContext) -> String {
5667        self.display_map
5668            .update(cx, |map, cx| map.snapshot(cx))
5669            .text()
5670    }
5671
5672    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
5673        let language = self.language(cx).map(|language| language.name());
5674        let settings = cx.global::<Settings>();
5675        let mode = self
5676            .soft_wrap_mode_override
5677            .unwrap_or_else(|| settings.soft_wrap(language.as_deref()));
5678        match mode {
5679            settings::SoftWrap::None => SoftWrap::None,
5680            settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
5681            settings::SoftWrap::PreferredLineLength => {
5682                SoftWrap::Column(settings.preferred_line_length(language.as_deref()))
5683            }
5684        }
5685    }
5686
5687    pub fn set_soft_wrap_mode(&mut self, mode: settings::SoftWrap, cx: &mut ViewContext<Self>) {
5688        self.soft_wrap_mode_override = Some(mode);
5689        cx.notify();
5690    }
5691
5692    pub fn set_wrap_width(&self, width: Option<f32>, cx: &mut MutableAppContext) -> bool {
5693        self.display_map
5694            .update(cx, |map, cx| map.set_wrap_width(width, cx))
5695    }
5696
5697    pub fn highlight_rows(&mut self, rows: Option<Range<u32>>) {
5698        self.highlighted_rows = rows;
5699    }
5700
5701    pub fn highlighted_rows(&self) -> Option<Range<u32>> {
5702        self.highlighted_rows.clone()
5703    }
5704
5705    pub fn highlight_background<T: 'static>(
5706        &mut self,
5707        ranges: Vec<Range<Anchor>>,
5708        color: Color,
5709        cx: &mut ViewContext<Self>,
5710    ) {
5711        self.background_highlights
5712            .insert(TypeId::of::<T>(), (color, ranges));
5713        cx.notify();
5714    }
5715
5716    pub fn clear_background_highlights<T: 'static>(
5717        &mut self,
5718        cx: &mut ViewContext<Self>,
5719    ) -> Option<(Color, Vec<Range<Anchor>>)> {
5720        cx.notify();
5721        self.background_highlights.remove(&TypeId::of::<T>())
5722    }
5723
5724    #[cfg(feature = "test-support")]
5725    pub fn all_background_highlights(
5726        &mut self,
5727        cx: &mut ViewContext<Self>,
5728    ) -> Vec<(Range<DisplayPoint>, Color)> {
5729        let snapshot = self.snapshot(cx);
5730        let buffer = &snapshot.buffer_snapshot;
5731        let start = buffer.anchor_before(0);
5732        let end = buffer.anchor_after(buffer.len());
5733        self.background_highlights_in_range(start..end, &snapshot)
5734    }
5735
5736    pub fn background_highlights_for_type<T: 'static>(&self) -> Option<(Color, &[Range<Anchor>])> {
5737        self.background_highlights
5738            .get(&TypeId::of::<T>())
5739            .map(|(color, ranges)| (*color, ranges.as_slice()))
5740    }
5741
5742    pub fn background_highlights_in_range(
5743        &self,
5744        search_range: Range<Anchor>,
5745        display_snapshot: &DisplaySnapshot,
5746    ) -> Vec<(Range<DisplayPoint>, Color)> {
5747        let mut results = Vec::new();
5748        let buffer = &display_snapshot.buffer_snapshot;
5749        for (color, ranges) in self.background_highlights.values() {
5750            let start_ix = match ranges.binary_search_by(|probe| {
5751                let cmp = probe.end.cmp(&search_range.start, &buffer);
5752                if cmp.is_gt() {
5753                    Ordering::Greater
5754                } else {
5755                    Ordering::Less
5756                }
5757            }) {
5758                Ok(i) | Err(i) => i,
5759            };
5760            for range in &ranges[start_ix..] {
5761                if range.start.cmp(&search_range.end, &buffer).is_ge() {
5762                    break;
5763                }
5764                let start = range
5765                    .start
5766                    .to_point(buffer)
5767                    .to_display_point(display_snapshot);
5768                let end = range
5769                    .end
5770                    .to_point(buffer)
5771                    .to_display_point(display_snapshot);
5772                results.push((start..end, *color))
5773            }
5774        }
5775        results
5776    }
5777
5778    pub fn highlight_text<T: 'static>(
5779        &mut self,
5780        ranges: Vec<Range<Anchor>>,
5781        style: HighlightStyle,
5782        cx: &mut ViewContext<Self>,
5783    ) {
5784        self.display_map.update(cx, |map, _| {
5785            map.highlight_text(TypeId::of::<T>(), ranges, style)
5786        });
5787        cx.notify();
5788    }
5789
5790    pub fn clear_text_highlights<T: 'static>(
5791        &mut self,
5792        cx: &mut ViewContext<Self>,
5793    ) -> Option<Arc<(HighlightStyle, Vec<Range<Anchor>>)>> {
5794        cx.notify();
5795        self.display_map
5796            .update(cx, |map, _| map.clear_text_highlights(TypeId::of::<T>()))
5797    }
5798
5799    fn next_blink_epoch(&mut self) -> usize {
5800        self.blink_epoch += 1;
5801        self.blink_epoch
5802    }
5803
5804    fn pause_cursor_blinking(&mut self, cx: &mut ViewContext<Self>) {
5805        if !self.focused {
5806            return;
5807        }
5808
5809        self.show_local_cursors = true;
5810        cx.notify();
5811
5812        let epoch = self.next_blink_epoch();
5813        cx.spawn(|this, mut cx| {
5814            let this = this.downgrade();
5815            async move {
5816                Timer::after(CURSOR_BLINK_INTERVAL).await;
5817                if let Some(this) = this.upgrade(&cx) {
5818                    this.update(&mut cx, |this, cx| this.resume_cursor_blinking(epoch, cx))
5819                }
5820            }
5821        })
5822        .detach();
5823    }
5824
5825    fn resume_cursor_blinking(&mut self, epoch: usize, cx: &mut ViewContext<Self>) {
5826        if epoch == self.blink_epoch {
5827            self.blinking_paused = false;
5828            self.blink_cursors(epoch, cx);
5829        }
5830    }
5831
5832    fn blink_cursors(&mut self, epoch: usize, cx: &mut ViewContext<Self>) {
5833        if epoch == self.blink_epoch && self.focused && !self.blinking_paused {
5834            self.show_local_cursors = !self.show_local_cursors;
5835            cx.notify();
5836
5837            let epoch = self.next_blink_epoch();
5838            cx.spawn(|this, mut cx| {
5839                let this = this.downgrade();
5840                async move {
5841                    Timer::after(CURSOR_BLINK_INTERVAL).await;
5842                    if let Some(this) = this.upgrade(&cx) {
5843                        this.update(&mut cx, |this, cx| this.blink_cursors(epoch, cx));
5844                    }
5845                }
5846            })
5847            .detach();
5848        }
5849    }
5850
5851    pub fn show_local_cursors(&self) -> bool {
5852        self.show_local_cursors && self.focused
5853    }
5854
5855    fn on_buffer_changed(&mut self, _: ModelHandle<MultiBuffer>, cx: &mut ViewContext<Self>) {
5856        cx.notify();
5857    }
5858
5859    fn on_buffer_event(
5860        &mut self,
5861        _: ModelHandle<MultiBuffer>,
5862        event: &language::Event,
5863        cx: &mut ViewContext<Self>,
5864    ) {
5865        match event {
5866            language::Event::Edited => {
5867                self.refresh_active_diagnostics(cx);
5868                self.refresh_code_actions(cx);
5869                cx.emit(Event::BufferEdited);
5870            }
5871            language::Event::Reparsed => cx.emit(Event::Reparsed),
5872            language::Event::Dirtied => cx.emit(Event::Dirtied),
5873            language::Event::Saved => cx.emit(Event::Saved),
5874            language::Event::FileHandleChanged => cx.emit(Event::TitleChanged),
5875            language::Event::Reloaded => cx.emit(Event::TitleChanged),
5876            language::Event::Closed => cx.emit(Event::Closed),
5877            language::Event::DiagnosticsUpdated => {
5878                self.refresh_active_diagnostics(cx);
5879            }
5880            _ => {}
5881        }
5882    }
5883
5884    fn on_display_map_changed(&mut self, _: ModelHandle<DisplayMap>, cx: &mut ViewContext<Self>) {
5885        cx.notify();
5886    }
5887
5888    pub fn set_searchable(&mut self, searchable: bool) {
5889        self.searchable = searchable;
5890    }
5891
5892    pub fn searchable(&self) -> bool {
5893        self.searchable
5894    }
5895
5896    fn open_excerpts(workspace: &mut Workspace, _: &OpenExcerpts, cx: &mut ViewContext<Workspace>) {
5897        let active_item = workspace.active_item(cx);
5898        let editor_handle = if let Some(editor) = active_item
5899            .as_ref()
5900            .and_then(|item| item.act_as::<Self>(cx))
5901        {
5902            editor
5903        } else {
5904            cx.propagate_action();
5905            return;
5906        };
5907
5908        let editor = editor_handle.read(cx);
5909        let buffer = editor.buffer.read(cx);
5910        if buffer.is_singleton() {
5911            cx.propagate_action();
5912            return;
5913        }
5914
5915        let mut new_selections_by_buffer = HashMap::default();
5916        for selection in editor.local_selections::<usize>(cx) {
5917            for (buffer, mut range) in
5918                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
5919            {
5920                if selection.reversed {
5921                    mem::swap(&mut range.start, &mut range.end);
5922                }
5923                new_selections_by_buffer
5924                    .entry(buffer)
5925                    .or_insert(Vec::new())
5926                    .push(range)
5927            }
5928        }
5929
5930        editor_handle.update(cx, |editor, cx| {
5931            editor.push_to_nav_history(editor.newest_anchor_selection().head(), None, cx);
5932        });
5933        let nav_history = workspace.active_pane().read(cx).nav_history().clone();
5934        nav_history.borrow_mut().disable();
5935
5936        // We defer the pane interaction because we ourselves are a workspace item
5937        // and activating a new item causes the pane to call a method on us reentrantly,
5938        // which panics if we're on the stack.
5939        cx.defer(move |workspace, cx| {
5940            workspace.activate_next_pane(cx);
5941
5942            for (buffer, ranges) in new_selections_by_buffer.into_iter() {
5943                let editor = workspace.open_project_item::<Self>(buffer, cx);
5944                editor.update(cx, |editor, cx| {
5945                    editor.select_ranges(ranges, Some(Autoscroll::Newest), cx);
5946                });
5947            }
5948
5949            nav_history.borrow_mut().enable();
5950        });
5951    }
5952}
5953
5954impl EditorSnapshot {
5955    pub fn is_focused(&self) -> bool {
5956        self.is_focused
5957    }
5958
5959    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
5960        self.placeholder_text.as_ref()
5961    }
5962
5963    pub fn scroll_position(&self) -> Vector2F {
5964        compute_scroll_position(
5965            &self.display_snapshot,
5966            self.scroll_position,
5967            &self.scroll_top_anchor,
5968        )
5969    }
5970}
5971
5972impl Deref for EditorSnapshot {
5973    type Target = DisplaySnapshot;
5974
5975    fn deref(&self) -> &Self::Target {
5976        &self.display_snapshot
5977    }
5978}
5979
5980fn compute_scroll_position(
5981    snapshot: &DisplaySnapshot,
5982    mut scroll_position: Vector2F,
5983    scroll_top_anchor: &Anchor,
5984) -> Vector2F {
5985    if *scroll_top_anchor != Anchor::min() {
5986        let scroll_top = scroll_top_anchor.to_display_point(snapshot).row() as f32;
5987        scroll_position.set_y(scroll_top + scroll_position.y());
5988    } else {
5989        scroll_position.set_y(0.);
5990    }
5991    scroll_position
5992}
5993
5994#[derive(Copy, Clone, Debug, PartialEq, Eq)]
5995pub enum Event {
5996    Activate,
5997    BufferEdited,
5998    Edited,
5999    Reparsed,
6000    Blurred,
6001    Dirtied,
6002    Saved,
6003    TitleChanged,
6004    SelectionsChanged { local: bool },
6005    ScrollPositionChanged { local: bool },
6006    Closed,
6007}
6008
6009pub struct EditorFocused(pub ViewHandle<Editor>);
6010pub struct EditorBlurred(pub ViewHandle<Editor>);
6011pub struct EditorReleased(pub WeakViewHandle<Editor>);
6012
6013impl Entity for Editor {
6014    type Event = Event;
6015
6016    fn release(&mut self, cx: &mut MutableAppContext) {
6017        cx.emit_global(EditorReleased(self.handle.clone()));
6018    }
6019}
6020
6021impl View for Editor {
6022    fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
6023        let style = self.style(cx);
6024        self.display_map.update(cx, |map, cx| {
6025            map.set_font(style.text.font_id, style.text.font_size, cx)
6026        });
6027        EditorElement::new(self.handle.clone(), style.clone(), self.cursor_shape).boxed()
6028    }
6029
6030    fn ui_name() -> &'static str {
6031        "Editor"
6032    }
6033
6034    fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
6035        let focused_event = EditorFocused(cx.handle());
6036        cx.emit_global(focused_event);
6037        if let Some(rename) = self.pending_rename.as_ref() {
6038            cx.focus(&rename.editor);
6039        } else {
6040            self.focused = true;
6041            self.blink_cursors(self.blink_epoch, cx);
6042            self.buffer.update(cx, |buffer, cx| {
6043                buffer.finalize_last_transaction(cx);
6044                if self.leader_replica_id.is_none() {
6045                    buffer.set_active_selections(&self.selections, cx);
6046                }
6047            });
6048        }
6049    }
6050
6051    fn on_blur(&mut self, cx: &mut ViewContext<Self>) {
6052        let blurred_event = EditorBlurred(cx.handle());
6053        cx.emit_global(blurred_event);
6054        self.focused = false;
6055        self.buffer
6056            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
6057        self.hide_context_menu(cx);
6058        cx.emit(Event::Blurred);
6059        cx.notify();
6060    }
6061
6062    fn keymap_context(&self, _: &AppContext) -> gpui::keymap::Context {
6063        let mut context = Self::default_keymap_context();
6064        let mode = match self.mode {
6065            EditorMode::SingleLine => "single_line",
6066            EditorMode::AutoHeight { .. } => "auto_height",
6067            EditorMode::Full => "full",
6068        };
6069        context.map.insert("mode".into(), mode.into());
6070        if self.pending_rename.is_some() {
6071            context.set.insert("renaming".into());
6072        }
6073        match self.context_menu.as_ref() {
6074            Some(ContextMenu::Completions(_)) => {
6075                context.set.insert("showing_completions".into());
6076            }
6077            Some(ContextMenu::CodeActions(_)) => {
6078                context.set.insert("showing_code_actions".into());
6079            }
6080            None => {}
6081        }
6082
6083        for layer in self.keymap_context_layers.values() {
6084            context.extend(layer);
6085        }
6086
6087        context
6088    }
6089}
6090
6091fn build_style(
6092    settings: &Settings,
6093    get_field_editor_theme: Option<GetFieldEditorTheme>,
6094    override_text_style: Option<&OverrideTextStyle>,
6095    cx: &AppContext,
6096) -> EditorStyle {
6097    let font_cache = cx.font_cache();
6098
6099    let mut theme = settings.theme.editor.clone();
6100    let mut style = if let Some(get_field_editor_theme) = get_field_editor_theme {
6101        let field_editor_theme = get_field_editor_theme(&settings.theme);
6102        theme.text_color = field_editor_theme.text.color;
6103        theme.selection = field_editor_theme.selection;
6104        theme.background = field_editor_theme
6105            .container
6106            .background_color
6107            .unwrap_or_default();
6108        EditorStyle {
6109            text: field_editor_theme.text,
6110            placeholder_text: field_editor_theme.placeholder_text,
6111            theme,
6112        }
6113    } else {
6114        let font_family_id = settings.buffer_font_family;
6115        let font_family_name = cx.font_cache().family_name(font_family_id).unwrap();
6116        let font_properties = Default::default();
6117        let font_id = font_cache
6118            .select_font(font_family_id, &font_properties)
6119            .unwrap();
6120        let font_size = settings.buffer_font_size;
6121        EditorStyle {
6122            text: TextStyle {
6123                color: settings.theme.editor.text_color,
6124                font_family_name,
6125                font_family_id,
6126                font_id,
6127                font_size,
6128                font_properties,
6129                underline: Default::default(),
6130            },
6131            placeholder_text: None,
6132            theme,
6133        }
6134    };
6135
6136    if let Some(highlight_style) = override_text_style.and_then(|build_style| build_style(&style)) {
6137        if let Some(highlighted) = style
6138            .text
6139            .clone()
6140            .highlight(highlight_style, font_cache)
6141            .log_err()
6142        {
6143            style.text = highlighted;
6144        }
6145    }
6146
6147    style
6148}
6149
6150trait SelectionExt {
6151    fn offset_range(&self, buffer: &MultiBufferSnapshot) -> Range<usize>;
6152    fn point_range(&self, buffer: &MultiBufferSnapshot) -> Range<Point>;
6153    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
6154    fn spanned_rows(&self, include_end_if_at_line_start: bool, map: &DisplaySnapshot)
6155        -> Range<u32>;
6156}
6157
6158impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
6159    fn point_range(&self, buffer: &MultiBufferSnapshot) -> Range<Point> {
6160        let start = self.start.to_point(buffer);
6161        let end = self.end.to_point(buffer);
6162        if self.reversed {
6163            end..start
6164        } else {
6165            start..end
6166        }
6167    }
6168
6169    fn offset_range(&self, buffer: &MultiBufferSnapshot) -> Range<usize> {
6170        let start = self.start.to_offset(buffer);
6171        let end = self.end.to_offset(buffer);
6172        if self.reversed {
6173            end..start
6174        } else {
6175            start..end
6176        }
6177    }
6178
6179    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
6180        let start = self
6181            .start
6182            .to_point(&map.buffer_snapshot)
6183            .to_display_point(map);
6184        let end = self
6185            .end
6186            .to_point(&map.buffer_snapshot)
6187            .to_display_point(map);
6188        if self.reversed {
6189            end..start
6190        } else {
6191            start..end
6192        }
6193    }
6194
6195    fn spanned_rows(
6196        &self,
6197        include_end_if_at_line_start: bool,
6198        map: &DisplaySnapshot,
6199    ) -> Range<u32> {
6200        let start = self.start.to_point(&map.buffer_snapshot);
6201        let mut end = self.end.to_point(&map.buffer_snapshot);
6202        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
6203            end.row -= 1;
6204        }
6205
6206        let buffer_start = map.prev_line_boundary(start).0;
6207        let buffer_end = map.next_line_boundary(end).0;
6208        buffer_start.row..buffer_end.row + 1
6209    }
6210}
6211
6212impl<T: InvalidationRegion> InvalidationStack<T> {
6213    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
6214    where
6215        S: Clone + ToOffset,
6216    {
6217        while let Some(region) = self.last() {
6218            let all_selections_inside_invalidation_ranges =
6219                if selections.len() == region.ranges().len() {
6220                    selections
6221                        .iter()
6222                        .zip(region.ranges().iter().map(|r| r.to_offset(&buffer)))
6223                        .all(|(selection, invalidation_range)| {
6224                            let head = selection.head().to_offset(&buffer);
6225                            invalidation_range.start <= head && invalidation_range.end >= head
6226                        })
6227                } else {
6228                    false
6229                };
6230
6231            if all_selections_inside_invalidation_ranges {
6232                break;
6233            } else {
6234                self.pop();
6235            }
6236        }
6237    }
6238}
6239
6240impl<T> Default for InvalidationStack<T> {
6241    fn default() -> Self {
6242        Self(Default::default())
6243    }
6244}
6245
6246impl<T> Deref for InvalidationStack<T> {
6247    type Target = Vec<T>;
6248
6249    fn deref(&self) -> &Self::Target {
6250        &self.0
6251    }
6252}
6253
6254impl<T> DerefMut for InvalidationStack<T> {
6255    fn deref_mut(&mut self) -> &mut Self::Target {
6256        &mut self.0
6257    }
6258}
6259
6260impl InvalidationRegion for BracketPairState {
6261    fn ranges(&self) -> &[Range<Anchor>] {
6262        &self.ranges
6263    }
6264}
6265
6266impl InvalidationRegion for SnippetState {
6267    fn ranges(&self) -> &[Range<Anchor>] {
6268        &self.ranges[self.active_index]
6269    }
6270}
6271
6272impl Deref for EditorStyle {
6273    type Target = theme::Editor;
6274
6275    fn deref(&self) -> &Self::Target {
6276        &self.theme
6277    }
6278}
6279
6280pub fn diagnostic_block_renderer(diagnostic: Diagnostic, is_valid: bool) -> RenderBlock {
6281    let mut highlighted_lines = Vec::new();
6282    for line in diagnostic.message.lines() {
6283        highlighted_lines.push(highlight_diagnostic_message(line));
6284    }
6285
6286    Arc::new(move |cx: &BlockContext| {
6287        let settings = cx.global::<Settings>();
6288        let theme = &settings.theme.editor;
6289        let style = diagnostic_style(diagnostic.severity, is_valid, theme);
6290        let font_size = (style.text_scale_factor * settings.buffer_font_size).round();
6291        Flex::column()
6292            .with_children(highlighted_lines.iter().map(|(line, highlights)| {
6293                Label::new(
6294                    line.clone(),
6295                    style.message.clone().with_font_size(font_size),
6296                )
6297                .with_highlights(highlights.clone())
6298                .contained()
6299                .with_margin_left(cx.anchor_x)
6300                .boxed()
6301            }))
6302            .aligned()
6303            .left()
6304            .boxed()
6305    })
6306}
6307
6308pub fn highlight_diagnostic_message(message: &str) -> (String, Vec<usize>) {
6309    let mut message_without_backticks = String::new();
6310    let mut prev_offset = 0;
6311    let mut inside_block = false;
6312    let mut highlights = Vec::new();
6313    for (match_ix, (offset, _)) in message
6314        .match_indices('`')
6315        .chain([(message.len(), "")])
6316        .enumerate()
6317    {
6318        message_without_backticks.push_str(&message[prev_offset..offset]);
6319        if inside_block {
6320            highlights.extend(prev_offset - match_ix..offset - match_ix);
6321        }
6322
6323        inside_block = !inside_block;
6324        prev_offset = offset + 1;
6325    }
6326
6327    (message_without_backticks, highlights)
6328}
6329
6330pub fn diagnostic_style(
6331    severity: DiagnosticSeverity,
6332    valid: bool,
6333    theme: &theme::Editor,
6334) -> DiagnosticStyle {
6335    match (severity, valid) {
6336        (DiagnosticSeverity::ERROR, true) => theme.error_diagnostic.clone(),
6337        (DiagnosticSeverity::ERROR, false) => theme.invalid_error_diagnostic.clone(),
6338        (DiagnosticSeverity::WARNING, true) => theme.warning_diagnostic.clone(),
6339        (DiagnosticSeverity::WARNING, false) => theme.invalid_warning_diagnostic.clone(),
6340        (DiagnosticSeverity::INFORMATION, true) => theme.information_diagnostic.clone(),
6341        (DiagnosticSeverity::INFORMATION, false) => theme.invalid_information_diagnostic.clone(),
6342        (DiagnosticSeverity::HINT, true) => theme.hint_diagnostic.clone(),
6343        (DiagnosticSeverity::HINT, false) => theme.invalid_hint_diagnostic.clone(),
6344        _ => theme.invalid_hint_diagnostic.clone(),
6345    }
6346}
6347
6348pub fn combine_syntax_and_fuzzy_match_highlights(
6349    text: &str,
6350    default_style: HighlightStyle,
6351    syntax_ranges: impl Iterator<Item = (Range<usize>, HighlightStyle)>,
6352    match_indices: &[usize],
6353) -> Vec<(Range<usize>, HighlightStyle)> {
6354    let mut result = Vec::new();
6355    let mut match_indices = match_indices.iter().copied().peekable();
6356
6357    for (range, mut syntax_highlight) in syntax_ranges.chain([(usize::MAX..0, Default::default())])
6358    {
6359        syntax_highlight.weight = None;
6360
6361        // Add highlights for any fuzzy match characters before the next
6362        // syntax highlight range.
6363        while let Some(&match_index) = match_indices.peek() {
6364            if match_index >= range.start {
6365                break;
6366            }
6367            match_indices.next();
6368            let end_index = char_ix_after(match_index, text);
6369            let mut match_style = default_style;
6370            match_style.weight = Some(fonts::Weight::BOLD);
6371            result.push((match_index..end_index, match_style));
6372        }
6373
6374        if range.start == usize::MAX {
6375            break;
6376        }
6377
6378        // Add highlights for any fuzzy match characters within the
6379        // syntax highlight range.
6380        let mut offset = range.start;
6381        while let Some(&match_index) = match_indices.peek() {
6382            if match_index >= range.end {
6383                break;
6384            }
6385
6386            match_indices.next();
6387            if match_index > offset {
6388                result.push((offset..match_index, syntax_highlight));
6389            }
6390
6391            let mut end_index = char_ix_after(match_index, text);
6392            while let Some(&next_match_index) = match_indices.peek() {
6393                if next_match_index == end_index && next_match_index < range.end {
6394                    end_index = char_ix_after(next_match_index, text);
6395                    match_indices.next();
6396                } else {
6397                    break;
6398                }
6399            }
6400
6401            let mut match_style = syntax_highlight;
6402            match_style.weight = Some(fonts::Weight::BOLD);
6403            result.push((match_index..end_index, match_style));
6404            offset = end_index;
6405        }
6406
6407        if offset < range.end {
6408            result.push((offset..range.end, syntax_highlight));
6409        }
6410    }
6411
6412    fn char_ix_after(ix: usize, text: &str) -> usize {
6413        ix + text[ix..].chars().next().unwrap().len_utf8()
6414    }
6415
6416    result
6417}
6418
6419pub fn styled_runs_for_code_label<'a>(
6420    label: &'a CodeLabel,
6421    syntax_theme: &'a theme::SyntaxTheme,
6422) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
6423    let fade_out = HighlightStyle {
6424        fade_out: Some(0.35),
6425        ..Default::default()
6426    };
6427
6428    let mut prev_end = label.filter_range.end;
6429    label
6430        .runs
6431        .iter()
6432        .enumerate()
6433        .flat_map(move |(ix, (range, highlight_id))| {
6434            let style = if let Some(style) = highlight_id.style(syntax_theme) {
6435                style
6436            } else {
6437                return Default::default();
6438            };
6439            let mut muted_style = style.clone();
6440            muted_style.highlight(fade_out);
6441
6442            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
6443            if range.start >= label.filter_range.end {
6444                if range.start > prev_end {
6445                    runs.push((prev_end..range.start, fade_out));
6446                }
6447                runs.push((range.clone(), muted_style));
6448            } else if range.end <= label.filter_range.end {
6449                runs.push((range.clone(), style));
6450            } else {
6451                runs.push((range.start..label.filter_range.end, style));
6452                runs.push((label.filter_range.end..range.end, muted_style));
6453            }
6454            prev_end = cmp::max(prev_end, range.end);
6455
6456            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
6457                runs.push((prev_end..label.text.len(), fade_out));
6458            }
6459
6460            runs
6461        })
6462}
6463
6464#[cfg(test)]
6465mod tests {
6466    use super::*;
6467    use gpui::{
6468        geometry::rect::RectF,
6469        platform::{WindowBounds, WindowOptions},
6470    };
6471    use language::{FakeLspAdapter, LanguageConfig};
6472    use lsp::FakeLanguageServer;
6473    use project::FakeFs;
6474    use smol::stream::StreamExt;
6475    use std::{cell::RefCell, rc::Rc, time::Instant};
6476    use text::Point;
6477    use unindent::Unindent;
6478    use util::test::{marked_text_by, marked_text_ranges, sample_text};
6479    use workspace::{FollowableItem, ItemHandle};
6480
6481    #[gpui::test]
6482    fn test_edit_events(cx: &mut MutableAppContext) {
6483        populate_settings(cx);
6484        let buffer = cx.add_model(|cx| language::Buffer::new(0, "123456", cx));
6485
6486        let events = Rc::new(RefCell::new(Vec::new()));
6487        let (_, editor1) = cx.add_window(Default::default(), {
6488            let events = events.clone();
6489            |cx| {
6490                cx.subscribe(&cx.handle(), move |_, _, event, _| {
6491                    if matches!(event, Event::Edited | Event::BufferEdited | Event::Dirtied) {
6492                        events.borrow_mut().push(("editor1", *event));
6493                    }
6494                })
6495                .detach();
6496                Editor::for_buffer(buffer.clone(), None, cx)
6497            }
6498        });
6499        let (_, editor2) = cx.add_window(Default::default(), {
6500            let events = events.clone();
6501            |cx| {
6502                cx.subscribe(&cx.handle(), move |_, _, event, _| {
6503                    if matches!(event, Event::Edited | Event::BufferEdited | Event::Dirtied) {
6504                        events.borrow_mut().push(("editor2", *event));
6505                    }
6506                })
6507                .detach();
6508                Editor::for_buffer(buffer.clone(), None, cx)
6509            }
6510        });
6511        assert_eq!(mem::take(&mut *events.borrow_mut()), []);
6512
6513        // Mutating editor 1 will emit an `Edited` event only for that editor.
6514        editor1.update(cx, |editor, cx| editor.insert("X", cx));
6515        assert_eq!(
6516            mem::take(&mut *events.borrow_mut()),
6517            [
6518                ("editor1", Event::Edited),
6519                ("editor1", Event::BufferEdited),
6520                ("editor2", Event::BufferEdited),
6521                ("editor1", Event::Dirtied),
6522                ("editor2", Event::Dirtied)
6523            ]
6524        );
6525
6526        // Mutating editor 2 will emit an `Edited` event only for that editor.
6527        editor2.update(cx, |editor, cx| editor.delete(&Delete, cx));
6528        assert_eq!(
6529            mem::take(&mut *events.borrow_mut()),
6530            [
6531                ("editor2", Event::Edited),
6532                ("editor1", Event::BufferEdited),
6533                ("editor2", Event::BufferEdited),
6534            ]
6535        );
6536
6537        // Undoing on editor 1 will emit an `Edited` event only for that editor.
6538        editor1.update(cx, |editor, cx| editor.undo(&Undo, cx));
6539        assert_eq!(
6540            mem::take(&mut *events.borrow_mut()),
6541            [
6542                ("editor1", Event::Edited),
6543                ("editor1", Event::BufferEdited),
6544                ("editor2", Event::BufferEdited),
6545            ]
6546        );
6547
6548        // Redoing on editor 1 will emit an `Edited` event only for that editor.
6549        editor1.update(cx, |editor, cx| editor.redo(&Redo, cx));
6550        assert_eq!(
6551            mem::take(&mut *events.borrow_mut()),
6552            [
6553                ("editor1", Event::Edited),
6554                ("editor1", Event::BufferEdited),
6555                ("editor2", Event::BufferEdited),
6556            ]
6557        );
6558
6559        // Undoing on editor 2 will emit an `Edited` event only for that editor.
6560        editor2.update(cx, |editor, cx| editor.undo(&Undo, cx));
6561        assert_eq!(
6562            mem::take(&mut *events.borrow_mut()),
6563            [
6564                ("editor2", Event::Edited),
6565                ("editor1", Event::BufferEdited),
6566                ("editor2", Event::BufferEdited),
6567            ]
6568        );
6569
6570        // Redoing on editor 2 will emit an `Edited` event only for that editor.
6571        editor2.update(cx, |editor, cx| editor.redo(&Redo, cx));
6572        assert_eq!(
6573            mem::take(&mut *events.borrow_mut()),
6574            [
6575                ("editor2", Event::Edited),
6576                ("editor1", Event::BufferEdited),
6577                ("editor2", Event::BufferEdited),
6578            ]
6579        );
6580
6581        // No event is emitted when the mutation is a no-op.
6582        editor2.update(cx, |editor, cx| {
6583            editor.select_ranges([0..0], None, cx);
6584            editor.backspace(&Backspace, cx);
6585        });
6586        assert_eq!(mem::take(&mut *events.borrow_mut()), []);
6587    }
6588
6589    #[gpui::test]
6590    fn test_undo_redo_with_selection_restoration(cx: &mut MutableAppContext) {
6591        populate_settings(cx);
6592        let mut now = Instant::now();
6593        let buffer = cx.add_model(|cx| language::Buffer::new(0, "123456", cx));
6594        let group_interval = buffer.read(cx).transaction_group_interval();
6595        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
6596        let (_, editor) = cx.add_window(Default::default(), |cx| build_editor(buffer.clone(), cx));
6597
6598        editor.update(cx, |editor, cx| {
6599            editor.start_transaction_at(now, cx);
6600            editor.select_ranges([2..4], None, cx);
6601            editor.insert("cd", cx);
6602            editor.end_transaction_at(now, cx);
6603            assert_eq!(editor.text(cx), "12cd56");
6604            assert_eq!(editor.selected_ranges(cx), vec![4..4]);
6605
6606            editor.start_transaction_at(now, cx);
6607            editor.select_ranges([4..5], None, cx);
6608            editor.insert("e", cx);
6609            editor.end_transaction_at(now, cx);
6610            assert_eq!(editor.text(cx), "12cde6");
6611            assert_eq!(editor.selected_ranges(cx), vec![5..5]);
6612
6613            now += group_interval + Duration::from_millis(1);
6614            editor.select_ranges([2..2], None, cx);
6615
6616            // Simulate an edit in another editor
6617            buffer.update(cx, |buffer, cx| {
6618                buffer.start_transaction_at(now, cx);
6619                buffer.edit([0..1], "a", cx);
6620                buffer.edit([1..1], "b", cx);
6621                buffer.end_transaction_at(now, cx);
6622            });
6623
6624            assert_eq!(editor.text(cx), "ab2cde6");
6625            assert_eq!(editor.selected_ranges(cx), vec![3..3]);
6626
6627            // Last transaction happened past the group interval in a different editor.
6628            // Undo it individually and don't restore selections.
6629            editor.undo(&Undo, cx);
6630            assert_eq!(editor.text(cx), "12cde6");
6631            assert_eq!(editor.selected_ranges(cx), vec![2..2]);
6632
6633            // First two transactions happened within the group interval in this editor.
6634            // Undo them together and restore selections.
6635            editor.undo(&Undo, cx);
6636            editor.undo(&Undo, cx); // Undo stack is empty here, so this is a no-op.
6637            assert_eq!(editor.text(cx), "123456");
6638            assert_eq!(editor.selected_ranges(cx), vec![0..0]);
6639
6640            // Redo the first two transactions together.
6641            editor.redo(&Redo, cx);
6642            assert_eq!(editor.text(cx), "12cde6");
6643            assert_eq!(editor.selected_ranges(cx), vec![5..5]);
6644
6645            // Redo the last transaction on its own.
6646            editor.redo(&Redo, cx);
6647            assert_eq!(editor.text(cx), "ab2cde6");
6648            assert_eq!(editor.selected_ranges(cx), vec![6..6]);
6649
6650            // Test empty transactions.
6651            editor.start_transaction_at(now, cx);
6652            editor.end_transaction_at(now, cx);
6653            editor.undo(&Undo, cx);
6654            assert_eq!(editor.text(cx), "12cde6");
6655        });
6656    }
6657
6658    #[gpui::test]
6659    fn test_selection_with_mouse(cx: &mut gpui::MutableAppContext) {
6660        populate_settings(cx);
6661
6662        let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\nddddddd\n", cx);
6663        let (_, editor) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
6664        editor.update(cx, |view, cx| {
6665            view.begin_selection(DisplayPoint::new(2, 2), false, 1, cx);
6666        });
6667        assert_eq!(
6668            editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
6669            [DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2)]
6670        );
6671
6672        editor.update(cx, |view, cx| {
6673            view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
6674        });
6675
6676        assert_eq!(
6677            editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
6678            [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
6679        );
6680
6681        editor.update(cx, |view, cx| {
6682            view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
6683        });
6684
6685        assert_eq!(
6686            editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
6687            [DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1)]
6688        );
6689
6690        editor.update(cx, |view, cx| {
6691            view.end_selection(cx);
6692            view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
6693        });
6694
6695        assert_eq!(
6696            editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
6697            [DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1)]
6698        );
6699
6700        editor.update(cx, |view, cx| {
6701            view.begin_selection(DisplayPoint::new(3, 3), true, 1, cx);
6702            view.update_selection(DisplayPoint::new(0, 0), 0, Vector2F::zero(), cx);
6703        });
6704
6705        assert_eq!(
6706            editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
6707            [
6708                DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1),
6709                DisplayPoint::new(3, 3)..DisplayPoint::new(0, 0)
6710            ]
6711        );
6712
6713        editor.update(cx, |view, cx| {
6714            view.end_selection(cx);
6715        });
6716
6717        assert_eq!(
6718            editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
6719            [DisplayPoint::new(3, 3)..DisplayPoint::new(0, 0)]
6720        );
6721    }
6722
6723    #[gpui::test]
6724    fn test_canceling_pending_selection(cx: &mut gpui::MutableAppContext) {
6725        populate_settings(cx);
6726        let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
6727        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
6728
6729        view.update(cx, |view, cx| {
6730            view.begin_selection(DisplayPoint::new(2, 2), false, 1, cx);
6731            assert_eq!(
6732                view.selected_display_ranges(cx),
6733                [DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2)]
6734            );
6735        });
6736
6737        view.update(cx, |view, cx| {
6738            view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
6739            assert_eq!(
6740                view.selected_display_ranges(cx),
6741                [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
6742            );
6743        });
6744
6745        view.update(cx, |view, cx| {
6746            view.cancel(&Cancel, cx);
6747            view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
6748            assert_eq!(
6749                view.selected_display_ranges(cx),
6750                [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
6751            );
6752        });
6753    }
6754
6755    #[gpui::test]
6756    fn test_navigation_history(cx: &mut gpui::MutableAppContext) {
6757        populate_settings(cx);
6758        use workspace::Item;
6759        let nav_history = Rc::new(RefCell::new(workspace::NavHistory::default()));
6760        let buffer = MultiBuffer::build_simple(&sample_text(30, 5, 'a'), cx);
6761
6762        cx.add_window(Default::default(), |cx| {
6763            let mut editor = build_editor(buffer.clone(), cx);
6764            editor.nav_history = Some(ItemNavHistory::new(nav_history.clone(), &cx.handle()));
6765
6766            // Move the cursor a small distance.
6767            // Nothing is added to the navigation history.
6768            editor.select_display_ranges(&[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)], cx);
6769            editor.select_display_ranges(&[DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0)], cx);
6770            assert!(nav_history.borrow_mut().pop_backward().is_none());
6771
6772            // Move the cursor a large distance.
6773            // The history can jump back to the previous position.
6774            editor.select_display_ranges(&[DisplayPoint::new(13, 0)..DisplayPoint::new(13, 3)], cx);
6775            let nav_entry = nav_history.borrow_mut().pop_backward().unwrap();
6776            editor.navigate(nav_entry.data.unwrap(), cx);
6777            assert_eq!(nav_entry.item.id(), cx.view_id());
6778            assert_eq!(
6779                editor.selected_display_ranges(cx),
6780                &[DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0)]
6781            );
6782            assert!(nav_history.borrow_mut().pop_backward().is_none());
6783
6784            // Move the cursor a small distance via the mouse.
6785            // Nothing is added to the navigation history.
6786            editor.begin_selection(DisplayPoint::new(5, 0), false, 1, cx);
6787            editor.end_selection(cx);
6788            assert_eq!(
6789                editor.selected_display_ranges(cx),
6790                &[DisplayPoint::new(5, 0)..DisplayPoint::new(5, 0)]
6791            );
6792            assert!(nav_history.borrow_mut().pop_backward().is_none());
6793
6794            // Move the cursor a large distance via the mouse.
6795            // The history can jump back to the previous position.
6796            editor.begin_selection(DisplayPoint::new(15, 0), false, 1, cx);
6797            editor.end_selection(cx);
6798            assert_eq!(
6799                editor.selected_display_ranges(cx),
6800                &[DisplayPoint::new(15, 0)..DisplayPoint::new(15, 0)]
6801            );
6802            let nav_entry = nav_history.borrow_mut().pop_backward().unwrap();
6803            editor.navigate(nav_entry.data.unwrap(), cx);
6804            assert_eq!(nav_entry.item.id(), cx.view_id());
6805            assert_eq!(
6806                editor.selected_display_ranges(cx),
6807                &[DisplayPoint::new(5, 0)..DisplayPoint::new(5, 0)]
6808            );
6809            assert!(nav_history.borrow_mut().pop_backward().is_none());
6810
6811            editor
6812        });
6813    }
6814
6815    #[gpui::test]
6816    fn test_cancel(cx: &mut gpui::MutableAppContext) {
6817        populate_settings(cx);
6818        let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
6819        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
6820
6821        view.update(cx, |view, cx| {
6822            view.begin_selection(DisplayPoint::new(3, 4), false, 1, cx);
6823            view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
6824            view.end_selection(cx);
6825
6826            view.begin_selection(DisplayPoint::new(0, 1), true, 1, cx);
6827            view.update_selection(DisplayPoint::new(0, 3), 0, Vector2F::zero(), cx);
6828            view.end_selection(cx);
6829            assert_eq!(
6830                view.selected_display_ranges(cx),
6831                [
6832                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
6833                    DisplayPoint::new(3, 4)..DisplayPoint::new(1, 1),
6834                ]
6835            );
6836        });
6837
6838        view.update(cx, |view, cx| {
6839            view.cancel(&Cancel, cx);
6840            assert_eq!(
6841                view.selected_display_ranges(cx),
6842                [DisplayPoint::new(3, 4)..DisplayPoint::new(1, 1)]
6843            );
6844        });
6845
6846        view.update(cx, |view, cx| {
6847            view.cancel(&Cancel, cx);
6848            assert_eq!(
6849                view.selected_display_ranges(cx),
6850                [DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1)]
6851            );
6852        });
6853    }
6854
6855    #[gpui::test]
6856    fn test_fold(cx: &mut gpui::MutableAppContext) {
6857        populate_settings(cx);
6858        let buffer = MultiBuffer::build_simple(
6859            &"
6860                impl Foo {
6861                    // Hello!
6862
6863                    fn a() {
6864                        1
6865                    }
6866
6867                    fn b() {
6868                        2
6869                    }
6870
6871                    fn c() {
6872                        3
6873                    }
6874                }
6875            "
6876            .unindent(),
6877            cx,
6878        );
6879        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer.clone(), cx));
6880
6881        view.update(cx, |view, cx| {
6882            view.select_display_ranges(&[DisplayPoint::new(8, 0)..DisplayPoint::new(12, 0)], cx);
6883            view.fold(&Fold, cx);
6884            assert_eq!(
6885                view.display_text(cx),
6886                "
6887                    impl Foo {
6888                        // Hello!
6889
6890                        fn a() {
6891                            1
6892                        }
6893
6894                        fn b() {…
6895                        }
6896
6897                        fn c() {…
6898                        }
6899                    }
6900                "
6901                .unindent(),
6902            );
6903
6904            view.fold(&Fold, cx);
6905            assert_eq!(
6906                view.display_text(cx),
6907                "
6908                    impl Foo {…
6909                    }
6910                "
6911                .unindent(),
6912            );
6913
6914            view.unfold_lines(&UnfoldLines, cx);
6915            assert_eq!(
6916                view.display_text(cx),
6917                "
6918                    impl Foo {
6919                        // Hello!
6920
6921                        fn a() {
6922                            1
6923                        }
6924
6925                        fn b() {…
6926                        }
6927
6928                        fn c() {…
6929                        }
6930                    }
6931                "
6932                .unindent(),
6933            );
6934
6935            view.unfold_lines(&UnfoldLines, cx);
6936            assert_eq!(view.display_text(cx), buffer.read(cx).read(cx).text());
6937        });
6938    }
6939
6940    #[gpui::test]
6941    fn test_move_cursor(cx: &mut gpui::MutableAppContext) {
6942        populate_settings(cx);
6943        let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
6944        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer.clone(), cx));
6945
6946        buffer.update(cx, |buffer, cx| {
6947            buffer.edit(
6948                vec![
6949                    Point::new(1, 0)..Point::new(1, 0),
6950                    Point::new(1, 1)..Point::new(1, 1),
6951                ],
6952                "\t",
6953                cx,
6954            );
6955        });
6956
6957        view.update(cx, |view, cx| {
6958            assert_eq!(
6959                view.selected_display_ranges(cx),
6960                &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
6961            );
6962
6963            view.move_down(&MoveDown, cx);
6964            assert_eq!(
6965                view.selected_display_ranges(cx),
6966                &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
6967            );
6968
6969            view.move_right(&MoveRight, cx);
6970            assert_eq!(
6971                view.selected_display_ranges(cx),
6972                &[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4)]
6973            );
6974
6975            view.move_left(&MoveLeft, cx);
6976            assert_eq!(
6977                view.selected_display_ranges(cx),
6978                &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
6979            );
6980
6981            view.move_up(&MoveUp, cx);
6982            assert_eq!(
6983                view.selected_display_ranges(cx),
6984                &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
6985            );
6986
6987            view.move_to_end(&MoveToEnd, cx);
6988            assert_eq!(
6989                view.selected_display_ranges(cx),
6990                &[DisplayPoint::new(5, 6)..DisplayPoint::new(5, 6)]
6991            );
6992
6993            view.move_to_beginning(&MoveToBeginning, cx);
6994            assert_eq!(
6995                view.selected_display_ranges(cx),
6996                &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
6997            );
6998
6999            view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 2)], cx);
7000            view.select_to_beginning(&SelectToBeginning, cx);
7001            assert_eq!(
7002                view.selected_display_ranges(cx),
7003                &[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 0)]
7004            );
7005
7006            view.select_to_end(&SelectToEnd, cx);
7007            assert_eq!(
7008                view.selected_display_ranges(cx),
7009                &[DisplayPoint::new(0, 1)..DisplayPoint::new(5, 6)]
7010            );
7011        });
7012    }
7013
7014    #[gpui::test]
7015    fn test_move_cursor_multibyte(cx: &mut gpui::MutableAppContext) {
7016        populate_settings(cx);
7017        let buffer = MultiBuffer::build_simple("ⓐⓑⓒⓓⓔ\nabcde\nαβγδε\n", cx);
7018        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer.clone(), cx));
7019
7020        assert_eq!('ⓐ'.len_utf8(), 3);
7021        assert_eq!('α'.len_utf8(), 2);
7022
7023        view.update(cx, |view, cx| {
7024            view.fold_ranges(
7025                vec![
7026                    Point::new(0, 6)..Point::new(0, 12),
7027                    Point::new(1, 2)..Point::new(1, 4),
7028                    Point::new(2, 4)..Point::new(2, 8),
7029                ],
7030                cx,
7031            );
7032            assert_eq!(view.display_text(cx), "ⓐⓑ…ⓔ\nab…e\nαβ…ε\n");
7033
7034            view.move_right(&MoveRight, cx);
7035            assert_eq!(
7036                view.selected_display_ranges(cx),
7037                &[empty_range(0, "".len())]
7038            );
7039            view.move_right(&MoveRight, cx);
7040            assert_eq!(
7041                view.selected_display_ranges(cx),
7042                &[empty_range(0, "ⓐⓑ".len())]
7043            );
7044            view.move_right(&MoveRight, cx);
7045            assert_eq!(
7046                view.selected_display_ranges(cx),
7047                &[empty_range(0, "ⓐⓑ…".len())]
7048            );
7049
7050            view.move_down(&MoveDown, cx);
7051            assert_eq!(
7052                view.selected_display_ranges(cx),
7053                &[empty_range(1, "ab…".len())]
7054            );
7055            view.move_left(&MoveLeft, cx);
7056            assert_eq!(
7057                view.selected_display_ranges(cx),
7058                &[empty_range(1, "ab".len())]
7059            );
7060            view.move_left(&MoveLeft, cx);
7061            assert_eq!(
7062                view.selected_display_ranges(cx),
7063                &[empty_range(1, "a".len())]
7064            );
7065
7066            view.move_down(&MoveDown, cx);
7067            assert_eq!(
7068                view.selected_display_ranges(cx),
7069                &[empty_range(2, "α".len())]
7070            );
7071            view.move_right(&MoveRight, cx);
7072            assert_eq!(
7073                view.selected_display_ranges(cx),
7074                &[empty_range(2, "αβ".len())]
7075            );
7076            view.move_right(&MoveRight, cx);
7077            assert_eq!(
7078                view.selected_display_ranges(cx),
7079                &[empty_range(2, "αβ…".len())]
7080            );
7081            view.move_right(&MoveRight, cx);
7082            assert_eq!(
7083                view.selected_display_ranges(cx),
7084                &[empty_range(2, "αβ…ε".len())]
7085            );
7086
7087            view.move_up(&MoveUp, cx);
7088            assert_eq!(
7089                view.selected_display_ranges(cx),
7090                &[empty_range(1, "ab…e".len())]
7091            );
7092            view.move_up(&MoveUp, cx);
7093            assert_eq!(
7094                view.selected_display_ranges(cx),
7095                &[empty_range(0, "ⓐⓑ…ⓔ".len())]
7096            );
7097            view.move_left(&MoveLeft, cx);
7098            assert_eq!(
7099                view.selected_display_ranges(cx),
7100                &[empty_range(0, "ⓐⓑ…".len())]
7101            );
7102            view.move_left(&MoveLeft, cx);
7103            assert_eq!(
7104                view.selected_display_ranges(cx),
7105                &[empty_range(0, "ⓐⓑ".len())]
7106            );
7107            view.move_left(&MoveLeft, cx);
7108            assert_eq!(
7109                view.selected_display_ranges(cx),
7110                &[empty_range(0, "".len())]
7111            );
7112        });
7113    }
7114
7115    #[gpui::test]
7116    fn test_move_cursor_different_line_lengths(cx: &mut gpui::MutableAppContext) {
7117        populate_settings(cx);
7118        let buffer = MultiBuffer::build_simple("ⓐⓑⓒⓓⓔ\nabcd\nαβγ\nabcd\nⓐⓑⓒⓓⓔ\n", cx);
7119        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer.clone(), cx));
7120        view.update(cx, |view, cx| {
7121            view.select_display_ranges(&[empty_range(0, "ⓐⓑⓒⓓⓔ".len())], cx);
7122            view.move_down(&MoveDown, cx);
7123            assert_eq!(
7124                view.selected_display_ranges(cx),
7125                &[empty_range(1, "abcd".len())]
7126            );
7127
7128            view.move_down(&MoveDown, cx);
7129            assert_eq!(
7130                view.selected_display_ranges(cx),
7131                &[empty_range(2, "αβγ".len())]
7132            );
7133
7134            view.move_down(&MoveDown, cx);
7135            assert_eq!(
7136                view.selected_display_ranges(cx),
7137                &[empty_range(3, "abcd".len())]
7138            );
7139
7140            view.move_down(&MoveDown, cx);
7141            assert_eq!(
7142                view.selected_display_ranges(cx),
7143                &[empty_range(4, "ⓐⓑⓒⓓⓔ".len())]
7144            );
7145
7146            view.move_up(&MoveUp, cx);
7147            assert_eq!(
7148                view.selected_display_ranges(cx),
7149                &[empty_range(3, "abcd".len())]
7150            );
7151
7152            view.move_up(&MoveUp, cx);
7153            assert_eq!(
7154                view.selected_display_ranges(cx),
7155                &[empty_range(2, "αβγ".len())]
7156            );
7157        });
7158    }
7159
7160    #[gpui::test]
7161    fn test_beginning_end_of_line(cx: &mut gpui::MutableAppContext) {
7162        populate_settings(cx);
7163        let buffer = MultiBuffer::build_simple("abc\n  def", cx);
7164        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
7165        view.update(cx, |view, cx| {
7166            view.select_display_ranges(
7167                &[
7168                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
7169                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4),
7170                ],
7171                cx,
7172            );
7173        });
7174
7175        view.update(cx, |view, cx| {
7176            view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
7177            assert_eq!(
7178                view.selected_display_ranges(cx),
7179                &[
7180                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
7181                    DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
7182                ]
7183            );
7184        });
7185
7186        view.update(cx, |view, cx| {
7187            view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
7188            assert_eq!(
7189                view.selected_display_ranges(cx),
7190                &[
7191                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
7192                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
7193                ]
7194            );
7195        });
7196
7197        view.update(cx, |view, cx| {
7198            view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
7199            assert_eq!(
7200                view.selected_display_ranges(cx),
7201                &[
7202                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
7203                    DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
7204                ]
7205            );
7206        });
7207
7208        view.update(cx, |view, cx| {
7209            view.move_to_end_of_line(&MoveToEndOfLine, cx);
7210            assert_eq!(
7211                view.selected_display_ranges(cx),
7212                &[
7213                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
7214                    DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
7215                ]
7216            );
7217        });
7218
7219        // Moving to the end of line again is a no-op.
7220        view.update(cx, |view, cx| {
7221            view.move_to_end_of_line(&MoveToEndOfLine, cx);
7222            assert_eq!(
7223                view.selected_display_ranges(cx),
7224                &[
7225                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
7226                    DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
7227                ]
7228            );
7229        });
7230
7231        view.update(cx, |view, cx| {
7232            view.move_left(&MoveLeft, cx);
7233            view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
7234            assert_eq!(
7235                view.selected_display_ranges(cx),
7236                &[
7237                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
7238                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 2),
7239                ]
7240            );
7241        });
7242
7243        view.update(cx, |view, cx| {
7244            view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
7245            assert_eq!(
7246                view.selected_display_ranges(cx),
7247                &[
7248                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
7249                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 0),
7250                ]
7251            );
7252        });
7253
7254        view.update(cx, |view, cx| {
7255            view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
7256            assert_eq!(
7257                view.selected_display_ranges(cx),
7258                &[
7259                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
7260                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 2),
7261                ]
7262            );
7263        });
7264
7265        view.update(cx, |view, cx| {
7266            view.select_to_end_of_line(&SelectToEndOfLine(true), cx);
7267            assert_eq!(
7268                view.selected_display_ranges(cx),
7269                &[
7270                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 3),
7271                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 5),
7272                ]
7273            );
7274        });
7275
7276        view.update(cx, |view, cx| {
7277            view.delete_to_end_of_line(&DeleteToEndOfLine, cx);
7278            assert_eq!(view.display_text(cx), "ab\n  de");
7279            assert_eq!(
7280                view.selected_display_ranges(cx),
7281                &[
7282                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7283                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4),
7284                ]
7285            );
7286        });
7287
7288        view.update(cx, |view, cx| {
7289            view.delete_to_beginning_of_line(&DeleteToBeginningOfLine, cx);
7290            assert_eq!(view.display_text(cx), "\n");
7291            assert_eq!(
7292                view.selected_display_ranges(cx),
7293                &[
7294                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
7295                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
7296                ]
7297            );
7298        });
7299    }
7300
7301    #[gpui::test]
7302    fn test_prev_next_word_boundary(cx: &mut gpui::MutableAppContext) {
7303        populate_settings(cx);
7304        let buffer = MultiBuffer::build_simple("use std::str::{foo, bar}\n\n  {baz.qux()}", cx);
7305        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
7306        view.update(cx, |view, cx| {
7307            view.select_display_ranges(
7308                &[
7309                    DisplayPoint::new(0, 11)..DisplayPoint::new(0, 11),
7310                    DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4),
7311                ],
7312                cx,
7313            );
7314
7315            view.move_to_previous_word_start(&MoveToPreviousWordStart, cx);
7316            assert_selection_ranges(
7317                "use std::<>str::{foo, bar}\n\n  {[]baz.qux()}",
7318                vec![('<', '>'), ('[', ']')],
7319                view,
7320                cx,
7321            );
7322
7323            view.move_to_previous_word_start(&MoveToPreviousWordStart, cx);
7324            assert_selection_ranges(
7325                "use std<>::str::{foo, bar}\n\n  []{baz.qux()}",
7326                vec![('<', '>'), ('[', ']')],
7327                view,
7328                cx,
7329            );
7330
7331            view.move_to_previous_word_start(&MoveToPreviousWordStart, cx);
7332            assert_selection_ranges(
7333                "use <>std::str::{foo, bar}\n\n[]  {baz.qux()}",
7334                vec![('<', '>'), ('[', ']')],
7335                view,
7336                cx,
7337            );
7338
7339            view.move_to_previous_word_start(&MoveToPreviousWordStart, cx);
7340            assert_selection_ranges(
7341                "<>use std::str::{foo, bar}\n[]\n  {baz.qux()}",
7342                vec![('<', '>'), ('[', ']')],
7343                view,
7344                cx,
7345            );
7346
7347            view.move_to_previous_word_start(&MoveToPreviousWordStart, cx);
7348            assert_selection_ranges(
7349                "<>use std::str::{foo, bar[]}\n\n  {baz.qux()}",
7350                vec![('<', '>'), ('[', ']')],
7351                view,
7352                cx,
7353            );
7354
7355            view.move_to_next_word_end(&MoveToNextWordEnd, cx);
7356            assert_selection_ranges(
7357                "use<> std::str::{foo, bar}[]\n\n  {baz.qux()}",
7358                vec![('<', '>'), ('[', ']')],
7359                view,
7360                cx,
7361            );
7362
7363            view.move_to_next_word_end(&MoveToNextWordEnd, cx);
7364            assert_selection_ranges(
7365                "use std<>::str::{foo, bar}\n[]\n  {baz.qux()}",
7366                vec![('<', '>'), ('[', ']')],
7367                view,
7368                cx,
7369            );
7370
7371            view.move_to_next_word_end(&MoveToNextWordEnd, cx);
7372            assert_selection_ranges(
7373                "use std::<>str::{foo, bar}\n\n  {[]baz.qux()}",
7374                vec![('<', '>'), ('[', ']')],
7375                view,
7376                cx,
7377            );
7378
7379            view.move_right(&MoveRight, cx);
7380            view.select_to_previous_word_start(&SelectToPreviousWordStart, cx);
7381            assert_selection_ranges(
7382                "use std::>s<tr::{foo, bar}\n\n  {]b[az.qux()}",
7383                vec![('<', '>'), ('[', ']')],
7384                view,
7385                cx,
7386            );
7387
7388            view.select_to_previous_word_start(&SelectToPreviousWordStart, cx);
7389            assert_selection_ranges(
7390                "use std>::s<tr::{foo, bar}\n\n  ]{b[az.qux()}",
7391                vec![('<', '>'), ('[', ']')],
7392                view,
7393                cx,
7394            );
7395
7396            view.select_to_next_word_end(&SelectToNextWordEnd, cx);
7397            assert_selection_ranges(
7398                "use std::>s<tr::{foo, bar}\n\n  {]b[az.qux()}",
7399                vec![('<', '>'), ('[', ']')],
7400                view,
7401                cx,
7402            );
7403        });
7404    }
7405
7406    #[gpui::test]
7407    fn test_prev_next_word_bounds_with_soft_wrap(cx: &mut gpui::MutableAppContext) {
7408        populate_settings(cx);
7409        let buffer = MultiBuffer::build_simple("use one::{\n    two::three::four::five\n};", cx);
7410        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
7411
7412        view.update(cx, |view, cx| {
7413            view.set_wrap_width(Some(140.), cx);
7414            assert_eq!(
7415                view.display_text(cx),
7416                "use one::{\n    two::three::\n    four::five\n};"
7417            );
7418
7419            view.select_display_ranges(&[DisplayPoint::new(1, 7)..DisplayPoint::new(1, 7)], cx);
7420
7421            view.move_to_next_word_end(&MoveToNextWordEnd, cx);
7422            assert_eq!(
7423                view.selected_display_ranges(cx),
7424                &[DisplayPoint::new(1, 9)..DisplayPoint::new(1, 9)]
7425            );
7426
7427            view.move_to_next_word_end(&MoveToNextWordEnd, cx);
7428            assert_eq!(
7429                view.selected_display_ranges(cx),
7430                &[DisplayPoint::new(1, 14)..DisplayPoint::new(1, 14)]
7431            );
7432
7433            view.move_to_next_word_end(&MoveToNextWordEnd, cx);
7434            assert_eq!(
7435                view.selected_display_ranges(cx),
7436                &[DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4)]
7437            );
7438
7439            view.move_to_next_word_end(&MoveToNextWordEnd, cx);
7440            assert_eq!(
7441                view.selected_display_ranges(cx),
7442                &[DisplayPoint::new(2, 8)..DisplayPoint::new(2, 8)]
7443            );
7444
7445            view.move_to_previous_word_start(&MoveToPreviousWordStart, cx);
7446            assert_eq!(
7447                view.selected_display_ranges(cx),
7448                &[DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4)]
7449            );
7450
7451            view.move_to_previous_word_start(&MoveToPreviousWordStart, cx);
7452            assert_eq!(
7453                view.selected_display_ranges(cx),
7454                &[DisplayPoint::new(1, 14)..DisplayPoint::new(1, 14)]
7455            );
7456        });
7457    }
7458
7459    #[gpui::test]
7460    fn test_delete_to_word_boundary(cx: &mut gpui::MutableAppContext) {
7461        populate_settings(cx);
7462        let buffer = MultiBuffer::build_simple("one two three four", cx);
7463        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer.clone(), cx));
7464
7465        view.update(cx, |view, cx| {
7466            view.select_display_ranges(
7467                &[
7468                    // an empty selection - the preceding word fragment is deleted
7469                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7470                    // characters selected - they are deleted
7471                    DisplayPoint::new(0, 9)..DisplayPoint::new(0, 12),
7472                ],
7473                cx,
7474            );
7475            view.delete_to_previous_word_start(&DeleteToPreviousWordStart, cx);
7476        });
7477
7478        assert_eq!(buffer.read(cx).read(cx).text(), "e two te four");
7479
7480        view.update(cx, |view, cx| {
7481            view.select_display_ranges(
7482                &[
7483                    // an empty selection - the following word fragment is deleted
7484                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
7485                    // characters selected - they are deleted
7486                    DisplayPoint::new(0, 9)..DisplayPoint::new(0, 10),
7487                ],
7488                cx,
7489            );
7490            view.delete_to_next_word_end(&DeleteToNextWordEnd, cx);
7491        });
7492
7493        assert_eq!(buffer.read(cx).read(cx).text(), "e t te our");
7494    }
7495
7496    #[gpui::test]
7497    fn test_newline(cx: &mut gpui::MutableAppContext) {
7498        populate_settings(cx);
7499        let buffer = MultiBuffer::build_simple("aaaa\n    bbbb\n", cx);
7500        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer.clone(), cx));
7501
7502        view.update(cx, |view, cx| {
7503            view.select_display_ranges(
7504                &[
7505                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7506                    DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
7507                    DisplayPoint::new(1, 6)..DisplayPoint::new(1, 6),
7508                ],
7509                cx,
7510            );
7511
7512            view.newline(&Newline, cx);
7513            assert_eq!(view.text(cx), "aa\naa\n  \n    bb\n    bb\n");
7514        });
7515    }
7516
7517    #[gpui::test]
7518    fn test_newline_with_old_selections(cx: &mut gpui::MutableAppContext) {
7519        populate_settings(cx);
7520        let buffer = MultiBuffer::build_simple(
7521            "
7522                a
7523                b(
7524                    X
7525                )
7526                c(
7527                    X
7528                )
7529            "
7530            .unindent()
7531            .as_str(),
7532            cx,
7533        );
7534
7535        let (_, editor) = cx.add_window(Default::default(), |cx| {
7536            let mut editor = build_editor(buffer.clone(), cx);
7537            editor.select_ranges(
7538                [
7539                    Point::new(2, 4)..Point::new(2, 5),
7540                    Point::new(5, 4)..Point::new(5, 5),
7541                ],
7542                None,
7543                cx,
7544            );
7545            editor
7546        });
7547
7548        // Edit the buffer directly, deleting ranges surrounding the editor's selections
7549        buffer.update(cx, |buffer, cx| {
7550            buffer.edit(
7551                [
7552                    Point::new(1, 2)..Point::new(3, 0),
7553                    Point::new(4, 2)..Point::new(6, 0),
7554                ],
7555                "",
7556                cx,
7557            );
7558            assert_eq!(
7559                buffer.read(cx).text(),
7560                "
7561                    a
7562                    b()
7563                    c()
7564                "
7565                .unindent()
7566            );
7567        });
7568
7569        editor.update(cx, |editor, cx| {
7570            assert_eq!(
7571                editor.selected_ranges(cx),
7572                &[
7573                    Point::new(1, 2)..Point::new(1, 2),
7574                    Point::new(2, 2)..Point::new(2, 2),
7575                ],
7576            );
7577
7578            editor.newline(&Newline, cx);
7579            assert_eq!(
7580                editor.text(cx),
7581                "
7582                    a
7583                    b(
7584                    )
7585                    c(
7586                    )
7587                "
7588                .unindent()
7589            );
7590
7591            // The selections are moved after the inserted newlines
7592            assert_eq!(
7593                editor.selected_ranges(cx),
7594                &[
7595                    Point::new(2, 0)..Point::new(2, 0),
7596                    Point::new(4, 0)..Point::new(4, 0),
7597                ],
7598            );
7599        });
7600    }
7601
7602    #[gpui::test]
7603    fn test_insert_with_old_selections(cx: &mut gpui::MutableAppContext) {
7604        populate_settings(cx);
7605        let buffer = MultiBuffer::build_simple("a( X ), b( Y ), c( Z )", cx);
7606        let (_, editor) = cx.add_window(Default::default(), |cx| {
7607            let mut editor = build_editor(buffer.clone(), cx);
7608            editor.select_ranges([3..4, 11..12, 19..20], None, cx);
7609            editor
7610        });
7611
7612        // Edit the buffer directly, deleting ranges surrounding the editor's selections
7613        buffer.update(cx, |buffer, cx| {
7614            buffer.edit([2..5, 10..13, 18..21], "", cx);
7615            assert_eq!(buffer.read(cx).text(), "a(), b(), c()".unindent());
7616        });
7617
7618        editor.update(cx, |editor, cx| {
7619            assert_eq!(editor.selected_ranges(cx), &[2..2, 7..7, 12..12],);
7620
7621            editor.insert("Z", cx);
7622            assert_eq!(editor.text(cx), "a(Z), b(Z), c(Z)");
7623
7624            // The selections are moved after the inserted characters
7625            assert_eq!(editor.selected_ranges(cx), &[3..3, 9..9, 15..15],);
7626        });
7627    }
7628
7629    #[gpui::test]
7630    fn test_indent_outdent(cx: &mut gpui::MutableAppContext) {
7631        populate_settings(cx);
7632        let buffer = MultiBuffer::build_simple("  one two\nthree\n four", cx);
7633        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer.clone(), cx));
7634
7635        view.update(cx, |view, cx| {
7636            // two selections on the same line
7637            view.select_display_ranges(
7638                &[
7639                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 5),
7640                    DisplayPoint::new(0, 6)..DisplayPoint::new(0, 9),
7641                ],
7642                cx,
7643            );
7644
7645            // indent from mid-tabstop to full tabstop
7646            view.tab(&Tab(Direction::Next), cx);
7647            assert_eq!(view.text(cx), "    one two\nthree\n four");
7648            assert_eq!(
7649                view.selected_display_ranges(cx),
7650                &[
7651                    DisplayPoint::new(0, 4)..DisplayPoint::new(0, 7),
7652                    DisplayPoint::new(0, 8)..DisplayPoint::new(0, 11),
7653                ]
7654            );
7655
7656            // outdent from 1 tabstop to 0 tabstops
7657            view.tab(&Tab(Direction::Prev), cx);
7658            assert_eq!(view.text(cx), "one two\nthree\n four");
7659            assert_eq!(
7660                view.selected_display_ranges(cx),
7661                &[
7662                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 3),
7663                    DisplayPoint::new(0, 4)..DisplayPoint::new(0, 7),
7664                ]
7665            );
7666
7667            // select across line ending
7668            view.select_display_ranges(&[DisplayPoint::new(1, 1)..DisplayPoint::new(2, 0)], cx);
7669
7670            // indent and outdent affect only the preceding line
7671            view.tab(&Tab(Direction::Next), cx);
7672            assert_eq!(view.text(cx), "one two\n    three\n four");
7673            assert_eq!(
7674                view.selected_display_ranges(cx),
7675                &[DisplayPoint::new(1, 5)..DisplayPoint::new(2, 0)]
7676            );
7677            view.tab(&Tab(Direction::Prev), cx);
7678            assert_eq!(view.text(cx), "one two\nthree\n four");
7679            assert_eq!(
7680                view.selected_display_ranges(cx),
7681                &[DisplayPoint::new(1, 1)..DisplayPoint::new(2, 0)]
7682            );
7683
7684            // Ensure that indenting/outdenting works when the cursor is at column 0.
7685            view.select_display_ranges(&[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)], cx);
7686            view.tab(&Tab(Direction::Next), cx);
7687            assert_eq!(view.text(cx), "one two\n    three\n four");
7688            assert_eq!(
7689                view.selected_display_ranges(cx),
7690                &[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4)]
7691            );
7692
7693            view.select_display_ranges(&[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)], cx);
7694            view.tab(&Tab(Direction::Prev), cx);
7695            assert_eq!(view.text(cx), "one two\nthree\n four");
7696            assert_eq!(
7697                view.selected_display_ranges(cx),
7698                &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
7699            );
7700        });
7701    }
7702
7703    #[gpui::test]
7704    fn test_backspace(cx: &mut gpui::MutableAppContext) {
7705        populate_settings(cx);
7706        let (_, view) = cx.add_window(Default::default(), |cx| {
7707            build_editor(MultiBuffer::build_simple("", cx), cx)
7708        });
7709
7710        view.update(cx, |view, cx| {
7711            view.set_text("one two three\nfour five six\nseven eight nine\nten\n", cx);
7712            view.select_display_ranges(
7713                &[
7714                    // an empty selection - the preceding character is deleted
7715                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7716                    // one character selected - it is deleted
7717                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
7718                    // a line suffix selected - it is deleted
7719                    DisplayPoint::new(2, 6)..DisplayPoint::new(3, 0),
7720                ],
7721                cx,
7722            );
7723            view.backspace(&Backspace, cx);
7724            assert_eq!(view.text(cx), "oe two three\nfou five six\nseven ten\n");
7725
7726            view.set_text("    one\n        two\n        three\n   four", cx);
7727            view.select_display_ranges(
7728                &[
7729                    // cursors at the the end of leading indent - last indent is deleted
7730                    DisplayPoint::new(0, 4)..DisplayPoint::new(0, 4),
7731                    DisplayPoint::new(1, 8)..DisplayPoint::new(1, 8),
7732                    // cursors inside leading indent - overlapping indent deletions are coalesced
7733                    DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4),
7734                    DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
7735                    DisplayPoint::new(2, 6)..DisplayPoint::new(2, 6),
7736                    // cursor at the beginning of a line - preceding newline is deleted
7737                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
7738                    // selection inside leading indent - only the selected character is deleted
7739                    DisplayPoint::new(3, 2)..DisplayPoint::new(3, 3),
7740                ],
7741                cx,
7742            );
7743            view.backspace(&Backspace, cx);
7744            assert_eq!(view.text(cx), "one\n    two\n  three  four");
7745        });
7746    }
7747
7748    #[gpui::test]
7749    fn test_delete(cx: &mut gpui::MutableAppContext) {
7750        populate_settings(cx);
7751        let buffer =
7752            MultiBuffer::build_simple("one two three\nfour five six\nseven eight nine\nten\n", cx);
7753        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer.clone(), cx));
7754
7755        view.update(cx, |view, cx| {
7756            view.select_display_ranges(
7757                &[
7758                    // an empty selection - the following character is deleted
7759                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7760                    // one character selected - it is deleted
7761                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
7762                    // a line suffix selected - it is deleted
7763                    DisplayPoint::new(2, 6)..DisplayPoint::new(3, 0),
7764                ],
7765                cx,
7766            );
7767            view.delete(&Delete, cx);
7768        });
7769
7770        assert_eq!(
7771            buffer.read(cx).read(cx).text(),
7772            "on two three\nfou five six\nseven ten\n"
7773        );
7774    }
7775
7776    #[gpui::test]
7777    fn test_delete_line(cx: &mut gpui::MutableAppContext) {
7778        populate_settings(cx);
7779        let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
7780        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
7781        view.update(cx, |view, cx| {
7782            view.select_display_ranges(
7783                &[
7784                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
7785                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 1),
7786                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
7787                ],
7788                cx,
7789            );
7790            view.delete_line(&DeleteLine, cx);
7791            assert_eq!(view.display_text(cx), "ghi");
7792            assert_eq!(
7793                view.selected_display_ranges(cx),
7794                vec![
7795                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
7796                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)
7797                ]
7798            );
7799        });
7800
7801        populate_settings(cx);
7802        let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
7803        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
7804        view.update(cx, |view, cx| {
7805            view.select_display_ranges(&[DisplayPoint::new(2, 0)..DisplayPoint::new(0, 1)], cx);
7806            view.delete_line(&DeleteLine, cx);
7807            assert_eq!(view.display_text(cx), "ghi\n");
7808            assert_eq!(
7809                view.selected_display_ranges(cx),
7810                vec![DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)]
7811            );
7812        });
7813    }
7814
7815    #[gpui::test]
7816    fn test_duplicate_line(cx: &mut gpui::MutableAppContext) {
7817        populate_settings(cx);
7818        let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
7819        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
7820        view.update(cx, |view, cx| {
7821            view.select_display_ranges(
7822                &[
7823                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
7824                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7825                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
7826                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
7827                ],
7828                cx,
7829            );
7830            view.duplicate_line(&DuplicateLine, cx);
7831            assert_eq!(view.display_text(cx), "abc\nabc\ndef\ndef\nghi\n\n");
7832            assert_eq!(
7833                view.selected_display_ranges(cx),
7834                vec![
7835                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 1),
7836                    DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
7837                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
7838                    DisplayPoint::new(6, 0)..DisplayPoint::new(6, 0),
7839                ]
7840            );
7841        });
7842
7843        let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
7844        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
7845        view.update(cx, |view, cx| {
7846            view.select_display_ranges(
7847                &[
7848                    DisplayPoint::new(0, 1)..DisplayPoint::new(1, 1),
7849                    DisplayPoint::new(1, 2)..DisplayPoint::new(2, 1),
7850                ],
7851                cx,
7852            );
7853            view.duplicate_line(&DuplicateLine, cx);
7854            assert_eq!(view.display_text(cx), "abc\ndef\nghi\nabc\ndef\nghi\n");
7855            assert_eq!(
7856                view.selected_display_ranges(cx),
7857                vec![
7858                    DisplayPoint::new(3, 1)..DisplayPoint::new(4, 1),
7859                    DisplayPoint::new(4, 2)..DisplayPoint::new(5, 1),
7860                ]
7861            );
7862        });
7863    }
7864
7865    #[gpui::test]
7866    fn test_move_line_up_down(cx: &mut gpui::MutableAppContext) {
7867        populate_settings(cx);
7868        let buffer = MultiBuffer::build_simple(&sample_text(10, 5, 'a'), cx);
7869        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
7870        view.update(cx, |view, cx| {
7871            view.fold_ranges(
7872                vec![
7873                    Point::new(0, 2)..Point::new(1, 2),
7874                    Point::new(2, 3)..Point::new(4, 1),
7875                    Point::new(7, 0)..Point::new(8, 4),
7876                ],
7877                cx,
7878            );
7879            view.select_display_ranges(
7880                &[
7881                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
7882                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
7883                    DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
7884                    DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2),
7885                ],
7886                cx,
7887            );
7888            assert_eq!(
7889                view.display_text(cx),
7890                "aa…bbb\nccc…eeee\nfffff\nggggg\n…i\njjjjj"
7891            );
7892
7893            view.move_line_up(&MoveLineUp, cx);
7894            assert_eq!(
7895                view.display_text(cx),
7896                "aa…bbb\nccc…eeee\nggggg\n…i\njjjjj\nfffff"
7897            );
7898            assert_eq!(
7899                view.selected_display_ranges(cx),
7900                vec![
7901                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
7902                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
7903                    DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3),
7904                    DisplayPoint::new(4, 0)..DisplayPoint::new(4, 2)
7905                ]
7906            );
7907        });
7908
7909        view.update(cx, |view, cx| {
7910            view.move_line_down(&MoveLineDown, cx);
7911            assert_eq!(
7912                view.display_text(cx),
7913                "ccc…eeee\naa…bbb\nfffff\nggggg\n…i\njjjjj"
7914            );
7915            assert_eq!(
7916                view.selected_display_ranges(cx),
7917                vec![
7918                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
7919                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
7920                    DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
7921                    DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2)
7922                ]
7923            );
7924        });
7925
7926        view.update(cx, |view, cx| {
7927            view.move_line_down(&MoveLineDown, cx);
7928            assert_eq!(
7929                view.display_text(cx),
7930                "ccc…eeee\nfffff\naa…bbb\nggggg\n…i\njjjjj"
7931            );
7932            assert_eq!(
7933                view.selected_display_ranges(cx),
7934                vec![
7935                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
7936                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
7937                    DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
7938                    DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2)
7939                ]
7940            );
7941        });
7942
7943        view.update(cx, |view, cx| {
7944            view.move_line_up(&MoveLineUp, cx);
7945            assert_eq!(
7946                view.display_text(cx),
7947                "ccc…eeee\naa…bbb\nggggg\n…i\njjjjj\nfffff"
7948            );
7949            assert_eq!(
7950                view.selected_display_ranges(cx),
7951                vec![
7952                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
7953                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
7954                    DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3),
7955                    DisplayPoint::new(4, 0)..DisplayPoint::new(4, 2)
7956                ]
7957            );
7958        });
7959    }
7960
7961    #[gpui::test]
7962    fn test_move_line_up_down_with_blocks(cx: &mut gpui::MutableAppContext) {
7963        populate_settings(cx);
7964        let buffer = MultiBuffer::build_simple(&sample_text(10, 5, 'a'), cx);
7965        let snapshot = buffer.read(cx).snapshot(cx);
7966        let (_, editor) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
7967        editor.update(cx, |editor, cx| {
7968            editor.insert_blocks(
7969                [BlockProperties {
7970                    position: snapshot.anchor_after(Point::new(2, 0)),
7971                    disposition: BlockDisposition::Below,
7972                    height: 1,
7973                    render: Arc::new(|_| Empty::new().boxed()),
7974                }],
7975                cx,
7976            );
7977            editor.select_ranges([Point::new(2, 0)..Point::new(2, 0)], None, cx);
7978            editor.move_line_down(&MoveLineDown, cx);
7979        });
7980    }
7981
7982    #[gpui::test]
7983    fn test_clipboard(cx: &mut gpui::MutableAppContext) {
7984        populate_settings(cx);
7985        let buffer = MultiBuffer::build_simple("one✅ two three four five six ", cx);
7986        let view = cx
7987            .add_window(Default::default(), |cx| build_editor(buffer.clone(), cx))
7988            .1;
7989
7990        // Cut with three selections. Clipboard text is divided into three slices.
7991        view.update(cx, |view, cx| {
7992            view.select_ranges(vec![0..7, 11..17, 22..27], None, cx);
7993            view.cut(&Cut, cx);
7994            assert_eq!(view.display_text(cx), "two four six ");
7995        });
7996
7997        // Paste with three cursors. Each cursor pastes one slice of the clipboard text.
7998        view.update(cx, |view, cx| {
7999            view.select_ranges(vec![4..4, 9..9, 13..13], None, cx);
8000            view.paste(&Paste, cx);
8001            assert_eq!(view.display_text(cx), "two one✅ four three six five ");
8002            assert_eq!(
8003                view.selected_display_ranges(cx),
8004                &[
8005                    DisplayPoint::new(0, 11)..DisplayPoint::new(0, 11),
8006                    DisplayPoint::new(0, 22)..DisplayPoint::new(0, 22),
8007                    DisplayPoint::new(0, 31)..DisplayPoint::new(0, 31)
8008                ]
8009            );
8010        });
8011
8012        // Paste again but with only two cursors. Since the number of cursors doesn't
8013        // match the number of slices in the clipboard, the entire clipboard text
8014        // is pasted at each cursor.
8015        view.update(cx, |view, cx| {
8016            view.select_ranges(vec![0..0, 31..31], None, cx);
8017            view.handle_input(&Input("( ".into()), cx);
8018            view.paste(&Paste, cx);
8019            view.handle_input(&Input(") ".into()), cx);
8020            assert_eq!(
8021                view.display_text(cx),
8022                "( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
8023            );
8024        });
8025
8026        view.update(cx, |view, cx| {
8027            view.select_ranges(vec![0..0], None, cx);
8028            view.handle_input(&Input("123\n4567\n89\n".into()), cx);
8029            assert_eq!(
8030                view.display_text(cx),
8031                "123\n4567\n89\n( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
8032            );
8033        });
8034
8035        // Cut with three selections, one of which is full-line.
8036        view.update(cx, |view, cx| {
8037            view.select_display_ranges(
8038                &[
8039                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 2),
8040                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
8041                    DisplayPoint::new(2, 0)..DisplayPoint::new(2, 1),
8042                ],
8043                cx,
8044            );
8045            view.cut(&Cut, cx);
8046            assert_eq!(
8047                view.display_text(cx),
8048                "13\n9\n( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
8049            );
8050        });
8051
8052        // Paste with three selections, noticing how the copied selection that was full-line
8053        // gets inserted before the second cursor.
8054        view.update(cx, |view, cx| {
8055            view.select_display_ranges(
8056                &[
8057                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
8058                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
8059                    DisplayPoint::new(2, 2)..DisplayPoint::new(2, 3),
8060                ],
8061                cx,
8062            );
8063            view.paste(&Paste, cx);
8064            assert_eq!(
8065                view.display_text(cx),
8066                "123\n4567\n9\n( 8ne✅ three five ) two one✅ four three six five ( one✅ three five ) "
8067            );
8068            assert_eq!(
8069                view.selected_display_ranges(cx),
8070                &[
8071                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
8072                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
8073                    DisplayPoint::new(3, 3)..DisplayPoint::new(3, 3),
8074                ]
8075            );
8076        });
8077
8078        // Copy with a single cursor only, which writes the whole line into the clipboard.
8079        view.update(cx, |view, cx| {
8080            view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)], cx);
8081            view.copy(&Copy, cx);
8082        });
8083
8084        // Paste with three selections, noticing how the copied full-line selection is inserted
8085        // before the empty selections but replaces the selection that is non-empty.
8086        view.update(cx, |view, cx| {
8087            view.select_display_ranges(
8088                &[
8089                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
8090                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 2),
8091                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
8092                ],
8093                cx,
8094            );
8095            view.paste(&Paste, cx);
8096            assert_eq!(
8097                view.display_text(cx),
8098                "123\n123\n123\n67\n123\n9\n( 8ne✅ three five ) two one✅ four three six five ( one✅ three five ) "
8099            );
8100            assert_eq!(
8101                view.selected_display_ranges(cx),
8102                &[
8103                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
8104                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
8105                    DisplayPoint::new(5, 1)..DisplayPoint::new(5, 1),
8106                ]
8107            );
8108        });
8109    }
8110
8111    #[gpui::test]
8112    fn test_select_all(cx: &mut gpui::MutableAppContext) {
8113        populate_settings(cx);
8114        let buffer = MultiBuffer::build_simple("abc\nde\nfgh", cx);
8115        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
8116        view.update(cx, |view, cx| {
8117            view.select_all(&SelectAll, cx);
8118            assert_eq!(
8119                view.selected_display_ranges(cx),
8120                &[DisplayPoint::new(0, 0)..DisplayPoint::new(2, 3)]
8121            );
8122        });
8123    }
8124
8125    #[gpui::test]
8126    fn test_select_line(cx: &mut gpui::MutableAppContext) {
8127        populate_settings(cx);
8128        let buffer = MultiBuffer::build_simple(&sample_text(6, 5, 'a'), cx);
8129        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
8130        view.update(cx, |view, cx| {
8131            view.select_display_ranges(
8132                &[
8133                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
8134                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
8135                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
8136                    DisplayPoint::new(4, 2)..DisplayPoint::new(4, 2),
8137                ],
8138                cx,
8139            );
8140            view.select_line(&SelectLine, cx);
8141            assert_eq!(
8142                view.selected_display_ranges(cx),
8143                vec![
8144                    DisplayPoint::new(0, 0)..DisplayPoint::new(2, 0),
8145                    DisplayPoint::new(4, 0)..DisplayPoint::new(5, 0),
8146                ]
8147            );
8148        });
8149
8150        view.update(cx, |view, cx| {
8151            view.select_line(&SelectLine, cx);
8152            assert_eq!(
8153                view.selected_display_ranges(cx),
8154                vec![
8155                    DisplayPoint::new(0, 0)..DisplayPoint::new(3, 0),
8156                    DisplayPoint::new(4, 0)..DisplayPoint::new(5, 5),
8157                ]
8158            );
8159        });
8160
8161        view.update(cx, |view, cx| {
8162            view.select_line(&SelectLine, cx);
8163            assert_eq!(
8164                view.selected_display_ranges(cx),
8165                vec![DisplayPoint::new(0, 0)..DisplayPoint::new(5, 5)]
8166            );
8167        });
8168    }
8169
8170    #[gpui::test]
8171    fn test_split_selection_into_lines(cx: &mut gpui::MutableAppContext) {
8172        populate_settings(cx);
8173        let buffer = MultiBuffer::build_simple(&sample_text(9, 5, 'a'), cx);
8174        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
8175        view.update(cx, |view, cx| {
8176            view.fold_ranges(
8177                vec![
8178                    Point::new(0, 2)..Point::new(1, 2),
8179                    Point::new(2, 3)..Point::new(4, 1),
8180                    Point::new(7, 0)..Point::new(8, 4),
8181                ],
8182                cx,
8183            );
8184            view.select_display_ranges(
8185                &[
8186                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
8187                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
8188                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
8189                    DisplayPoint::new(4, 4)..DisplayPoint::new(4, 4),
8190                ],
8191                cx,
8192            );
8193            assert_eq!(view.display_text(cx), "aa…bbb\nccc…eeee\nfffff\nggggg\n…i");
8194        });
8195
8196        view.update(cx, |view, cx| {
8197            view.split_selection_into_lines(&SplitSelectionIntoLines, cx);
8198            assert_eq!(
8199                view.display_text(cx),
8200                "aaaaa\nbbbbb\nccc…eeee\nfffff\nggggg\n…i"
8201            );
8202            assert_eq!(
8203                view.selected_display_ranges(cx),
8204                [
8205                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
8206                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
8207                    DisplayPoint::new(2, 0)..DisplayPoint::new(2, 0),
8208                    DisplayPoint::new(5, 4)..DisplayPoint::new(5, 4)
8209                ]
8210            );
8211        });
8212
8213        view.update(cx, |view, cx| {
8214            view.select_display_ranges(&[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 1)], cx);
8215            view.split_selection_into_lines(&SplitSelectionIntoLines, cx);
8216            assert_eq!(
8217                view.display_text(cx),
8218                "aaaaa\nbbbbb\nccccc\nddddd\neeeee\nfffff\nggggg\nhhhhh\niiiii"
8219            );
8220            assert_eq!(
8221                view.selected_display_ranges(cx),
8222                [
8223                    DisplayPoint::new(0, 5)..DisplayPoint::new(0, 5),
8224                    DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
8225                    DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
8226                    DisplayPoint::new(3, 5)..DisplayPoint::new(3, 5),
8227                    DisplayPoint::new(4, 5)..DisplayPoint::new(4, 5),
8228                    DisplayPoint::new(5, 5)..DisplayPoint::new(5, 5),
8229                    DisplayPoint::new(6, 5)..DisplayPoint::new(6, 5),
8230                    DisplayPoint::new(7, 0)..DisplayPoint::new(7, 0)
8231                ]
8232            );
8233        });
8234    }
8235
8236    #[gpui::test]
8237    fn test_add_selection_above_below(cx: &mut gpui::MutableAppContext) {
8238        populate_settings(cx);
8239        let buffer = MultiBuffer::build_simple("abc\ndefghi\n\njk\nlmno\n", cx);
8240        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
8241
8242        view.update(cx, |view, cx| {
8243            view.select_display_ranges(&[DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)], cx);
8244        });
8245        view.update(cx, |view, cx| {
8246            view.add_selection_above(&AddSelectionAbove, cx);
8247            assert_eq!(
8248                view.selected_display_ranges(cx),
8249                vec![
8250                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
8251                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)
8252                ]
8253            );
8254        });
8255
8256        view.update(cx, |view, cx| {
8257            view.add_selection_above(&AddSelectionAbove, cx);
8258            assert_eq!(
8259                view.selected_display_ranges(cx),
8260                vec![
8261                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
8262                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)
8263                ]
8264            );
8265        });
8266
8267        view.update(cx, |view, cx| {
8268            view.add_selection_below(&AddSelectionBelow, cx);
8269            assert_eq!(
8270                view.selected_display_ranges(cx),
8271                vec![DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)]
8272            );
8273
8274            view.undo_selection(&UndoSelection, cx);
8275            assert_eq!(
8276                view.selected_display_ranges(cx),
8277                vec![
8278                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
8279                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)
8280                ]
8281            );
8282
8283            view.redo_selection(&RedoSelection, cx);
8284            assert_eq!(
8285                view.selected_display_ranges(cx),
8286                vec![DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)]
8287            );
8288        });
8289
8290        view.update(cx, |view, cx| {
8291            view.add_selection_below(&AddSelectionBelow, cx);
8292            assert_eq!(
8293                view.selected_display_ranges(cx),
8294                vec![
8295                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
8296                    DisplayPoint::new(4, 3)..DisplayPoint::new(4, 3)
8297                ]
8298            );
8299        });
8300
8301        view.update(cx, |view, cx| {
8302            view.add_selection_below(&AddSelectionBelow, cx);
8303            assert_eq!(
8304                view.selected_display_ranges(cx),
8305                vec![
8306                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
8307                    DisplayPoint::new(4, 3)..DisplayPoint::new(4, 3)
8308                ]
8309            );
8310        });
8311
8312        view.update(cx, |view, cx| {
8313            view.select_display_ranges(&[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)], cx);
8314        });
8315        view.update(cx, |view, cx| {
8316            view.add_selection_below(&AddSelectionBelow, cx);
8317            assert_eq!(
8318                view.selected_display_ranges(cx),
8319                vec![
8320                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
8321                    DisplayPoint::new(4, 4)..DisplayPoint::new(4, 3)
8322                ]
8323            );
8324        });
8325
8326        view.update(cx, |view, cx| {
8327            view.add_selection_below(&AddSelectionBelow, cx);
8328            assert_eq!(
8329                view.selected_display_ranges(cx),
8330                vec![
8331                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
8332                    DisplayPoint::new(4, 4)..DisplayPoint::new(4, 3)
8333                ]
8334            );
8335        });
8336
8337        view.update(cx, |view, cx| {
8338            view.add_selection_above(&AddSelectionAbove, cx);
8339            assert_eq!(
8340                view.selected_display_ranges(cx),
8341                vec![DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)]
8342            );
8343        });
8344
8345        view.update(cx, |view, cx| {
8346            view.add_selection_above(&AddSelectionAbove, cx);
8347            assert_eq!(
8348                view.selected_display_ranges(cx),
8349                vec![DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)]
8350            );
8351        });
8352
8353        view.update(cx, |view, cx| {
8354            view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(1, 4)], cx);
8355            view.add_selection_below(&AddSelectionBelow, cx);
8356            assert_eq!(
8357                view.selected_display_ranges(cx),
8358                vec![
8359                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
8360                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
8361                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
8362                ]
8363            );
8364        });
8365
8366        view.update(cx, |view, cx| {
8367            view.add_selection_below(&AddSelectionBelow, cx);
8368            assert_eq!(
8369                view.selected_display_ranges(cx),
8370                vec![
8371                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
8372                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
8373                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
8374                    DisplayPoint::new(4, 1)..DisplayPoint::new(4, 4),
8375                ]
8376            );
8377        });
8378
8379        view.update(cx, |view, cx| {
8380            view.add_selection_above(&AddSelectionAbove, cx);
8381            assert_eq!(
8382                view.selected_display_ranges(cx),
8383                vec![
8384                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
8385                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
8386                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
8387                ]
8388            );
8389        });
8390
8391        view.update(cx, |view, cx| {
8392            view.select_display_ranges(&[DisplayPoint::new(4, 3)..DisplayPoint::new(1, 1)], cx);
8393        });
8394        view.update(cx, |view, cx| {
8395            view.add_selection_above(&AddSelectionAbove, cx);
8396            assert_eq!(
8397                view.selected_display_ranges(cx),
8398                vec![
8399                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 1),
8400                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 1),
8401                    DisplayPoint::new(3, 2)..DisplayPoint::new(3, 1),
8402                    DisplayPoint::new(4, 3)..DisplayPoint::new(4, 1),
8403                ]
8404            );
8405        });
8406
8407        view.update(cx, |view, cx| {
8408            view.add_selection_below(&AddSelectionBelow, cx);
8409            assert_eq!(
8410                view.selected_display_ranges(cx),
8411                vec![
8412                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 1),
8413                    DisplayPoint::new(3, 2)..DisplayPoint::new(3, 1),
8414                    DisplayPoint::new(4, 3)..DisplayPoint::new(4, 1),
8415                ]
8416            );
8417        });
8418    }
8419
8420    #[gpui::test]
8421    fn test_select_next(cx: &mut gpui::MutableAppContext) {
8422        populate_settings(cx);
8423
8424        let (text, ranges) = marked_text_ranges("[abc]\n[abc] [abc]\ndefabc\n[abc]");
8425        let buffer = MultiBuffer::build_simple(&text, cx);
8426        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
8427
8428        view.update(cx, |view, cx| {
8429            view.select_ranges([ranges[1].start + 1..ranges[1].start + 1], None, cx);
8430            view.select_next(&SelectNext(false), cx);
8431            assert_eq!(view.selected_ranges(cx), &ranges[1..2]);
8432
8433            view.select_next(&SelectNext(false), cx);
8434            assert_eq!(view.selected_ranges(cx), &ranges[1..3]);
8435
8436            view.undo_selection(&UndoSelection, cx);
8437            assert_eq!(view.selected_ranges(cx), &ranges[1..2]);
8438
8439            view.redo_selection(&RedoSelection, cx);
8440            assert_eq!(view.selected_ranges(cx), &ranges[1..3]);
8441
8442            view.select_next(&SelectNext(false), cx);
8443            assert_eq!(view.selected_ranges(cx), &ranges[1..4]);
8444
8445            view.select_next(&SelectNext(false), cx);
8446            assert_eq!(view.selected_ranges(cx), &ranges[0..4]);
8447        });
8448    }
8449
8450    #[gpui::test]
8451    async fn test_select_larger_smaller_syntax_node(cx: &mut gpui::TestAppContext) {
8452        cx.update(populate_settings);
8453        let language = Arc::new(Language::new(
8454            LanguageConfig::default(),
8455            Some(tree_sitter_rust::language()),
8456        ));
8457
8458        let text = r#"
8459            use mod1::mod2::{mod3, mod4};
8460
8461            fn fn_1(param1: bool, param2: &str) {
8462                let var1 = "text";
8463            }
8464        "#
8465        .unindent();
8466
8467        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
8468        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
8469        let (_, view) = cx.add_window(|cx| build_editor(buffer, cx));
8470        view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
8471            .await;
8472
8473        view.update(cx, |view, cx| {
8474            view.select_display_ranges(
8475                &[
8476                    DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
8477                    DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
8478                    DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
8479                ],
8480                cx,
8481            );
8482            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
8483        });
8484        assert_eq!(
8485            view.update(cx, |view, cx| view.selected_display_ranges(cx)),
8486            &[
8487                DisplayPoint::new(0, 23)..DisplayPoint::new(0, 27),
8488                DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
8489                DisplayPoint::new(3, 15)..DisplayPoint::new(3, 21),
8490            ]
8491        );
8492
8493        view.update(cx, |view, cx| {
8494            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
8495        });
8496        assert_eq!(
8497            view.update(cx, |view, cx| view.selected_display_ranges(cx)),
8498            &[
8499                DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
8500                DisplayPoint::new(4, 1)..DisplayPoint::new(2, 0),
8501            ]
8502        );
8503
8504        view.update(cx, |view, cx| {
8505            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
8506        });
8507        assert_eq!(
8508            view.update(cx, |view, cx| view.selected_display_ranges(cx)),
8509            &[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 0)]
8510        );
8511
8512        // Trying to expand the selected syntax node one more time has no effect.
8513        view.update(cx, |view, cx| {
8514            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
8515        });
8516        assert_eq!(
8517            view.update(cx, |view, cx| view.selected_display_ranges(cx)),
8518            &[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 0)]
8519        );
8520
8521        view.update(cx, |view, cx| {
8522            view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
8523        });
8524        assert_eq!(
8525            view.update(cx, |view, cx| view.selected_display_ranges(cx)),
8526            &[
8527                DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
8528                DisplayPoint::new(4, 1)..DisplayPoint::new(2, 0),
8529            ]
8530        );
8531
8532        view.update(cx, |view, cx| {
8533            view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
8534        });
8535        assert_eq!(
8536            view.update(cx, |view, cx| view.selected_display_ranges(cx)),
8537            &[
8538                DisplayPoint::new(0, 23)..DisplayPoint::new(0, 27),
8539                DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
8540                DisplayPoint::new(3, 15)..DisplayPoint::new(3, 21),
8541            ]
8542        );
8543
8544        view.update(cx, |view, cx| {
8545            view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
8546        });
8547        assert_eq!(
8548            view.update(cx, |view, cx| view.selected_display_ranges(cx)),
8549            &[
8550                DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
8551                DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
8552                DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
8553            ]
8554        );
8555
8556        // Trying to shrink the selected syntax node one more time has no effect.
8557        view.update(cx, |view, cx| {
8558            view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
8559        });
8560        assert_eq!(
8561            view.update(cx, |view, cx| view.selected_display_ranges(cx)),
8562            &[
8563                DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
8564                DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
8565                DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
8566            ]
8567        );
8568
8569        // Ensure that we keep expanding the selection if the larger selection starts or ends within
8570        // a fold.
8571        view.update(cx, |view, cx| {
8572            view.fold_ranges(
8573                vec![
8574                    Point::new(0, 21)..Point::new(0, 24),
8575                    Point::new(3, 20)..Point::new(3, 22),
8576                ],
8577                cx,
8578            );
8579            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
8580        });
8581        assert_eq!(
8582            view.update(cx, |view, cx| view.selected_display_ranges(cx)),
8583            &[
8584                DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
8585                DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
8586                DisplayPoint::new(3, 4)..DisplayPoint::new(3, 23),
8587            ]
8588        );
8589    }
8590
8591    #[gpui::test]
8592    async fn test_autoindent_selections(cx: &mut gpui::TestAppContext) {
8593        cx.update(populate_settings);
8594        let language = Arc::new(
8595            Language::new(
8596                LanguageConfig {
8597                    brackets: vec![
8598                        BracketPair {
8599                            start: "{".to_string(),
8600                            end: "}".to_string(),
8601                            close: false,
8602                            newline: true,
8603                        },
8604                        BracketPair {
8605                            start: "(".to_string(),
8606                            end: ")".to_string(),
8607                            close: false,
8608                            newline: true,
8609                        },
8610                    ],
8611                    ..Default::default()
8612                },
8613                Some(tree_sitter_rust::language()),
8614            )
8615            .with_indents_query(
8616                r#"
8617                (_ "(" ")" @end) @indent
8618                (_ "{" "}" @end) @indent
8619                "#,
8620            )
8621            .unwrap(),
8622        );
8623
8624        let text = "fn a() {}";
8625
8626        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
8627        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
8628        let (_, editor) = cx.add_window(|cx| build_editor(buffer, cx));
8629        editor
8630            .condition(&cx, |editor, cx| !editor.buffer.read(cx).is_parsing(cx))
8631            .await;
8632
8633        editor.update(cx, |editor, cx| {
8634            editor.select_ranges([5..5, 8..8, 9..9], None, cx);
8635            editor.newline(&Newline, cx);
8636            assert_eq!(editor.text(cx), "fn a(\n    \n) {\n    \n}\n");
8637            assert_eq!(
8638                editor.selected_ranges(cx),
8639                &[
8640                    Point::new(1, 4)..Point::new(1, 4),
8641                    Point::new(3, 4)..Point::new(3, 4),
8642                    Point::new(5, 0)..Point::new(5, 0)
8643                ]
8644            );
8645        });
8646    }
8647
8648    #[gpui::test]
8649    async fn test_autoclose_pairs(cx: &mut gpui::TestAppContext) {
8650        cx.update(populate_settings);
8651        let language = Arc::new(Language::new(
8652            LanguageConfig {
8653                brackets: vec![
8654                    BracketPair {
8655                        start: "{".to_string(),
8656                        end: "}".to_string(),
8657                        close: true,
8658                        newline: true,
8659                    },
8660                    BracketPair {
8661                        start: "/*".to_string(),
8662                        end: " */".to_string(),
8663                        close: true,
8664                        newline: true,
8665                    },
8666                ],
8667                autoclose_before: "})]".to_string(),
8668                ..Default::default()
8669            },
8670            Some(tree_sitter_rust::language()),
8671        ));
8672
8673        let text = r#"
8674            a
8675
8676            /
8677
8678        "#
8679        .unindent();
8680
8681        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
8682        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
8683        let (_, view) = cx.add_window(|cx| build_editor(buffer, cx));
8684        view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
8685            .await;
8686
8687        view.update(cx, |view, cx| {
8688            view.select_display_ranges(
8689                &[
8690                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
8691                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
8692                ],
8693                cx,
8694            );
8695
8696            view.handle_input(&Input("{".to_string()), cx);
8697            view.handle_input(&Input("{".to_string()), cx);
8698            view.handle_input(&Input("{".to_string()), cx);
8699            assert_eq!(
8700                view.text(cx),
8701                "
8702                {{{}}}
8703                {{{}}}
8704                /
8705
8706                "
8707                .unindent()
8708            );
8709
8710            view.move_right(&MoveRight, cx);
8711            view.handle_input(&Input("}".to_string()), cx);
8712            view.handle_input(&Input("}".to_string()), cx);
8713            view.handle_input(&Input("}".to_string()), cx);
8714            assert_eq!(
8715                view.text(cx),
8716                "
8717                {{{}}}}
8718                {{{}}}}
8719                /
8720
8721                "
8722                .unindent()
8723            );
8724
8725            view.undo(&Undo, cx);
8726            view.handle_input(&Input("/".to_string()), cx);
8727            view.handle_input(&Input("*".to_string()), cx);
8728            assert_eq!(
8729                view.text(cx),
8730                "
8731                /* */
8732                /* */
8733                /
8734
8735                "
8736                .unindent()
8737            );
8738
8739            view.undo(&Undo, cx);
8740            view.select_display_ranges(
8741                &[
8742                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
8743                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
8744                ],
8745                cx,
8746            );
8747            view.handle_input(&Input("*".to_string()), cx);
8748            assert_eq!(
8749                view.text(cx),
8750                "
8751                a
8752
8753                /*
8754                *
8755                "
8756                .unindent()
8757            );
8758
8759            // Don't autoclose if the next character isn't whitespace and isn't
8760            // listed in the language's "autoclose_before" section.
8761            view.finalize_last_transaction(cx);
8762            view.select_display_ranges(&[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)], cx);
8763            view.handle_input(&Input("{".to_string()), cx);
8764            assert_eq!(
8765                view.text(cx),
8766                "
8767                {a
8768
8769                /*
8770                *
8771                "
8772                .unindent()
8773            );
8774
8775            view.undo(&Undo, cx);
8776            view.select_display_ranges(&[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1)], cx);
8777            view.handle_input(&Input("{".to_string()), cx);
8778            assert_eq!(
8779                view.text(cx),
8780                "
8781                {a}
8782
8783                /*
8784                *
8785                "
8786                .unindent()
8787            );
8788            assert_eq!(
8789                view.selected_display_ranges(cx),
8790                [DisplayPoint::new(0, 1)..DisplayPoint::new(0, 2)]
8791            );
8792        });
8793    }
8794
8795    #[gpui::test]
8796    async fn test_snippets(cx: &mut gpui::TestAppContext) {
8797        cx.update(populate_settings);
8798
8799        let text = "
8800            a. b
8801            a. b
8802            a. b
8803        "
8804        .unindent();
8805        let buffer = cx.update(|cx| MultiBuffer::build_simple(&text, cx));
8806        let (_, editor) = cx.add_window(|cx| build_editor(buffer, cx));
8807
8808        editor.update(cx, |editor, cx| {
8809            let buffer = &editor.snapshot(cx).buffer_snapshot;
8810            let snippet = Snippet::parse("f(${1:one}, ${2:two}, ${1:three})$0").unwrap();
8811            let insertion_ranges = [
8812                Point::new(0, 2).to_offset(buffer)..Point::new(0, 2).to_offset(buffer),
8813                Point::new(1, 2).to_offset(buffer)..Point::new(1, 2).to_offset(buffer),
8814                Point::new(2, 2).to_offset(buffer)..Point::new(2, 2).to_offset(buffer),
8815            ];
8816
8817            editor
8818                .insert_snippet(&insertion_ranges, snippet, cx)
8819                .unwrap();
8820            assert_eq!(
8821                editor.text(cx),
8822                "
8823                    a.f(one, two, three) b
8824                    a.f(one, two, three) b
8825                    a.f(one, two, three) b
8826                "
8827                .unindent()
8828            );
8829            assert_eq!(
8830                editor.selected_ranges::<Point>(cx),
8831                &[
8832                    Point::new(0, 4)..Point::new(0, 7),
8833                    Point::new(0, 14)..Point::new(0, 19),
8834                    Point::new(1, 4)..Point::new(1, 7),
8835                    Point::new(1, 14)..Point::new(1, 19),
8836                    Point::new(2, 4)..Point::new(2, 7),
8837                    Point::new(2, 14)..Point::new(2, 19),
8838                ]
8839            );
8840
8841            // Can't move earlier than the first tab stop
8842            editor.move_to_prev_snippet_tabstop(cx);
8843            assert_eq!(
8844                editor.selected_ranges::<Point>(cx),
8845                &[
8846                    Point::new(0, 4)..Point::new(0, 7),
8847                    Point::new(0, 14)..Point::new(0, 19),
8848                    Point::new(1, 4)..Point::new(1, 7),
8849                    Point::new(1, 14)..Point::new(1, 19),
8850                    Point::new(2, 4)..Point::new(2, 7),
8851                    Point::new(2, 14)..Point::new(2, 19),
8852                ]
8853            );
8854
8855            assert!(editor.move_to_next_snippet_tabstop(cx));
8856            assert_eq!(
8857                editor.selected_ranges::<Point>(cx),
8858                &[
8859                    Point::new(0, 9)..Point::new(0, 12),
8860                    Point::new(1, 9)..Point::new(1, 12),
8861                    Point::new(2, 9)..Point::new(2, 12)
8862                ]
8863            );
8864
8865            editor.move_to_prev_snippet_tabstop(cx);
8866            assert_eq!(
8867                editor.selected_ranges::<Point>(cx),
8868                &[
8869                    Point::new(0, 4)..Point::new(0, 7),
8870                    Point::new(0, 14)..Point::new(0, 19),
8871                    Point::new(1, 4)..Point::new(1, 7),
8872                    Point::new(1, 14)..Point::new(1, 19),
8873                    Point::new(2, 4)..Point::new(2, 7),
8874                    Point::new(2, 14)..Point::new(2, 19),
8875                ]
8876            );
8877
8878            assert!(editor.move_to_next_snippet_tabstop(cx));
8879            assert!(editor.move_to_next_snippet_tabstop(cx));
8880            assert_eq!(
8881                editor.selected_ranges::<Point>(cx),
8882                &[
8883                    Point::new(0, 20)..Point::new(0, 20),
8884                    Point::new(1, 20)..Point::new(1, 20),
8885                    Point::new(2, 20)..Point::new(2, 20)
8886                ]
8887            );
8888
8889            // As soon as the last tab stop is reached, snippet state is gone
8890            editor.move_to_prev_snippet_tabstop(cx);
8891            assert_eq!(
8892                editor.selected_ranges::<Point>(cx),
8893                &[
8894                    Point::new(0, 20)..Point::new(0, 20),
8895                    Point::new(1, 20)..Point::new(1, 20),
8896                    Point::new(2, 20)..Point::new(2, 20)
8897                ]
8898            );
8899        });
8900    }
8901
8902    #[gpui::test]
8903    async fn test_format_during_save(cx: &mut gpui::TestAppContext) {
8904        cx.foreground().forbid_parking();
8905        cx.update(populate_settings);
8906
8907        let mut language = Language::new(
8908            LanguageConfig {
8909                name: "Rust".into(),
8910                path_suffixes: vec!["rs".to_string()],
8911                ..Default::default()
8912            },
8913            Some(tree_sitter_rust::language()),
8914        );
8915        let mut fake_servers = language.set_fake_lsp_adapter(FakeLspAdapter {
8916            capabilities: lsp::ServerCapabilities {
8917                document_formatting_provider: Some(lsp::OneOf::Left(true)),
8918                ..Default::default()
8919            },
8920            ..Default::default()
8921        });
8922
8923        let fs = FakeFs::new(cx.background().clone());
8924        fs.insert_file("/file.rs", Default::default()).await;
8925
8926        let project = Project::test(fs, cx);
8927        project.update(cx, |project, _| project.languages().add(Arc::new(language)));
8928
8929        let worktree_id = project
8930            .update(cx, |project, cx| {
8931                project.find_or_create_local_worktree("/file.rs", true, cx)
8932            })
8933            .await
8934            .unwrap()
8935            .0
8936            .read_with(cx, |tree, _| tree.id());
8937        let buffer = project
8938            .update(cx, |project, cx| project.open_buffer((worktree_id, ""), cx))
8939            .await
8940            .unwrap();
8941
8942        cx.foreground().start_waiting();
8943        let fake_server = fake_servers.next().await.unwrap();
8944
8945        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
8946        let (_, editor) = cx.add_window(|cx| build_editor(buffer, cx));
8947        editor.update(cx, |editor, cx| editor.set_text("one\ntwo\nthree\n", cx));
8948        assert!(cx.read(|cx| editor.is_dirty(cx)));
8949
8950        let save = cx.update(|cx| editor.save(project.clone(), cx));
8951        fake_server
8952            .handle_request::<lsp::request::Formatting, _, _>(move |params, _| async move {
8953                assert_eq!(
8954                    params.text_document.uri,
8955                    lsp::Url::from_file_path("/file.rs").unwrap()
8956                );
8957                Ok(Some(vec![lsp::TextEdit::new(
8958                    lsp::Range::new(lsp::Position::new(0, 3), lsp::Position::new(1, 0)),
8959                    ", ".to_string(),
8960                )]))
8961            })
8962            .next()
8963            .await;
8964        cx.foreground().start_waiting();
8965        save.await.unwrap();
8966        assert_eq!(
8967            editor.read_with(cx, |editor, cx| editor.text(cx)),
8968            "one, two\nthree\n"
8969        );
8970        assert!(!cx.read(|cx| editor.is_dirty(cx)));
8971
8972        editor.update(cx, |editor, cx| editor.set_text("one\ntwo\nthree\n", cx));
8973        assert!(cx.read(|cx| editor.is_dirty(cx)));
8974
8975        // Ensure we can still save even if formatting hangs.
8976        fake_server.handle_request::<lsp::request::Formatting, _, _>(move |params, _| async move {
8977            assert_eq!(
8978                params.text_document.uri,
8979                lsp::Url::from_file_path("/file.rs").unwrap()
8980            );
8981            futures::future::pending::<()>().await;
8982            unreachable!()
8983        });
8984        let save = cx.update(|cx| editor.save(project.clone(), cx));
8985        cx.foreground().advance_clock(items::FORMAT_TIMEOUT);
8986        cx.foreground().start_waiting();
8987        save.await.unwrap();
8988        assert_eq!(
8989            editor.read_with(cx, |editor, cx| editor.text(cx)),
8990            "one\ntwo\nthree\n"
8991        );
8992        assert!(!cx.read(|cx| editor.is_dirty(cx)));
8993    }
8994
8995    #[gpui::test]
8996    async fn test_completion(cx: &mut gpui::TestAppContext) {
8997        cx.update(populate_settings);
8998
8999        let mut language = Language::new(
9000            LanguageConfig {
9001                name: "Rust".into(),
9002                path_suffixes: vec!["rs".to_string()],
9003                ..Default::default()
9004            },
9005            Some(tree_sitter_rust::language()),
9006        );
9007        let mut fake_servers = language.set_fake_lsp_adapter(FakeLspAdapter {
9008            capabilities: lsp::ServerCapabilities {
9009                completion_provider: Some(lsp::CompletionOptions {
9010                    trigger_characters: Some(vec![".".to_string(), ":".to_string()]),
9011                    ..Default::default()
9012                }),
9013                ..Default::default()
9014            },
9015            ..Default::default()
9016        });
9017
9018        let text = "
9019            one
9020            two
9021            three
9022        "
9023        .unindent();
9024
9025        let fs = FakeFs::new(cx.background().clone());
9026        fs.insert_file("/file.rs", text).await;
9027
9028        let project = Project::test(fs, cx);
9029        project.update(cx, |project, _| project.languages().add(Arc::new(language)));
9030
9031        let worktree_id = project
9032            .update(cx, |project, cx| {
9033                project.find_or_create_local_worktree("/file.rs", true, cx)
9034            })
9035            .await
9036            .unwrap()
9037            .0
9038            .read_with(cx, |tree, _| tree.id());
9039        let buffer = project
9040            .update(cx, |project, cx| project.open_buffer((worktree_id, ""), cx))
9041            .await
9042            .unwrap();
9043        let mut fake_server = fake_servers.next().await.unwrap();
9044
9045        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
9046        let (_, editor) = cx.add_window(|cx| build_editor(buffer, cx));
9047
9048        editor.update(cx, |editor, cx| {
9049            editor.project = Some(project);
9050            editor.select_ranges([Point::new(0, 3)..Point::new(0, 3)], None, cx);
9051            editor.handle_input(&Input(".".to_string()), cx);
9052        });
9053
9054        handle_completion_request(
9055            &mut fake_server,
9056            "/file.rs",
9057            Point::new(0, 4),
9058            vec![
9059                (Point::new(0, 4)..Point::new(0, 4), "first_completion"),
9060                (Point::new(0, 4)..Point::new(0, 4), "second_completion"),
9061            ],
9062        )
9063        .await;
9064        editor
9065            .condition(&cx, |editor, _| editor.context_menu_visible())
9066            .await;
9067
9068        let apply_additional_edits = editor.update(cx, |editor, cx| {
9069            editor.move_down(&MoveDown, cx);
9070            let apply_additional_edits = editor
9071                .confirm_completion(&ConfirmCompletion(None), cx)
9072                .unwrap();
9073            assert_eq!(
9074                editor.text(cx),
9075                "
9076                    one.second_completion
9077                    two
9078                    three
9079                "
9080                .unindent()
9081            );
9082            apply_additional_edits
9083        });
9084
9085        handle_resolve_completion_request(
9086            &mut fake_server,
9087            Some((Point::new(2, 5)..Point::new(2, 5), "\nadditional edit")),
9088        )
9089        .await;
9090        apply_additional_edits.await.unwrap();
9091        assert_eq!(
9092            editor.read_with(cx, |editor, cx| editor.text(cx)),
9093            "
9094                one.second_completion
9095                two
9096                three
9097                additional edit
9098            "
9099            .unindent()
9100        );
9101
9102        editor.update(cx, |editor, cx| {
9103            editor.select_ranges(
9104                [
9105                    Point::new(1, 3)..Point::new(1, 3),
9106                    Point::new(2, 5)..Point::new(2, 5),
9107                ],
9108                None,
9109                cx,
9110            );
9111
9112            editor.handle_input(&Input(" ".to_string()), cx);
9113            assert!(editor.context_menu.is_none());
9114            editor.handle_input(&Input("s".to_string()), cx);
9115            assert!(editor.context_menu.is_none());
9116        });
9117
9118        handle_completion_request(
9119            &mut fake_server,
9120            "/file.rs",
9121            Point::new(2, 7),
9122            vec![
9123                (Point::new(2, 6)..Point::new(2, 7), "fourth_completion"),
9124                (Point::new(2, 6)..Point::new(2, 7), "fifth_completion"),
9125                (Point::new(2, 6)..Point::new(2, 7), "sixth_completion"),
9126            ],
9127        )
9128        .await;
9129        editor
9130            .condition(&cx, |editor, _| editor.context_menu_visible())
9131            .await;
9132
9133        editor.update(cx, |editor, cx| {
9134            editor.handle_input(&Input("i".to_string()), cx);
9135        });
9136
9137        handle_completion_request(
9138            &mut fake_server,
9139            "/file.rs",
9140            Point::new(2, 8),
9141            vec![
9142                (Point::new(2, 6)..Point::new(2, 8), "fourth_completion"),
9143                (Point::new(2, 6)..Point::new(2, 8), "fifth_completion"),
9144                (Point::new(2, 6)..Point::new(2, 8), "sixth_completion"),
9145            ],
9146        )
9147        .await;
9148        editor
9149            .condition(&cx, |editor, _| editor.context_menu_visible())
9150            .await;
9151
9152        let apply_additional_edits = editor.update(cx, |editor, cx| {
9153            let apply_additional_edits = editor
9154                .confirm_completion(&ConfirmCompletion(None), cx)
9155                .unwrap();
9156            assert_eq!(
9157                editor.text(cx),
9158                "
9159                    one.second_completion
9160                    two sixth_completion
9161                    three sixth_completion
9162                    additional edit
9163                "
9164                .unindent()
9165            );
9166            apply_additional_edits
9167        });
9168        handle_resolve_completion_request(&mut fake_server, None).await;
9169        apply_additional_edits.await.unwrap();
9170
9171        async fn handle_completion_request(
9172            fake: &mut FakeLanguageServer,
9173            path: &'static str,
9174            position: Point,
9175            completions: Vec<(Range<Point>, &'static str)>,
9176        ) {
9177            fake.handle_request::<lsp::request::Completion, _, _>(move |params, _| {
9178                let completions = completions.clone();
9179                async move {
9180                    assert_eq!(
9181                        params.text_document_position.text_document.uri,
9182                        lsp::Url::from_file_path(path).unwrap()
9183                    );
9184                    assert_eq!(
9185                        params.text_document_position.position,
9186                        lsp::Position::new(position.row, position.column)
9187                    );
9188                    Ok(Some(lsp::CompletionResponse::Array(
9189                        completions
9190                            .iter()
9191                            .map(|(range, new_text)| lsp::CompletionItem {
9192                                label: new_text.to_string(),
9193                                text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
9194                                    range: lsp::Range::new(
9195                                        lsp::Position::new(range.start.row, range.start.column),
9196                                        lsp::Position::new(range.start.row, range.start.column),
9197                                    ),
9198                                    new_text: new_text.to_string(),
9199                                })),
9200                                ..Default::default()
9201                            })
9202                            .collect(),
9203                    )))
9204                }
9205            })
9206            .next()
9207            .await;
9208        }
9209
9210        async fn handle_resolve_completion_request(
9211            fake: &mut FakeLanguageServer,
9212            edit: Option<(Range<Point>, &'static str)>,
9213        ) {
9214            fake.handle_request::<lsp::request::ResolveCompletionItem, _, _>(move |_, _| {
9215                let edit = edit.clone();
9216                async move {
9217                    Ok(lsp::CompletionItem {
9218                        additional_text_edits: edit.map(|(range, new_text)| {
9219                            vec![lsp::TextEdit::new(
9220                                lsp::Range::new(
9221                                    lsp::Position::new(range.start.row, range.start.column),
9222                                    lsp::Position::new(range.end.row, range.end.column),
9223                                ),
9224                                new_text.to_string(),
9225                            )]
9226                        }),
9227                        ..Default::default()
9228                    })
9229                }
9230            })
9231            .next()
9232            .await;
9233        }
9234    }
9235
9236    #[gpui::test]
9237    async fn test_toggle_comment(cx: &mut gpui::TestAppContext) {
9238        cx.update(populate_settings);
9239        let language = Arc::new(Language::new(
9240            LanguageConfig {
9241                line_comment: Some("// ".to_string()),
9242                ..Default::default()
9243            },
9244            Some(tree_sitter_rust::language()),
9245        ));
9246
9247        let text = "
9248            fn a() {
9249                //b();
9250                // c();
9251                //  d();
9252            }
9253        "
9254        .unindent();
9255
9256        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
9257        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
9258        let (_, view) = cx.add_window(|cx| build_editor(buffer, cx));
9259
9260        view.update(cx, |editor, cx| {
9261            // If multiple selections intersect a line, the line is only
9262            // toggled once.
9263            editor.select_display_ranges(
9264                &[
9265                    DisplayPoint::new(1, 3)..DisplayPoint::new(2, 3),
9266                    DisplayPoint::new(3, 5)..DisplayPoint::new(3, 6),
9267                ],
9268                cx,
9269            );
9270            editor.toggle_comments(&ToggleComments, cx);
9271            assert_eq!(
9272                editor.text(cx),
9273                "
9274                    fn a() {
9275                        b();
9276                        c();
9277                         d();
9278                    }
9279                "
9280                .unindent()
9281            );
9282
9283            // The comment prefix is inserted at the same column for every line
9284            // in a selection.
9285            editor.select_display_ranges(&[DisplayPoint::new(1, 3)..DisplayPoint::new(3, 6)], cx);
9286            editor.toggle_comments(&ToggleComments, cx);
9287            assert_eq!(
9288                editor.text(cx),
9289                "
9290                    fn a() {
9291                        // b();
9292                        // c();
9293                        //  d();
9294                    }
9295                "
9296                .unindent()
9297            );
9298
9299            // If a selection ends at the beginning of a line, that line is not toggled.
9300            editor.select_display_ranges(&[DisplayPoint::new(2, 0)..DisplayPoint::new(3, 0)], cx);
9301            editor.toggle_comments(&ToggleComments, cx);
9302            assert_eq!(
9303                editor.text(cx),
9304                "
9305                        fn a() {
9306                            // b();
9307                            c();
9308                            //  d();
9309                        }
9310                    "
9311                .unindent()
9312            );
9313        });
9314    }
9315
9316    #[gpui::test]
9317    fn test_editing_disjoint_excerpts(cx: &mut gpui::MutableAppContext) {
9318        populate_settings(cx);
9319        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(3, 4, 'a'), cx));
9320        let multibuffer = cx.add_model(|cx| {
9321            let mut multibuffer = MultiBuffer::new(0);
9322            multibuffer.push_excerpts(
9323                buffer.clone(),
9324                [
9325                    Point::new(0, 0)..Point::new(0, 4),
9326                    Point::new(1, 0)..Point::new(1, 4),
9327                ],
9328                cx,
9329            );
9330            multibuffer
9331        });
9332
9333        assert_eq!(multibuffer.read(cx).read(cx).text(), "aaaa\nbbbb");
9334
9335        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(multibuffer, cx));
9336        view.update(cx, |view, cx| {
9337            assert_eq!(view.text(cx), "aaaa\nbbbb");
9338            view.select_ranges(
9339                [
9340                    Point::new(0, 0)..Point::new(0, 0),
9341                    Point::new(1, 0)..Point::new(1, 0),
9342                ],
9343                None,
9344                cx,
9345            );
9346
9347            view.handle_input(&Input("X".to_string()), cx);
9348            assert_eq!(view.text(cx), "Xaaaa\nXbbbb");
9349            assert_eq!(
9350                view.selected_ranges(cx),
9351                [
9352                    Point::new(0, 1)..Point::new(0, 1),
9353                    Point::new(1, 1)..Point::new(1, 1),
9354                ]
9355            )
9356        });
9357    }
9358
9359    #[gpui::test]
9360    fn test_editing_overlapping_excerpts(cx: &mut gpui::MutableAppContext) {
9361        populate_settings(cx);
9362        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(3, 4, 'a'), cx));
9363        let multibuffer = cx.add_model(|cx| {
9364            let mut multibuffer = MultiBuffer::new(0);
9365            multibuffer.push_excerpts(
9366                buffer,
9367                [
9368                    Point::new(0, 0)..Point::new(1, 4),
9369                    Point::new(1, 0)..Point::new(2, 4),
9370                ],
9371                cx,
9372            );
9373            multibuffer
9374        });
9375
9376        assert_eq!(
9377            multibuffer.read(cx).read(cx).text(),
9378            "aaaa\nbbbb\nbbbb\ncccc"
9379        );
9380
9381        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(multibuffer, cx));
9382        view.update(cx, |view, cx| {
9383            view.select_ranges(
9384                [
9385                    Point::new(1, 1)..Point::new(1, 1),
9386                    Point::new(2, 3)..Point::new(2, 3),
9387                ],
9388                None,
9389                cx,
9390            );
9391
9392            view.handle_input(&Input("X".to_string()), cx);
9393            assert_eq!(view.text(cx), "aaaa\nbXbbXb\nbXbbXb\ncccc");
9394            assert_eq!(
9395                view.selected_ranges(cx),
9396                [
9397                    Point::new(1, 2)..Point::new(1, 2),
9398                    Point::new(2, 5)..Point::new(2, 5),
9399                ]
9400            );
9401
9402            view.newline(&Newline, cx);
9403            assert_eq!(view.text(cx), "aaaa\nbX\nbbX\nb\nbX\nbbX\nb\ncccc");
9404            assert_eq!(
9405                view.selected_ranges(cx),
9406                [
9407                    Point::new(2, 0)..Point::new(2, 0),
9408                    Point::new(6, 0)..Point::new(6, 0),
9409                ]
9410            );
9411        });
9412    }
9413
9414    #[gpui::test]
9415    fn test_refresh_selections(cx: &mut gpui::MutableAppContext) {
9416        populate_settings(cx);
9417        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(3, 4, 'a'), cx));
9418        let mut excerpt1_id = None;
9419        let multibuffer = cx.add_model(|cx| {
9420            let mut multibuffer = MultiBuffer::new(0);
9421            excerpt1_id = multibuffer
9422                .push_excerpts(
9423                    buffer.clone(),
9424                    [
9425                        Point::new(0, 0)..Point::new(1, 4),
9426                        Point::new(1, 0)..Point::new(2, 4),
9427                    ],
9428                    cx,
9429                )
9430                .into_iter()
9431                .next();
9432            multibuffer
9433        });
9434        assert_eq!(
9435            multibuffer.read(cx).read(cx).text(),
9436            "aaaa\nbbbb\nbbbb\ncccc"
9437        );
9438        let (_, editor) = cx.add_window(Default::default(), |cx| {
9439            let mut editor = build_editor(multibuffer.clone(), cx);
9440            let snapshot = editor.snapshot(cx);
9441            editor.select_ranges([Point::new(1, 3)..Point::new(1, 3)], None, cx);
9442            editor.begin_selection(Point::new(2, 1).to_display_point(&snapshot), true, 1, cx);
9443            assert_eq!(
9444                editor.selected_ranges(cx),
9445                [
9446                    Point::new(1, 3)..Point::new(1, 3),
9447                    Point::new(2, 1)..Point::new(2, 1),
9448                ]
9449            );
9450            editor
9451        });
9452
9453        // Refreshing selections is a no-op when excerpts haven't changed.
9454        editor.update(cx, |editor, cx| {
9455            editor.refresh_selections(cx);
9456            assert_eq!(
9457                editor.selected_ranges(cx),
9458                [
9459                    Point::new(1, 3)..Point::new(1, 3),
9460                    Point::new(2, 1)..Point::new(2, 1),
9461                ]
9462            );
9463        });
9464
9465        multibuffer.update(cx, |multibuffer, cx| {
9466            multibuffer.remove_excerpts([&excerpt1_id.unwrap()], cx);
9467        });
9468        editor.update(cx, |editor, cx| {
9469            // Removing an excerpt causes the first selection to become degenerate.
9470            assert_eq!(
9471                editor.selected_ranges(cx),
9472                [
9473                    Point::new(0, 0)..Point::new(0, 0),
9474                    Point::new(0, 1)..Point::new(0, 1)
9475                ]
9476            );
9477
9478            // Refreshing selections will relocate the first selection to the original buffer
9479            // location.
9480            editor.refresh_selections(cx);
9481            assert_eq!(
9482                editor.selected_ranges(cx),
9483                [
9484                    Point::new(0, 1)..Point::new(0, 1),
9485                    Point::new(0, 3)..Point::new(0, 3)
9486                ]
9487            );
9488            assert!(editor.pending_selection.is_some());
9489        });
9490    }
9491
9492    #[gpui::test]
9493    fn test_refresh_selections_while_selecting_with_mouse(cx: &mut gpui::MutableAppContext) {
9494        populate_settings(cx);
9495        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(3, 4, 'a'), cx));
9496        let mut excerpt1_id = None;
9497        let multibuffer = cx.add_model(|cx| {
9498            let mut multibuffer = MultiBuffer::new(0);
9499            excerpt1_id = multibuffer
9500                .push_excerpts(
9501                    buffer.clone(),
9502                    [
9503                        Point::new(0, 0)..Point::new(1, 4),
9504                        Point::new(1, 0)..Point::new(2, 4),
9505                    ],
9506                    cx,
9507                )
9508                .into_iter()
9509                .next();
9510            multibuffer
9511        });
9512        assert_eq!(
9513            multibuffer.read(cx).read(cx).text(),
9514            "aaaa\nbbbb\nbbbb\ncccc"
9515        );
9516        let (_, editor) = cx.add_window(Default::default(), |cx| {
9517            let mut editor = build_editor(multibuffer.clone(), cx);
9518            let snapshot = editor.snapshot(cx);
9519            editor.begin_selection(Point::new(1, 3).to_display_point(&snapshot), false, 1, cx);
9520            assert_eq!(
9521                editor.selected_ranges(cx),
9522                [Point::new(1, 3)..Point::new(1, 3)]
9523            );
9524            editor
9525        });
9526
9527        multibuffer.update(cx, |multibuffer, cx| {
9528            multibuffer.remove_excerpts([&excerpt1_id.unwrap()], cx);
9529        });
9530        editor.update(cx, |editor, cx| {
9531            assert_eq!(
9532                editor.selected_ranges(cx),
9533                [Point::new(0, 0)..Point::new(0, 0)]
9534            );
9535
9536            // Ensure we don't panic when selections are refreshed and that the pending selection is finalized.
9537            editor.refresh_selections(cx);
9538            assert_eq!(
9539                editor.selected_ranges(cx),
9540                [Point::new(0, 3)..Point::new(0, 3)]
9541            );
9542            assert!(editor.pending_selection.is_some());
9543        });
9544    }
9545
9546    #[gpui::test]
9547    async fn test_extra_newline_insertion(cx: &mut gpui::TestAppContext) {
9548        cx.update(populate_settings);
9549        let language = Arc::new(Language::new(
9550            LanguageConfig {
9551                brackets: vec![
9552                    BracketPair {
9553                        start: "{".to_string(),
9554                        end: "}".to_string(),
9555                        close: true,
9556                        newline: true,
9557                    },
9558                    BracketPair {
9559                        start: "/* ".to_string(),
9560                        end: " */".to_string(),
9561                        close: true,
9562                        newline: true,
9563                    },
9564                ],
9565                ..Default::default()
9566            },
9567            Some(tree_sitter_rust::language()),
9568        ));
9569
9570        let text = concat!(
9571            "{   }\n",     // Suppress rustfmt
9572            "  x\n",       //
9573            "  /*   */\n", //
9574            "x\n",         //
9575            "{{} }\n",     //
9576        );
9577
9578        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
9579        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
9580        let (_, view) = cx.add_window(|cx| build_editor(buffer, cx));
9581        view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
9582            .await;
9583
9584        view.update(cx, |view, cx| {
9585            view.select_display_ranges(
9586                &[
9587                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 3),
9588                    DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
9589                    DisplayPoint::new(4, 4)..DisplayPoint::new(4, 4),
9590                ],
9591                cx,
9592            );
9593            view.newline(&Newline, cx);
9594
9595            assert_eq!(
9596                view.buffer().read(cx).read(cx).text(),
9597                concat!(
9598                    "{ \n",    // Suppress rustfmt
9599                    "\n",      //
9600                    "}\n",     //
9601                    "  x\n",   //
9602                    "  /* \n", //
9603                    "  \n",    //
9604                    "  */\n",  //
9605                    "x\n",     //
9606                    "{{} \n",  //
9607                    "}\n",     //
9608                )
9609            );
9610        });
9611    }
9612
9613    #[gpui::test]
9614    fn test_highlighted_ranges(cx: &mut gpui::MutableAppContext) {
9615        let buffer = MultiBuffer::build_simple(&sample_text(16, 8, 'a'), cx);
9616        populate_settings(cx);
9617        let (_, editor) = cx.add_window(Default::default(), |cx| build_editor(buffer.clone(), cx));
9618
9619        editor.update(cx, |editor, cx| {
9620            struct Type1;
9621            struct Type2;
9622
9623            let buffer = buffer.read(cx).snapshot(cx);
9624
9625            let anchor_range = |range: Range<Point>| {
9626                buffer.anchor_after(range.start)..buffer.anchor_after(range.end)
9627            };
9628
9629            editor.highlight_background::<Type1>(
9630                vec![
9631                    anchor_range(Point::new(2, 1)..Point::new(2, 3)),
9632                    anchor_range(Point::new(4, 2)..Point::new(4, 4)),
9633                    anchor_range(Point::new(6, 3)..Point::new(6, 5)),
9634                    anchor_range(Point::new(8, 4)..Point::new(8, 6)),
9635                ],
9636                Color::red(),
9637                cx,
9638            );
9639            editor.highlight_background::<Type2>(
9640                vec![
9641                    anchor_range(Point::new(3, 2)..Point::new(3, 5)),
9642                    anchor_range(Point::new(5, 3)..Point::new(5, 6)),
9643                    anchor_range(Point::new(7, 4)..Point::new(7, 7)),
9644                    anchor_range(Point::new(9, 5)..Point::new(9, 8)),
9645                ],
9646                Color::green(),
9647                cx,
9648            );
9649
9650            let snapshot = editor.snapshot(cx);
9651            let mut highlighted_ranges = editor.background_highlights_in_range(
9652                anchor_range(Point::new(3, 4)..Point::new(7, 4)),
9653                &snapshot,
9654            );
9655            // Enforce a consistent ordering based on color without relying on the ordering of the
9656            // highlight's `TypeId` which is non-deterministic.
9657            highlighted_ranges.sort_unstable_by_key(|(_, color)| *color);
9658            assert_eq!(
9659                highlighted_ranges,
9660                &[
9661                    (
9662                        DisplayPoint::new(3, 2)..DisplayPoint::new(3, 5),
9663                        Color::green(),
9664                    ),
9665                    (
9666                        DisplayPoint::new(5, 3)..DisplayPoint::new(5, 6),
9667                        Color::green(),
9668                    ),
9669                    (
9670                        DisplayPoint::new(4, 2)..DisplayPoint::new(4, 4),
9671                        Color::red(),
9672                    ),
9673                    (
9674                        DisplayPoint::new(6, 3)..DisplayPoint::new(6, 5),
9675                        Color::red(),
9676                    ),
9677                ]
9678            );
9679            assert_eq!(
9680                editor.background_highlights_in_range(
9681                    anchor_range(Point::new(5, 6)..Point::new(6, 4)),
9682                    &snapshot,
9683                ),
9684                &[(
9685                    DisplayPoint::new(6, 3)..DisplayPoint::new(6, 5),
9686                    Color::red(),
9687                )]
9688            );
9689        });
9690    }
9691
9692    #[gpui::test]
9693    fn test_following(cx: &mut gpui::MutableAppContext) {
9694        let buffer = MultiBuffer::build_simple(&sample_text(16, 8, 'a'), cx);
9695        populate_settings(cx);
9696
9697        let (_, leader) = cx.add_window(Default::default(), |cx| build_editor(buffer.clone(), cx));
9698        let (_, follower) = cx.add_window(
9699            WindowOptions {
9700                bounds: WindowBounds::Fixed(RectF::from_points(vec2f(0., 0.), vec2f(10., 80.))),
9701                ..Default::default()
9702            },
9703            |cx| build_editor(buffer.clone(), cx),
9704        );
9705
9706        let pending_update = Rc::new(RefCell::new(None));
9707        follower.update(cx, {
9708            let update = pending_update.clone();
9709            |_, cx| {
9710                cx.subscribe(&leader, move |_, leader, event, cx| {
9711                    leader
9712                        .read(cx)
9713                        .add_event_to_update_proto(event, &mut *update.borrow_mut(), cx);
9714                })
9715                .detach();
9716            }
9717        });
9718
9719        // Update the selections only
9720        leader.update(cx, |leader, cx| {
9721            leader.select_ranges([1..1], None, cx);
9722        });
9723        follower.update(cx, |follower, cx| {
9724            follower
9725                .apply_update_proto(pending_update.borrow_mut().take().unwrap(), cx)
9726                .unwrap();
9727        });
9728        assert_eq!(follower.read(cx).selected_ranges(cx), vec![1..1]);
9729
9730        // Update the scroll position only
9731        leader.update(cx, |leader, cx| {
9732            leader.set_scroll_position(vec2f(1.5, 3.5), cx);
9733        });
9734        follower.update(cx, |follower, cx| {
9735            follower
9736                .apply_update_proto(pending_update.borrow_mut().take().unwrap(), cx)
9737                .unwrap();
9738        });
9739        assert_eq!(
9740            follower.update(cx, |follower, cx| follower.scroll_position(cx)),
9741            vec2f(1.5, 3.5)
9742        );
9743
9744        // Update the selections and scroll position
9745        leader.update(cx, |leader, cx| {
9746            leader.select_ranges([0..0], None, cx);
9747            leader.request_autoscroll(Autoscroll::Newest, cx);
9748            leader.set_scroll_position(vec2f(1.5, 3.5), cx);
9749        });
9750        follower.update(cx, |follower, cx| {
9751            let initial_scroll_position = follower.scroll_position(cx);
9752            follower
9753                .apply_update_proto(pending_update.borrow_mut().take().unwrap(), cx)
9754                .unwrap();
9755            assert_eq!(follower.scroll_position(cx), initial_scroll_position);
9756            assert!(follower.autoscroll_request.is_some());
9757        });
9758        assert_eq!(follower.read(cx).selected_ranges(cx), vec![0..0]);
9759
9760        // Creating a pending selection that precedes another selection
9761        leader.update(cx, |leader, cx| {
9762            leader.select_ranges([1..1], None, cx);
9763            leader.begin_selection(DisplayPoint::new(0, 0), true, 1, cx);
9764        });
9765        follower.update(cx, |follower, cx| {
9766            follower
9767                .apply_update_proto(pending_update.borrow_mut().take().unwrap(), cx)
9768                .unwrap();
9769        });
9770        assert_eq!(follower.read(cx).selected_ranges(cx), vec![0..0, 1..1]);
9771
9772        // Extend the pending selection so that it surrounds another selection
9773        leader.update(cx, |leader, cx| {
9774            leader.extend_selection(DisplayPoint::new(0, 2), 1, cx);
9775        });
9776        follower.update(cx, |follower, cx| {
9777            follower
9778                .apply_update_proto(pending_update.borrow_mut().take().unwrap(), cx)
9779                .unwrap();
9780        });
9781        assert_eq!(follower.read(cx).selected_ranges(cx), vec![0..2]);
9782    }
9783
9784    #[test]
9785    fn test_combine_syntax_and_fuzzy_match_highlights() {
9786        let string = "abcdefghijklmnop";
9787        let syntax_ranges = [
9788            (
9789                0..3,
9790                HighlightStyle {
9791                    color: Some(Color::red()),
9792                    ..Default::default()
9793                },
9794            ),
9795            (
9796                4..8,
9797                HighlightStyle {
9798                    color: Some(Color::green()),
9799                    ..Default::default()
9800                },
9801            ),
9802        ];
9803        let match_indices = [4, 6, 7, 8];
9804        assert_eq!(
9805            combine_syntax_and_fuzzy_match_highlights(
9806                &string,
9807                Default::default(),
9808                syntax_ranges.into_iter(),
9809                &match_indices,
9810            ),
9811            &[
9812                (
9813                    0..3,
9814                    HighlightStyle {
9815                        color: Some(Color::red()),
9816                        ..Default::default()
9817                    },
9818                ),
9819                (
9820                    4..5,
9821                    HighlightStyle {
9822                        color: Some(Color::green()),
9823                        weight: Some(fonts::Weight::BOLD),
9824                        ..Default::default()
9825                    },
9826                ),
9827                (
9828                    5..6,
9829                    HighlightStyle {
9830                        color: Some(Color::green()),
9831                        ..Default::default()
9832                    },
9833                ),
9834                (
9835                    6..8,
9836                    HighlightStyle {
9837                        color: Some(Color::green()),
9838                        weight: Some(fonts::Weight::BOLD),
9839                        ..Default::default()
9840                    },
9841                ),
9842                (
9843                    8..9,
9844                    HighlightStyle {
9845                        weight: Some(fonts::Weight::BOLD),
9846                        ..Default::default()
9847                    },
9848                ),
9849            ]
9850        );
9851    }
9852
9853    fn empty_range(row: usize, column: usize) -> Range<DisplayPoint> {
9854        let point = DisplayPoint::new(row as u32, column as u32);
9855        point..point
9856    }
9857
9858    fn build_editor(buffer: ModelHandle<MultiBuffer>, cx: &mut ViewContext<Editor>) -> Editor {
9859        Editor::new(EditorMode::Full, buffer, None, None, cx)
9860    }
9861
9862    fn populate_settings(cx: &mut gpui::MutableAppContext) {
9863        let settings = Settings::test(cx);
9864        cx.set_global(settings);
9865    }
9866
9867    fn assert_selection_ranges(
9868        marked_text: &str,
9869        selection_marker_pairs: Vec<(char, char)>,
9870        view: &mut Editor,
9871        cx: &mut ViewContext<Editor>,
9872    ) {
9873        let snapshot = view.snapshot(cx).display_snapshot;
9874        let mut marker_chars = Vec::new();
9875        for (start, end) in selection_marker_pairs.iter() {
9876            marker_chars.push(*start);
9877            marker_chars.push(*end);
9878        }
9879        let (_, markers) = marked_text_by(marked_text, marker_chars);
9880        let asserted_ranges: Vec<Range<DisplayPoint>> = selection_marker_pairs
9881            .iter()
9882            .map(|(start, end)| {
9883                let start = markers.get(start).unwrap()[0].to_display_point(&snapshot);
9884                let end = markers.get(end).unwrap()[0].to_display_point(&snapshot);
9885                start..end
9886            })
9887            .collect();
9888        assert_eq!(
9889            view.selected_display_ranges(cx),
9890            &asserted_ranges[..],
9891            "Assert selections are {}",
9892            marked_text
9893        );
9894    }
9895}
9896
9897trait RangeExt<T> {
9898    fn sorted(&self) -> Range<T>;
9899    fn to_inclusive(&self) -> RangeInclusive<T>;
9900}
9901
9902impl<T: Ord + Clone> RangeExt<T> for Range<T> {
9903    fn sorted(&self) -> Self {
9904        cmp::min(&self.start, &self.end).clone()..cmp::max(&self.start, &self.end).clone()
9905    }
9906
9907    fn to_inclusive(&self) -> RangeInclusive<T> {
9908        self.start.clone()..=self.end.clone()
9909    }
9910}