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