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    use crate::test::marked_text_by;
6171
6172    use super::*;
6173    use gpui::{
6174        geometry::rect::RectF,
6175        platform::{WindowBounds, WindowOptions},
6176    };
6177    use language::{LanguageConfig, LanguageServerConfig};
6178    use lsp::FakeLanguageServer;
6179    use project::FakeFs;
6180    use smol::stream::StreamExt;
6181    use std::{cell::RefCell, rc::Rc, time::Instant};
6182    use text::Point;
6183    use unindent::Unindent;
6184    use util::test::sample_text;
6185    use workspace::FollowableItem;
6186
6187    #[gpui::test]
6188    fn test_edit_events(cx: &mut MutableAppContext) {
6189        populate_settings(cx);
6190        let buffer = cx.add_model(|cx| language::Buffer::new(0, "123456", cx));
6191
6192        let events = Rc::new(RefCell::new(Vec::new()));
6193        let (_, editor1) = cx.add_window(Default::default(), {
6194            let events = events.clone();
6195            |cx| {
6196                cx.subscribe(&cx.handle(), move |_, _, event, _| {
6197                    if matches!(event, Event::Edited | Event::BufferEdited | Event::Dirtied) {
6198                        events.borrow_mut().push(("editor1", *event));
6199                    }
6200                })
6201                .detach();
6202                Editor::for_buffer(buffer.clone(), None, cx)
6203            }
6204        });
6205        let (_, editor2) = cx.add_window(Default::default(), {
6206            let events = events.clone();
6207            |cx| {
6208                cx.subscribe(&cx.handle(), move |_, _, event, _| {
6209                    if matches!(event, Event::Edited | Event::BufferEdited | Event::Dirtied) {
6210                        events.borrow_mut().push(("editor2", *event));
6211                    }
6212                })
6213                .detach();
6214                Editor::for_buffer(buffer.clone(), None, cx)
6215            }
6216        });
6217        assert_eq!(mem::take(&mut *events.borrow_mut()), []);
6218
6219        // Mutating editor 1 will emit an `Edited` event only for that editor.
6220        editor1.update(cx, |editor, cx| editor.insert("X", cx));
6221        assert_eq!(
6222            mem::take(&mut *events.borrow_mut()),
6223            [
6224                ("editor1", Event::Edited),
6225                ("editor1", Event::BufferEdited),
6226                ("editor2", Event::BufferEdited),
6227                ("editor1", Event::Dirtied),
6228                ("editor2", Event::Dirtied)
6229            ]
6230        );
6231
6232        // Mutating editor 2 will emit an `Edited` event only for that editor.
6233        editor2.update(cx, |editor, cx| editor.delete(&Delete, cx));
6234        assert_eq!(
6235            mem::take(&mut *events.borrow_mut()),
6236            [
6237                ("editor2", Event::Edited),
6238                ("editor1", Event::BufferEdited),
6239                ("editor2", Event::BufferEdited),
6240            ]
6241        );
6242
6243        // Undoing on editor 1 will emit an `Edited` event only for that editor.
6244        editor1.update(cx, |editor, cx| editor.undo(&Undo, cx));
6245        assert_eq!(
6246            mem::take(&mut *events.borrow_mut()),
6247            [
6248                ("editor1", Event::Edited),
6249                ("editor1", Event::BufferEdited),
6250                ("editor2", Event::BufferEdited),
6251            ]
6252        );
6253
6254        // Redoing on editor 1 will emit an `Edited` event only for that editor.
6255        editor1.update(cx, |editor, cx| editor.redo(&Redo, cx));
6256        assert_eq!(
6257            mem::take(&mut *events.borrow_mut()),
6258            [
6259                ("editor1", Event::Edited),
6260                ("editor1", Event::BufferEdited),
6261                ("editor2", Event::BufferEdited),
6262            ]
6263        );
6264
6265        // Undoing on editor 2 will emit an `Edited` event only for that editor.
6266        editor2.update(cx, |editor, cx| editor.undo(&Undo, cx));
6267        assert_eq!(
6268            mem::take(&mut *events.borrow_mut()),
6269            [
6270                ("editor2", Event::Edited),
6271                ("editor1", Event::BufferEdited),
6272                ("editor2", Event::BufferEdited),
6273            ]
6274        );
6275
6276        // Redoing on editor 2 will emit an `Edited` event only for that editor.
6277        editor2.update(cx, |editor, cx| editor.redo(&Redo, cx));
6278        assert_eq!(
6279            mem::take(&mut *events.borrow_mut()),
6280            [
6281                ("editor2", Event::Edited),
6282                ("editor1", Event::BufferEdited),
6283                ("editor2", Event::BufferEdited),
6284            ]
6285        );
6286
6287        // No event is emitted when the mutation is a no-op.
6288        editor2.update(cx, |editor, cx| {
6289            editor.select_ranges([0..0], None, cx);
6290            editor.backspace(&Backspace, cx);
6291        });
6292        assert_eq!(mem::take(&mut *events.borrow_mut()), []);
6293    }
6294
6295    #[gpui::test]
6296    fn test_undo_redo_with_selection_restoration(cx: &mut MutableAppContext) {
6297        populate_settings(cx);
6298        let mut now = Instant::now();
6299        let buffer = cx.add_model(|cx| language::Buffer::new(0, "123456", cx));
6300        let group_interval = buffer.read(cx).transaction_group_interval();
6301        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
6302        let (_, editor) = cx.add_window(Default::default(), |cx| build_editor(buffer.clone(), cx));
6303
6304        editor.update(cx, |editor, cx| {
6305            editor.start_transaction_at(now, cx);
6306            editor.select_ranges([2..4], None, cx);
6307            editor.insert("cd", cx);
6308            editor.end_transaction_at(now, cx);
6309            assert_eq!(editor.text(cx), "12cd56");
6310            assert_eq!(editor.selected_ranges(cx), vec![4..4]);
6311
6312            editor.start_transaction_at(now, cx);
6313            editor.select_ranges([4..5], None, cx);
6314            editor.insert("e", cx);
6315            editor.end_transaction_at(now, cx);
6316            assert_eq!(editor.text(cx), "12cde6");
6317            assert_eq!(editor.selected_ranges(cx), vec![5..5]);
6318
6319            now += group_interval + Duration::from_millis(1);
6320            editor.select_ranges([2..2], None, cx);
6321
6322            // Simulate an edit in another editor
6323            buffer.update(cx, |buffer, cx| {
6324                buffer.start_transaction_at(now, cx);
6325                buffer.edit([0..1], "a", cx);
6326                buffer.edit([1..1], "b", cx);
6327                buffer.end_transaction_at(now, cx);
6328            });
6329
6330            assert_eq!(editor.text(cx), "ab2cde6");
6331            assert_eq!(editor.selected_ranges(cx), vec![3..3]);
6332
6333            // Last transaction happened past the group interval in a different editor.
6334            // Undo it individually and don't restore selections.
6335            editor.undo(&Undo, cx);
6336            assert_eq!(editor.text(cx), "12cde6");
6337            assert_eq!(editor.selected_ranges(cx), vec![2..2]);
6338
6339            // First two transactions happened within the group interval in this editor.
6340            // Undo them together and restore selections.
6341            editor.undo(&Undo, cx);
6342            editor.undo(&Undo, cx); // Undo stack is empty here, so this is a no-op.
6343            assert_eq!(editor.text(cx), "123456");
6344            assert_eq!(editor.selected_ranges(cx), vec![0..0]);
6345
6346            // Redo the first two transactions together.
6347            editor.redo(&Redo, cx);
6348            assert_eq!(editor.text(cx), "12cde6");
6349            assert_eq!(editor.selected_ranges(cx), vec![5..5]);
6350
6351            // Redo the last transaction on its own.
6352            editor.redo(&Redo, cx);
6353            assert_eq!(editor.text(cx), "ab2cde6");
6354            assert_eq!(editor.selected_ranges(cx), vec![6..6]);
6355
6356            // Test empty transactions.
6357            editor.start_transaction_at(now, cx);
6358            editor.end_transaction_at(now, cx);
6359            editor.undo(&Undo, cx);
6360            assert_eq!(editor.text(cx), "12cde6");
6361        });
6362    }
6363
6364    #[gpui::test]
6365    fn test_selection_with_mouse(cx: &mut gpui::MutableAppContext) {
6366        populate_settings(cx);
6367
6368        let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\nddddddd\n", cx);
6369        let (_, editor) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
6370        editor.update(cx, |view, cx| {
6371            view.begin_selection(DisplayPoint::new(2, 2), false, 1, cx);
6372        });
6373        assert_eq!(
6374            editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
6375            [DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2)]
6376        );
6377
6378        editor.update(cx, |view, cx| {
6379            view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
6380        });
6381
6382        assert_eq!(
6383            editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
6384            [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
6385        );
6386
6387        editor.update(cx, |view, cx| {
6388            view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
6389        });
6390
6391        assert_eq!(
6392            editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
6393            [DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1)]
6394        );
6395
6396        editor.update(cx, |view, cx| {
6397            view.end_selection(cx);
6398            view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
6399        });
6400
6401        assert_eq!(
6402            editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
6403            [DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1)]
6404        );
6405
6406        editor.update(cx, |view, cx| {
6407            view.begin_selection(DisplayPoint::new(3, 3), true, 1, cx);
6408            view.update_selection(DisplayPoint::new(0, 0), 0, Vector2F::zero(), cx);
6409        });
6410
6411        assert_eq!(
6412            editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
6413            [
6414                DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1),
6415                DisplayPoint::new(3, 3)..DisplayPoint::new(0, 0)
6416            ]
6417        );
6418
6419        editor.update(cx, |view, cx| {
6420            view.end_selection(cx);
6421        });
6422
6423        assert_eq!(
6424            editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
6425            [DisplayPoint::new(3, 3)..DisplayPoint::new(0, 0)]
6426        );
6427    }
6428
6429    #[gpui::test]
6430    fn test_canceling_pending_selection(cx: &mut gpui::MutableAppContext) {
6431        populate_settings(cx);
6432        let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
6433        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
6434
6435        view.update(cx, |view, cx| {
6436            view.begin_selection(DisplayPoint::new(2, 2), false, 1, cx);
6437            assert_eq!(
6438                view.selected_display_ranges(cx),
6439                [DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2)]
6440            );
6441        });
6442
6443        view.update(cx, |view, cx| {
6444            view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
6445            assert_eq!(
6446                view.selected_display_ranges(cx),
6447                [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
6448            );
6449        });
6450
6451        view.update(cx, |view, cx| {
6452            view.cancel(&Cancel, cx);
6453            view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
6454            assert_eq!(
6455                view.selected_display_ranges(cx),
6456                [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
6457            );
6458        });
6459    }
6460
6461    #[gpui::test]
6462    fn test_navigation_history(cx: &mut gpui::MutableAppContext) {
6463        populate_settings(cx);
6464        use workspace::Item;
6465        let nav_history = Rc::new(RefCell::new(workspace::NavHistory::default()));
6466        let buffer = MultiBuffer::build_simple(&sample_text(30, 5, 'a'), cx);
6467
6468        cx.add_window(Default::default(), |cx| {
6469            let mut editor = build_editor(buffer.clone(), cx);
6470            editor.nav_history = Some(ItemNavHistory::new(nav_history.clone(), &cx.handle()));
6471
6472            // Move the cursor a small distance.
6473            // Nothing is added to the navigation history.
6474            editor.select_display_ranges(&[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)], cx);
6475            editor.select_display_ranges(&[DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0)], cx);
6476            assert!(nav_history.borrow_mut().pop_backward().is_none());
6477
6478            // Move the cursor a large distance.
6479            // The history can jump back to the previous position.
6480            editor.select_display_ranges(&[DisplayPoint::new(13, 0)..DisplayPoint::new(13, 3)], cx);
6481            let nav_entry = nav_history.borrow_mut().pop_backward().unwrap();
6482            editor.navigate(nav_entry.data.unwrap(), cx);
6483            assert_eq!(nav_entry.item.id(), cx.view_id());
6484            assert_eq!(
6485                editor.selected_display_ranges(cx),
6486                &[DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0)]
6487            );
6488            assert!(nav_history.borrow_mut().pop_backward().is_none());
6489
6490            // Move the cursor a small distance via the mouse.
6491            // Nothing is added to the navigation history.
6492            editor.begin_selection(DisplayPoint::new(5, 0), false, 1, cx);
6493            editor.end_selection(cx);
6494            assert_eq!(
6495                editor.selected_display_ranges(cx),
6496                &[DisplayPoint::new(5, 0)..DisplayPoint::new(5, 0)]
6497            );
6498            assert!(nav_history.borrow_mut().pop_backward().is_none());
6499
6500            // Move the cursor a large distance via the mouse.
6501            // The history can jump back to the previous position.
6502            editor.begin_selection(DisplayPoint::new(15, 0), false, 1, cx);
6503            editor.end_selection(cx);
6504            assert_eq!(
6505                editor.selected_display_ranges(cx),
6506                &[DisplayPoint::new(15, 0)..DisplayPoint::new(15, 0)]
6507            );
6508            let nav_entry = nav_history.borrow_mut().pop_backward().unwrap();
6509            editor.navigate(nav_entry.data.unwrap(), cx);
6510            assert_eq!(nav_entry.item.id(), cx.view_id());
6511            assert_eq!(
6512                editor.selected_display_ranges(cx),
6513                &[DisplayPoint::new(5, 0)..DisplayPoint::new(5, 0)]
6514            );
6515            assert!(nav_history.borrow_mut().pop_backward().is_none());
6516
6517            editor
6518        });
6519    }
6520
6521    #[gpui::test]
6522    fn test_cancel(cx: &mut gpui::MutableAppContext) {
6523        populate_settings(cx);
6524        let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
6525        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
6526
6527        view.update(cx, |view, cx| {
6528            view.begin_selection(DisplayPoint::new(3, 4), false, 1, cx);
6529            view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
6530            view.end_selection(cx);
6531
6532            view.begin_selection(DisplayPoint::new(0, 1), true, 1, cx);
6533            view.update_selection(DisplayPoint::new(0, 3), 0, Vector2F::zero(), cx);
6534            view.end_selection(cx);
6535            assert_eq!(
6536                view.selected_display_ranges(cx),
6537                [
6538                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
6539                    DisplayPoint::new(3, 4)..DisplayPoint::new(1, 1),
6540                ]
6541            );
6542        });
6543
6544        view.update(cx, |view, cx| {
6545            view.cancel(&Cancel, cx);
6546            assert_eq!(
6547                view.selected_display_ranges(cx),
6548                [DisplayPoint::new(3, 4)..DisplayPoint::new(1, 1)]
6549            );
6550        });
6551
6552        view.update(cx, |view, cx| {
6553            view.cancel(&Cancel, cx);
6554            assert_eq!(
6555                view.selected_display_ranges(cx),
6556                [DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1)]
6557            );
6558        });
6559    }
6560
6561    #[gpui::test]
6562    fn test_fold(cx: &mut gpui::MutableAppContext) {
6563        populate_settings(cx);
6564        let buffer = MultiBuffer::build_simple(
6565            &"
6566                impl Foo {
6567                    // Hello!
6568
6569                    fn a() {
6570                        1
6571                    }
6572
6573                    fn b() {
6574                        2
6575                    }
6576
6577                    fn c() {
6578                        3
6579                    }
6580                }
6581            "
6582            .unindent(),
6583            cx,
6584        );
6585        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer.clone(), cx));
6586
6587        view.update(cx, |view, cx| {
6588            view.select_display_ranges(&[DisplayPoint::new(8, 0)..DisplayPoint::new(12, 0)], cx);
6589            view.fold(&Fold, cx);
6590            assert_eq!(
6591                view.display_text(cx),
6592                "
6593                    impl Foo {
6594                        // Hello!
6595
6596                        fn a() {
6597                            1
6598                        }
6599
6600                        fn b() {…
6601                        }
6602
6603                        fn c() {…
6604                        }
6605                    }
6606                "
6607                .unindent(),
6608            );
6609
6610            view.fold(&Fold, cx);
6611            assert_eq!(
6612                view.display_text(cx),
6613                "
6614                    impl Foo {…
6615                    }
6616                "
6617                .unindent(),
6618            );
6619
6620            view.unfold(&Unfold, cx);
6621            assert_eq!(
6622                view.display_text(cx),
6623                "
6624                    impl Foo {
6625                        // Hello!
6626
6627                        fn a() {
6628                            1
6629                        }
6630
6631                        fn b() {…
6632                        }
6633
6634                        fn c() {…
6635                        }
6636                    }
6637                "
6638                .unindent(),
6639            );
6640
6641            view.unfold(&Unfold, cx);
6642            assert_eq!(view.display_text(cx), buffer.read(cx).read(cx).text());
6643        });
6644    }
6645
6646    #[gpui::test]
6647    fn test_move_cursor(cx: &mut gpui::MutableAppContext) {
6648        populate_settings(cx);
6649        let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
6650        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer.clone(), cx));
6651
6652        buffer.update(cx, |buffer, cx| {
6653            buffer.edit(
6654                vec![
6655                    Point::new(1, 0)..Point::new(1, 0),
6656                    Point::new(1, 1)..Point::new(1, 1),
6657                ],
6658                "\t",
6659                cx,
6660            );
6661        });
6662
6663        view.update(cx, |view, cx| {
6664            assert_eq!(
6665                view.selected_display_ranges(cx),
6666                &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
6667            );
6668
6669            view.move_down(&MoveDown, cx);
6670            assert_eq!(
6671                view.selected_display_ranges(cx),
6672                &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
6673            );
6674
6675            view.move_right(&MoveRight, cx);
6676            assert_eq!(
6677                view.selected_display_ranges(cx),
6678                &[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4)]
6679            );
6680
6681            view.move_left(&MoveLeft, cx);
6682            assert_eq!(
6683                view.selected_display_ranges(cx),
6684                &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
6685            );
6686
6687            view.move_up(&MoveUp, cx);
6688            assert_eq!(
6689                view.selected_display_ranges(cx),
6690                &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
6691            );
6692
6693            view.move_to_end(&MoveToEnd, cx);
6694            assert_eq!(
6695                view.selected_display_ranges(cx),
6696                &[DisplayPoint::new(5, 6)..DisplayPoint::new(5, 6)]
6697            );
6698
6699            view.move_to_beginning(&MoveToBeginning, cx);
6700            assert_eq!(
6701                view.selected_display_ranges(cx),
6702                &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
6703            );
6704
6705            view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 2)], cx);
6706            view.select_to_beginning(&SelectToBeginning, cx);
6707            assert_eq!(
6708                view.selected_display_ranges(cx),
6709                &[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 0)]
6710            );
6711
6712            view.select_to_end(&SelectToEnd, cx);
6713            assert_eq!(
6714                view.selected_display_ranges(cx),
6715                &[DisplayPoint::new(0, 1)..DisplayPoint::new(5, 6)]
6716            );
6717        });
6718    }
6719
6720    #[gpui::test]
6721    fn test_move_cursor_multibyte(cx: &mut gpui::MutableAppContext) {
6722        populate_settings(cx);
6723        let buffer = MultiBuffer::build_simple("ⓐⓑⓒⓓⓔ\nabcde\nαβγδε\n", cx);
6724        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer.clone(), cx));
6725
6726        assert_eq!('ⓐ'.len_utf8(), 3);
6727        assert_eq!('α'.len_utf8(), 2);
6728
6729        view.update(cx, |view, cx| {
6730            view.fold_ranges(
6731                vec![
6732                    Point::new(0, 6)..Point::new(0, 12),
6733                    Point::new(1, 2)..Point::new(1, 4),
6734                    Point::new(2, 4)..Point::new(2, 8),
6735                ],
6736                cx,
6737            );
6738            assert_eq!(view.display_text(cx), "ⓐⓑ…ⓔ\nab…e\nαβ…ε\n");
6739
6740            view.move_right(&MoveRight, cx);
6741            assert_eq!(
6742                view.selected_display_ranges(cx),
6743                &[empty_range(0, "".len())]
6744            );
6745            view.move_right(&MoveRight, cx);
6746            assert_eq!(
6747                view.selected_display_ranges(cx),
6748                &[empty_range(0, "ⓐⓑ".len())]
6749            );
6750            view.move_right(&MoveRight, cx);
6751            assert_eq!(
6752                view.selected_display_ranges(cx),
6753                &[empty_range(0, "ⓐⓑ…".len())]
6754            );
6755
6756            view.move_down(&MoveDown, cx);
6757            assert_eq!(
6758                view.selected_display_ranges(cx),
6759                &[empty_range(1, "ab…".len())]
6760            );
6761            view.move_left(&MoveLeft, cx);
6762            assert_eq!(
6763                view.selected_display_ranges(cx),
6764                &[empty_range(1, "ab".len())]
6765            );
6766            view.move_left(&MoveLeft, cx);
6767            assert_eq!(
6768                view.selected_display_ranges(cx),
6769                &[empty_range(1, "a".len())]
6770            );
6771
6772            view.move_down(&MoveDown, cx);
6773            assert_eq!(
6774                view.selected_display_ranges(cx),
6775                &[empty_range(2, "α".len())]
6776            );
6777            view.move_right(&MoveRight, cx);
6778            assert_eq!(
6779                view.selected_display_ranges(cx),
6780                &[empty_range(2, "αβ".len())]
6781            );
6782            view.move_right(&MoveRight, cx);
6783            assert_eq!(
6784                view.selected_display_ranges(cx),
6785                &[empty_range(2, "αβ…".len())]
6786            );
6787            view.move_right(&MoveRight, cx);
6788            assert_eq!(
6789                view.selected_display_ranges(cx),
6790                &[empty_range(2, "αβ…ε".len())]
6791            );
6792
6793            view.move_up(&MoveUp, cx);
6794            assert_eq!(
6795                view.selected_display_ranges(cx),
6796                &[empty_range(1, "ab…e".len())]
6797            );
6798            view.move_up(&MoveUp, cx);
6799            assert_eq!(
6800                view.selected_display_ranges(cx),
6801                &[empty_range(0, "ⓐⓑ…ⓔ".len())]
6802            );
6803            view.move_left(&MoveLeft, cx);
6804            assert_eq!(
6805                view.selected_display_ranges(cx),
6806                &[empty_range(0, "ⓐⓑ…".len())]
6807            );
6808            view.move_left(&MoveLeft, cx);
6809            assert_eq!(
6810                view.selected_display_ranges(cx),
6811                &[empty_range(0, "ⓐⓑ".len())]
6812            );
6813            view.move_left(&MoveLeft, cx);
6814            assert_eq!(
6815                view.selected_display_ranges(cx),
6816                &[empty_range(0, "".len())]
6817            );
6818        });
6819    }
6820
6821    #[gpui::test]
6822    fn test_move_cursor_different_line_lengths(cx: &mut gpui::MutableAppContext) {
6823        populate_settings(cx);
6824        let buffer = MultiBuffer::build_simple("ⓐⓑⓒⓓⓔ\nabcd\nαβγ\nabcd\nⓐⓑⓒⓓⓔ\n", cx);
6825        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer.clone(), cx));
6826        view.update(cx, |view, cx| {
6827            view.select_display_ranges(&[empty_range(0, "ⓐⓑⓒⓓⓔ".len())], cx);
6828            view.move_down(&MoveDown, cx);
6829            assert_eq!(
6830                view.selected_display_ranges(cx),
6831                &[empty_range(1, "abcd".len())]
6832            );
6833
6834            view.move_down(&MoveDown, cx);
6835            assert_eq!(
6836                view.selected_display_ranges(cx),
6837                &[empty_range(2, "αβγ".len())]
6838            );
6839
6840            view.move_down(&MoveDown, cx);
6841            assert_eq!(
6842                view.selected_display_ranges(cx),
6843                &[empty_range(3, "abcd".len())]
6844            );
6845
6846            view.move_down(&MoveDown, cx);
6847            assert_eq!(
6848                view.selected_display_ranges(cx),
6849                &[empty_range(4, "ⓐⓑⓒⓓⓔ".len())]
6850            );
6851
6852            view.move_up(&MoveUp, cx);
6853            assert_eq!(
6854                view.selected_display_ranges(cx),
6855                &[empty_range(3, "abcd".len())]
6856            );
6857
6858            view.move_up(&MoveUp, cx);
6859            assert_eq!(
6860                view.selected_display_ranges(cx),
6861                &[empty_range(2, "αβγ".len())]
6862            );
6863        });
6864    }
6865
6866    #[gpui::test]
6867    fn test_beginning_end_of_line(cx: &mut gpui::MutableAppContext) {
6868        populate_settings(cx);
6869        let buffer = MultiBuffer::build_simple("abc\n  def", cx);
6870        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
6871        view.update(cx, |view, cx| {
6872            view.select_display_ranges(
6873                &[
6874                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
6875                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4),
6876                ],
6877                cx,
6878            );
6879        });
6880
6881        view.update(cx, |view, cx| {
6882            view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
6883            assert_eq!(
6884                view.selected_display_ranges(cx),
6885                &[
6886                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
6887                    DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
6888                ]
6889            );
6890        });
6891
6892        view.update(cx, |view, cx| {
6893            view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
6894            assert_eq!(
6895                view.selected_display_ranges(cx),
6896                &[
6897                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
6898                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
6899                ]
6900            );
6901        });
6902
6903        view.update(cx, |view, cx| {
6904            view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
6905            assert_eq!(
6906                view.selected_display_ranges(cx),
6907                &[
6908                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
6909                    DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
6910                ]
6911            );
6912        });
6913
6914        view.update(cx, |view, cx| {
6915            view.move_to_end_of_line(&MoveToEndOfLine, cx);
6916            assert_eq!(
6917                view.selected_display_ranges(cx),
6918                &[
6919                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
6920                    DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
6921                ]
6922            );
6923        });
6924
6925        // Moving to the end of line again is a no-op.
6926        view.update(cx, |view, cx| {
6927            view.move_to_end_of_line(&MoveToEndOfLine, cx);
6928            assert_eq!(
6929                view.selected_display_ranges(cx),
6930                &[
6931                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
6932                    DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
6933                ]
6934            );
6935        });
6936
6937        view.update(cx, |view, cx| {
6938            view.move_left(&MoveLeft, cx);
6939            view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
6940            assert_eq!(
6941                view.selected_display_ranges(cx),
6942                &[
6943                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
6944                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 2),
6945                ]
6946            );
6947        });
6948
6949        view.update(cx, |view, cx| {
6950            view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
6951            assert_eq!(
6952                view.selected_display_ranges(cx),
6953                &[
6954                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
6955                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 0),
6956                ]
6957            );
6958        });
6959
6960        view.update(cx, |view, cx| {
6961            view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
6962            assert_eq!(
6963                view.selected_display_ranges(cx),
6964                &[
6965                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
6966                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 2),
6967                ]
6968            );
6969        });
6970
6971        view.update(cx, |view, cx| {
6972            view.select_to_end_of_line(&SelectToEndOfLine(true), cx);
6973            assert_eq!(
6974                view.selected_display_ranges(cx),
6975                &[
6976                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 3),
6977                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 5),
6978                ]
6979            );
6980        });
6981
6982        view.update(cx, |view, cx| {
6983            view.delete_to_end_of_line(&DeleteToEndOfLine, cx);
6984            assert_eq!(view.display_text(cx), "ab\n  de");
6985            assert_eq!(
6986                view.selected_display_ranges(cx),
6987                &[
6988                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
6989                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4),
6990                ]
6991            );
6992        });
6993
6994        view.update(cx, |view, cx| {
6995            view.delete_to_beginning_of_line(&DeleteToBeginningOfLine, cx);
6996            assert_eq!(view.display_text(cx), "\n");
6997            assert_eq!(
6998                view.selected_display_ranges(cx),
6999                &[
7000                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
7001                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
7002                ]
7003            );
7004        });
7005    }
7006
7007    #[gpui::test]
7008    fn test_prev_next_word_boundary(cx: &mut gpui::MutableAppContext) {
7009        populate_settings(cx);
7010        let buffer = MultiBuffer::build_simple("use std::str::{foo, bar}\n\n  {baz.qux()}", cx);
7011        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
7012        view.update(cx, |view, cx| {
7013            view.select_display_ranges(
7014                &[
7015                    DisplayPoint::new(0, 11)..DisplayPoint::new(0, 11),
7016                    DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4),
7017                ],
7018                cx,
7019            );
7020
7021            view.move_to_previous_word_start(&MoveToPreviousWordStart, cx);
7022            assert_selection_ranges(
7023                "use std::<>str::{foo, bar}\n\n  {[]baz.qux()}",
7024                vec![('<', '>'), ('[', ']')],
7025                view,
7026                cx,
7027            );
7028
7029            view.move_to_previous_word_start(&MoveToPreviousWordStart, cx);
7030            assert_selection_ranges(
7031                "use std<>::str::{foo, bar}\n\n  []{baz.qux()}",
7032                vec![('<', '>'), ('[', ']')],
7033                view,
7034                cx,
7035            );
7036
7037            view.move_to_previous_word_start(&MoveToPreviousWordStart, cx);
7038            assert_selection_ranges(
7039                "use <>std::str::{foo, bar}\n\n[]  {baz.qux()}",
7040                vec![('<', '>'), ('[', ']')],
7041                view,
7042                cx,
7043            );
7044
7045            view.move_to_previous_word_start(&MoveToPreviousWordStart, cx);
7046            assert_selection_ranges(
7047                "<>use std::str::{foo, bar}\n[]\n  {baz.qux()}",
7048                vec![('<', '>'), ('[', ']')],
7049                view,
7050                cx,
7051            );
7052
7053            view.move_to_previous_word_start(&MoveToPreviousWordStart, cx);
7054            assert_selection_ranges(
7055                "<>use std::str::{foo, bar[]}\n\n  {baz.qux()}",
7056                vec![('<', '>'), ('[', ']')],
7057                view,
7058                cx,
7059            );
7060
7061            view.move_to_next_word_end(&MoveToNextWordEnd, cx);
7062            assert_selection_ranges(
7063                "use<> std::str::{foo, bar}[]\n\n  {baz.qux()}",
7064                vec![('<', '>'), ('[', ']')],
7065                view,
7066                cx,
7067            );
7068
7069            view.move_to_next_word_end(&MoveToNextWordEnd, cx);
7070            assert_selection_ranges(
7071                "use std<>::str::{foo, bar}\n[]\n  {baz.qux()}",
7072                vec![('<', '>'), ('[', ']')],
7073                view,
7074                cx,
7075            );
7076
7077            view.move_to_next_word_end(&MoveToNextWordEnd, cx);
7078            assert_selection_ranges(
7079                "use std::<>str::{foo, bar}\n\n  {[]baz.qux()}",
7080                vec![('<', '>'), ('[', ']')],
7081                view,
7082                cx,
7083            );
7084
7085            view.move_right(&MoveRight, cx);
7086            view.select_to_previous_word_start(&SelectToPreviousWordBoundary, cx);
7087            assert_selection_ranges(
7088                "use std::>s<tr::{foo, bar}\n\n  {]b[az.qux()}",
7089                vec![('<', '>'), ('[', ']')],
7090                view,
7091                cx,
7092            );
7093
7094            view.select_to_previous_word_start(&SelectToPreviousWordBoundary, cx);
7095            assert_selection_ranges(
7096                "use std>::s<tr::{foo, bar}\n\n  ]{b[az.qux()}",
7097                vec![('<', '>'), ('[', ']')],
7098                view,
7099                cx,
7100            );
7101
7102            view.select_to_next_word_end(&SelectToNextWordBoundary, cx);
7103            assert_selection_ranges(
7104                "use std::>s<tr::{foo, bar}\n\n  {]b[az.qux()}",
7105                vec![('<', '>'), ('[', ']')],
7106                view,
7107                cx,
7108            );
7109        });
7110    }
7111
7112    #[gpui::test]
7113    fn test_prev_next_word_bounds_with_soft_wrap(cx: &mut gpui::MutableAppContext) {
7114        populate_settings(cx);
7115        let buffer = MultiBuffer::build_simple("use one::{\n    two::three::four::five\n};", cx);
7116        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
7117
7118        view.update(cx, |view, cx| {
7119            view.set_wrap_width(Some(140.), cx);
7120            assert_eq!(
7121                view.display_text(cx),
7122                "use one::{\n    two::three::\n    four::five\n};"
7123            );
7124
7125            view.select_display_ranges(&[DisplayPoint::new(1, 7)..DisplayPoint::new(1, 7)], cx);
7126
7127            view.move_to_next_word_end(&MoveToNextWordEnd, cx);
7128            assert_eq!(
7129                view.selected_display_ranges(cx),
7130                &[DisplayPoint::new(1, 9)..DisplayPoint::new(1, 9)]
7131            );
7132
7133            view.move_to_next_word_end(&MoveToNextWordEnd, cx);
7134            assert_eq!(
7135                view.selected_display_ranges(cx),
7136                &[DisplayPoint::new(1, 14)..DisplayPoint::new(1, 14)]
7137            );
7138
7139            view.move_to_next_word_end(&MoveToNextWordEnd, cx);
7140            assert_eq!(
7141                view.selected_display_ranges(cx),
7142                &[DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4)]
7143            );
7144
7145            view.move_to_next_word_end(&MoveToNextWordEnd, cx);
7146            assert_eq!(
7147                view.selected_display_ranges(cx),
7148                &[DisplayPoint::new(2, 8)..DisplayPoint::new(2, 8)]
7149            );
7150
7151            view.move_to_previous_word_start(&MoveToPreviousWordStart, cx);
7152            assert_eq!(
7153                view.selected_display_ranges(cx),
7154                &[DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4)]
7155            );
7156
7157            view.move_to_previous_word_start(&MoveToPreviousWordStart, cx);
7158            assert_eq!(
7159                view.selected_display_ranges(cx),
7160                &[DisplayPoint::new(1, 14)..DisplayPoint::new(1, 14)]
7161            );
7162        });
7163    }
7164
7165    #[gpui::test]
7166    fn test_delete_to_word_boundary(cx: &mut gpui::MutableAppContext) {
7167        populate_settings(cx);
7168        let buffer = MultiBuffer::build_simple("one two three four", cx);
7169        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer.clone(), cx));
7170
7171        view.update(cx, |view, cx| {
7172            view.select_display_ranges(
7173                &[
7174                    // an empty selection - the preceding word fragment is deleted
7175                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7176                    // characters selected - they are deleted
7177                    DisplayPoint::new(0, 9)..DisplayPoint::new(0, 12),
7178                ],
7179                cx,
7180            );
7181            view.delete_to_previous_word_start(&DeleteToPreviousWordBoundary, cx);
7182        });
7183
7184        assert_eq!(buffer.read(cx).read(cx).text(), "e two te four");
7185
7186        view.update(cx, |view, cx| {
7187            view.select_display_ranges(
7188                &[
7189                    // an empty selection - the following word fragment is deleted
7190                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
7191                    // characters selected - they are deleted
7192                    DisplayPoint::new(0, 9)..DisplayPoint::new(0, 10),
7193                ],
7194                cx,
7195            );
7196            view.delete_to_next_word_end(&DeleteToNextWordBoundary, cx);
7197        });
7198
7199        assert_eq!(buffer.read(cx).read(cx).text(), "e t te our");
7200    }
7201
7202    #[gpui::test]
7203    fn test_newline(cx: &mut gpui::MutableAppContext) {
7204        populate_settings(cx);
7205        let buffer = MultiBuffer::build_simple("aaaa\n    bbbb\n", cx);
7206        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer.clone(), cx));
7207
7208        view.update(cx, |view, cx| {
7209            view.select_display_ranges(
7210                &[
7211                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7212                    DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
7213                    DisplayPoint::new(1, 6)..DisplayPoint::new(1, 6),
7214                ],
7215                cx,
7216            );
7217
7218            view.newline(&Newline, cx);
7219            assert_eq!(view.text(cx), "aa\naa\n  \n    bb\n    bb\n");
7220        });
7221    }
7222
7223    #[gpui::test]
7224    fn test_newline_with_old_selections(cx: &mut gpui::MutableAppContext) {
7225        populate_settings(cx);
7226        let buffer = MultiBuffer::build_simple(
7227            "
7228                a
7229                b(
7230                    X
7231                )
7232                c(
7233                    X
7234                )
7235            "
7236            .unindent()
7237            .as_str(),
7238            cx,
7239        );
7240
7241        let (_, editor) = cx.add_window(Default::default(), |cx| {
7242            let mut editor = build_editor(buffer.clone(), cx);
7243            editor.select_ranges(
7244                [
7245                    Point::new(2, 4)..Point::new(2, 5),
7246                    Point::new(5, 4)..Point::new(5, 5),
7247                ],
7248                None,
7249                cx,
7250            );
7251            editor
7252        });
7253
7254        // Edit the buffer directly, deleting ranges surrounding the editor's selections
7255        buffer.update(cx, |buffer, cx| {
7256            buffer.edit(
7257                [
7258                    Point::new(1, 2)..Point::new(3, 0),
7259                    Point::new(4, 2)..Point::new(6, 0),
7260                ],
7261                "",
7262                cx,
7263            );
7264            assert_eq!(
7265                buffer.read(cx).text(),
7266                "
7267                    a
7268                    b()
7269                    c()
7270                "
7271                .unindent()
7272            );
7273        });
7274
7275        editor.update(cx, |editor, cx| {
7276            assert_eq!(
7277                editor.selected_ranges(cx),
7278                &[
7279                    Point::new(1, 2)..Point::new(1, 2),
7280                    Point::new(2, 2)..Point::new(2, 2),
7281                ],
7282            );
7283
7284            editor.newline(&Newline, cx);
7285            assert_eq!(
7286                editor.text(cx),
7287                "
7288                    a
7289                    b(
7290                    )
7291                    c(
7292                    )
7293                "
7294                .unindent()
7295            );
7296
7297            // The selections are moved after the inserted newlines
7298            assert_eq!(
7299                editor.selected_ranges(cx),
7300                &[
7301                    Point::new(2, 0)..Point::new(2, 0),
7302                    Point::new(4, 0)..Point::new(4, 0),
7303                ],
7304            );
7305        });
7306    }
7307
7308    #[gpui::test]
7309    fn test_insert_with_old_selections(cx: &mut gpui::MutableAppContext) {
7310        populate_settings(cx);
7311        let buffer = MultiBuffer::build_simple("a( X ), b( Y ), c( Z )", cx);
7312        let (_, editor) = cx.add_window(Default::default(), |cx| {
7313            let mut editor = build_editor(buffer.clone(), cx);
7314            editor.select_ranges([3..4, 11..12, 19..20], None, cx);
7315            editor
7316        });
7317
7318        // Edit the buffer directly, deleting ranges surrounding the editor's selections
7319        buffer.update(cx, |buffer, cx| {
7320            buffer.edit([2..5, 10..13, 18..21], "", cx);
7321            assert_eq!(buffer.read(cx).text(), "a(), b(), c()".unindent());
7322        });
7323
7324        editor.update(cx, |editor, cx| {
7325            assert_eq!(editor.selected_ranges(cx), &[2..2, 7..7, 12..12],);
7326
7327            editor.insert("Z", cx);
7328            assert_eq!(editor.text(cx), "a(Z), b(Z), c(Z)");
7329
7330            // The selections are moved after the inserted characters
7331            assert_eq!(editor.selected_ranges(cx), &[3..3, 9..9, 15..15],);
7332        });
7333    }
7334
7335    #[gpui::test]
7336    fn test_indent_outdent(cx: &mut gpui::MutableAppContext) {
7337        populate_settings(cx);
7338        let buffer = MultiBuffer::build_simple("  one two\nthree\n four", cx);
7339        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer.clone(), cx));
7340
7341        view.update(cx, |view, cx| {
7342            // two selections on the same line
7343            view.select_display_ranges(
7344                &[
7345                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 5),
7346                    DisplayPoint::new(0, 6)..DisplayPoint::new(0, 9),
7347                ],
7348                cx,
7349            );
7350
7351            // indent from mid-tabstop to full tabstop
7352            view.tab(&Tab, cx);
7353            assert_eq!(view.text(cx), "    one two\nthree\n four");
7354            assert_eq!(
7355                view.selected_display_ranges(cx),
7356                &[
7357                    DisplayPoint::new(0, 4)..DisplayPoint::new(0, 7),
7358                    DisplayPoint::new(0, 8)..DisplayPoint::new(0, 11),
7359                ]
7360            );
7361
7362            // outdent from 1 tabstop to 0 tabstops
7363            view.outdent(&Outdent, cx);
7364            assert_eq!(view.text(cx), "one two\nthree\n four");
7365            assert_eq!(
7366                view.selected_display_ranges(cx),
7367                &[
7368                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 3),
7369                    DisplayPoint::new(0, 4)..DisplayPoint::new(0, 7),
7370                ]
7371            );
7372
7373            // select across line ending
7374            view.select_display_ranges(&[DisplayPoint::new(1, 1)..DisplayPoint::new(2, 0)], cx);
7375
7376            // indent and outdent affect only the preceding line
7377            view.tab(&Tab, cx);
7378            assert_eq!(view.text(cx), "one two\n    three\n four");
7379            assert_eq!(
7380                view.selected_display_ranges(cx),
7381                &[DisplayPoint::new(1, 5)..DisplayPoint::new(2, 0)]
7382            );
7383            view.outdent(&Outdent, cx);
7384            assert_eq!(view.text(cx), "one two\nthree\n four");
7385            assert_eq!(
7386                view.selected_display_ranges(cx),
7387                &[DisplayPoint::new(1, 1)..DisplayPoint::new(2, 0)]
7388            );
7389
7390            // Ensure that indenting/outdenting works when the cursor is at column 0.
7391            view.select_display_ranges(&[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)], cx);
7392            view.tab(&Tab, cx);
7393            assert_eq!(view.text(cx), "one two\n    three\n four");
7394            assert_eq!(
7395                view.selected_display_ranges(cx),
7396                &[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4)]
7397            );
7398
7399            view.select_display_ranges(&[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)], cx);
7400            view.outdent(&Outdent, cx);
7401            assert_eq!(view.text(cx), "one two\nthree\n four");
7402            assert_eq!(
7403                view.selected_display_ranges(cx),
7404                &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
7405            );
7406        });
7407    }
7408
7409    #[gpui::test]
7410    fn test_backspace(cx: &mut gpui::MutableAppContext) {
7411        populate_settings(cx);
7412        let (_, view) = cx.add_window(Default::default(), |cx| {
7413            build_editor(MultiBuffer::build_simple("", cx), cx)
7414        });
7415
7416        view.update(cx, |view, cx| {
7417            view.set_text("one two three\nfour five six\nseven eight nine\nten\n", cx);
7418            view.select_display_ranges(
7419                &[
7420                    // an empty selection - the preceding character is deleted
7421                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7422                    // one character selected - it is deleted
7423                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
7424                    // a line suffix selected - it is deleted
7425                    DisplayPoint::new(2, 6)..DisplayPoint::new(3, 0),
7426                ],
7427                cx,
7428            );
7429            view.backspace(&Backspace, cx);
7430            assert_eq!(view.text(cx), "oe two three\nfou five six\nseven ten\n");
7431
7432            view.set_text("    one\n        two\n        three\n   four", cx);
7433            view.select_display_ranges(
7434                &[
7435                    // cursors at the the end of leading indent - last indent is deleted
7436                    DisplayPoint::new(0, 4)..DisplayPoint::new(0, 4),
7437                    DisplayPoint::new(1, 8)..DisplayPoint::new(1, 8),
7438                    // cursors inside leading indent - overlapping indent deletions are coalesced
7439                    DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4),
7440                    DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
7441                    DisplayPoint::new(2, 6)..DisplayPoint::new(2, 6),
7442                    // cursor at the beginning of a line - preceding newline is deleted
7443                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
7444                    // selection inside leading indent - only the selected character is deleted
7445                    DisplayPoint::new(3, 2)..DisplayPoint::new(3, 3),
7446                ],
7447                cx,
7448            );
7449            view.backspace(&Backspace, cx);
7450            assert_eq!(view.text(cx), "one\n    two\n  three  four");
7451        });
7452    }
7453
7454    #[gpui::test]
7455    fn test_delete(cx: &mut gpui::MutableAppContext) {
7456        populate_settings(cx);
7457        let buffer =
7458            MultiBuffer::build_simple("one two three\nfour five six\nseven eight nine\nten\n", cx);
7459        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer.clone(), cx));
7460
7461        view.update(cx, |view, cx| {
7462            view.select_display_ranges(
7463                &[
7464                    // an empty selection - the following character is deleted
7465                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7466                    // one character selected - it is deleted
7467                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
7468                    // a line suffix selected - it is deleted
7469                    DisplayPoint::new(2, 6)..DisplayPoint::new(3, 0),
7470                ],
7471                cx,
7472            );
7473            view.delete(&Delete, cx);
7474        });
7475
7476        assert_eq!(
7477            buffer.read(cx).read(cx).text(),
7478            "on two three\nfou five six\nseven ten\n"
7479        );
7480    }
7481
7482    #[gpui::test]
7483    fn test_delete_line(cx: &mut gpui::MutableAppContext) {
7484        populate_settings(cx);
7485        let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
7486        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
7487        view.update(cx, |view, cx| {
7488            view.select_display_ranges(
7489                &[
7490                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
7491                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 1),
7492                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
7493                ],
7494                cx,
7495            );
7496            view.delete_line(&DeleteLine, cx);
7497            assert_eq!(view.display_text(cx), "ghi");
7498            assert_eq!(
7499                view.selected_display_ranges(cx),
7500                vec![
7501                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
7502                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)
7503                ]
7504            );
7505        });
7506
7507        populate_settings(cx);
7508        let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
7509        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
7510        view.update(cx, |view, cx| {
7511            view.select_display_ranges(&[DisplayPoint::new(2, 0)..DisplayPoint::new(0, 1)], cx);
7512            view.delete_line(&DeleteLine, cx);
7513            assert_eq!(view.display_text(cx), "ghi\n");
7514            assert_eq!(
7515                view.selected_display_ranges(cx),
7516                vec![DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)]
7517            );
7518        });
7519    }
7520
7521    #[gpui::test]
7522    fn test_duplicate_line(cx: &mut gpui::MutableAppContext) {
7523        populate_settings(cx);
7524        let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
7525        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
7526        view.update(cx, |view, cx| {
7527            view.select_display_ranges(
7528                &[
7529                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
7530                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7531                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
7532                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
7533                ],
7534                cx,
7535            );
7536            view.duplicate_line(&DuplicateLine, cx);
7537            assert_eq!(view.display_text(cx), "abc\nabc\ndef\ndef\nghi\n\n");
7538            assert_eq!(
7539                view.selected_display_ranges(cx),
7540                vec![
7541                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 1),
7542                    DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
7543                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
7544                    DisplayPoint::new(6, 0)..DisplayPoint::new(6, 0),
7545                ]
7546            );
7547        });
7548
7549        let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
7550        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
7551        view.update(cx, |view, cx| {
7552            view.select_display_ranges(
7553                &[
7554                    DisplayPoint::new(0, 1)..DisplayPoint::new(1, 1),
7555                    DisplayPoint::new(1, 2)..DisplayPoint::new(2, 1),
7556                ],
7557                cx,
7558            );
7559            view.duplicate_line(&DuplicateLine, cx);
7560            assert_eq!(view.display_text(cx), "abc\ndef\nghi\nabc\ndef\nghi\n");
7561            assert_eq!(
7562                view.selected_display_ranges(cx),
7563                vec![
7564                    DisplayPoint::new(3, 1)..DisplayPoint::new(4, 1),
7565                    DisplayPoint::new(4, 2)..DisplayPoint::new(5, 1),
7566                ]
7567            );
7568        });
7569    }
7570
7571    #[gpui::test]
7572    fn test_move_line_up_down(cx: &mut gpui::MutableAppContext) {
7573        populate_settings(cx);
7574        let buffer = MultiBuffer::build_simple(&sample_text(10, 5, 'a'), cx);
7575        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
7576        view.update(cx, |view, cx| {
7577            view.fold_ranges(
7578                vec![
7579                    Point::new(0, 2)..Point::new(1, 2),
7580                    Point::new(2, 3)..Point::new(4, 1),
7581                    Point::new(7, 0)..Point::new(8, 4),
7582                ],
7583                cx,
7584            );
7585            view.select_display_ranges(
7586                &[
7587                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
7588                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
7589                    DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
7590                    DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2),
7591                ],
7592                cx,
7593            );
7594            assert_eq!(
7595                view.display_text(cx),
7596                "aa…bbb\nccc…eeee\nfffff\nggggg\n…i\njjjjj"
7597            );
7598
7599            view.move_line_up(&MoveLineUp, cx);
7600            assert_eq!(
7601                view.display_text(cx),
7602                "aa…bbb\nccc…eeee\nggggg\n…i\njjjjj\nfffff"
7603            );
7604            assert_eq!(
7605                view.selected_display_ranges(cx),
7606                vec![
7607                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
7608                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
7609                    DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3),
7610                    DisplayPoint::new(4, 0)..DisplayPoint::new(4, 2)
7611                ]
7612            );
7613        });
7614
7615        view.update(cx, |view, cx| {
7616            view.move_line_down(&MoveLineDown, cx);
7617            assert_eq!(
7618                view.display_text(cx),
7619                "ccc…eeee\naa…bbb\nfffff\nggggg\n…i\njjjjj"
7620            );
7621            assert_eq!(
7622                view.selected_display_ranges(cx),
7623                vec![
7624                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
7625                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
7626                    DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
7627                    DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2)
7628                ]
7629            );
7630        });
7631
7632        view.update(cx, |view, cx| {
7633            view.move_line_down(&MoveLineDown, cx);
7634            assert_eq!(
7635                view.display_text(cx),
7636                "ccc…eeee\nfffff\naa…bbb\nggggg\n…i\njjjjj"
7637            );
7638            assert_eq!(
7639                view.selected_display_ranges(cx),
7640                vec![
7641                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
7642                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
7643                    DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
7644                    DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2)
7645                ]
7646            );
7647        });
7648
7649        view.update(cx, |view, cx| {
7650            view.move_line_up(&MoveLineUp, cx);
7651            assert_eq!(
7652                view.display_text(cx),
7653                "ccc…eeee\naa…bbb\nggggg\n…i\njjjjj\nfffff"
7654            );
7655            assert_eq!(
7656                view.selected_display_ranges(cx),
7657                vec![
7658                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
7659                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
7660                    DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3),
7661                    DisplayPoint::new(4, 0)..DisplayPoint::new(4, 2)
7662                ]
7663            );
7664        });
7665    }
7666
7667    #[gpui::test]
7668    fn test_move_line_up_down_with_blocks(cx: &mut gpui::MutableAppContext) {
7669        populate_settings(cx);
7670        let buffer = MultiBuffer::build_simple(&sample_text(10, 5, 'a'), cx);
7671        let snapshot = buffer.read(cx).snapshot(cx);
7672        let (_, editor) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
7673        editor.update(cx, |editor, cx| {
7674            editor.insert_blocks(
7675                [BlockProperties {
7676                    position: snapshot.anchor_after(Point::new(2, 0)),
7677                    disposition: BlockDisposition::Below,
7678                    height: 1,
7679                    render: Arc::new(|_| Empty::new().boxed()),
7680                }],
7681                cx,
7682            );
7683            editor.select_ranges([Point::new(2, 0)..Point::new(2, 0)], None, cx);
7684            editor.move_line_down(&MoveLineDown, cx);
7685        });
7686    }
7687
7688    #[gpui::test]
7689    fn test_clipboard(cx: &mut gpui::MutableAppContext) {
7690        populate_settings(cx);
7691        let buffer = MultiBuffer::build_simple("one✅ two three four five six ", cx);
7692        let view = cx
7693            .add_window(Default::default(), |cx| build_editor(buffer.clone(), cx))
7694            .1;
7695
7696        // Cut with three selections. Clipboard text is divided into three slices.
7697        view.update(cx, |view, cx| {
7698            view.select_ranges(vec![0..7, 11..17, 22..27], None, cx);
7699            view.cut(&Cut, cx);
7700            assert_eq!(view.display_text(cx), "two four six ");
7701        });
7702
7703        // Paste with three cursors. Each cursor pastes one slice of the clipboard text.
7704        view.update(cx, |view, cx| {
7705            view.select_ranges(vec![4..4, 9..9, 13..13], None, cx);
7706            view.paste(&Paste, cx);
7707            assert_eq!(view.display_text(cx), "two one✅ four three six five ");
7708            assert_eq!(
7709                view.selected_display_ranges(cx),
7710                &[
7711                    DisplayPoint::new(0, 11)..DisplayPoint::new(0, 11),
7712                    DisplayPoint::new(0, 22)..DisplayPoint::new(0, 22),
7713                    DisplayPoint::new(0, 31)..DisplayPoint::new(0, 31)
7714                ]
7715            );
7716        });
7717
7718        // Paste again but with only two cursors. Since the number of cursors doesn't
7719        // match the number of slices in the clipboard, the entire clipboard text
7720        // is pasted at each cursor.
7721        view.update(cx, |view, cx| {
7722            view.select_ranges(vec![0..0, 31..31], None, cx);
7723            view.handle_input(&Input("( ".into()), cx);
7724            view.paste(&Paste, cx);
7725            view.handle_input(&Input(") ".into()), cx);
7726            assert_eq!(
7727                view.display_text(cx),
7728                "( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
7729            );
7730        });
7731
7732        view.update(cx, |view, cx| {
7733            view.select_ranges(vec![0..0], None, cx);
7734            view.handle_input(&Input("123\n4567\n89\n".into()), cx);
7735            assert_eq!(
7736                view.display_text(cx),
7737                "123\n4567\n89\n( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
7738            );
7739        });
7740
7741        // Cut with three selections, one of which is full-line.
7742        view.update(cx, |view, cx| {
7743            view.select_display_ranges(
7744                &[
7745                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 2),
7746                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
7747                    DisplayPoint::new(2, 0)..DisplayPoint::new(2, 1),
7748                ],
7749                cx,
7750            );
7751            view.cut(&Cut, cx);
7752            assert_eq!(
7753                view.display_text(cx),
7754                "13\n9\n( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
7755            );
7756        });
7757
7758        // Paste with three selections, noticing how the copied selection that was full-line
7759        // gets inserted before the second cursor.
7760        view.update(cx, |view, cx| {
7761            view.select_display_ranges(
7762                &[
7763                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
7764                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
7765                    DisplayPoint::new(2, 2)..DisplayPoint::new(2, 3),
7766                ],
7767                cx,
7768            );
7769            view.paste(&Paste, cx);
7770            assert_eq!(
7771                view.display_text(cx),
7772                "123\n4567\n9\n( 8ne✅ three five ) two one✅ four three six five ( one✅ three five ) "
7773            );
7774            assert_eq!(
7775                view.selected_display_ranges(cx),
7776                &[
7777                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7778                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
7779                    DisplayPoint::new(3, 3)..DisplayPoint::new(3, 3),
7780                ]
7781            );
7782        });
7783
7784        // Copy with a single cursor only, which writes the whole line into the clipboard.
7785        view.update(cx, |view, cx| {
7786            view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)], cx);
7787            view.copy(&Copy, cx);
7788        });
7789
7790        // Paste with three selections, noticing how the copied full-line selection is inserted
7791        // before the empty selections but replaces the selection that is non-empty.
7792        view.update(cx, |view, cx| {
7793            view.select_display_ranges(
7794                &[
7795                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
7796                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 2),
7797                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
7798                ],
7799                cx,
7800            );
7801            view.paste(&Paste, cx);
7802            assert_eq!(
7803                view.display_text(cx),
7804                "123\n123\n123\n67\n123\n9\n( 8ne✅ three five ) two one✅ four three six five ( one✅ three five ) "
7805            );
7806            assert_eq!(
7807                view.selected_display_ranges(cx),
7808                &[
7809                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
7810                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
7811                    DisplayPoint::new(5, 1)..DisplayPoint::new(5, 1),
7812                ]
7813            );
7814        });
7815    }
7816
7817    #[gpui::test]
7818    fn test_select_all(cx: &mut gpui::MutableAppContext) {
7819        populate_settings(cx);
7820        let buffer = MultiBuffer::build_simple("abc\nde\nfgh", cx);
7821        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
7822        view.update(cx, |view, cx| {
7823            view.select_all(&SelectAll, cx);
7824            assert_eq!(
7825                view.selected_display_ranges(cx),
7826                &[DisplayPoint::new(0, 0)..DisplayPoint::new(2, 3)]
7827            );
7828        });
7829    }
7830
7831    #[gpui::test]
7832    fn test_select_line(cx: &mut gpui::MutableAppContext) {
7833        populate_settings(cx);
7834        let buffer = MultiBuffer::build_simple(&sample_text(6, 5, 'a'), cx);
7835        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
7836        view.update(cx, |view, cx| {
7837            view.select_display_ranges(
7838                &[
7839                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
7840                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7841                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
7842                    DisplayPoint::new(4, 2)..DisplayPoint::new(4, 2),
7843                ],
7844                cx,
7845            );
7846            view.select_line(&SelectLine, cx);
7847            assert_eq!(
7848                view.selected_display_ranges(cx),
7849                vec![
7850                    DisplayPoint::new(0, 0)..DisplayPoint::new(2, 0),
7851                    DisplayPoint::new(4, 0)..DisplayPoint::new(5, 0),
7852                ]
7853            );
7854        });
7855
7856        view.update(cx, |view, cx| {
7857            view.select_line(&SelectLine, cx);
7858            assert_eq!(
7859                view.selected_display_ranges(cx),
7860                vec![
7861                    DisplayPoint::new(0, 0)..DisplayPoint::new(3, 0),
7862                    DisplayPoint::new(4, 0)..DisplayPoint::new(5, 5),
7863                ]
7864            );
7865        });
7866
7867        view.update(cx, |view, cx| {
7868            view.select_line(&SelectLine, cx);
7869            assert_eq!(
7870                view.selected_display_ranges(cx),
7871                vec![DisplayPoint::new(0, 0)..DisplayPoint::new(5, 5)]
7872            );
7873        });
7874    }
7875
7876    #[gpui::test]
7877    fn test_split_selection_into_lines(cx: &mut gpui::MutableAppContext) {
7878        populate_settings(cx);
7879        let buffer = MultiBuffer::build_simple(&sample_text(9, 5, 'a'), cx);
7880        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
7881        view.update(cx, |view, cx| {
7882            view.fold_ranges(
7883                vec![
7884                    Point::new(0, 2)..Point::new(1, 2),
7885                    Point::new(2, 3)..Point::new(4, 1),
7886                    Point::new(7, 0)..Point::new(8, 4),
7887                ],
7888                cx,
7889            );
7890            view.select_display_ranges(
7891                &[
7892                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
7893                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7894                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
7895                    DisplayPoint::new(4, 4)..DisplayPoint::new(4, 4),
7896                ],
7897                cx,
7898            );
7899            assert_eq!(view.display_text(cx), "aa…bbb\nccc…eeee\nfffff\nggggg\n…i");
7900        });
7901
7902        view.update(cx, |view, cx| {
7903            view.split_selection_into_lines(&SplitSelectionIntoLines, cx);
7904            assert_eq!(
7905                view.display_text(cx),
7906                "aaaaa\nbbbbb\nccc…eeee\nfffff\nggggg\n…i"
7907            );
7908            assert_eq!(
7909                view.selected_display_ranges(cx),
7910                [
7911                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
7912                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7913                    DisplayPoint::new(2, 0)..DisplayPoint::new(2, 0),
7914                    DisplayPoint::new(5, 4)..DisplayPoint::new(5, 4)
7915                ]
7916            );
7917        });
7918
7919        view.update(cx, |view, cx| {
7920            view.select_display_ranges(&[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 1)], cx);
7921            view.split_selection_into_lines(&SplitSelectionIntoLines, cx);
7922            assert_eq!(
7923                view.display_text(cx),
7924                "aaaaa\nbbbbb\nccccc\nddddd\neeeee\nfffff\nggggg\nhhhhh\niiiii"
7925            );
7926            assert_eq!(
7927                view.selected_display_ranges(cx),
7928                [
7929                    DisplayPoint::new(0, 5)..DisplayPoint::new(0, 5),
7930                    DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
7931                    DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
7932                    DisplayPoint::new(3, 5)..DisplayPoint::new(3, 5),
7933                    DisplayPoint::new(4, 5)..DisplayPoint::new(4, 5),
7934                    DisplayPoint::new(5, 5)..DisplayPoint::new(5, 5),
7935                    DisplayPoint::new(6, 5)..DisplayPoint::new(6, 5),
7936                    DisplayPoint::new(7, 0)..DisplayPoint::new(7, 0)
7937                ]
7938            );
7939        });
7940    }
7941
7942    #[gpui::test]
7943    fn test_add_selection_above_below(cx: &mut gpui::MutableAppContext) {
7944        populate_settings(cx);
7945        let buffer = MultiBuffer::build_simple("abc\ndefghi\n\njk\nlmno\n", cx);
7946        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
7947
7948        view.update(cx, |view, cx| {
7949            view.select_display_ranges(&[DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)], cx);
7950        });
7951        view.update(cx, |view, cx| {
7952            view.add_selection_above(&AddSelectionAbove, cx);
7953            assert_eq!(
7954                view.selected_display_ranges(cx),
7955                vec![
7956                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
7957                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)
7958                ]
7959            );
7960        });
7961
7962        view.update(cx, |view, cx| {
7963            view.add_selection_above(&AddSelectionAbove, cx);
7964            assert_eq!(
7965                view.selected_display_ranges(cx),
7966                vec![
7967                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
7968                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)
7969                ]
7970            );
7971        });
7972
7973        view.update(cx, |view, cx| {
7974            view.add_selection_below(&AddSelectionBelow, cx);
7975            assert_eq!(
7976                view.selected_display_ranges(cx),
7977                vec![DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)]
7978            );
7979        });
7980
7981        view.update(cx, |view, cx| {
7982            view.add_selection_below(&AddSelectionBelow, cx);
7983            assert_eq!(
7984                view.selected_display_ranges(cx),
7985                vec![
7986                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
7987                    DisplayPoint::new(4, 3)..DisplayPoint::new(4, 3)
7988                ]
7989            );
7990        });
7991
7992        view.update(cx, |view, cx| {
7993            view.add_selection_below(&AddSelectionBelow, cx);
7994            assert_eq!(
7995                view.selected_display_ranges(cx),
7996                vec![
7997                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
7998                    DisplayPoint::new(4, 3)..DisplayPoint::new(4, 3)
7999                ]
8000            );
8001        });
8002
8003        view.update(cx, |view, cx| {
8004            view.select_display_ranges(&[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)], cx);
8005        });
8006        view.update(cx, |view, cx| {
8007            view.add_selection_below(&AddSelectionBelow, cx);
8008            assert_eq!(
8009                view.selected_display_ranges(cx),
8010                vec![
8011                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
8012                    DisplayPoint::new(4, 4)..DisplayPoint::new(4, 3)
8013                ]
8014            );
8015        });
8016
8017        view.update(cx, |view, cx| {
8018            view.add_selection_below(&AddSelectionBelow, cx);
8019            assert_eq!(
8020                view.selected_display_ranges(cx),
8021                vec![
8022                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
8023                    DisplayPoint::new(4, 4)..DisplayPoint::new(4, 3)
8024                ]
8025            );
8026        });
8027
8028        view.update(cx, |view, cx| {
8029            view.add_selection_above(&AddSelectionAbove, cx);
8030            assert_eq!(
8031                view.selected_display_ranges(cx),
8032                vec![DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)]
8033            );
8034        });
8035
8036        view.update(cx, |view, cx| {
8037            view.add_selection_above(&AddSelectionAbove, cx);
8038            assert_eq!(
8039                view.selected_display_ranges(cx),
8040                vec![DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)]
8041            );
8042        });
8043
8044        view.update(cx, |view, cx| {
8045            view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(1, 4)], cx);
8046            view.add_selection_below(&AddSelectionBelow, cx);
8047            assert_eq!(
8048                view.selected_display_ranges(cx),
8049                vec![
8050                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
8051                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
8052                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
8053                ]
8054            );
8055        });
8056
8057        view.update(cx, |view, cx| {
8058            view.add_selection_below(&AddSelectionBelow, cx);
8059            assert_eq!(
8060                view.selected_display_ranges(cx),
8061                vec![
8062                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
8063                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
8064                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
8065                    DisplayPoint::new(4, 1)..DisplayPoint::new(4, 4),
8066                ]
8067            );
8068        });
8069
8070        view.update(cx, |view, cx| {
8071            view.add_selection_above(&AddSelectionAbove, cx);
8072            assert_eq!(
8073                view.selected_display_ranges(cx),
8074                vec![
8075                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
8076                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
8077                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
8078                ]
8079            );
8080        });
8081
8082        view.update(cx, |view, cx| {
8083            view.select_display_ranges(&[DisplayPoint::new(4, 3)..DisplayPoint::new(1, 1)], cx);
8084        });
8085        view.update(cx, |view, cx| {
8086            view.add_selection_above(&AddSelectionAbove, cx);
8087            assert_eq!(
8088                view.selected_display_ranges(cx),
8089                vec![
8090                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 1),
8091                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 1),
8092                    DisplayPoint::new(3, 2)..DisplayPoint::new(3, 1),
8093                    DisplayPoint::new(4, 3)..DisplayPoint::new(4, 1),
8094                ]
8095            );
8096        });
8097
8098        view.update(cx, |view, cx| {
8099            view.add_selection_below(&AddSelectionBelow, cx);
8100            assert_eq!(
8101                view.selected_display_ranges(cx),
8102                vec![
8103                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 1),
8104                    DisplayPoint::new(3, 2)..DisplayPoint::new(3, 1),
8105                    DisplayPoint::new(4, 3)..DisplayPoint::new(4, 1),
8106                ]
8107            );
8108        });
8109    }
8110
8111    #[gpui::test]
8112    async fn test_select_larger_smaller_syntax_node(cx: &mut gpui::TestAppContext) {
8113        cx.update(populate_settings);
8114        let language = Arc::new(Language::new(
8115            LanguageConfig::default(),
8116            Some(tree_sitter_rust::language()),
8117        ));
8118
8119        let text = r#"
8120            use mod1::mod2::{mod3, mod4};
8121
8122            fn fn_1(param1: bool, param2: &str) {
8123                let var1 = "text";
8124            }
8125        "#
8126        .unindent();
8127
8128        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
8129        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
8130        let (_, view) = cx.add_window(|cx| build_editor(buffer, cx));
8131        view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
8132            .await;
8133
8134        view.update(cx, |view, cx| {
8135            view.select_display_ranges(
8136                &[
8137                    DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
8138                    DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
8139                    DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
8140                ],
8141                cx,
8142            );
8143            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
8144        });
8145        assert_eq!(
8146            view.update(cx, |view, cx| view.selected_display_ranges(cx)),
8147            &[
8148                DisplayPoint::new(0, 23)..DisplayPoint::new(0, 27),
8149                DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
8150                DisplayPoint::new(3, 15)..DisplayPoint::new(3, 21),
8151            ]
8152        );
8153
8154        view.update(cx, |view, cx| {
8155            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
8156        });
8157        assert_eq!(
8158            view.update(cx, |view, cx| view.selected_display_ranges(cx)),
8159            &[
8160                DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
8161                DisplayPoint::new(4, 1)..DisplayPoint::new(2, 0),
8162            ]
8163        );
8164
8165        view.update(cx, |view, cx| {
8166            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
8167        });
8168        assert_eq!(
8169            view.update(cx, |view, cx| view.selected_display_ranges(cx)),
8170            &[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 0)]
8171        );
8172
8173        // Trying to expand the selected syntax node one more time has no effect.
8174        view.update(cx, |view, cx| {
8175            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
8176        });
8177        assert_eq!(
8178            view.update(cx, |view, cx| view.selected_display_ranges(cx)),
8179            &[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 0)]
8180        );
8181
8182        view.update(cx, |view, cx| {
8183            view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
8184        });
8185        assert_eq!(
8186            view.update(cx, |view, cx| view.selected_display_ranges(cx)),
8187            &[
8188                DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
8189                DisplayPoint::new(4, 1)..DisplayPoint::new(2, 0),
8190            ]
8191        );
8192
8193        view.update(cx, |view, cx| {
8194            view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
8195        });
8196        assert_eq!(
8197            view.update(cx, |view, cx| view.selected_display_ranges(cx)),
8198            &[
8199                DisplayPoint::new(0, 23)..DisplayPoint::new(0, 27),
8200                DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
8201                DisplayPoint::new(3, 15)..DisplayPoint::new(3, 21),
8202            ]
8203        );
8204
8205        view.update(cx, |view, cx| {
8206            view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
8207        });
8208        assert_eq!(
8209            view.update(cx, |view, cx| view.selected_display_ranges(cx)),
8210            &[
8211                DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
8212                DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
8213                DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
8214            ]
8215        );
8216
8217        // Trying to shrink the selected syntax node one more time has no effect.
8218        view.update(cx, |view, cx| {
8219            view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
8220        });
8221        assert_eq!(
8222            view.update(cx, |view, cx| view.selected_display_ranges(cx)),
8223            &[
8224                DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
8225                DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
8226                DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
8227            ]
8228        );
8229
8230        // Ensure that we keep expanding the selection if the larger selection starts or ends within
8231        // a fold.
8232        view.update(cx, |view, cx| {
8233            view.fold_ranges(
8234                vec![
8235                    Point::new(0, 21)..Point::new(0, 24),
8236                    Point::new(3, 20)..Point::new(3, 22),
8237                ],
8238                cx,
8239            );
8240            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
8241        });
8242        assert_eq!(
8243            view.update(cx, |view, cx| view.selected_display_ranges(cx)),
8244            &[
8245                DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
8246                DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
8247                DisplayPoint::new(3, 4)..DisplayPoint::new(3, 23),
8248            ]
8249        );
8250    }
8251
8252    #[gpui::test]
8253    async fn test_autoindent_selections(cx: &mut gpui::TestAppContext) {
8254        cx.update(populate_settings);
8255        let language = Arc::new(
8256            Language::new(
8257                LanguageConfig {
8258                    brackets: vec![
8259                        BracketPair {
8260                            start: "{".to_string(),
8261                            end: "}".to_string(),
8262                            close: false,
8263                            newline: true,
8264                        },
8265                        BracketPair {
8266                            start: "(".to_string(),
8267                            end: ")".to_string(),
8268                            close: false,
8269                            newline: true,
8270                        },
8271                    ],
8272                    ..Default::default()
8273                },
8274                Some(tree_sitter_rust::language()),
8275            )
8276            .with_indents_query(
8277                r#"
8278                (_ "(" ")" @end) @indent
8279                (_ "{" "}" @end) @indent
8280                "#,
8281            )
8282            .unwrap(),
8283        );
8284
8285        let text = "fn a() {}";
8286
8287        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
8288        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
8289        let (_, editor) = cx.add_window(|cx| build_editor(buffer, cx));
8290        editor
8291            .condition(&cx, |editor, cx| !editor.buffer.read(cx).is_parsing(cx))
8292            .await;
8293
8294        editor.update(cx, |editor, cx| {
8295            editor.select_ranges([5..5, 8..8, 9..9], None, cx);
8296            editor.newline(&Newline, cx);
8297            assert_eq!(editor.text(cx), "fn a(\n    \n) {\n    \n}\n");
8298            assert_eq!(
8299                editor.selected_ranges(cx),
8300                &[
8301                    Point::new(1, 4)..Point::new(1, 4),
8302                    Point::new(3, 4)..Point::new(3, 4),
8303                    Point::new(5, 0)..Point::new(5, 0)
8304                ]
8305            );
8306        });
8307    }
8308
8309    #[gpui::test]
8310    async fn test_autoclose_pairs(cx: &mut gpui::TestAppContext) {
8311        cx.update(populate_settings);
8312        let language = Arc::new(Language::new(
8313            LanguageConfig {
8314                brackets: vec![
8315                    BracketPair {
8316                        start: "{".to_string(),
8317                        end: "}".to_string(),
8318                        close: true,
8319                        newline: true,
8320                    },
8321                    BracketPair {
8322                        start: "/*".to_string(),
8323                        end: " */".to_string(),
8324                        close: true,
8325                        newline: true,
8326                    },
8327                ],
8328                autoclose_before: "})]".to_string(),
8329                ..Default::default()
8330            },
8331            Some(tree_sitter_rust::language()),
8332        ));
8333
8334        let text = r#"
8335            a
8336
8337            /
8338
8339        "#
8340        .unindent();
8341
8342        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
8343        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
8344        let (_, view) = cx.add_window(|cx| build_editor(buffer, cx));
8345        view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
8346            .await;
8347
8348        view.update(cx, |view, cx| {
8349            view.select_display_ranges(
8350                &[
8351                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
8352                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
8353                ],
8354                cx,
8355            );
8356
8357            view.handle_input(&Input("{".to_string()), cx);
8358            view.handle_input(&Input("{".to_string()), cx);
8359            view.handle_input(&Input("{".to_string()), cx);
8360            assert_eq!(
8361                view.text(cx),
8362                "
8363                {{{}}}
8364                {{{}}}
8365                /
8366
8367                "
8368                .unindent()
8369            );
8370
8371            view.move_right(&MoveRight, cx);
8372            view.handle_input(&Input("}".to_string()), cx);
8373            view.handle_input(&Input("}".to_string()), cx);
8374            view.handle_input(&Input("}".to_string()), cx);
8375            assert_eq!(
8376                view.text(cx),
8377                "
8378                {{{}}}}
8379                {{{}}}}
8380                /
8381
8382                "
8383                .unindent()
8384            );
8385
8386            view.undo(&Undo, cx);
8387            view.handle_input(&Input("/".to_string()), cx);
8388            view.handle_input(&Input("*".to_string()), cx);
8389            assert_eq!(
8390                view.text(cx),
8391                "
8392                /* */
8393                /* */
8394                /
8395
8396                "
8397                .unindent()
8398            );
8399
8400            view.undo(&Undo, cx);
8401            view.select_display_ranges(
8402                &[
8403                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
8404                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
8405                ],
8406                cx,
8407            );
8408            view.handle_input(&Input("*".to_string()), cx);
8409            assert_eq!(
8410                view.text(cx),
8411                "
8412                a
8413
8414                /*
8415                *
8416                "
8417                .unindent()
8418            );
8419
8420            // Don't autoclose if the next character isn't whitespace and isn't
8421            // listed in the language's "autoclose_before" section.
8422            view.finalize_last_transaction(cx);
8423            view.select_display_ranges(&[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)], cx);
8424            view.handle_input(&Input("{".to_string()), cx);
8425            assert_eq!(
8426                view.text(cx),
8427                "
8428                {a
8429
8430                /*
8431                *
8432                "
8433                .unindent()
8434            );
8435
8436            view.undo(&Undo, cx);
8437            view.select_display_ranges(&[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1)], cx);
8438            view.handle_input(&Input("{".to_string()), cx);
8439            assert_eq!(
8440                view.text(cx),
8441                "
8442                {a}
8443
8444                /*
8445                *
8446                "
8447                .unindent()
8448            );
8449            assert_eq!(
8450                view.selected_display_ranges(cx),
8451                [DisplayPoint::new(0, 1)..DisplayPoint::new(0, 2)]
8452            );
8453        });
8454    }
8455
8456    #[gpui::test]
8457    async fn test_snippets(cx: &mut gpui::TestAppContext) {
8458        cx.update(populate_settings);
8459
8460        let text = "
8461            a. b
8462            a. b
8463            a. b
8464        "
8465        .unindent();
8466        let buffer = cx.update(|cx| MultiBuffer::build_simple(&text, cx));
8467        let (_, editor) = cx.add_window(|cx| build_editor(buffer, cx));
8468
8469        editor.update(cx, |editor, cx| {
8470            let buffer = &editor.snapshot(cx).buffer_snapshot;
8471            let snippet = Snippet::parse("f(${1:one}, ${2:two}, ${1:three})$0").unwrap();
8472            let insertion_ranges = [
8473                Point::new(0, 2).to_offset(buffer)..Point::new(0, 2).to_offset(buffer),
8474                Point::new(1, 2).to_offset(buffer)..Point::new(1, 2).to_offset(buffer),
8475                Point::new(2, 2).to_offset(buffer)..Point::new(2, 2).to_offset(buffer),
8476            ];
8477
8478            editor
8479                .insert_snippet(&insertion_ranges, snippet, cx)
8480                .unwrap();
8481            assert_eq!(
8482                editor.text(cx),
8483                "
8484                    a.f(one, two, three) b
8485                    a.f(one, two, three) b
8486                    a.f(one, two, three) b
8487                "
8488                .unindent()
8489            );
8490            assert_eq!(
8491                editor.selected_ranges::<Point>(cx),
8492                &[
8493                    Point::new(0, 4)..Point::new(0, 7),
8494                    Point::new(0, 14)..Point::new(0, 19),
8495                    Point::new(1, 4)..Point::new(1, 7),
8496                    Point::new(1, 14)..Point::new(1, 19),
8497                    Point::new(2, 4)..Point::new(2, 7),
8498                    Point::new(2, 14)..Point::new(2, 19),
8499                ]
8500            );
8501
8502            // Can't move earlier than the first tab stop
8503            editor.move_to_prev_snippet_tabstop(cx);
8504            assert_eq!(
8505                editor.selected_ranges::<Point>(cx),
8506                &[
8507                    Point::new(0, 4)..Point::new(0, 7),
8508                    Point::new(0, 14)..Point::new(0, 19),
8509                    Point::new(1, 4)..Point::new(1, 7),
8510                    Point::new(1, 14)..Point::new(1, 19),
8511                    Point::new(2, 4)..Point::new(2, 7),
8512                    Point::new(2, 14)..Point::new(2, 19),
8513                ]
8514            );
8515
8516            assert!(editor.move_to_next_snippet_tabstop(cx));
8517            assert_eq!(
8518                editor.selected_ranges::<Point>(cx),
8519                &[
8520                    Point::new(0, 9)..Point::new(0, 12),
8521                    Point::new(1, 9)..Point::new(1, 12),
8522                    Point::new(2, 9)..Point::new(2, 12)
8523                ]
8524            );
8525
8526            editor.move_to_prev_snippet_tabstop(cx);
8527            assert_eq!(
8528                editor.selected_ranges::<Point>(cx),
8529                &[
8530                    Point::new(0, 4)..Point::new(0, 7),
8531                    Point::new(0, 14)..Point::new(0, 19),
8532                    Point::new(1, 4)..Point::new(1, 7),
8533                    Point::new(1, 14)..Point::new(1, 19),
8534                    Point::new(2, 4)..Point::new(2, 7),
8535                    Point::new(2, 14)..Point::new(2, 19),
8536                ]
8537            );
8538
8539            assert!(editor.move_to_next_snippet_tabstop(cx));
8540            assert!(editor.move_to_next_snippet_tabstop(cx));
8541            assert_eq!(
8542                editor.selected_ranges::<Point>(cx),
8543                &[
8544                    Point::new(0, 20)..Point::new(0, 20),
8545                    Point::new(1, 20)..Point::new(1, 20),
8546                    Point::new(2, 20)..Point::new(2, 20)
8547                ]
8548            );
8549
8550            // As soon as the last tab stop is reached, snippet state is gone
8551            editor.move_to_prev_snippet_tabstop(cx);
8552            assert_eq!(
8553                editor.selected_ranges::<Point>(cx),
8554                &[
8555                    Point::new(0, 20)..Point::new(0, 20),
8556                    Point::new(1, 20)..Point::new(1, 20),
8557                    Point::new(2, 20)..Point::new(2, 20)
8558                ]
8559            );
8560        });
8561    }
8562
8563    #[gpui::test]
8564    async fn test_completion(cx: &mut gpui::TestAppContext) {
8565        cx.update(populate_settings);
8566
8567        let (mut language_server_config, mut fake_servers) = LanguageServerConfig::fake();
8568        language_server_config.set_fake_capabilities(lsp::ServerCapabilities {
8569            completion_provider: Some(lsp::CompletionOptions {
8570                trigger_characters: Some(vec![".".to_string(), ":".to_string()]),
8571                ..Default::default()
8572            }),
8573            ..Default::default()
8574        });
8575        let language = Arc::new(Language::new(
8576            LanguageConfig {
8577                name: "Rust".into(),
8578                path_suffixes: vec!["rs".to_string()],
8579                language_server: Some(language_server_config),
8580                ..Default::default()
8581            },
8582            Some(tree_sitter_rust::language()),
8583        ));
8584
8585        let text = "
8586            one
8587            two
8588            three
8589        "
8590        .unindent();
8591
8592        let fs = FakeFs::new(cx.background().clone());
8593        fs.insert_file("/file.rs", text).await;
8594
8595        let project = Project::test(fs, cx);
8596        project.update(cx, |project, _| project.languages().add(language));
8597
8598        let worktree_id = project
8599            .update(cx, |project, cx| {
8600                project.find_or_create_local_worktree("/file.rs", true, cx)
8601            })
8602            .await
8603            .unwrap()
8604            .0
8605            .read_with(cx, |tree, _| tree.id());
8606        let buffer = project
8607            .update(cx, |project, cx| project.open_buffer((worktree_id, ""), cx))
8608            .await
8609            .unwrap();
8610        let mut fake_server = fake_servers.next().await.unwrap();
8611
8612        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
8613        let (_, editor) = cx.add_window(|cx| build_editor(buffer, cx));
8614
8615        editor.update(cx, |editor, cx| {
8616            editor.project = Some(project);
8617            editor.select_ranges([Point::new(0, 3)..Point::new(0, 3)], None, cx);
8618            editor.handle_input(&Input(".".to_string()), cx);
8619        });
8620
8621        handle_completion_request(
8622            &mut fake_server,
8623            "/file.rs",
8624            Point::new(0, 4),
8625            vec![
8626                (Point::new(0, 4)..Point::new(0, 4), "first_completion"),
8627                (Point::new(0, 4)..Point::new(0, 4), "second_completion"),
8628            ],
8629        )
8630        .await;
8631        editor
8632            .condition(&cx, |editor, _| editor.context_menu_visible())
8633            .await;
8634
8635        let apply_additional_edits = editor.update(cx, |editor, cx| {
8636            editor.move_down(&MoveDown, cx);
8637            let apply_additional_edits = editor
8638                .confirm_completion(&ConfirmCompletion(None), cx)
8639                .unwrap();
8640            assert_eq!(
8641                editor.text(cx),
8642                "
8643                    one.second_completion
8644                    two
8645                    three
8646                "
8647                .unindent()
8648            );
8649            apply_additional_edits
8650        });
8651
8652        handle_resolve_completion_request(
8653            &mut fake_server,
8654            Some((Point::new(2, 5)..Point::new(2, 5), "\nadditional edit")),
8655        )
8656        .await;
8657        apply_additional_edits.await.unwrap();
8658        assert_eq!(
8659            editor.read_with(cx, |editor, cx| editor.text(cx)),
8660            "
8661                one.second_completion
8662                two
8663                three
8664                additional edit
8665            "
8666            .unindent()
8667        );
8668
8669        editor.update(cx, |editor, cx| {
8670            editor.select_ranges(
8671                [
8672                    Point::new(1, 3)..Point::new(1, 3),
8673                    Point::new(2, 5)..Point::new(2, 5),
8674                ],
8675                None,
8676                cx,
8677            );
8678
8679            editor.handle_input(&Input(" ".to_string()), cx);
8680            assert!(editor.context_menu.is_none());
8681            editor.handle_input(&Input("s".to_string()), cx);
8682            assert!(editor.context_menu.is_none());
8683        });
8684
8685        handle_completion_request(
8686            &mut fake_server,
8687            "/file.rs",
8688            Point::new(2, 7),
8689            vec![
8690                (Point::new(2, 6)..Point::new(2, 7), "fourth_completion"),
8691                (Point::new(2, 6)..Point::new(2, 7), "fifth_completion"),
8692                (Point::new(2, 6)..Point::new(2, 7), "sixth_completion"),
8693            ],
8694        )
8695        .await;
8696        editor
8697            .condition(&cx, |editor, _| editor.context_menu_visible())
8698            .await;
8699
8700        editor.update(cx, |editor, cx| {
8701            editor.handle_input(&Input("i".to_string()), cx);
8702        });
8703
8704        handle_completion_request(
8705            &mut fake_server,
8706            "/file.rs",
8707            Point::new(2, 8),
8708            vec![
8709                (Point::new(2, 6)..Point::new(2, 8), "fourth_completion"),
8710                (Point::new(2, 6)..Point::new(2, 8), "fifth_completion"),
8711                (Point::new(2, 6)..Point::new(2, 8), "sixth_completion"),
8712            ],
8713        )
8714        .await;
8715        editor
8716            .condition(&cx, |editor, _| editor.context_menu_visible())
8717            .await;
8718
8719        let apply_additional_edits = editor.update(cx, |editor, cx| {
8720            let apply_additional_edits = editor
8721                .confirm_completion(&ConfirmCompletion(None), cx)
8722                .unwrap();
8723            assert_eq!(
8724                editor.text(cx),
8725                "
8726                    one.second_completion
8727                    two sixth_completion
8728                    three sixth_completion
8729                    additional edit
8730                "
8731                .unindent()
8732            );
8733            apply_additional_edits
8734        });
8735        handle_resolve_completion_request(&mut fake_server, None).await;
8736        apply_additional_edits.await.unwrap();
8737
8738        async fn handle_completion_request(
8739            fake: &mut FakeLanguageServer,
8740            path: &'static str,
8741            position: Point,
8742            completions: Vec<(Range<Point>, &'static str)>,
8743        ) {
8744            fake.handle_request::<lsp::request::Completion, _>(move |params, _| {
8745                assert_eq!(
8746                    params.text_document_position.text_document.uri,
8747                    lsp::Url::from_file_path(path).unwrap()
8748                );
8749                assert_eq!(
8750                    params.text_document_position.position,
8751                    lsp::Position::new(position.row, position.column)
8752                );
8753                Some(lsp::CompletionResponse::Array(
8754                    completions
8755                        .iter()
8756                        .map(|(range, new_text)| lsp::CompletionItem {
8757                            label: new_text.to_string(),
8758                            text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
8759                                range: lsp::Range::new(
8760                                    lsp::Position::new(range.start.row, range.start.column),
8761                                    lsp::Position::new(range.start.row, range.start.column),
8762                                ),
8763                                new_text: new_text.to_string(),
8764                            })),
8765                            ..Default::default()
8766                        })
8767                        .collect(),
8768                ))
8769            })
8770            .next()
8771            .await;
8772        }
8773
8774        async fn handle_resolve_completion_request(
8775            fake: &mut FakeLanguageServer,
8776            edit: Option<(Range<Point>, &'static str)>,
8777        ) {
8778            fake.handle_request::<lsp::request::ResolveCompletionItem, _>(move |_, _| {
8779                lsp::CompletionItem {
8780                    additional_text_edits: edit.clone().map(|(range, new_text)| {
8781                        vec![lsp::TextEdit::new(
8782                            lsp::Range::new(
8783                                lsp::Position::new(range.start.row, range.start.column),
8784                                lsp::Position::new(range.end.row, range.end.column),
8785                            ),
8786                            new_text.to_string(),
8787                        )]
8788                    }),
8789                    ..Default::default()
8790                }
8791            })
8792            .next()
8793            .await;
8794        }
8795    }
8796
8797    #[gpui::test]
8798    async fn test_toggle_comment(cx: &mut gpui::TestAppContext) {
8799        cx.update(populate_settings);
8800        let language = Arc::new(Language::new(
8801            LanguageConfig {
8802                line_comment: Some("// ".to_string()),
8803                ..Default::default()
8804            },
8805            Some(tree_sitter_rust::language()),
8806        ));
8807
8808        let text = "
8809            fn a() {
8810                //b();
8811                // c();
8812                //  d();
8813            }
8814        "
8815        .unindent();
8816
8817        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
8818        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
8819        let (_, view) = cx.add_window(|cx| build_editor(buffer, cx));
8820
8821        view.update(cx, |editor, cx| {
8822            // If multiple selections intersect a line, the line is only
8823            // toggled once.
8824            editor.select_display_ranges(
8825                &[
8826                    DisplayPoint::new(1, 3)..DisplayPoint::new(2, 3),
8827                    DisplayPoint::new(3, 5)..DisplayPoint::new(3, 6),
8828                ],
8829                cx,
8830            );
8831            editor.toggle_comments(&ToggleComments, cx);
8832            assert_eq!(
8833                editor.text(cx),
8834                "
8835                    fn a() {
8836                        b();
8837                        c();
8838                         d();
8839                    }
8840                "
8841                .unindent()
8842            );
8843
8844            // The comment prefix is inserted at the same column for every line
8845            // in a selection.
8846            editor.select_display_ranges(&[DisplayPoint::new(1, 3)..DisplayPoint::new(3, 6)], cx);
8847            editor.toggle_comments(&ToggleComments, cx);
8848            assert_eq!(
8849                editor.text(cx),
8850                "
8851                    fn a() {
8852                        // b();
8853                        // c();
8854                        //  d();
8855                    }
8856                "
8857                .unindent()
8858            );
8859
8860            // If a selection ends at the beginning of a line, that line is not toggled.
8861            editor.select_display_ranges(&[DisplayPoint::new(2, 0)..DisplayPoint::new(3, 0)], cx);
8862            editor.toggle_comments(&ToggleComments, cx);
8863            assert_eq!(
8864                editor.text(cx),
8865                "
8866                        fn a() {
8867                            // b();
8868                            c();
8869                            //  d();
8870                        }
8871                    "
8872                .unindent()
8873            );
8874        });
8875    }
8876
8877    #[gpui::test]
8878    fn test_editing_disjoint_excerpts(cx: &mut gpui::MutableAppContext) {
8879        populate_settings(cx);
8880        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(3, 4, 'a'), cx));
8881        let multibuffer = cx.add_model(|cx| {
8882            let mut multibuffer = MultiBuffer::new(0);
8883            multibuffer.push_excerpts(
8884                buffer.clone(),
8885                [
8886                    Point::new(0, 0)..Point::new(0, 4),
8887                    Point::new(1, 0)..Point::new(1, 4),
8888                ],
8889                cx,
8890            );
8891            multibuffer
8892        });
8893
8894        assert_eq!(multibuffer.read(cx).read(cx).text(), "aaaa\nbbbb");
8895
8896        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(multibuffer, cx));
8897        view.update(cx, |view, cx| {
8898            assert_eq!(view.text(cx), "aaaa\nbbbb");
8899            view.select_ranges(
8900                [
8901                    Point::new(0, 0)..Point::new(0, 0),
8902                    Point::new(1, 0)..Point::new(1, 0),
8903                ],
8904                None,
8905                cx,
8906            );
8907
8908            view.handle_input(&Input("X".to_string()), cx);
8909            assert_eq!(view.text(cx), "Xaaaa\nXbbbb");
8910            assert_eq!(
8911                view.selected_ranges(cx),
8912                [
8913                    Point::new(0, 1)..Point::new(0, 1),
8914                    Point::new(1, 1)..Point::new(1, 1),
8915                ]
8916            )
8917        });
8918    }
8919
8920    #[gpui::test]
8921    fn test_editing_overlapping_excerpts(cx: &mut gpui::MutableAppContext) {
8922        populate_settings(cx);
8923        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(3, 4, 'a'), cx));
8924        let multibuffer = cx.add_model(|cx| {
8925            let mut multibuffer = MultiBuffer::new(0);
8926            multibuffer.push_excerpts(
8927                buffer,
8928                [
8929                    Point::new(0, 0)..Point::new(1, 4),
8930                    Point::new(1, 0)..Point::new(2, 4),
8931                ],
8932                cx,
8933            );
8934            multibuffer
8935        });
8936
8937        assert_eq!(
8938            multibuffer.read(cx).read(cx).text(),
8939            "aaaa\nbbbb\nbbbb\ncccc"
8940        );
8941
8942        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(multibuffer, cx));
8943        view.update(cx, |view, cx| {
8944            view.select_ranges(
8945                [
8946                    Point::new(1, 1)..Point::new(1, 1),
8947                    Point::new(2, 3)..Point::new(2, 3),
8948                ],
8949                None,
8950                cx,
8951            );
8952
8953            view.handle_input(&Input("X".to_string()), cx);
8954            assert_eq!(view.text(cx), "aaaa\nbXbbXb\nbXbbXb\ncccc");
8955            assert_eq!(
8956                view.selected_ranges(cx),
8957                [
8958                    Point::new(1, 2)..Point::new(1, 2),
8959                    Point::new(2, 5)..Point::new(2, 5),
8960                ]
8961            );
8962
8963            view.newline(&Newline, cx);
8964            assert_eq!(view.text(cx), "aaaa\nbX\nbbX\nb\nbX\nbbX\nb\ncccc");
8965            assert_eq!(
8966                view.selected_ranges(cx),
8967                [
8968                    Point::new(2, 0)..Point::new(2, 0),
8969                    Point::new(6, 0)..Point::new(6, 0),
8970                ]
8971            );
8972        });
8973    }
8974
8975    #[gpui::test]
8976    fn test_refresh_selections(cx: &mut gpui::MutableAppContext) {
8977        populate_settings(cx);
8978        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(3, 4, 'a'), cx));
8979        let mut excerpt1_id = None;
8980        let multibuffer = cx.add_model(|cx| {
8981            let mut multibuffer = MultiBuffer::new(0);
8982            excerpt1_id = multibuffer
8983                .push_excerpts(
8984                    buffer.clone(),
8985                    [
8986                        Point::new(0, 0)..Point::new(1, 4),
8987                        Point::new(1, 0)..Point::new(2, 4),
8988                    ],
8989                    cx,
8990                )
8991                .into_iter()
8992                .next();
8993            multibuffer
8994        });
8995        assert_eq!(
8996            multibuffer.read(cx).read(cx).text(),
8997            "aaaa\nbbbb\nbbbb\ncccc"
8998        );
8999        let (_, editor) = cx.add_window(Default::default(), |cx| {
9000            let mut editor = build_editor(multibuffer.clone(), cx);
9001            let snapshot = editor.snapshot(cx);
9002            editor.select_ranges([Point::new(1, 3)..Point::new(1, 3)], None, cx);
9003            editor.begin_selection(Point::new(2, 1).to_display_point(&snapshot), true, 1, cx);
9004            assert_eq!(
9005                editor.selected_ranges(cx),
9006                [
9007                    Point::new(1, 3)..Point::new(1, 3),
9008                    Point::new(2, 1)..Point::new(2, 1),
9009                ]
9010            );
9011            editor
9012        });
9013
9014        // Refreshing selections is a no-op when excerpts haven't changed.
9015        editor.update(cx, |editor, cx| {
9016            editor.refresh_selections(cx);
9017            assert_eq!(
9018                editor.selected_ranges(cx),
9019                [
9020                    Point::new(1, 3)..Point::new(1, 3),
9021                    Point::new(2, 1)..Point::new(2, 1),
9022                ]
9023            );
9024        });
9025
9026        multibuffer.update(cx, |multibuffer, cx| {
9027            multibuffer.remove_excerpts([&excerpt1_id.unwrap()], cx);
9028        });
9029        editor.update(cx, |editor, cx| {
9030            // Removing an excerpt causes the first selection to become degenerate.
9031            assert_eq!(
9032                editor.selected_ranges(cx),
9033                [
9034                    Point::new(0, 0)..Point::new(0, 0),
9035                    Point::new(0, 1)..Point::new(0, 1)
9036                ]
9037            );
9038
9039            // Refreshing selections will relocate the first selection to the original buffer
9040            // location.
9041            editor.refresh_selections(cx);
9042            assert_eq!(
9043                editor.selected_ranges(cx),
9044                [
9045                    Point::new(0, 1)..Point::new(0, 1),
9046                    Point::new(0, 3)..Point::new(0, 3)
9047                ]
9048            );
9049            assert!(editor.pending_selection.is_some());
9050        });
9051    }
9052
9053    #[gpui::test]
9054    fn test_refresh_selections_while_selecting_with_mouse(cx: &mut gpui::MutableAppContext) {
9055        populate_settings(cx);
9056        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(3, 4, 'a'), cx));
9057        let mut excerpt1_id = None;
9058        let multibuffer = cx.add_model(|cx| {
9059            let mut multibuffer = MultiBuffer::new(0);
9060            excerpt1_id = multibuffer
9061                .push_excerpts(
9062                    buffer.clone(),
9063                    [
9064                        Point::new(0, 0)..Point::new(1, 4),
9065                        Point::new(1, 0)..Point::new(2, 4),
9066                    ],
9067                    cx,
9068                )
9069                .into_iter()
9070                .next();
9071            multibuffer
9072        });
9073        assert_eq!(
9074            multibuffer.read(cx).read(cx).text(),
9075            "aaaa\nbbbb\nbbbb\ncccc"
9076        );
9077        let (_, editor) = cx.add_window(Default::default(), |cx| {
9078            let mut editor = build_editor(multibuffer.clone(), cx);
9079            let snapshot = editor.snapshot(cx);
9080            editor.begin_selection(Point::new(1, 3).to_display_point(&snapshot), false, 1, cx);
9081            assert_eq!(
9082                editor.selected_ranges(cx),
9083                [Point::new(1, 3)..Point::new(1, 3)]
9084            );
9085            editor
9086        });
9087
9088        multibuffer.update(cx, |multibuffer, cx| {
9089            multibuffer.remove_excerpts([&excerpt1_id.unwrap()], cx);
9090        });
9091        editor.update(cx, |editor, cx| {
9092            assert_eq!(
9093                editor.selected_ranges(cx),
9094                [Point::new(0, 0)..Point::new(0, 0)]
9095            );
9096
9097            // Ensure we don't panic when selections are refreshed and that the pending selection is finalized.
9098            editor.refresh_selections(cx);
9099            assert_eq!(
9100                editor.selected_ranges(cx),
9101                [Point::new(0, 3)..Point::new(0, 3)]
9102            );
9103            assert!(editor.pending_selection.is_some());
9104        });
9105    }
9106
9107    #[gpui::test]
9108    async fn test_extra_newline_insertion(cx: &mut gpui::TestAppContext) {
9109        cx.update(populate_settings);
9110        let language = Arc::new(Language::new(
9111            LanguageConfig {
9112                brackets: vec![
9113                    BracketPair {
9114                        start: "{".to_string(),
9115                        end: "}".to_string(),
9116                        close: true,
9117                        newline: true,
9118                    },
9119                    BracketPair {
9120                        start: "/* ".to_string(),
9121                        end: " */".to_string(),
9122                        close: true,
9123                        newline: true,
9124                    },
9125                ],
9126                ..Default::default()
9127            },
9128            Some(tree_sitter_rust::language()),
9129        ));
9130
9131        let text = concat!(
9132            "{   }\n",     // Suppress rustfmt
9133            "  x\n",       //
9134            "  /*   */\n", //
9135            "x\n",         //
9136            "{{} }\n",     //
9137        );
9138
9139        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
9140        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
9141        let (_, view) = cx.add_window(|cx| build_editor(buffer, cx));
9142        view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
9143            .await;
9144
9145        view.update(cx, |view, cx| {
9146            view.select_display_ranges(
9147                &[
9148                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 3),
9149                    DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
9150                    DisplayPoint::new(4, 4)..DisplayPoint::new(4, 4),
9151                ],
9152                cx,
9153            );
9154            view.newline(&Newline, cx);
9155
9156            assert_eq!(
9157                view.buffer().read(cx).read(cx).text(),
9158                concat!(
9159                    "{ \n",    // Suppress rustfmt
9160                    "\n",      //
9161                    "}\n",     //
9162                    "  x\n",   //
9163                    "  /* \n", //
9164                    "  \n",    //
9165                    "  */\n",  //
9166                    "x\n",     //
9167                    "{{} \n",  //
9168                    "}\n",     //
9169                )
9170            );
9171        });
9172    }
9173
9174    #[gpui::test]
9175    fn test_highlighted_ranges(cx: &mut gpui::MutableAppContext) {
9176        let buffer = MultiBuffer::build_simple(&sample_text(16, 8, 'a'), cx);
9177        populate_settings(cx);
9178        let (_, editor) = cx.add_window(Default::default(), |cx| build_editor(buffer.clone(), cx));
9179
9180        editor.update(cx, |editor, cx| {
9181            struct Type1;
9182            struct Type2;
9183
9184            let buffer = buffer.read(cx).snapshot(cx);
9185
9186            let anchor_range = |range: Range<Point>| {
9187                buffer.anchor_after(range.start)..buffer.anchor_after(range.end)
9188            };
9189
9190            editor.highlight_background::<Type1>(
9191                vec![
9192                    anchor_range(Point::new(2, 1)..Point::new(2, 3)),
9193                    anchor_range(Point::new(4, 2)..Point::new(4, 4)),
9194                    anchor_range(Point::new(6, 3)..Point::new(6, 5)),
9195                    anchor_range(Point::new(8, 4)..Point::new(8, 6)),
9196                ],
9197                Color::red(),
9198                cx,
9199            );
9200            editor.highlight_background::<Type2>(
9201                vec![
9202                    anchor_range(Point::new(3, 2)..Point::new(3, 5)),
9203                    anchor_range(Point::new(5, 3)..Point::new(5, 6)),
9204                    anchor_range(Point::new(7, 4)..Point::new(7, 7)),
9205                    anchor_range(Point::new(9, 5)..Point::new(9, 8)),
9206                ],
9207                Color::green(),
9208                cx,
9209            );
9210
9211            let snapshot = editor.snapshot(cx);
9212            let mut highlighted_ranges = editor.background_highlights_in_range(
9213                anchor_range(Point::new(3, 4)..Point::new(7, 4)),
9214                &snapshot,
9215            );
9216            // Enforce a consistent ordering based on color without relying on the ordering of the
9217            // highlight's `TypeId` which is non-deterministic.
9218            highlighted_ranges.sort_unstable_by_key(|(_, color)| *color);
9219            assert_eq!(
9220                highlighted_ranges,
9221                &[
9222                    (
9223                        DisplayPoint::new(3, 2)..DisplayPoint::new(3, 5),
9224                        Color::green(),
9225                    ),
9226                    (
9227                        DisplayPoint::new(5, 3)..DisplayPoint::new(5, 6),
9228                        Color::green(),
9229                    ),
9230                    (
9231                        DisplayPoint::new(4, 2)..DisplayPoint::new(4, 4),
9232                        Color::red(),
9233                    ),
9234                    (
9235                        DisplayPoint::new(6, 3)..DisplayPoint::new(6, 5),
9236                        Color::red(),
9237                    ),
9238                ]
9239            );
9240            assert_eq!(
9241                editor.background_highlights_in_range(
9242                    anchor_range(Point::new(5, 6)..Point::new(6, 4)),
9243                    &snapshot,
9244                ),
9245                &[(
9246                    DisplayPoint::new(6, 3)..DisplayPoint::new(6, 5),
9247                    Color::red(),
9248                )]
9249            );
9250        });
9251    }
9252
9253    #[gpui::test]
9254    fn test_following(cx: &mut gpui::MutableAppContext) {
9255        let buffer = MultiBuffer::build_simple(&sample_text(16, 8, 'a'), cx);
9256        populate_settings(cx);
9257
9258        let (_, leader) = cx.add_window(Default::default(), |cx| build_editor(buffer.clone(), cx));
9259        let (_, follower) = cx.add_window(
9260            WindowOptions {
9261                bounds: WindowBounds::Fixed(RectF::from_points(vec2f(0., 0.), vec2f(10., 80.))),
9262                ..Default::default()
9263            },
9264            |cx| build_editor(buffer.clone(), cx),
9265        );
9266
9267        let pending_update = Rc::new(RefCell::new(None));
9268        follower.update(cx, {
9269            let update = pending_update.clone();
9270            |_, cx| {
9271                cx.subscribe(&leader, move |_, leader, event, cx| {
9272                    leader
9273                        .read(cx)
9274                        .add_event_to_update_proto(event, &mut *update.borrow_mut(), cx);
9275                })
9276                .detach();
9277            }
9278        });
9279
9280        // Update the selections only
9281        leader.update(cx, |leader, cx| {
9282            leader.select_ranges([1..1], None, cx);
9283        });
9284        follower.update(cx, |follower, cx| {
9285            follower
9286                .apply_update_proto(pending_update.borrow_mut().take().unwrap(), cx)
9287                .unwrap();
9288        });
9289        assert_eq!(follower.read(cx).selected_ranges(cx), vec![1..1]);
9290
9291        // Update the scroll position only
9292        leader.update(cx, |leader, cx| {
9293            leader.set_scroll_position(vec2f(1.5, 3.5), cx);
9294        });
9295        follower.update(cx, |follower, cx| {
9296            follower
9297                .apply_update_proto(pending_update.borrow_mut().take().unwrap(), cx)
9298                .unwrap();
9299        });
9300        assert_eq!(
9301            follower.update(cx, |follower, cx| follower.scroll_position(cx)),
9302            vec2f(1.5, 3.5)
9303        );
9304
9305        // Update the selections and scroll position
9306        leader.update(cx, |leader, cx| {
9307            leader.select_ranges([0..0], None, cx);
9308            leader.request_autoscroll(Autoscroll::Newest, cx);
9309            leader.set_scroll_position(vec2f(1.5, 3.5), cx);
9310        });
9311        follower.update(cx, |follower, cx| {
9312            let initial_scroll_position = follower.scroll_position(cx);
9313            follower
9314                .apply_update_proto(pending_update.borrow_mut().take().unwrap(), cx)
9315                .unwrap();
9316            assert_eq!(follower.scroll_position(cx), initial_scroll_position);
9317            assert!(follower.autoscroll_request.is_some());
9318        });
9319        assert_eq!(follower.read(cx).selected_ranges(cx), vec![0..0]);
9320
9321        // Creating a pending selection that precedes another selection
9322        leader.update(cx, |leader, cx| {
9323            leader.select_ranges([1..1], None, cx);
9324            leader.begin_selection(DisplayPoint::new(0, 0), true, 1, cx);
9325        });
9326        follower.update(cx, |follower, cx| {
9327            follower
9328                .apply_update_proto(pending_update.borrow_mut().take().unwrap(), cx)
9329                .unwrap();
9330        });
9331        assert_eq!(follower.read(cx).selected_ranges(cx), vec![0..0, 1..1]);
9332
9333        // Extend the pending selection so that it surrounds another selection
9334        leader.update(cx, |leader, cx| {
9335            leader.extend_selection(DisplayPoint::new(0, 2), 1, cx);
9336        });
9337        follower.update(cx, |follower, cx| {
9338            follower
9339                .apply_update_proto(pending_update.borrow_mut().take().unwrap(), cx)
9340                .unwrap();
9341        });
9342        assert_eq!(follower.read(cx).selected_ranges(cx), vec![0..2]);
9343    }
9344
9345    #[test]
9346    fn test_combine_syntax_and_fuzzy_match_highlights() {
9347        let string = "abcdefghijklmnop";
9348        let syntax_ranges = [
9349            (
9350                0..3,
9351                HighlightStyle {
9352                    color: Some(Color::red()),
9353                    ..Default::default()
9354                },
9355            ),
9356            (
9357                4..8,
9358                HighlightStyle {
9359                    color: Some(Color::green()),
9360                    ..Default::default()
9361                },
9362            ),
9363        ];
9364        let match_indices = [4, 6, 7, 8];
9365        assert_eq!(
9366            combine_syntax_and_fuzzy_match_highlights(
9367                &string,
9368                Default::default(),
9369                syntax_ranges.into_iter(),
9370                &match_indices,
9371            ),
9372            &[
9373                (
9374                    0..3,
9375                    HighlightStyle {
9376                        color: Some(Color::red()),
9377                        ..Default::default()
9378                    },
9379                ),
9380                (
9381                    4..5,
9382                    HighlightStyle {
9383                        color: Some(Color::green()),
9384                        weight: Some(fonts::Weight::BOLD),
9385                        ..Default::default()
9386                    },
9387                ),
9388                (
9389                    5..6,
9390                    HighlightStyle {
9391                        color: Some(Color::green()),
9392                        ..Default::default()
9393                    },
9394                ),
9395                (
9396                    6..8,
9397                    HighlightStyle {
9398                        color: Some(Color::green()),
9399                        weight: Some(fonts::Weight::BOLD),
9400                        ..Default::default()
9401                    },
9402                ),
9403                (
9404                    8..9,
9405                    HighlightStyle {
9406                        weight: Some(fonts::Weight::BOLD),
9407                        ..Default::default()
9408                    },
9409                ),
9410            ]
9411        );
9412    }
9413
9414    fn empty_range(row: usize, column: usize) -> Range<DisplayPoint> {
9415        let point = DisplayPoint::new(row as u32, column as u32);
9416        point..point
9417    }
9418
9419    fn build_editor(buffer: ModelHandle<MultiBuffer>, cx: &mut ViewContext<Editor>) -> Editor {
9420        Editor::new(EditorMode::Full, buffer, None, None, cx)
9421    }
9422
9423    fn populate_settings(cx: &mut gpui::MutableAppContext) {
9424        let settings = Settings::test(cx);
9425        cx.set_global(settings);
9426    }
9427
9428    fn assert_selection_ranges(
9429        marked_text: &str,
9430        selection_marker_pairs: Vec<(char, char)>,
9431        view: &mut Editor,
9432        cx: &mut ViewContext<Editor>,
9433    ) {
9434        let snapshot = view.snapshot(cx).display_snapshot;
9435        let mut marker_chars = Vec::new();
9436        for (start, end) in selection_marker_pairs.iter() {
9437            marker_chars.push(*start);
9438            marker_chars.push(*end);
9439        }
9440        let (_, markers) = marked_text_by(marked_text, marker_chars);
9441        let asserted_ranges: Vec<Range<DisplayPoint>> = selection_marker_pairs
9442            .iter()
9443            .map(|(start, end)| {
9444                let start = markers.get(start).unwrap()[0].to_display_point(&snapshot);
9445                let end = markers.get(end).unwrap()[0].to_display_point(&snapshot);
9446                start..end
9447            })
9448            .collect();
9449        assert_eq!(
9450            view.selected_display_ranges(cx),
9451            &asserted_ranges[..],
9452            "Assert selections are {}",
9453            marked_text
9454        );
9455    }
9456}
9457
9458trait RangeExt<T> {
9459    fn sorted(&self) -> Range<T>;
9460    fn to_inclusive(&self) -> RangeInclusive<T>;
9461}
9462
9463impl<T: Ord + Clone> RangeExt<T> for Range<T> {
9464    fn sorted(&self) -> Self {
9465        cmp::min(&self.start, &self.end).clone()..cmp::max(&self.start, &self.end).clone()
9466    }
9467
9468    fn to_inclusive(&self) -> RangeInclusive<T> {
9469        self.start.clone()..=self.end.clone()
9470    }
9471}