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