editor.rs

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