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