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