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