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