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