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!(UnfoldLines);
 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-]", UnfoldLines, 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_lines);
 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, true, 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, true, 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, true, 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.unfold_ranges([next_selected_range], false, cx);
3960                    self.update_selections(selections, Some(Autoscroll::Newest), cx);
3961                } else {
3962                    select_next_state.done = true;
3963                }
3964            }
3965
3966            self.select_next_state = Some(select_next_state);
3967        } else if selections.len() == 1 {
3968            let selection = selections.last_mut().unwrap();
3969            if selection.start == selection.end {
3970                let word_range = movement::surrounding_word(
3971                    &display_map,
3972                    selection.start.to_display_point(&display_map),
3973                );
3974                selection.start = word_range.start.to_offset(&display_map, Bias::Left);
3975                selection.end = word_range.end.to_offset(&display_map, Bias::Left);
3976                selection.goal = SelectionGoal::None;
3977                selection.reversed = false;
3978
3979                let query = buffer
3980                    .text_for_range(selection.start..selection.end)
3981                    .collect::<String>();
3982                let select_state = SelectNextState {
3983                    query: AhoCorasick::new_auto_configured(&[query]),
3984                    wordwise: true,
3985                    done: false,
3986                };
3987                self.unfold_ranges([selection.start..selection.end], false, cx);
3988                self.update_selections(selections, Some(Autoscroll::Newest), cx);
3989                self.select_next_state = Some(select_state);
3990            } else {
3991                let query = buffer
3992                    .text_for_range(selection.start..selection.end)
3993                    .collect::<String>();
3994                self.select_next_state = Some(SelectNextState {
3995                    query: AhoCorasick::new_auto_configured(&[query]),
3996                    wordwise: false,
3997                    done: false,
3998                });
3999                self.select_next(action, cx);
4000            }
4001        }
4002    }
4003
4004    pub fn toggle_comments(&mut self, _: &ToggleComments, cx: &mut ViewContext<Self>) {
4005        // Get the line comment prefix. Split its trailing whitespace into a separate string,
4006        // as that portion won't be used for detecting if a line is a comment.
4007        let full_comment_prefix =
4008            if let Some(prefix) = self.language(cx).and_then(|l| l.line_comment_prefix()) {
4009                prefix.to_string()
4010            } else {
4011                return;
4012            };
4013        let comment_prefix = full_comment_prefix.trim_end_matches(' ');
4014        let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
4015
4016        self.transact(cx, |this, cx| {
4017            let mut selections = this.local_selections::<Point>(cx);
4018            let mut all_selection_lines_are_comments = true;
4019            let mut edit_ranges = Vec::new();
4020            let mut last_toggled_row = None;
4021            this.buffer.update(cx, |buffer, cx| {
4022                for selection in &mut selections {
4023                    edit_ranges.clear();
4024                    let snapshot = buffer.snapshot(cx);
4025
4026                    let end_row =
4027                        if selection.end.row > selection.start.row && selection.end.column == 0 {
4028                            selection.end.row
4029                        } else {
4030                            selection.end.row + 1
4031                        };
4032
4033                    for row in selection.start.row..end_row {
4034                        // If multiple selections contain a given row, avoid processing that
4035                        // row more than once.
4036                        if last_toggled_row == Some(row) {
4037                            continue;
4038                        } else {
4039                            last_toggled_row = Some(row);
4040                        }
4041
4042                        if snapshot.is_line_blank(row) {
4043                            continue;
4044                        }
4045
4046                        let start = Point::new(row, snapshot.indent_column_for_line(row));
4047                        let mut line_bytes = snapshot
4048                            .bytes_in_range(start..snapshot.max_point())
4049                            .flatten()
4050                            .copied();
4051
4052                        // If this line currently begins with the line comment prefix, then record
4053                        // the range containing the prefix.
4054                        if all_selection_lines_are_comments
4055                            && line_bytes
4056                                .by_ref()
4057                                .take(comment_prefix.len())
4058                                .eq(comment_prefix.bytes())
4059                        {
4060                            // Include any whitespace that matches the comment prefix.
4061                            let matching_whitespace_len = line_bytes
4062                                .zip(comment_prefix_whitespace.bytes())
4063                                .take_while(|(a, b)| a == b)
4064                                .count()
4065                                as u32;
4066                            let end = Point::new(
4067                                row,
4068                                start.column
4069                                    + comment_prefix.len() as u32
4070                                    + matching_whitespace_len,
4071                            );
4072                            edit_ranges.push(start..end);
4073                        }
4074                        // If this line does not begin with the line comment prefix, then record
4075                        // the position where the prefix should be inserted.
4076                        else {
4077                            all_selection_lines_are_comments = false;
4078                            edit_ranges.push(start..start);
4079                        }
4080                    }
4081
4082                    if !edit_ranges.is_empty() {
4083                        if all_selection_lines_are_comments {
4084                            buffer.edit(edit_ranges.iter().cloned(), "", cx);
4085                        } else {
4086                            let min_column =
4087                                edit_ranges.iter().map(|r| r.start.column).min().unwrap();
4088                            let edit_ranges = edit_ranges.iter().map(|range| {
4089                                let position = Point::new(range.start.row, min_column);
4090                                position..position
4091                            });
4092                            buffer.edit(edit_ranges, &full_comment_prefix, cx);
4093                        }
4094                    }
4095                }
4096            });
4097
4098            this.update_selections(
4099                this.local_selections::<usize>(cx),
4100                Some(Autoscroll::Fit),
4101                cx,
4102            );
4103        });
4104    }
4105
4106    pub fn select_larger_syntax_node(
4107        &mut self,
4108        _: &SelectLargerSyntaxNode,
4109        cx: &mut ViewContext<Self>,
4110    ) {
4111        let old_selections = self.local_selections::<usize>(cx).into_boxed_slice();
4112        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
4113        let buffer = self.buffer.read(cx).snapshot(cx);
4114
4115        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
4116        let mut selected_larger_node = false;
4117        let new_selections = old_selections
4118            .iter()
4119            .map(|selection| {
4120                let old_range = selection.start..selection.end;
4121                let mut new_range = old_range.clone();
4122                while let Some(containing_range) =
4123                    buffer.range_for_syntax_ancestor(new_range.clone())
4124                {
4125                    new_range = containing_range;
4126                    if !display_map.intersects_fold(new_range.start)
4127                        && !display_map.intersects_fold(new_range.end)
4128                    {
4129                        break;
4130                    }
4131                }
4132
4133                selected_larger_node |= new_range != old_range;
4134                Selection {
4135                    id: selection.id,
4136                    start: new_range.start,
4137                    end: new_range.end,
4138                    goal: SelectionGoal::None,
4139                    reversed: selection.reversed,
4140                }
4141            })
4142            .collect::<Vec<_>>();
4143
4144        if selected_larger_node {
4145            stack.push(old_selections);
4146            self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
4147        }
4148        self.select_larger_syntax_node_stack = stack;
4149    }
4150
4151    pub fn select_smaller_syntax_node(
4152        &mut self,
4153        _: &SelectSmallerSyntaxNode,
4154        cx: &mut ViewContext<Self>,
4155    ) {
4156        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
4157        if let Some(selections) = stack.pop() {
4158            self.update_selections(selections.to_vec(), Some(Autoscroll::Fit), cx);
4159        }
4160        self.select_larger_syntax_node_stack = stack;
4161    }
4162
4163    pub fn move_to_enclosing_bracket(
4164        &mut self,
4165        _: &MoveToEnclosingBracket,
4166        cx: &mut ViewContext<Self>,
4167    ) {
4168        let mut selections = self.local_selections::<usize>(cx);
4169        let buffer = self.buffer.read(cx).snapshot(cx);
4170        for selection in &mut selections {
4171            if let Some((open_range, close_range)) =
4172                buffer.enclosing_bracket_ranges(selection.start..selection.end)
4173            {
4174                let close_range = close_range.to_inclusive();
4175                let destination = if close_range.contains(&selection.start)
4176                    && close_range.contains(&selection.end)
4177                {
4178                    open_range.end
4179                } else {
4180                    *close_range.start()
4181                };
4182                selection.start = destination;
4183                selection.end = destination;
4184            }
4185        }
4186
4187        self.update_selections(selections, Some(Autoscroll::Fit), cx);
4188    }
4189
4190    pub fn go_to_diagnostic(
4191        &mut self,
4192        &GoToDiagnostic(direction): &GoToDiagnostic,
4193        cx: &mut ViewContext<Self>,
4194    ) {
4195        let buffer = self.buffer.read(cx).snapshot(cx);
4196        let selection = self.newest_selection_with_snapshot::<usize>(&buffer);
4197        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
4198            active_diagnostics
4199                .primary_range
4200                .to_offset(&buffer)
4201                .to_inclusive()
4202        });
4203        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
4204            if active_primary_range.contains(&selection.head()) {
4205                *active_primary_range.end()
4206            } else {
4207                selection.head()
4208            }
4209        } else {
4210            selection.head()
4211        };
4212
4213        loop {
4214            let mut diagnostics = if direction == Direction::Prev {
4215                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
4216            } else {
4217                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
4218            };
4219            let group = diagnostics.find_map(|entry| {
4220                if entry.diagnostic.is_primary
4221                    && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
4222                    && !entry.range.is_empty()
4223                    && Some(entry.range.end) != active_primary_range.as_ref().map(|r| *r.end())
4224                {
4225                    Some((entry.range, entry.diagnostic.group_id))
4226                } else {
4227                    None
4228                }
4229            });
4230
4231            if let Some((primary_range, group_id)) = group {
4232                self.activate_diagnostics(group_id, cx);
4233                self.update_selections(
4234                    vec![Selection {
4235                        id: selection.id,
4236                        start: primary_range.start,
4237                        end: primary_range.start,
4238                        reversed: false,
4239                        goal: SelectionGoal::None,
4240                    }],
4241                    Some(Autoscroll::Center),
4242                    cx,
4243                );
4244                break;
4245            } else {
4246                // Cycle around to the start of the buffer, potentially moving back to the start of
4247                // the currently active diagnostic.
4248                active_primary_range.take();
4249                if direction == Direction::Prev {
4250                    if search_start == buffer.len() {
4251                        break;
4252                    } else {
4253                        search_start = buffer.len();
4254                    }
4255                } else {
4256                    if search_start == 0 {
4257                        break;
4258                    } else {
4259                        search_start = 0;
4260                    }
4261                }
4262            }
4263        }
4264    }
4265
4266    pub fn go_to_definition(
4267        workspace: &mut Workspace,
4268        _: &GoToDefinition,
4269        cx: &mut ViewContext<Workspace>,
4270    ) {
4271        let active_item = workspace.active_item(cx);
4272        let editor_handle = if let Some(editor) = active_item
4273            .as_ref()
4274            .and_then(|item| item.act_as::<Self>(cx))
4275        {
4276            editor
4277        } else {
4278            return;
4279        };
4280
4281        let editor = editor_handle.read(cx);
4282        let head = editor.newest_selection::<usize>(cx).head();
4283        let (buffer, head) =
4284            if let Some(text_anchor) = editor.buffer.read(cx).text_anchor_for_position(head, cx) {
4285                text_anchor
4286            } else {
4287                return;
4288            };
4289
4290        let project = workspace.project().clone();
4291        let definitions = project.update(cx, |project, cx| project.definition(&buffer, head, cx));
4292        cx.spawn(|workspace, mut cx| async move {
4293            let definitions = definitions.await?;
4294            workspace.update(&mut cx, |workspace, cx| {
4295                let nav_history = workspace.active_pane().read(cx).nav_history().clone();
4296                for definition in definitions {
4297                    let range = definition.range.to_offset(definition.buffer.read(cx));
4298
4299                    let target_editor_handle = workspace.open_project_item(definition.buffer, cx);
4300                    target_editor_handle.update(cx, |target_editor, cx| {
4301                        // When selecting a definition in a different buffer, disable the nav history
4302                        // to avoid creating a history entry at the previous cursor location.
4303                        if editor_handle != target_editor_handle {
4304                            nav_history.borrow_mut().disable();
4305                        }
4306                        target_editor.select_ranges([range], Some(Autoscroll::Center), cx);
4307                        nav_history.borrow_mut().enable();
4308                    });
4309                }
4310            });
4311
4312            Ok::<(), anyhow::Error>(())
4313        })
4314        .detach_and_log_err(cx);
4315    }
4316
4317    pub fn find_all_references(
4318        workspace: &mut Workspace,
4319        _: &FindAllReferences,
4320        cx: &mut ViewContext<Workspace>,
4321    ) -> Option<Task<Result<()>>> {
4322        let active_item = workspace.active_item(cx)?;
4323        let editor_handle = active_item.act_as::<Self>(cx)?;
4324
4325        let editor = editor_handle.read(cx);
4326        let head = editor.newest_selection::<usize>(cx).head();
4327        let (buffer, head) = editor.buffer.read(cx).text_anchor_for_position(head, cx)?;
4328        let replica_id = editor.replica_id(cx);
4329
4330        let project = workspace.project().clone();
4331        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
4332        Some(cx.spawn(|workspace, mut cx| async move {
4333            let mut locations = references.await?;
4334            if locations.is_empty() {
4335                return Ok(());
4336            }
4337
4338            locations.sort_by_key(|location| location.buffer.id());
4339            let mut locations = locations.into_iter().peekable();
4340            let mut ranges_to_highlight = Vec::new();
4341
4342            let excerpt_buffer = cx.add_model(|cx| {
4343                let mut symbol_name = None;
4344                let mut multibuffer = MultiBuffer::new(replica_id);
4345                while let Some(location) = locations.next() {
4346                    let buffer = location.buffer.read(cx);
4347                    let mut ranges_for_buffer = Vec::new();
4348                    let range = location.range.to_offset(buffer);
4349                    ranges_for_buffer.push(range.clone());
4350                    if symbol_name.is_none() {
4351                        symbol_name = Some(buffer.text_for_range(range).collect::<String>());
4352                    }
4353
4354                    while let Some(next_location) = locations.peek() {
4355                        if next_location.buffer == location.buffer {
4356                            ranges_for_buffer.push(next_location.range.to_offset(buffer));
4357                            locations.next();
4358                        } else {
4359                            break;
4360                        }
4361                    }
4362
4363                    ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
4364                    ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
4365                        location.buffer.clone(),
4366                        ranges_for_buffer,
4367                        1,
4368                        cx,
4369                    ));
4370                }
4371                multibuffer.with_title(format!("References to `{}`", symbol_name.unwrap()))
4372            });
4373
4374            workspace.update(&mut cx, |workspace, cx| {
4375                let editor =
4376                    cx.add_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), cx));
4377                editor.update(cx, |editor, cx| {
4378                    let color = editor.style(cx).highlighted_line_background;
4379                    editor.highlight_background::<Self>(ranges_to_highlight, color, cx);
4380                });
4381                workspace.add_item(Box::new(editor), cx);
4382            });
4383
4384            Ok(())
4385        }))
4386    }
4387
4388    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
4389        use language::ToOffset as _;
4390
4391        let project = self.project.clone()?;
4392        let selection = self.newest_anchor_selection().clone();
4393        let (cursor_buffer, cursor_buffer_position) = self
4394            .buffer
4395            .read(cx)
4396            .text_anchor_for_position(selection.head(), cx)?;
4397        let (tail_buffer, _) = self
4398            .buffer
4399            .read(cx)
4400            .text_anchor_for_position(selection.tail(), cx)?;
4401        if tail_buffer != cursor_buffer {
4402            return None;
4403        }
4404
4405        let snapshot = cursor_buffer.read(cx).snapshot();
4406        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
4407        let prepare_rename = project.update(cx, |project, cx| {
4408            project.prepare_rename(cursor_buffer, cursor_buffer_offset, cx)
4409        });
4410
4411        Some(cx.spawn(|this, mut cx| async move {
4412            if let Some(rename_range) = prepare_rename.await? {
4413                let rename_buffer_range = rename_range.to_offset(&snapshot);
4414                let cursor_offset_in_rename_range =
4415                    cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
4416
4417                this.update(&mut cx, |this, cx| {
4418                    this.take_rename(false, cx);
4419                    let style = this.style(cx);
4420                    let buffer = this.buffer.read(cx).read(cx);
4421                    let cursor_offset = selection.head().to_offset(&buffer);
4422                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
4423                    let rename_end = rename_start + rename_buffer_range.len();
4424                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
4425                    let mut old_highlight_id = None;
4426                    let old_name = buffer
4427                        .chunks(rename_start..rename_end, true)
4428                        .map(|chunk| {
4429                            if old_highlight_id.is_none() {
4430                                old_highlight_id = chunk.syntax_highlight_id;
4431                            }
4432                            chunk.text
4433                        })
4434                        .collect();
4435
4436                    drop(buffer);
4437
4438                    // Position the selection in the rename editor so that it matches the current selection.
4439                    this.show_local_selections = false;
4440                    let rename_editor = cx.add_view(|cx| {
4441                        let mut editor = Editor::single_line(None, cx);
4442                        if let Some(old_highlight_id) = old_highlight_id {
4443                            editor.override_text_style =
4444                                Some(Box::new(move |style| old_highlight_id.style(&style.syntax)));
4445                        }
4446                        editor
4447                            .buffer
4448                            .update(cx, |buffer, cx| buffer.edit([0..0], &old_name, cx));
4449                        editor.select_all(&SelectAll, cx);
4450                        editor
4451                    });
4452
4453                    let ranges = this
4454                        .clear_background_highlights::<DocumentHighlightWrite>(cx)
4455                        .into_iter()
4456                        .flat_map(|(_, ranges)| ranges)
4457                        .chain(
4458                            this.clear_background_highlights::<DocumentHighlightRead>(cx)
4459                                .into_iter()
4460                                .flat_map(|(_, ranges)| ranges),
4461                        )
4462                        .collect();
4463
4464                    this.highlight_text::<Rename>(
4465                        ranges,
4466                        HighlightStyle {
4467                            fade_out: Some(style.rename_fade),
4468                            ..Default::default()
4469                        },
4470                        cx,
4471                    );
4472                    cx.focus(&rename_editor);
4473                    let block_id = this.insert_blocks(
4474                        [BlockProperties {
4475                            position: range.start.clone(),
4476                            height: 1,
4477                            render: Arc::new({
4478                                let editor = rename_editor.clone();
4479                                move |cx: &BlockContext| {
4480                                    ChildView::new(editor.clone())
4481                                        .contained()
4482                                        .with_padding_left(cx.anchor_x)
4483                                        .boxed()
4484                                }
4485                            }),
4486                            disposition: BlockDisposition::Below,
4487                        }],
4488                        cx,
4489                    )[0];
4490                    this.pending_rename = Some(RenameState {
4491                        range,
4492                        old_name,
4493                        editor: rename_editor,
4494                        block_id,
4495                    });
4496                });
4497            }
4498
4499            Ok(())
4500        }))
4501    }
4502
4503    pub fn confirm_rename(
4504        workspace: &mut Workspace,
4505        _: &ConfirmRename,
4506        cx: &mut ViewContext<Workspace>,
4507    ) -> Option<Task<Result<()>>> {
4508        let editor = workspace.active_item(cx)?.act_as::<Editor>(cx)?;
4509
4510        let (buffer, range, old_name, new_name) = editor.update(cx, |editor, cx| {
4511            let rename = editor.take_rename(false, cx)?;
4512            let buffer = editor.buffer.read(cx);
4513            let (start_buffer, start) =
4514                buffer.text_anchor_for_position(rename.range.start.clone(), cx)?;
4515            let (end_buffer, end) =
4516                buffer.text_anchor_for_position(rename.range.end.clone(), cx)?;
4517            if start_buffer == end_buffer {
4518                let new_name = rename.editor.read(cx).text(cx);
4519                Some((start_buffer, start..end, rename.old_name, new_name))
4520            } else {
4521                None
4522            }
4523        })?;
4524
4525        let rename = workspace.project().clone().update(cx, |project, cx| {
4526            project.perform_rename(
4527                buffer.clone(),
4528                range.start.clone(),
4529                new_name.clone(),
4530                true,
4531                cx,
4532            )
4533        });
4534
4535        Some(cx.spawn(|workspace, mut cx| async move {
4536            let project_transaction = rename.await?;
4537            Self::open_project_transaction(
4538                editor.clone(),
4539                workspace,
4540                project_transaction,
4541                format!("Rename: {}{}", old_name, new_name),
4542                cx.clone(),
4543            )
4544            .await?;
4545
4546            editor.update(&mut cx, |editor, cx| {
4547                editor.refresh_document_highlights(cx);
4548            });
4549            Ok(())
4550        }))
4551    }
4552
4553    fn take_rename(
4554        &mut self,
4555        moving_cursor: bool,
4556        cx: &mut ViewContext<Self>,
4557    ) -> Option<RenameState> {
4558        let rename = self.pending_rename.take()?;
4559        self.remove_blocks([rename.block_id].into_iter().collect(), cx);
4560        self.clear_text_highlights::<Rename>(cx);
4561        self.show_local_selections = true;
4562
4563        if moving_cursor {
4564            let cursor_in_rename_editor =
4565                rename.editor.read(cx).newest_selection::<usize>(cx).head();
4566
4567            // Update the selection to match the position of the selection inside
4568            // the rename editor.
4569            let snapshot = self.buffer.read(cx).read(cx);
4570            let rename_range = rename.range.to_offset(&snapshot);
4571            let cursor_in_editor = snapshot
4572                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
4573                .min(rename_range.end);
4574            drop(snapshot);
4575
4576            self.update_selections(
4577                vec![Selection {
4578                    id: self.newest_anchor_selection().id,
4579                    start: cursor_in_editor,
4580                    end: cursor_in_editor,
4581                    reversed: false,
4582                    goal: SelectionGoal::None,
4583                }],
4584                None,
4585                cx,
4586            );
4587        }
4588
4589        Some(rename)
4590    }
4591
4592    fn invalidate_rename_range(
4593        &mut self,
4594        buffer: &MultiBufferSnapshot,
4595        cx: &mut ViewContext<Self>,
4596    ) {
4597        if let Some(rename) = self.pending_rename.as_ref() {
4598            if self.selections.len() == 1 {
4599                let head = self.selections[0].head().to_offset(buffer);
4600                let range = rename.range.to_offset(buffer).to_inclusive();
4601                if range.contains(&head) {
4602                    return;
4603                }
4604            }
4605            let rename = self.pending_rename.take().unwrap();
4606            self.remove_blocks([rename.block_id].into_iter().collect(), cx);
4607            self.clear_background_highlights::<Rename>(cx);
4608        }
4609    }
4610
4611    #[cfg(any(test, feature = "test-support"))]
4612    pub fn pending_rename(&self) -> Option<&RenameState> {
4613        self.pending_rename.as_ref()
4614    }
4615
4616    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
4617        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
4618            let buffer = self.buffer.read(cx).snapshot(cx);
4619            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
4620            let is_valid = buffer
4621                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
4622                .any(|entry| {
4623                    entry.diagnostic.is_primary
4624                        && !entry.range.is_empty()
4625                        && entry.range.start == primary_range_start
4626                        && entry.diagnostic.message == active_diagnostics.primary_message
4627                });
4628
4629            if is_valid != active_diagnostics.is_valid {
4630                active_diagnostics.is_valid = is_valid;
4631                let mut new_styles = HashMap::default();
4632                for (block_id, diagnostic) in &active_diagnostics.blocks {
4633                    new_styles.insert(
4634                        *block_id,
4635                        diagnostic_block_renderer(diagnostic.clone(), is_valid),
4636                    );
4637                }
4638                self.display_map
4639                    .update(cx, |display_map, _| display_map.replace_blocks(new_styles));
4640            }
4641        }
4642    }
4643
4644    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) {
4645        self.dismiss_diagnostics(cx);
4646        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
4647            let buffer = self.buffer.read(cx).snapshot(cx);
4648
4649            let mut primary_range = None;
4650            let mut primary_message = None;
4651            let mut group_end = Point::zero();
4652            let diagnostic_group = buffer
4653                .diagnostic_group::<Point>(group_id)
4654                .map(|entry| {
4655                    if entry.range.end > group_end {
4656                        group_end = entry.range.end;
4657                    }
4658                    if entry.diagnostic.is_primary {
4659                        primary_range = Some(entry.range.clone());
4660                        primary_message = Some(entry.diagnostic.message.clone());
4661                    }
4662                    entry
4663                })
4664                .collect::<Vec<_>>();
4665            let primary_range = primary_range.unwrap();
4666            let primary_message = primary_message.unwrap();
4667            let primary_range =
4668                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
4669
4670            let blocks = display_map
4671                .insert_blocks(
4672                    diagnostic_group.iter().map(|entry| {
4673                        let diagnostic = entry.diagnostic.clone();
4674                        let message_height = diagnostic.message.lines().count() as u8;
4675                        BlockProperties {
4676                            position: buffer.anchor_after(entry.range.start),
4677                            height: message_height,
4678                            render: diagnostic_block_renderer(diagnostic, true),
4679                            disposition: BlockDisposition::Below,
4680                        }
4681                    }),
4682                    cx,
4683                )
4684                .into_iter()
4685                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
4686                .collect();
4687
4688            Some(ActiveDiagnosticGroup {
4689                primary_range,
4690                primary_message,
4691                blocks,
4692                is_valid: true,
4693            })
4694        });
4695    }
4696
4697    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
4698        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
4699            self.display_map.update(cx, |display_map, cx| {
4700                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
4701            });
4702            cx.notify();
4703        }
4704    }
4705
4706    fn build_columnar_selection(
4707        &mut self,
4708        display_map: &DisplaySnapshot,
4709        row: u32,
4710        columns: &Range<u32>,
4711        reversed: bool,
4712    ) -> Option<Selection<Point>> {
4713        let is_empty = columns.start == columns.end;
4714        let line_len = display_map.line_len(row);
4715        if columns.start < line_len || (is_empty && columns.start == line_len) {
4716            let start = DisplayPoint::new(row, columns.start);
4717            let end = DisplayPoint::new(row, cmp::min(columns.end, line_len));
4718            Some(Selection {
4719                id: post_inc(&mut self.next_selection_id),
4720                start: start.to_point(display_map),
4721                end: end.to_point(display_map),
4722                reversed,
4723                goal: SelectionGoal::ColumnRange {
4724                    start: columns.start,
4725                    end: columns.end,
4726                },
4727            })
4728        } else {
4729            None
4730        }
4731    }
4732
4733    pub fn local_selections_in_range(
4734        &self,
4735        range: Range<Anchor>,
4736        display_map: &DisplaySnapshot,
4737    ) -> Vec<Selection<Point>> {
4738        let buffer = &display_map.buffer_snapshot;
4739
4740        let start_ix = match self
4741            .selections
4742            .binary_search_by(|probe| probe.end.cmp(&range.start, &buffer))
4743        {
4744            Ok(ix) | Err(ix) => ix,
4745        };
4746        let end_ix = match self
4747            .selections
4748            .binary_search_by(|probe| probe.start.cmp(&range.end, &buffer))
4749        {
4750            Ok(ix) => ix + 1,
4751            Err(ix) => ix,
4752        };
4753
4754        fn point_selection(
4755            selection: &Selection<Anchor>,
4756            buffer: &MultiBufferSnapshot,
4757        ) -> Selection<Point> {
4758            let start = selection.start.to_point(&buffer);
4759            let end = selection.end.to_point(&buffer);
4760            Selection {
4761                id: selection.id,
4762                start,
4763                end,
4764                reversed: selection.reversed,
4765                goal: selection.goal,
4766            }
4767        }
4768
4769        self.selections[start_ix..end_ix]
4770            .iter()
4771            .chain(
4772                self.pending_selection
4773                    .as_ref()
4774                    .map(|pending| &pending.selection),
4775            )
4776            .map(|s| point_selection(s, &buffer))
4777            .collect()
4778    }
4779
4780    pub fn local_selections<'a, D>(&self, cx: &'a AppContext) -> Vec<Selection<D>>
4781    where
4782        D: 'a + TextDimension + Ord + Sub<D, Output = D>,
4783    {
4784        let buffer = self.buffer.read(cx).snapshot(cx);
4785        let mut selections = self
4786            .resolve_selections::<D, _>(self.selections.iter(), &buffer)
4787            .peekable();
4788
4789        let mut pending_selection = self.pending_selection::<D>(&buffer);
4790
4791        iter::from_fn(move || {
4792            if let Some(pending) = pending_selection.as_mut() {
4793                while let Some(next_selection) = selections.peek() {
4794                    if pending.start <= next_selection.end && pending.end >= next_selection.start {
4795                        let next_selection = selections.next().unwrap();
4796                        if next_selection.start < pending.start {
4797                            pending.start = next_selection.start;
4798                        }
4799                        if next_selection.end > pending.end {
4800                            pending.end = next_selection.end;
4801                        }
4802                    } else if next_selection.end < pending.start {
4803                        return selections.next();
4804                    } else {
4805                        break;
4806                    }
4807                }
4808
4809                pending_selection.take()
4810            } else {
4811                selections.next()
4812            }
4813        })
4814        .collect()
4815    }
4816
4817    fn resolve_selections<'a, D, I>(
4818        &self,
4819        selections: I,
4820        snapshot: &MultiBufferSnapshot,
4821    ) -> impl 'a + Iterator<Item = Selection<D>>
4822    where
4823        D: TextDimension + Ord + Sub<D, Output = D>,
4824        I: 'a + IntoIterator<Item = &'a Selection<Anchor>>,
4825    {
4826        let (to_summarize, selections) = selections.into_iter().tee();
4827        let mut summaries = snapshot
4828            .summaries_for_anchors::<D, _>(to_summarize.flat_map(|s| [&s.start, &s.end]))
4829            .into_iter();
4830        selections.map(move |s| Selection {
4831            id: s.id,
4832            start: summaries.next().unwrap(),
4833            end: summaries.next().unwrap(),
4834            reversed: s.reversed,
4835            goal: s.goal,
4836        })
4837    }
4838
4839    fn pending_selection<D: TextDimension + Ord + Sub<D, Output = D>>(
4840        &self,
4841        snapshot: &MultiBufferSnapshot,
4842    ) -> Option<Selection<D>> {
4843        self.pending_selection
4844            .as_ref()
4845            .map(|pending| self.resolve_selection(&pending.selection, &snapshot))
4846    }
4847
4848    fn resolve_selection<D: TextDimension + Ord + Sub<D, Output = D>>(
4849        &self,
4850        selection: &Selection<Anchor>,
4851        buffer: &MultiBufferSnapshot,
4852    ) -> Selection<D> {
4853        Selection {
4854            id: selection.id,
4855            start: selection.start.summary::<D>(&buffer),
4856            end: selection.end.summary::<D>(&buffer),
4857            reversed: selection.reversed,
4858            goal: selection.goal,
4859        }
4860    }
4861
4862    fn selection_count<'a>(&self) -> usize {
4863        let mut count = self.selections.len();
4864        if self.pending_selection.is_some() {
4865            count += 1;
4866        }
4867        count
4868    }
4869
4870    pub fn oldest_selection<D: TextDimension + Ord + Sub<D, Output = D>>(
4871        &self,
4872        cx: &AppContext,
4873    ) -> Selection<D> {
4874        let snapshot = self.buffer.read(cx).read(cx);
4875        self.selections
4876            .iter()
4877            .min_by_key(|s| s.id)
4878            .map(|selection| self.resolve_selection(selection, &snapshot))
4879            .or_else(|| self.pending_selection(&snapshot))
4880            .unwrap()
4881    }
4882
4883    pub fn newest_selection<D: TextDimension + Ord + Sub<D, Output = D>>(
4884        &self,
4885        cx: &AppContext,
4886    ) -> Selection<D> {
4887        self.resolve_selection(
4888            self.newest_anchor_selection(),
4889            &self.buffer.read(cx).read(cx),
4890        )
4891    }
4892
4893    pub fn newest_selection_with_snapshot<D: TextDimension + Ord + Sub<D, Output = D>>(
4894        &self,
4895        snapshot: &MultiBufferSnapshot,
4896    ) -> Selection<D> {
4897        self.resolve_selection(self.newest_anchor_selection(), snapshot)
4898    }
4899
4900    pub fn newest_anchor_selection(&self) -> &Selection<Anchor> {
4901        self.pending_selection
4902            .as_ref()
4903            .map(|s| &s.selection)
4904            .or_else(|| self.selections.iter().max_by_key(|s| s.id))
4905            .unwrap()
4906    }
4907
4908    pub fn update_selections<T>(
4909        &mut self,
4910        mut selections: Vec<Selection<T>>,
4911        autoscroll: Option<Autoscroll>,
4912        cx: &mut ViewContext<Self>,
4913    ) where
4914        T: ToOffset + ToPoint + Ord + std::marker::Copy + std::fmt::Debug,
4915    {
4916        let buffer = self.buffer.read(cx).snapshot(cx);
4917        selections.sort_unstable_by_key(|s| s.start);
4918
4919        // Merge overlapping selections.
4920        let mut i = 1;
4921        while i < selections.len() {
4922            if selections[i - 1].end >= selections[i].start {
4923                let removed = selections.remove(i);
4924                if removed.start < selections[i - 1].start {
4925                    selections[i - 1].start = removed.start;
4926                }
4927                if removed.end > selections[i - 1].end {
4928                    selections[i - 1].end = removed.end;
4929                }
4930            } else {
4931                i += 1;
4932            }
4933        }
4934
4935        if let Some(autoscroll) = autoscroll {
4936            self.request_autoscroll(autoscroll, cx);
4937        }
4938
4939        self.set_selections(
4940            Arc::from_iter(selections.into_iter().map(|selection| {
4941                let end_bias = if selection.end > selection.start {
4942                    Bias::Left
4943                } else {
4944                    Bias::Right
4945                };
4946                Selection {
4947                    id: selection.id,
4948                    start: buffer.anchor_after(selection.start),
4949                    end: buffer.anchor_at(selection.end, end_bias),
4950                    reversed: selection.reversed,
4951                    goal: selection.goal,
4952                }
4953            })),
4954            None,
4955            true,
4956            cx,
4957        );
4958    }
4959
4960    pub fn set_selections_from_remote(
4961        &mut self,
4962        mut selections: Vec<Selection<Anchor>>,
4963        cx: &mut ViewContext<Self>,
4964    ) {
4965        let buffer = self.buffer.read(cx);
4966        let buffer = buffer.read(cx);
4967        selections.sort_by(|a, b| {
4968            a.start
4969                .cmp(&b.start, &*buffer)
4970                .then_with(|| b.end.cmp(&a.end, &*buffer))
4971        });
4972
4973        // Merge overlapping selections
4974        let mut i = 1;
4975        while i < selections.len() {
4976            if selections[i - 1]
4977                .end
4978                .cmp(&selections[i].start, &*buffer)
4979                .is_ge()
4980            {
4981                let removed = selections.remove(i);
4982                if removed
4983                    .start
4984                    .cmp(&selections[i - 1].start, &*buffer)
4985                    .is_lt()
4986                {
4987                    selections[i - 1].start = removed.start;
4988                }
4989                if removed.end.cmp(&selections[i - 1].end, &*buffer).is_gt() {
4990                    selections[i - 1].end = removed.end;
4991                }
4992            } else {
4993                i += 1;
4994            }
4995        }
4996
4997        drop(buffer);
4998        self.set_selections(selections.into(), None, false, cx);
4999    }
5000
5001    /// Compute new ranges for any selections that were located in excerpts that have
5002    /// since been removed.
5003    ///
5004    /// Returns a `HashMap` indicating which selections whose former head position
5005    /// was no longer present. The keys of the map are selection ids. The values are
5006    /// the id of the new excerpt where the head of the selection has been moved.
5007    pub fn refresh_selections(&mut self, cx: &mut ViewContext<Self>) -> HashMap<usize, ExcerptId> {
5008        let snapshot = self.buffer.read(cx).read(cx);
5009        let mut selections_with_lost_position = HashMap::default();
5010
5011        let mut pending_selection = self.pending_selection.take();
5012        if let Some(pending) = pending_selection.as_mut() {
5013            let anchors =
5014                snapshot.refresh_anchors([&pending.selection.start, &pending.selection.end]);
5015            let (_, start, kept_start) = anchors[0].clone();
5016            let (_, end, kept_end) = anchors[1].clone();
5017            let kept_head = if pending.selection.reversed {
5018                kept_start
5019            } else {
5020                kept_end
5021            };
5022            if !kept_head {
5023                selections_with_lost_position.insert(
5024                    pending.selection.id,
5025                    pending.selection.head().excerpt_id.clone(),
5026                );
5027            }
5028
5029            pending.selection.start = start;
5030            pending.selection.end = end;
5031        }
5032
5033        let anchors_with_status = snapshot.refresh_anchors(
5034            self.selections
5035                .iter()
5036                .flat_map(|selection| [&selection.start, &selection.end]),
5037        );
5038        self.selections = anchors_with_status
5039            .chunks(2)
5040            .map(|selection_anchors| {
5041                let (anchor_ix, start, kept_start) = selection_anchors[0].clone();
5042                let (_, end, kept_end) = selection_anchors[1].clone();
5043                let selection = &self.selections[anchor_ix / 2];
5044                let kept_head = if selection.reversed {
5045                    kept_start
5046                } else {
5047                    kept_end
5048                };
5049                if !kept_head {
5050                    selections_with_lost_position
5051                        .insert(selection.id, selection.head().excerpt_id.clone());
5052                }
5053
5054                Selection {
5055                    id: selection.id,
5056                    start,
5057                    end,
5058                    reversed: selection.reversed,
5059                    goal: selection.goal,
5060                }
5061            })
5062            .collect();
5063        drop(snapshot);
5064
5065        let new_selections = self.local_selections::<usize>(cx);
5066        if !new_selections.is_empty() {
5067            self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
5068        }
5069        self.pending_selection = pending_selection;
5070
5071        selections_with_lost_position
5072    }
5073
5074    fn set_selections(
5075        &mut self,
5076        selections: Arc<[Selection<Anchor>]>,
5077        pending_selection: Option<PendingSelection>,
5078        local: bool,
5079        cx: &mut ViewContext<Self>,
5080    ) {
5081        assert!(
5082            !selections.is_empty() || pending_selection.is_some(),
5083            "must have at least one selection"
5084        );
5085
5086        let old_cursor_position = self.newest_anchor_selection().head();
5087
5088        self.selections = selections;
5089        self.pending_selection = pending_selection;
5090        if self.focused && self.leader_replica_id.is_none() {
5091            self.buffer.update(cx, |buffer, cx| {
5092                buffer.set_active_selections(&self.selections, cx)
5093            });
5094        }
5095
5096        let display_map = self
5097            .display_map
5098            .update(cx, |display_map, cx| display_map.snapshot(cx));
5099        let buffer = &display_map.buffer_snapshot;
5100        self.add_selections_state = None;
5101        self.select_next_state = None;
5102        self.select_larger_syntax_node_stack.clear();
5103        self.autoclose_stack.invalidate(&self.selections, &buffer);
5104        self.snippet_stack.invalidate(&self.selections, &buffer);
5105        self.invalidate_rename_range(&buffer, cx);
5106
5107        let new_cursor_position = self.newest_anchor_selection().head();
5108
5109        self.push_to_nav_history(
5110            old_cursor_position.clone(),
5111            Some(new_cursor_position.to_point(&buffer)),
5112            cx,
5113        );
5114
5115        if local {
5116            let completion_menu = match self.context_menu.as_mut() {
5117                Some(ContextMenu::Completions(menu)) => Some(menu),
5118                _ => {
5119                    self.context_menu.take();
5120                    None
5121                }
5122            };
5123
5124            if let Some(completion_menu) = completion_menu {
5125                let cursor_position = new_cursor_position.to_offset(&buffer);
5126                let (word_range, kind) =
5127                    buffer.surrounding_word(completion_menu.initial_position.clone());
5128                if kind == Some(CharKind::Word)
5129                    && word_range.to_inclusive().contains(&cursor_position)
5130                {
5131                    let query = Self::completion_query(&buffer, cursor_position);
5132                    cx.background()
5133                        .block(completion_menu.filter(query.as_deref(), cx.background().clone()));
5134                    self.show_completions(&ShowCompletions, cx);
5135                } else {
5136                    self.hide_context_menu(cx);
5137                }
5138            }
5139
5140            if old_cursor_position.to_display_point(&display_map).row()
5141                != new_cursor_position.to_display_point(&display_map).row()
5142            {
5143                self.available_code_actions.take();
5144            }
5145            self.refresh_code_actions(cx);
5146            self.refresh_document_highlights(cx);
5147        }
5148
5149        self.pause_cursor_blinking(cx);
5150        cx.emit(Event::SelectionsChanged { local });
5151    }
5152
5153    pub fn request_autoscroll(&mut self, autoscroll: Autoscroll, cx: &mut ViewContext<Self>) {
5154        self.autoscroll_request = Some((autoscroll, true));
5155        cx.notify();
5156    }
5157
5158    fn request_autoscroll_remotely(&mut self, autoscroll: Autoscroll, cx: &mut ViewContext<Self>) {
5159        self.autoscroll_request = Some((autoscroll, false));
5160        cx.notify();
5161    }
5162
5163    pub fn transact(
5164        &mut self,
5165        cx: &mut ViewContext<Self>,
5166        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
5167    ) {
5168        self.start_transaction_at(Instant::now(), cx);
5169        update(self, cx);
5170        self.end_transaction_at(Instant::now(), cx);
5171    }
5172
5173    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
5174        self.end_selection(cx);
5175        if let Some(tx_id) = self
5176            .buffer
5177            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
5178        {
5179            self.selection_history
5180                .insert(tx_id, (self.selections.clone(), None));
5181        }
5182    }
5183
5184    fn end_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
5185        if let Some(tx_id) = self
5186            .buffer
5187            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
5188        {
5189            if let Some((_, end_selections)) = self.selection_history.get_mut(&tx_id) {
5190                *end_selections = Some(self.selections.clone());
5191            } else {
5192                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
5193            }
5194
5195            cx.emit(Event::Edited);
5196        }
5197    }
5198
5199    pub fn page_up(&mut self, _: &PageUp, _: &mut ViewContext<Self>) {
5200        log::info!("Editor::page_up");
5201    }
5202
5203    pub fn page_down(&mut self, _: &PageDown, _: &mut ViewContext<Self>) {
5204        log::info!("Editor::page_down");
5205    }
5206
5207    pub fn fold(&mut self, _: &Fold, cx: &mut ViewContext<Self>) {
5208        let mut fold_ranges = Vec::new();
5209
5210        let selections = self.local_selections::<Point>(cx);
5211        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5212        for selection in selections {
5213            let range = selection.display_range(&display_map).sorted();
5214            let buffer_start_row = range.start.to_point(&display_map).row;
5215
5216            for row in (0..=range.end.row()).rev() {
5217                if self.is_line_foldable(&display_map, row) && !display_map.is_line_folded(row) {
5218                    let fold_range = self.foldable_range_for_line(&display_map, row);
5219                    if fold_range.end.row >= buffer_start_row {
5220                        fold_ranges.push(fold_range);
5221                        if row <= range.start.row() {
5222                            break;
5223                        }
5224                    }
5225                }
5226            }
5227        }
5228
5229        self.fold_ranges(fold_ranges, cx);
5230    }
5231
5232    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
5233        let selections = self.local_selections::<Point>(cx);
5234        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5235        let buffer = &display_map.buffer_snapshot;
5236        let ranges = selections
5237            .iter()
5238            .map(|s| {
5239                let range = s.display_range(&display_map).sorted();
5240                let mut start = range.start.to_point(&display_map);
5241                let mut end = range.end.to_point(&display_map);
5242                start.column = 0;
5243                end.column = buffer.line_len(end.row);
5244                start..end
5245            })
5246            .collect::<Vec<_>>();
5247        self.unfold_ranges(ranges, true, cx);
5248    }
5249
5250    fn is_line_foldable(&self, display_map: &DisplaySnapshot, display_row: u32) -> bool {
5251        let max_point = display_map.max_point();
5252        if display_row >= max_point.row() {
5253            false
5254        } else {
5255            let (start_indent, is_blank) = display_map.line_indent(display_row);
5256            if is_blank {
5257                false
5258            } else {
5259                for display_row in display_row + 1..=max_point.row() {
5260                    let (indent, is_blank) = display_map.line_indent(display_row);
5261                    if !is_blank {
5262                        return indent > start_indent;
5263                    }
5264                }
5265                false
5266            }
5267        }
5268    }
5269
5270    fn foldable_range_for_line(
5271        &self,
5272        display_map: &DisplaySnapshot,
5273        start_row: u32,
5274    ) -> Range<Point> {
5275        let max_point = display_map.max_point();
5276
5277        let (start_indent, _) = display_map.line_indent(start_row);
5278        let start = DisplayPoint::new(start_row, display_map.line_len(start_row));
5279        let mut end = None;
5280        for row in start_row + 1..=max_point.row() {
5281            let (indent, is_blank) = display_map.line_indent(row);
5282            if !is_blank && indent <= start_indent {
5283                end = Some(DisplayPoint::new(row - 1, display_map.line_len(row - 1)));
5284                break;
5285            }
5286        }
5287
5288        let end = end.unwrap_or(max_point);
5289        return start.to_point(display_map)..end.to_point(display_map);
5290    }
5291
5292    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
5293        let selections = self.local_selections::<Point>(cx);
5294        let ranges = selections.into_iter().map(|s| s.start..s.end);
5295        self.fold_ranges(ranges, cx);
5296    }
5297
5298    pub fn fold_ranges<T: ToOffset>(
5299        &mut self,
5300        ranges: impl IntoIterator<Item = Range<T>>,
5301        cx: &mut ViewContext<Self>,
5302    ) {
5303        let mut ranges = ranges.into_iter().peekable();
5304        if ranges.peek().is_some() {
5305            self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
5306            self.request_autoscroll(Autoscroll::Fit, cx);
5307            cx.notify();
5308        }
5309    }
5310
5311    pub fn unfold_ranges<T: ToOffset>(
5312        &mut self,
5313        ranges: impl IntoIterator<Item = Range<T>>,
5314        inclusive: bool,
5315        cx: &mut ViewContext<Self>,
5316    ) {
5317        let mut ranges = ranges.into_iter().peekable();
5318        if ranges.peek().is_some() {
5319            self.display_map
5320                .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
5321            self.request_autoscroll(Autoscroll::Fit, cx);
5322            cx.notify();
5323        }
5324    }
5325
5326    pub fn insert_blocks(
5327        &mut self,
5328        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
5329        cx: &mut ViewContext<Self>,
5330    ) -> Vec<BlockId> {
5331        let blocks = self
5332            .display_map
5333            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
5334        self.request_autoscroll(Autoscroll::Fit, cx);
5335        blocks
5336    }
5337
5338    pub fn replace_blocks(
5339        &mut self,
5340        blocks: HashMap<BlockId, RenderBlock>,
5341        cx: &mut ViewContext<Self>,
5342    ) {
5343        self.display_map
5344            .update(cx, |display_map, _| display_map.replace_blocks(blocks));
5345        self.request_autoscroll(Autoscroll::Fit, cx);
5346    }
5347
5348    pub fn remove_blocks(&mut self, block_ids: HashSet<BlockId>, cx: &mut ViewContext<Self>) {
5349        self.display_map.update(cx, |display_map, cx| {
5350            display_map.remove_blocks(block_ids, cx)
5351        });
5352    }
5353
5354    pub fn longest_row(&self, cx: &mut MutableAppContext) -> u32 {
5355        self.display_map
5356            .update(cx, |map, cx| map.snapshot(cx))
5357            .longest_row()
5358    }
5359
5360    pub fn max_point(&self, cx: &mut MutableAppContext) -> DisplayPoint {
5361        self.display_map
5362            .update(cx, |map, cx| map.snapshot(cx))
5363            .max_point()
5364    }
5365
5366    pub fn text(&self, cx: &AppContext) -> String {
5367        self.buffer.read(cx).read(cx).text()
5368    }
5369
5370    pub fn set_text(&mut self, text: impl Into<String>, cx: &mut ViewContext<Self>) {
5371        self.transact(cx, |this, cx| {
5372            this.buffer
5373                .read(cx)
5374                .as_singleton()
5375                .expect("you can only call set_text on editors for singleton buffers")
5376                .update(cx, |buffer, cx| buffer.set_text(text, cx));
5377        });
5378    }
5379
5380    pub fn display_text(&self, cx: &mut MutableAppContext) -> String {
5381        self.display_map
5382            .update(cx, |map, cx| map.snapshot(cx))
5383            .text()
5384    }
5385
5386    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
5387        let language = self.language(cx);
5388        let settings = cx.global::<Settings>();
5389        let mode = self
5390            .soft_wrap_mode_override
5391            .unwrap_or_else(|| settings.soft_wrap(language));
5392        match mode {
5393            settings::SoftWrap::None => SoftWrap::None,
5394            settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
5395            settings::SoftWrap::PreferredLineLength => {
5396                SoftWrap::Column(settings.preferred_line_length(language))
5397            }
5398        }
5399    }
5400
5401    pub fn set_soft_wrap_mode(&mut self, mode: settings::SoftWrap, cx: &mut ViewContext<Self>) {
5402        self.soft_wrap_mode_override = Some(mode);
5403        cx.notify();
5404    }
5405
5406    pub fn set_wrap_width(&self, width: Option<f32>, cx: &mut MutableAppContext) -> bool {
5407        self.display_map
5408            .update(cx, |map, cx| map.set_wrap_width(width, cx))
5409    }
5410
5411    pub fn highlight_rows(&mut self, rows: Option<Range<u32>>) {
5412        self.highlighted_rows = rows;
5413    }
5414
5415    pub fn highlighted_rows(&self) -> Option<Range<u32>> {
5416        self.highlighted_rows.clone()
5417    }
5418
5419    pub fn highlight_background<T: 'static>(
5420        &mut self,
5421        ranges: Vec<Range<Anchor>>,
5422        color: Color,
5423        cx: &mut ViewContext<Self>,
5424    ) {
5425        self.background_highlights
5426            .insert(TypeId::of::<T>(), (color, ranges));
5427        cx.notify();
5428    }
5429
5430    pub fn clear_background_highlights<T: 'static>(
5431        &mut self,
5432        cx: &mut ViewContext<Self>,
5433    ) -> Option<(Color, Vec<Range<Anchor>>)> {
5434        cx.notify();
5435        self.background_highlights.remove(&TypeId::of::<T>())
5436    }
5437
5438    #[cfg(feature = "test-support")]
5439    pub fn all_background_highlights(
5440        &mut self,
5441        cx: &mut ViewContext<Self>,
5442    ) -> Vec<(Range<DisplayPoint>, Color)> {
5443        let snapshot = self.snapshot(cx);
5444        let buffer = &snapshot.buffer_snapshot;
5445        let start = buffer.anchor_before(0);
5446        let end = buffer.anchor_after(buffer.len());
5447        self.background_highlights_in_range(start..end, &snapshot)
5448    }
5449
5450    pub fn background_highlights_for_type<T: 'static>(&self) -> Option<(Color, &[Range<Anchor>])> {
5451        self.background_highlights
5452            .get(&TypeId::of::<T>())
5453            .map(|(color, ranges)| (*color, ranges.as_slice()))
5454    }
5455
5456    pub fn background_highlights_in_range(
5457        &self,
5458        search_range: Range<Anchor>,
5459        display_snapshot: &DisplaySnapshot,
5460    ) -> Vec<(Range<DisplayPoint>, Color)> {
5461        let mut results = Vec::new();
5462        let buffer = &display_snapshot.buffer_snapshot;
5463        for (color, ranges) in self.background_highlights.values() {
5464            let start_ix = match ranges.binary_search_by(|probe| {
5465                let cmp = probe.end.cmp(&search_range.start, &buffer);
5466                if cmp.is_gt() {
5467                    Ordering::Greater
5468                } else {
5469                    Ordering::Less
5470                }
5471            }) {
5472                Ok(i) | Err(i) => i,
5473            };
5474            for range in &ranges[start_ix..] {
5475                if range.start.cmp(&search_range.end, &buffer).is_ge() {
5476                    break;
5477                }
5478                let start = range
5479                    .start
5480                    .to_point(buffer)
5481                    .to_display_point(display_snapshot);
5482                let end = range
5483                    .end
5484                    .to_point(buffer)
5485                    .to_display_point(display_snapshot);
5486                results.push((start..end, *color))
5487            }
5488        }
5489        results
5490    }
5491
5492    pub fn highlight_text<T: 'static>(
5493        &mut self,
5494        ranges: Vec<Range<Anchor>>,
5495        style: HighlightStyle,
5496        cx: &mut ViewContext<Self>,
5497    ) {
5498        self.display_map.update(cx, |map, _| {
5499            map.highlight_text(TypeId::of::<T>(), ranges, style)
5500        });
5501        cx.notify();
5502    }
5503
5504    pub fn clear_text_highlights<T: 'static>(
5505        &mut self,
5506        cx: &mut ViewContext<Self>,
5507    ) -> Option<Arc<(HighlightStyle, Vec<Range<Anchor>>)>> {
5508        cx.notify();
5509        self.display_map
5510            .update(cx, |map, _| map.clear_text_highlights(TypeId::of::<T>()))
5511    }
5512
5513    fn next_blink_epoch(&mut self) -> usize {
5514        self.blink_epoch += 1;
5515        self.blink_epoch
5516    }
5517
5518    fn pause_cursor_blinking(&mut self, cx: &mut ViewContext<Self>) {
5519        if !self.focused {
5520            return;
5521        }
5522
5523        self.show_local_cursors = true;
5524        cx.notify();
5525
5526        let epoch = self.next_blink_epoch();
5527        cx.spawn(|this, mut cx| {
5528            let this = this.downgrade();
5529            async move {
5530                Timer::after(CURSOR_BLINK_INTERVAL).await;
5531                if let Some(this) = this.upgrade(&cx) {
5532                    this.update(&mut cx, |this, cx| this.resume_cursor_blinking(epoch, cx))
5533                }
5534            }
5535        })
5536        .detach();
5537    }
5538
5539    fn resume_cursor_blinking(&mut self, epoch: usize, cx: &mut ViewContext<Self>) {
5540        if epoch == self.blink_epoch {
5541            self.blinking_paused = false;
5542            self.blink_cursors(epoch, cx);
5543        }
5544    }
5545
5546    fn blink_cursors(&mut self, epoch: usize, cx: &mut ViewContext<Self>) {
5547        if epoch == self.blink_epoch && self.focused && !self.blinking_paused {
5548            self.show_local_cursors = !self.show_local_cursors;
5549            cx.notify();
5550
5551            let epoch = self.next_blink_epoch();
5552            cx.spawn(|this, mut cx| {
5553                let this = this.downgrade();
5554                async move {
5555                    Timer::after(CURSOR_BLINK_INTERVAL).await;
5556                    if let Some(this) = this.upgrade(&cx) {
5557                        this.update(&mut cx, |this, cx| this.blink_cursors(epoch, cx));
5558                    }
5559                }
5560            })
5561            .detach();
5562        }
5563    }
5564
5565    pub fn show_local_cursors(&self) -> bool {
5566        self.show_local_cursors && self.focused
5567    }
5568
5569    fn on_buffer_changed(&mut self, _: ModelHandle<MultiBuffer>, cx: &mut ViewContext<Self>) {
5570        cx.notify();
5571    }
5572
5573    fn on_buffer_event(
5574        &mut self,
5575        _: ModelHandle<MultiBuffer>,
5576        event: &language::Event,
5577        cx: &mut ViewContext<Self>,
5578    ) {
5579        match event {
5580            language::Event::Edited => {
5581                self.refresh_active_diagnostics(cx);
5582                self.refresh_code_actions(cx);
5583                cx.emit(Event::BufferEdited);
5584            }
5585            language::Event::Dirtied => cx.emit(Event::Dirtied),
5586            language::Event::Saved => cx.emit(Event::Saved),
5587            language::Event::FileHandleChanged => cx.emit(Event::TitleChanged),
5588            language::Event::Reloaded => cx.emit(Event::TitleChanged),
5589            language::Event::Closed => cx.emit(Event::Closed),
5590            language::Event::DiagnosticsUpdated => {
5591                self.refresh_active_diagnostics(cx);
5592            }
5593            _ => {}
5594        }
5595    }
5596
5597    fn on_display_map_changed(&mut self, _: ModelHandle<DisplayMap>, cx: &mut ViewContext<Self>) {
5598        cx.notify();
5599    }
5600
5601    pub fn set_searchable(&mut self, searchable: bool) {
5602        self.searchable = searchable;
5603    }
5604
5605    pub fn searchable(&self) -> bool {
5606        self.searchable
5607    }
5608
5609    fn open_excerpts(workspace: &mut Workspace, _: &OpenExcerpts, cx: &mut ViewContext<Workspace>) {
5610        let active_item = workspace.active_item(cx);
5611        let editor_handle = if let Some(editor) = active_item
5612            .as_ref()
5613            .and_then(|item| item.act_as::<Self>(cx))
5614        {
5615            editor
5616        } else {
5617            cx.propagate_action();
5618            return;
5619        };
5620
5621        let editor = editor_handle.read(cx);
5622        let buffer = editor.buffer.read(cx);
5623        if buffer.is_singleton() {
5624            cx.propagate_action();
5625            return;
5626        }
5627
5628        let mut new_selections_by_buffer = HashMap::default();
5629        for selection in editor.local_selections::<usize>(cx) {
5630            for (buffer, mut range) in
5631                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
5632            {
5633                if selection.reversed {
5634                    mem::swap(&mut range.start, &mut range.end);
5635                }
5636                new_selections_by_buffer
5637                    .entry(buffer)
5638                    .or_insert(Vec::new())
5639                    .push(range)
5640            }
5641        }
5642
5643        editor_handle.update(cx, |editor, cx| {
5644            editor.push_to_nav_history(editor.newest_anchor_selection().head(), None, cx);
5645        });
5646        let nav_history = workspace.active_pane().read(cx).nav_history().clone();
5647        nav_history.borrow_mut().disable();
5648
5649        // We defer the pane interaction because we ourselves are a workspace item
5650        // and activating a new item causes the pane to call a method on us reentrantly,
5651        // which panics if we're on the stack.
5652        cx.defer(move |workspace, cx| {
5653            workspace.activate_next_pane(cx);
5654
5655            for (buffer, ranges) in new_selections_by_buffer.into_iter() {
5656                let editor = workspace.open_project_item::<Self>(buffer, cx);
5657                editor.update(cx, |editor, cx| {
5658                    editor.select_ranges(ranges, Some(Autoscroll::Newest), cx);
5659                });
5660            }
5661
5662            nav_history.borrow_mut().enable();
5663        });
5664    }
5665}
5666
5667impl EditorSnapshot {
5668    pub fn is_focused(&self) -> bool {
5669        self.is_focused
5670    }
5671
5672    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
5673        self.placeholder_text.as_ref()
5674    }
5675
5676    pub fn scroll_position(&self) -> Vector2F {
5677        compute_scroll_position(
5678            &self.display_snapshot,
5679            self.scroll_position,
5680            &self.scroll_top_anchor,
5681        )
5682    }
5683}
5684
5685impl Deref for EditorSnapshot {
5686    type Target = DisplaySnapshot;
5687
5688    fn deref(&self) -> &Self::Target {
5689        &self.display_snapshot
5690    }
5691}
5692
5693fn compute_scroll_position(
5694    snapshot: &DisplaySnapshot,
5695    mut scroll_position: Vector2F,
5696    scroll_top_anchor: &Anchor,
5697) -> Vector2F {
5698    if *scroll_top_anchor != Anchor::min() {
5699        let scroll_top = scroll_top_anchor.to_display_point(snapshot).row() as f32;
5700        scroll_position.set_y(scroll_top + scroll_position.y());
5701    } else {
5702        scroll_position.set_y(0.);
5703    }
5704    scroll_position
5705}
5706
5707#[derive(Copy, Clone, Debug, PartialEq, Eq)]
5708pub enum Event {
5709    Activate,
5710    BufferEdited,
5711    Edited,
5712    Blurred,
5713    Dirtied,
5714    Saved,
5715    TitleChanged,
5716    SelectionsChanged { local: bool },
5717    ScrollPositionChanged { local: bool },
5718    Closed,
5719}
5720
5721pub struct EditorFocused(pub ViewHandle<Editor>);
5722pub struct EditorBlurred(pub ViewHandle<Editor>);
5723pub struct EditorReleased(pub WeakViewHandle<Editor>);
5724
5725impl Entity for Editor {
5726    type Event = Event;
5727
5728    fn release(&mut self, cx: &mut MutableAppContext) {
5729        cx.emit_global(EditorReleased(self.handle.clone()));
5730    }
5731}
5732
5733impl View for Editor {
5734    fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
5735        let style = self.style(cx);
5736        self.display_map.update(cx, |map, cx| {
5737            map.set_font(style.text.font_id, style.text.font_size, cx)
5738        });
5739        EditorElement::new(self.handle.clone(), style.clone(), self.cursor_shape).boxed()
5740    }
5741
5742    fn ui_name() -> &'static str {
5743        "Editor"
5744    }
5745
5746    fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
5747        let focused_event = EditorFocused(cx.handle());
5748        cx.emit_global(focused_event);
5749        if let Some(rename) = self.pending_rename.as_ref() {
5750            cx.focus(&rename.editor);
5751        } else {
5752            self.focused = true;
5753            self.blink_cursors(self.blink_epoch, cx);
5754            self.buffer.update(cx, |buffer, cx| {
5755                buffer.finalize_last_transaction(cx);
5756                if self.leader_replica_id.is_none() {
5757                    buffer.set_active_selections(&self.selections, cx);
5758                }
5759            });
5760        }
5761    }
5762
5763    fn on_blur(&mut self, cx: &mut ViewContext<Self>) {
5764        let blurred_event = EditorBlurred(cx.handle());
5765        cx.emit_global(blurred_event);
5766        self.focused = false;
5767        self.buffer
5768            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
5769        self.hide_context_menu(cx);
5770        cx.emit(Event::Blurred);
5771        cx.notify();
5772    }
5773
5774    fn keymap_context(&self, _: &AppContext) -> gpui::keymap::Context {
5775        let mut context = Self::default_keymap_context();
5776        let mode = match self.mode {
5777            EditorMode::SingleLine => "single_line",
5778            EditorMode::AutoHeight { .. } => "auto_height",
5779            EditorMode::Full => "full",
5780        };
5781        context.map.insert("mode".into(), mode.into());
5782        if self.pending_rename.is_some() {
5783            context.set.insert("renaming".into());
5784        }
5785        match self.context_menu.as_ref() {
5786            Some(ContextMenu::Completions(_)) => {
5787                context.set.insert("showing_completions".into());
5788            }
5789            Some(ContextMenu::CodeActions(_)) => {
5790                context.set.insert("showing_code_actions".into());
5791            }
5792            None => {}
5793        }
5794
5795        for layer in self.keymap_context_layers.values() {
5796            context.extend(layer);
5797        }
5798
5799        context
5800    }
5801}
5802
5803fn build_style(
5804    settings: &Settings,
5805    get_field_editor_theme: Option<GetFieldEditorTheme>,
5806    override_text_style: Option<&OverrideTextStyle>,
5807    cx: &AppContext,
5808) -> EditorStyle {
5809    let font_cache = cx.font_cache();
5810
5811    let mut theme = settings.theme.editor.clone();
5812    let mut style = if let Some(get_field_editor_theme) = get_field_editor_theme {
5813        let field_editor_theme = get_field_editor_theme(&settings.theme);
5814        theme.text_color = field_editor_theme.text.color;
5815        theme.selection = field_editor_theme.selection;
5816        theme.background = field_editor_theme
5817            .container
5818            .background_color
5819            .unwrap_or_default();
5820        EditorStyle {
5821            text: field_editor_theme.text,
5822            placeholder_text: field_editor_theme.placeholder_text,
5823            theme,
5824        }
5825    } else {
5826        let font_family_id = settings.buffer_font_family;
5827        let font_family_name = cx.font_cache().family_name(font_family_id).unwrap();
5828        let font_properties = Default::default();
5829        let font_id = font_cache
5830            .select_font(font_family_id, &font_properties)
5831            .unwrap();
5832        let font_size = settings.buffer_font_size;
5833        EditorStyle {
5834            text: TextStyle {
5835                color: settings.theme.editor.text_color,
5836                font_family_name,
5837                font_family_id,
5838                font_id,
5839                font_size,
5840                font_properties,
5841                underline: Default::default(),
5842            },
5843            placeholder_text: None,
5844            theme,
5845        }
5846    };
5847
5848    if let Some(highlight_style) = override_text_style.and_then(|build_style| build_style(&style)) {
5849        if let Some(highlighted) = style
5850            .text
5851            .clone()
5852            .highlight(highlight_style, font_cache)
5853            .log_err()
5854        {
5855            style.text = highlighted;
5856        }
5857    }
5858
5859    style
5860}
5861
5862trait SelectionExt {
5863    fn offset_range(&self, buffer: &MultiBufferSnapshot) -> Range<usize>;
5864    fn point_range(&self, buffer: &MultiBufferSnapshot) -> Range<Point>;
5865    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
5866    fn spanned_rows(&self, include_end_if_at_line_start: bool, map: &DisplaySnapshot)
5867        -> Range<u32>;
5868}
5869
5870impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
5871    fn point_range(&self, buffer: &MultiBufferSnapshot) -> Range<Point> {
5872        let start = self.start.to_point(buffer);
5873        let end = self.end.to_point(buffer);
5874        if self.reversed {
5875            end..start
5876        } else {
5877            start..end
5878        }
5879    }
5880
5881    fn offset_range(&self, buffer: &MultiBufferSnapshot) -> Range<usize> {
5882        let start = self.start.to_offset(buffer);
5883        let end = self.end.to_offset(buffer);
5884        if self.reversed {
5885            end..start
5886        } else {
5887            start..end
5888        }
5889    }
5890
5891    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
5892        let start = self
5893            .start
5894            .to_point(&map.buffer_snapshot)
5895            .to_display_point(map);
5896        let end = self
5897            .end
5898            .to_point(&map.buffer_snapshot)
5899            .to_display_point(map);
5900        if self.reversed {
5901            end..start
5902        } else {
5903            start..end
5904        }
5905    }
5906
5907    fn spanned_rows(
5908        &self,
5909        include_end_if_at_line_start: bool,
5910        map: &DisplaySnapshot,
5911    ) -> Range<u32> {
5912        let start = self.start.to_point(&map.buffer_snapshot);
5913        let mut end = self.end.to_point(&map.buffer_snapshot);
5914        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
5915            end.row -= 1;
5916        }
5917
5918        let buffer_start = map.prev_line_boundary(start).0;
5919        let buffer_end = map.next_line_boundary(end).0;
5920        buffer_start.row..buffer_end.row + 1
5921    }
5922}
5923
5924impl<T: InvalidationRegion> InvalidationStack<T> {
5925    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
5926    where
5927        S: Clone + ToOffset,
5928    {
5929        while let Some(region) = self.last() {
5930            let all_selections_inside_invalidation_ranges =
5931                if selections.len() == region.ranges().len() {
5932                    selections
5933                        .iter()
5934                        .zip(region.ranges().iter().map(|r| r.to_offset(&buffer)))
5935                        .all(|(selection, invalidation_range)| {
5936                            let head = selection.head().to_offset(&buffer);
5937                            invalidation_range.start <= head && invalidation_range.end >= head
5938                        })
5939                } else {
5940                    false
5941                };
5942
5943            if all_selections_inside_invalidation_ranges {
5944                break;
5945            } else {
5946                self.pop();
5947            }
5948        }
5949    }
5950}
5951
5952impl<T> Default for InvalidationStack<T> {
5953    fn default() -> Self {
5954        Self(Default::default())
5955    }
5956}
5957
5958impl<T> Deref for InvalidationStack<T> {
5959    type Target = Vec<T>;
5960
5961    fn deref(&self) -> &Self::Target {
5962        &self.0
5963    }
5964}
5965
5966impl<T> DerefMut for InvalidationStack<T> {
5967    fn deref_mut(&mut self) -> &mut Self::Target {
5968        &mut self.0
5969    }
5970}
5971
5972impl InvalidationRegion for BracketPairState {
5973    fn ranges(&self) -> &[Range<Anchor>] {
5974        &self.ranges
5975    }
5976}
5977
5978impl InvalidationRegion for SnippetState {
5979    fn ranges(&self) -> &[Range<Anchor>] {
5980        &self.ranges[self.active_index]
5981    }
5982}
5983
5984impl Deref for EditorStyle {
5985    type Target = theme::Editor;
5986
5987    fn deref(&self) -> &Self::Target {
5988        &self.theme
5989    }
5990}
5991
5992pub fn diagnostic_block_renderer(diagnostic: Diagnostic, is_valid: bool) -> RenderBlock {
5993    let mut highlighted_lines = Vec::new();
5994    for line in diagnostic.message.lines() {
5995        highlighted_lines.push(highlight_diagnostic_message(line));
5996    }
5997
5998    Arc::new(move |cx: &BlockContext| {
5999        let settings = cx.global::<Settings>();
6000        let theme = &settings.theme.editor;
6001        let style = diagnostic_style(diagnostic.severity, is_valid, theme);
6002        let font_size = (style.text_scale_factor * settings.buffer_font_size).round();
6003        Flex::column()
6004            .with_children(highlighted_lines.iter().map(|(line, highlights)| {
6005                Label::new(
6006                    line.clone(),
6007                    style.message.clone().with_font_size(font_size),
6008                )
6009                .with_highlights(highlights.clone())
6010                .contained()
6011                .with_margin_left(cx.anchor_x)
6012                .boxed()
6013            }))
6014            .aligned()
6015            .left()
6016            .boxed()
6017    })
6018}
6019
6020pub fn highlight_diagnostic_message(message: &str) -> (String, Vec<usize>) {
6021    let mut message_without_backticks = String::new();
6022    let mut prev_offset = 0;
6023    let mut inside_block = false;
6024    let mut highlights = Vec::new();
6025    for (match_ix, (offset, _)) in message
6026        .match_indices('`')
6027        .chain([(message.len(), "")])
6028        .enumerate()
6029    {
6030        message_without_backticks.push_str(&message[prev_offset..offset]);
6031        if inside_block {
6032            highlights.extend(prev_offset - match_ix..offset - match_ix);
6033        }
6034
6035        inside_block = !inside_block;
6036        prev_offset = offset + 1;
6037    }
6038
6039    (message_without_backticks, highlights)
6040}
6041
6042pub fn diagnostic_style(
6043    severity: DiagnosticSeverity,
6044    valid: bool,
6045    theme: &theme::Editor,
6046) -> DiagnosticStyle {
6047    match (severity, valid) {
6048        (DiagnosticSeverity::ERROR, true) => theme.error_diagnostic.clone(),
6049        (DiagnosticSeverity::ERROR, false) => theme.invalid_error_diagnostic.clone(),
6050        (DiagnosticSeverity::WARNING, true) => theme.warning_diagnostic.clone(),
6051        (DiagnosticSeverity::WARNING, false) => theme.invalid_warning_diagnostic.clone(),
6052        (DiagnosticSeverity::INFORMATION, true) => theme.information_diagnostic.clone(),
6053        (DiagnosticSeverity::INFORMATION, false) => theme.invalid_information_diagnostic.clone(),
6054        (DiagnosticSeverity::HINT, true) => theme.hint_diagnostic.clone(),
6055        (DiagnosticSeverity::HINT, false) => theme.invalid_hint_diagnostic.clone(),
6056        _ => theme.invalid_hint_diagnostic.clone(),
6057    }
6058}
6059
6060pub fn combine_syntax_and_fuzzy_match_highlights(
6061    text: &str,
6062    default_style: HighlightStyle,
6063    syntax_ranges: impl Iterator<Item = (Range<usize>, HighlightStyle)>,
6064    match_indices: &[usize],
6065) -> Vec<(Range<usize>, HighlightStyle)> {
6066    let mut result = Vec::new();
6067    let mut match_indices = match_indices.iter().copied().peekable();
6068
6069    for (range, mut syntax_highlight) in syntax_ranges.chain([(usize::MAX..0, Default::default())])
6070    {
6071        syntax_highlight.weight = None;
6072
6073        // Add highlights for any fuzzy match characters before the next
6074        // syntax highlight range.
6075        while let Some(&match_index) = match_indices.peek() {
6076            if match_index >= range.start {
6077                break;
6078            }
6079            match_indices.next();
6080            let end_index = char_ix_after(match_index, text);
6081            let mut match_style = default_style;
6082            match_style.weight = Some(fonts::Weight::BOLD);
6083            result.push((match_index..end_index, match_style));
6084        }
6085
6086        if range.start == usize::MAX {
6087            break;
6088        }
6089
6090        // Add highlights for any fuzzy match characters within the
6091        // syntax highlight range.
6092        let mut offset = range.start;
6093        while let Some(&match_index) = match_indices.peek() {
6094            if match_index >= range.end {
6095                break;
6096            }
6097
6098            match_indices.next();
6099            if match_index > offset {
6100                result.push((offset..match_index, syntax_highlight));
6101            }
6102
6103            let mut end_index = char_ix_after(match_index, text);
6104            while let Some(&next_match_index) = match_indices.peek() {
6105                if next_match_index == end_index && next_match_index < range.end {
6106                    end_index = char_ix_after(next_match_index, text);
6107                    match_indices.next();
6108                } else {
6109                    break;
6110                }
6111            }
6112
6113            let mut match_style = syntax_highlight;
6114            match_style.weight = Some(fonts::Weight::BOLD);
6115            result.push((match_index..end_index, match_style));
6116            offset = end_index;
6117        }
6118
6119        if offset < range.end {
6120            result.push((offset..range.end, syntax_highlight));
6121        }
6122    }
6123
6124    fn char_ix_after(ix: usize, text: &str) -> usize {
6125        ix + text[ix..].chars().next().unwrap().len_utf8()
6126    }
6127
6128    result
6129}
6130
6131pub fn styled_runs_for_code_label<'a>(
6132    label: &'a CodeLabel,
6133    syntax_theme: &'a theme::SyntaxTheme,
6134) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
6135    let fade_out = HighlightStyle {
6136        fade_out: Some(0.35),
6137        ..Default::default()
6138    };
6139
6140    let mut prev_end = label.filter_range.end;
6141    label
6142        .runs
6143        .iter()
6144        .enumerate()
6145        .flat_map(move |(ix, (range, highlight_id))| {
6146            let style = if let Some(style) = highlight_id.style(syntax_theme) {
6147                style
6148            } else {
6149                return Default::default();
6150            };
6151            let mut muted_style = style.clone();
6152            muted_style.highlight(fade_out);
6153
6154            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
6155            if range.start >= label.filter_range.end {
6156                if range.start > prev_end {
6157                    runs.push((prev_end..range.start, fade_out));
6158                }
6159                runs.push((range.clone(), muted_style));
6160            } else if range.end <= label.filter_range.end {
6161                runs.push((range.clone(), style));
6162            } else {
6163                runs.push((range.start..label.filter_range.end, style));
6164                runs.push((label.filter_range.end..range.end, muted_style));
6165            }
6166            prev_end = cmp::max(prev_end, range.end);
6167
6168            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
6169                runs.push((prev_end..label.text.len(), fade_out));
6170            }
6171
6172            runs
6173        })
6174}
6175
6176#[cfg(test)]
6177mod tests {
6178
6179    use super::*;
6180    use gpui::{
6181        geometry::rect::RectF,
6182        platform::{WindowBounds, WindowOptions},
6183    };
6184    use language::{LanguageConfig, LanguageServerConfig};
6185    use lsp::FakeLanguageServer;
6186    use project::FakeFs;
6187    use smol::stream::StreamExt;
6188    use std::{cell::RefCell, rc::Rc, time::Instant};
6189    use text::Point;
6190    use unindent::Unindent;
6191    use util::test::{marked_text_by, sample_text};
6192    use workspace::FollowableItem;
6193
6194    #[gpui::test]
6195    fn test_edit_events(cx: &mut MutableAppContext) {
6196        populate_settings(cx);
6197        let buffer = cx.add_model(|cx| language::Buffer::new(0, "123456", cx));
6198
6199        let events = Rc::new(RefCell::new(Vec::new()));
6200        let (_, editor1) = cx.add_window(Default::default(), {
6201            let events = events.clone();
6202            |cx| {
6203                cx.subscribe(&cx.handle(), move |_, _, event, _| {
6204                    if matches!(event, Event::Edited | Event::BufferEdited | Event::Dirtied) {
6205                        events.borrow_mut().push(("editor1", *event));
6206                    }
6207                })
6208                .detach();
6209                Editor::for_buffer(buffer.clone(), None, cx)
6210            }
6211        });
6212        let (_, editor2) = cx.add_window(Default::default(), {
6213            let events = events.clone();
6214            |cx| {
6215                cx.subscribe(&cx.handle(), move |_, _, event, _| {
6216                    if matches!(event, Event::Edited | Event::BufferEdited | Event::Dirtied) {
6217                        events.borrow_mut().push(("editor2", *event));
6218                    }
6219                })
6220                .detach();
6221                Editor::for_buffer(buffer.clone(), None, cx)
6222            }
6223        });
6224        assert_eq!(mem::take(&mut *events.borrow_mut()), []);
6225
6226        // Mutating editor 1 will emit an `Edited` event only for that editor.
6227        editor1.update(cx, |editor, cx| editor.insert("X", cx));
6228        assert_eq!(
6229            mem::take(&mut *events.borrow_mut()),
6230            [
6231                ("editor1", Event::Edited),
6232                ("editor1", Event::BufferEdited),
6233                ("editor2", Event::BufferEdited),
6234                ("editor1", Event::Dirtied),
6235                ("editor2", Event::Dirtied)
6236            ]
6237        );
6238
6239        // Mutating editor 2 will emit an `Edited` event only for that editor.
6240        editor2.update(cx, |editor, cx| editor.delete(&Delete, cx));
6241        assert_eq!(
6242            mem::take(&mut *events.borrow_mut()),
6243            [
6244                ("editor2", Event::Edited),
6245                ("editor1", Event::BufferEdited),
6246                ("editor2", Event::BufferEdited),
6247            ]
6248        );
6249
6250        // Undoing on editor 1 will emit an `Edited` event only for that editor.
6251        editor1.update(cx, |editor, cx| editor.undo(&Undo, cx));
6252        assert_eq!(
6253            mem::take(&mut *events.borrow_mut()),
6254            [
6255                ("editor1", Event::Edited),
6256                ("editor1", Event::BufferEdited),
6257                ("editor2", Event::BufferEdited),
6258            ]
6259        );
6260
6261        // Redoing on editor 1 will emit an `Edited` event only for that editor.
6262        editor1.update(cx, |editor, cx| editor.redo(&Redo, cx));
6263        assert_eq!(
6264            mem::take(&mut *events.borrow_mut()),
6265            [
6266                ("editor1", Event::Edited),
6267                ("editor1", Event::BufferEdited),
6268                ("editor2", Event::BufferEdited),
6269            ]
6270        );
6271
6272        // Undoing on editor 2 will emit an `Edited` event only for that editor.
6273        editor2.update(cx, |editor, cx| editor.undo(&Undo, cx));
6274        assert_eq!(
6275            mem::take(&mut *events.borrow_mut()),
6276            [
6277                ("editor2", Event::Edited),
6278                ("editor1", Event::BufferEdited),
6279                ("editor2", Event::BufferEdited),
6280            ]
6281        );
6282
6283        // Redoing on editor 2 will emit an `Edited` event only for that editor.
6284        editor2.update(cx, |editor, cx| editor.redo(&Redo, cx));
6285        assert_eq!(
6286            mem::take(&mut *events.borrow_mut()),
6287            [
6288                ("editor2", Event::Edited),
6289                ("editor1", Event::BufferEdited),
6290                ("editor2", Event::BufferEdited),
6291            ]
6292        );
6293
6294        // No event is emitted when the mutation is a no-op.
6295        editor2.update(cx, |editor, cx| {
6296            editor.select_ranges([0..0], None, cx);
6297            editor.backspace(&Backspace, cx);
6298        });
6299        assert_eq!(mem::take(&mut *events.borrow_mut()), []);
6300    }
6301
6302    #[gpui::test]
6303    fn test_undo_redo_with_selection_restoration(cx: &mut MutableAppContext) {
6304        populate_settings(cx);
6305        let mut now = Instant::now();
6306        let buffer = cx.add_model(|cx| language::Buffer::new(0, "123456", cx));
6307        let group_interval = buffer.read(cx).transaction_group_interval();
6308        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
6309        let (_, editor) = cx.add_window(Default::default(), |cx| build_editor(buffer.clone(), cx));
6310
6311        editor.update(cx, |editor, cx| {
6312            editor.start_transaction_at(now, cx);
6313            editor.select_ranges([2..4], None, cx);
6314            editor.insert("cd", cx);
6315            editor.end_transaction_at(now, cx);
6316            assert_eq!(editor.text(cx), "12cd56");
6317            assert_eq!(editor.selected_ranges(cx), vec![4..4]);
6318
6319            editor.start_transaction_at(now, cx);
6320            editor.select_ranges([4..5], None, cx);
6321            editor.insert("e", cx);
6322            editor.end_transaction_at(now, cx);
6323            assert_eq!(editor.text(cx), "12cde6");
6324            assert_eq!(editor.selected_ranges(cx), vec![5..5]);
6325
6326            now += group_interval + Duration::from_millis(1);
6327            editor.select_ranges([2..2], None, cx);
6328
6329            // Simulate an edit in another editor
6330            buffer.update(cx, |buffer, cx| {
6331                buffer.start_transaction_at(now, cx);
6332                buffer.edit([0..1], "a", cx);
6333                buffer.edit([1..1], "b", cx);
6334                buffer.end_transaction_at(now, cx);
6335            });
6336
6337            assert_eq!(editor.text(cx), "ab2cde6");
6338            assert_eq!(editor.selected_ranges(cx), vec![3..3]);
6339
6340            // Last transaction happened past the group interval in a different editor.
6341            // Undo it individually and don't restore selections.
6342            editor.undo(&Undo, cx);
6343            assert_eq!(editor.text(cx), "12cde6");
6344            assert_eq!(editor.selected_ranges(cx), vec![2..2]);
6345
6346            // First two transactions happened within the group interval in this editor.
6347            // Undo them together and restore selections.
6348            editor.undo(&Undo, cx);
6349            editor.undo(&Undo, cx); // Undo stack is empty here, so this is a no-op.
6350            assert_eq!(editor.text(cx), "123456");
6351            assert_eq!(editor.selected_ranges(cx), vec![0..0]);
6352
6353            // Redo the first two transactions together.
6354            editor.redo(&Redo, cx);
6355            assert_eq!(editor.text(cx), "12cde6");
6356            assert_eq!(editor.selected_ranges(cx), vec![5..5]);
6357
6358            // Redo the last transaction on its own.
6359            editor.redo(&Redo, cx);
6360            assert_eq!(editor.text(cx), "ab2cde6");
6361            assert_eq!(editor.selected_ranges(cx), vec![6..6]);
6362
6363            // Test empty transactions.
6364            editor.start_transaction_at(now, cx);
6365            editor.end_transaction_at(now, cx);
6366            editor.undo(&Undo, cx);
6367            assert_eq!(editor.text(cx), "12cde6");
6368        });
6369    }
6370
6371    #[gpui::test]
6372    fn test_selection_with_mouse(cx: &mut gpui::MutableAppContext) {
6373        populate_settings(cx);
6374
6375        let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\nddddddd\n", cx);
6376        let (_, editor) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
6377        editor.update(cx, |view, cx| {
6378            view.begin_selection(DisplayPoint::new(2, 2), false, 1, cx);
6379        });
6380        assert_eq!(
6381            editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
6382            [DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2)]
6383        );
6384
6385        editor.update(cx, |view, cx| {
6386            view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
6387        });
6388
6389        assert_eq!(
6390            editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
6391            [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
6392        );
6393
6394        editor.update(cx, |view, cx| {
6395            view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
6396        });
6397
6398        assert_eq!(
6399            editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
6400            [DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1)]
6401        );
6402
6403        editor.update(cx, |view, cx| {
6404            view.end_selection(cx);
6405            view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
6406        });
6407
6408        assert_eq!(
6409            editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
6410            [DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1)]
6411        );
6412
6413        editor.update(cx, |view, cx| {
6414            view.begin_selection(DisplayPoint::new(3, 3), true, 1, cx);
6415            view.update_selection(DisplayPoint::new(0, 0), 0, Vector2F::zero(), cx);
6416        });
6417
6418        assert_eq!(
6419            editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
6420            [
6421                DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1),
6422                DisplayPoint::new(3, 3)..DisplayPoint::new(0, 0)
6423            ]
6424        );
6425
6426        editor.update(cx, |view, cx| {
6427            view.end_selection(cx);
6428        });
6429
6430        assert_eq!(
6431            editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
6432            [DisplayPoint::new(3, 3)..DisplayPoint::new(0, 0)]
6433        );
6434    }
6435
6436    #[gpui::test]
6437    fn test_canceling_pending_selection(cx: &mut gpui::MutableAppContext) {
6438        populate_settings(cx);
6439        let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
6440        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
6441
6442        view.update(cx, |view, cx| {
6443            view.begin_selection(DisplayPoint::new(2, 2), false, 1, cx);
6444            assert_eq!(
6445                view.selected_display_ranges(cx),
6446                [DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2)]
6447            );
6448        });
6449
6450        view.update(cx, |view, cx| {
6451            view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
6452            assert_eq!(
6453                view.selected_display_ranges(cx),
6454                [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
6455            );
6456        });
6457
6458        view.update(cx, |view, cx| {
6459            view.cancel(&Cancel, cx);
6460            view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
6461            assert_eq!(
6462                view.selected_display_ranges(cx),
6463                [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
6464            );
6465        });
6466    }
6467
6468    #[gpui::test]
6469    fn test_navigation_history(cx: &mut gpui::MutableAppContext) {
6470        populate_settings(cx);
6471        use workspace::Item;
6472        let nav_history = Rc::new(RefCell::new(workspace::NavHistory::default()));
6473        let buffer = MultiBuffer::build_simple(&sample_text(30, 5, 'a'), cx);
6474
6475        cx.add_window(Default::default(), |cx| {
6476            let mut editor = build_editor(buffer.clone(), cx);
6477            editor.nav_history = Some(ItemNavHistory::new(nav_history.clone(), &cx.handle()));
6478
6479            // Move the cursor a small distance.
6480            // Nothing is added to the navigation history.
6481            editor.select_display_ranges(&[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)], cx);
6482            editor.select_display_ranges(&[DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0)], cx);
6483            assert!(nav_history.borrow_mut().pop_backward().is_none());
6484
6485            // Move the cursor a large distance.
6486            // The history can jump back to the previous position.
6487            editor.select_display_ranges(&[DisplayPoint::new(13, 0)..DisplayPoint::new(13, 3)], cx);
6488            let nav_entry = nav_history.borrow_mut().pop_backward().unwrap();
6489            editor.navigate(nav_entry.data.unwrap(), cx);
6490            assert_eq!(nav_entry.item.id(), cx.view_id());
6491            assert_eq!(
6492                editor.selected_display_ranges(cx),
6493                &[DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0)]
6494            );
6495            assert!(nav_history.borrow_mut().pop_backward().is_none());
6496
6497            // Move the cursor a small distance via the mouse.
6498            // Nothing is added to the navigation history.
6499            editor.begin_selection(DisplayPoint::new(5, 0), false, 1, cx);
6500            editor.end_selection(cx);
6501            assert_eq!(
6502                editor.selected_display_ranges(cx),
6503                &[DisplayPoint::new(5, 0)..DisplayPoint::new(5, 0)]
6504            );
6505            assert!(nav_history.borrow_mut().pop_backward().is_none());
6506
6507            // Move the cursor a large distance via the mouse.
6508            // The history can jump back to the previous position.
6509            editor.begin_selection(DisplayPoint::new(15, 0), false, 1, cx);
6510            editor.end_selection(cx);
6511            assert_eq!(
6512                editor.selected_display_ranges(cx),
6513                &[DisplayPoint::new(15, 0)..DisplayPoint::new(15, 0)]
6514            );
6515            let nav_entry = nav_history.borrow_mut().pop_backward().unwrap();
6516            editor.navigate(nav_entry.data.unwrap(), cx);
6517            assert_eq!(nav_entry.item.id(), cx.view_id());
6518            assert_eq!(
6519                editor.selected_display_ranges(cx),
6520                &[DisplayPoint::new(5, 0)..DisplayPoint::new(5, 0)]
6521            );
6522            assert!(nav_history.borrow_mut().pop_backward().is_none());
6523
6524            editor
6525        });
6526    }
6527
6528    #[gpui::test]
6529    fn test_cancel(cx: &mut gpui::MutableAppContext) {
6530        populate_settings(cx);
6531        let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
6532        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
6533
6534        view.update(cx, |view, cx| {
6535            view.begin_selection(DisplayPoint::new(3, 4), false, 1, cx);
6536            view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
6537            view.end_selection(cx);
6538
6539            view.begin_selection(DisplayPoint::new(0, 1), true, 1, cx);
6540            view.update_selection(DisplayPoint::new(0, 3), 0, Vector2F::zero(), cx);
6541            view.end_selection(cx);
6542            assert_eq!(
6543                view.selected_display_ranges(cx),
6544                [
6545                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
6546                    DisplayPoint::new(3, 4)..DisplayPoint::new(1, 1),
6547                ]
6548            );
6549        });
6550
6551        view.update(cx, |view, cx| {
6552            view.cancel(&Cancel, cx);
6553            assert_eq!(
6554                view.selected_display_ranges(cx),
6555                [DisplayPoint::new(3, 4)..DisplayPoint::new(1, 1)]
6556            );
6557        });
6558
6559        view.update(cx, |view, cx| {
6560            view.cancel(&Cancel, cx);
6561            assert_eq!(
6562                view.selected_display_ranges(cx),
6563                [DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1)]
6564            );
6565        });
6566    }
6567
6568    #[gpui::test]
6569    fn test_fold(cx: &mut gpui::MutableAppContext) {
6570        populate_settings(cx);
6571        let buffer = MultiBuffer::build_simple(
6572            &"
6573                impl Foo {
6574                    // Hello!
6575
6576                    fn a() {
6577                        1
6578                    }
6579
6580                    fn b() {
6581                        2
6582                    }
6583
6584                    fn c() {
6585                        3
6586                    }
6587                }
6588            "
6589            .unindent(),
6590            cx,
6591        );
6592        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer.clone(), cx));
6593
6594        view.update(cx, |view, cx| {
6595            view.select_display_ranges(&[DisplayPoint::new(8, 0)..DisplayPoint::new(12, 0)], cx);
6596            view.fold(&Fold, cx);
6597            assert_eq!(
6598                view.display_text(cx),
6599                "
6600                    impl Foo {
6601                        // Hello!
6602
6603                        fn a() {
6604                            1
6605                        }
6606
6607                        fn b() {…
6608                        }
6609
6610                        fn c() {…
6611                        }
6612                    }
6613                "
6614                .unindent(),
6615            );
6616
6617            view.fold(&Fold, cx);
6618            assert_eq!(
6619                view.display_text(cx),
6620                "
6621                    impl Foo {…
6622                    }
6623                "
6624                .unindent(),
6625            );
6626
6627            view.unfold_lines(&UnfoldLines, cx);
6628            assert_eq!(
6629                view.display_text(cx),
6630                "
6631                    impl Foo {
6632                        // Hello!
6633
6634                        fn a() {
6635                            1
6636                        }
6637
6638                        fn b() {…
6639                        }
6640
6641                        fn c() {…
6642                        }
6643                    }
6644                "
6645                .unindent(),
6646            );
6647
6648            view.unfold_lines(&UnfoldLines, cx);
6649            assert_eq!(view.display_text(cx), buffer.read(cx).read(cx).text());
6650        });
6651    }
6652
6653    #[gpui::test]
6654    fn test_move_cursor(cx: &mut gpui::MutableAppContext) {
6655        populate_settings(cx);
6656        let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
6657        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer.clone(), cx));
6658
6659        buffer.update(cx, |buffer, cx| {
6660            buffer.edit(
6661                vec![
6662                    Point::new(1, 0)..Point::new(1, 0),
6663                    Point::new(1, 1)..Point::new(1, 1),
6664                ],
6665                "\t",
6666                cx,
6667            );
6668        });
6669
6670        view.update(cx, |view, cx| {
6671            assert_eq!(
6672                view.selected_display_ranges(cx),
6673                &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
6674            );
6675
6676            view.move_down(&MoveDown, cx);
6677            assert_eq!(
6678                view.selected_display_ranges(cx),
6679                &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
6680            );
6681
6682            view.move_right(&MoveRight, cx);
6683            assert_eq!(
6684                view.selected_display_ranges(cx),
6685                &[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4)]
6686            );
6687
6688            view.move_left(&MoveLeft, cx);
6689            assert_eq!(
6690                view.selected_display_ranges(cx),
6691                &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
6692            );
6693
6694            view.move_up(&MoveUp, cx);
6695            assert_eq!(
6696                view.selected_display_ranges(cx),
6697                &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
6698            );
6699
6700            view.move_to_end(&MoveToEnd, cx);
6701            assert_eq!(
6702                view.selected_display_ranges(cx),
6703                &[DisplayPoint::new(5, 6)..DisplayPoint::new(5, 6)]
6704            );
6705
6706            view.move_to_beginning(&MoveToBeginning, cx);
6707            assert_eq!(
6708                view.selected_display_ranges(cx),
6709                &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
6710            );
6711
6712            view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 2)], cx);
6713            view.select_to_beginning(&SelectToBeginning, cx);
6714            assert_eq!(
6715                view.selected_display_ranges(cx),
6716                &[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 0)]
6717            );
6718
6719            view.select_to_end(&SelectToEnd, cx);
6720            assert_eq!(
6721                view.selected_display_ranges(cx),
6722                &[DisplayPoint::new(0, 1)..DisplayPoint::new(5, 6)]
6723            );
6724        });
6725    }
6726
6727    #[gpui::test]
6728    fn test_move_cursor_multibyte(cx: &mut gpui::MutableAppContext) {
6729        populate_settings(cx);
6730        let buffer = MultiBuffer::build_simple("ⓐⓑⓒⓓⓔ\nabcde\nαβγδε\n", cx);
6731        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer.clone(), cx));
6732
6733        assert_eq!('ⓐ'.len_utf8(), 3);
6734        assert_eq!('α'.len_utf8(), 2);
6735
6736        view.update(cx, |view, cx| {
6737            view.fold_ranges(
6738                vec![
6739                    Point::new(0, 6)..Point::new(0, 12),
6740                    Point::new(1, 2)..Point::new(1, 4),
6741                    Point::new(2, 4)..Point::new(2, 8),
6742                ],
6743                cx,
6744            );
6745            assert_eq!(view.display_text(cx), "ⓐⓑ…ⓔ\nab…e\nαβ…ε\n");
6746
6747            view.move_right(&MoveRight, cx);
6748            assert_eq!(
6749                view.selected_display_ranges(cx),
6750                &[empty_range(0, "".len())]
6751            );
6752            view.move_right(&MoveRight, cx);
6753            assert_eq!(
6754                view.selected_display_ranges(cx),
6755                &[empty_range(0, "ⓐⓑ".len())]
6756            );
6757            view.move_right(&MoveRight, cx);
6758            assert_eq!(
6759                view.selected_display_ranges(cx),
6760                &[empty_range(0, "ⓐⓑ…".len())]
6761            );
6762
6763            view.move_down(&MoveDown, cx);
6764            assert_eq!(
6765                view.selected_display_ranges(cx),
6766                &[empty_range(1, "ab…".len())]
6767            );
6768            view.move_left(&MoveLeft, cx);
6769            assert_eq!(
6770                view.selected_display_ranges(cx),
6771                &[empty_range(1, "ab".len())]
6772            );
6773            view.move_left(&MoveLeft, cx);
6774            assert_eq!(
6775                view.selected_display_ranges(cx),
6776                &[empty_range(1, "a".len())]
6777            );
6778
6779            view.move_down(&MoveDown, cx);
6780            assert_eq!(
6781                view.selected_display_ranges(cx),
6782                &[empty_range(2, "α".len())]
6783            );
6784            view.move_right(&MoveRight, cx);
6785            assert_eq!(
6786                view.selected_display_ranges(cx),
6787                &[empty_range(2, "αβ".len())]
6788            );
6789            view.move_right(&MoveRight, cx);
6790            assert_eq!(
6791                view.selected_display_ranges(cx),
6792                &[empty_range(2, "αβ…".len())]
6793            );
6794            view.move_right(&MoveRight, cx);
6795            assert_eq!(
6796                view.selected_display_ranges(cx),
6797                &[empty_range(2, "αβ…ε".len())]
6798            );
6799
6800            view.move_up(&MoveUp, cx);
6801            assert_eq!(
6802                view.selected_display_ranges(cx),
6803                &[empty_range(1, "ab…e".len())]
6804            );
6805            view.move_up(&MoveUp, cx);
6806            assert_eq!(
6807                view.selected_display_ranges(cx),
6808                &[empty_range(0, "ⓐⓑ…ⓔ".len())]
6809            );
6810            view.move_left(&MoveLeft, cx);
6811            assert_eq!(
6812                view.selected_display_ranges(cx),
6813                &[empty_range(0, "ⓐⓑ…".len())]
6814            );
6815            view.move_left(&MoveLeft, cx);
6816            assert_eq!(
6817                view.selected_display_ranges(cx),
6818                &[empty_range(0, "ⓐⓑ".len())]
6819            );
6820            view.move_left(&MoveLeft, cx);
6821            assert_eq!(
6822                view.selected_display_ranges(cx),
6823                &[empty_range(0, "".len())]
6824            );
6825        });
6826    }
6827
6828    #[gpui::test]
6829    fn test_move_cursor_different_line_lengths(cx: &mut gpui::MutableAppContext) {
6830        populate_settings(cx);
6831        let buffer = MultiBuffer::build_simple("ⓐⓑⓒⓓⓔ\nabcd\nαβγ\nabcd\nⓐⓑⓒⓓⓔ\n", cx);
6832        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer.clone(), cx));
6833        view.update(cx, |view, cx| {
6834            view.select_display_ranges(&[empty_range(0, "ⓐⓑⓒⓓⓔ".len())], cx);
6835            view.move_down(&MoveDown, cx);
6836            assert_eq!(
6837                view.selected_display_ranges(cx),
6838                &[empty_range(1, "abcd".len())]
6839            );
6840
6841            view.move_down(&MoveDown, cx);
6842            assert_eq!(
6843                view.selected_display_ranges(cx),
6844                &[empty_range(2, "αβγ".len())]
6845            );
6846
6847            view.move_down(&MoveDown, cx);
6848            assert_eq!(
6849                view.selected_display_ranges(cx),
6850                &[empty_range(3, "abcd".len())]
6851            );
6852
6853            view.move_down(&MoveDown, cx);
6854            assert_eq!(
6855                view.selected_display_ranges(cx),
6856                &[empty_range(4, "ⓐⓑⓒⓓⓔ".len())]
6857            );
6858
6859            view.move_up(&MoveUp, cx);
6860            assert_eq!(
6861                view.selected_display_ranges(cx),
6862                &[empty_range(3, "abcd".len())]
6863            );
6864
6865            view.move_up(&MoveUp, cx);
6866            assert_eq!(
6867                view.selected_display_ranges(cx),
6868                &[empty_range(2, "αβγ".len())]
6869            );
6870        });
6871    }
6872
6873    #[gpui::test]
6874    fn test_beginning_end_of_line(cx: &mut gpui::MutableAppContext) {
6875        populate_settings(cx);
6876        let buffer = MultiBuffer::build_simple("abc\n  def", cx);
6877        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
6878        view.update(cx, |view, cx| {
6879            view.select_display_ranges(
6880                &[
6881                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
6882                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4),
6883                ],
6884                cx,
6885            );
6886        });
6887
6888        view.update(cx, |view, cx| {
6889            view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
6890            assert_eq!(
6891                view.selected_display_ranges(cx),
6892                &[
6893                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
6894                    DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
6895                ]
6896            );
6897        });
6898
6899        view.update(cx, |view, cx| {
6900            view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
6901            assert_eq!(
6902                view.selected_display_ranges(cx),
6903                &[
6904                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
6905                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
6906                ]
6907            );
6908        });
6909
6910        view.update(cx, |view, cx| {
6911            view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
6912            assert_eq!(
6913                view.selected_display_ranges(cx),
6914                &[
6915                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
6916                    DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
6917                ]
6918            );
6919        });
6920
6921        view.update(cx, |view, cx| {
6922            view.move_to_end_of_line(&MoveToEndOfLine, cx);
6923            assert_eq!(
6924                view.selected_display_ranges(cx),
6925                &[
6926                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
6927                    DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
6928                ]
6929            );
6930        });
6931
6932        // Moving to the end of line again is a no-op.
6933        view.update(cx, |view, cx| {
6934            view.move_to_end_of_line(&MoveToEndOfLine, cx);
6935            assert_eq!(
6936                view.selected_display_ranges(cx),
6937                &[
6938                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
6939                    DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
6940                ]
6941            );
6942        });
6943
6944        view.update(cx, |view, cx| {
6945            view.move_left(&MoveLeft, cx);
6946            view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
6947            assert_eq!(
6948                view.selected_display_ranges(cx),
6949                &[
6950                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
6951                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 2),
6952                ]
6953            );
6954        });
6955
6956        view.update(cx, |view, cx| {
6957            view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
6958            assert_eq!(
6959                view.selected_display_ranges(cx),
6960                &[
6961                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
6962                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 0),
6963                ]
6964            );
6965        });
6966
6967        view.update(cx, |view, cx| {
6968            view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
6969            assert_eq!(
6970                view.selected_display_ranges(cx),
6971                &[
6972                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
6973                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 2),
6974                ]
6975            );
6976        });
6977
6978        view.update(cx, |view, cx| {
6979            view.select_to_end_of_line(&SelectToEndOfLine(true), cx);
6980            assert_eq!(
6981                view.selected_display_ranges(cx),
6982                &[
6983                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 3),
6984                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 5),
6985                ]
6986            );
6987        });
6988
6989        view.update(cx, |view, cx| {
6990            view.delete_to_end_of_line(&DeleteToEndOfLine, cx);
6991            assert_eq!(view.display_text(cx), "ab\n  de");
6992            assert_eq!(
6993                view.selected_display_ranges(cx),
6994                &[
6995                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
6996                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4),
6997                ]
6998            );
6999        });
7000
7001        view.update(cx, |view, cx| {
7002            view.delete_to_beginning_of_line(&DeleteToBeginningOfLine, cx);
7003            assert_eq!(view.display_text(cx), "\n");
7004            assert_eq!(
7005                view.selected_display_ranges(cx),
7006                &[
7007                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
7008                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
7009                ]
7010            );
7011        });
7012    }
7013
7014    #[gpui::test]
7015    fn test_prev_next_word_boundary(cx: &mut gpui::MutableAppContext) {
7016        populate_settings(cx);
7017        let buffer = MultiBuffer::build_simple("use std::str::{foo, bar}\n\n  {baz.qux()}", cx);
7018        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
7019        view.update(cx, |view, cx| {
7020            view.select_display_ranges(
7021                &[
7022                    DisplayPoint::new(0, 11)..DisplayPoint::new(0, 11),
7023                    DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4),
7024                ],
7025                cx,
7026            );
7027
7028            view.move_to_previous_word_start(&MoveToPreviousWordStart, cx);
7029            assert_selection_ranges(
7030                "use std::<>str::{foo, bar}\n\n  {[]baz.qux()}",
7031                vec![('<', '>'), ('[', ']')],
7032                view,
7033                cx,
7034            );
7035
7036            view.move_to_previous_word_start(&MoveToPreviousWordStart, cx);
7037            assert_selection_ranges(
7038                "use std<>::str::{foo, bar}\n\n  []{baz.qux()}",
7039                vec![('<', '>'), ('[', ']')],
7040                view,
7041                cx,
7042            );
7043
7044            view.move_to_previous_word_start(&MoveToPreviousWordStart, cx);
7045            assert_selection_ranges(
7046                "use <>std::str::{foo, bar}\n\n[]  {baz.qux()}",
7047                vec![('<', '>'), ('[', ']')],
7048                view,
7049                cx,
7050            );
7051
7052            view.move_to_previous_word_start(&MoveToPreviousWordStart, cx);
7053            assert_selection_ranges(
7054                "<>use std::str::{foo, bar}\n[]\n  {baz.qux()}",
7055                vec![('<', '>'), ('[', ']')],
7056                view,
7057                cx,
7058            );
7059
7060            view.move_to_previous_word_start(&MoveToPreviousWordStart, cx);
7061            assert_selection_ranges(
7062                "<>use std::str::{foo, bar[]}\n\n  {baz.qux()}",
7063                vec![('<', '>'), ('[', ']')],
7064                view,
7065                cx,
7066            );
7067
7068            view.move_to_next_word_end(&MoveToNextWordEnd, cx);
7069            assert_selection_ranges(
7070                "use<> std::str::{foo, bar}[]\n\n  {baz.qux()}",
7071                vec![('<', '>'), ('[', ']')],
7072                view,
7073                cx,
7074            );
7075
7076            view.move_to_next_word_end(&MoveToNextWordEnd, cx);
7077            assert_selection_ranges(
7078                "use std<>::str::{foo, bar}\n[]\n  {baz.qux()}",
7079                vec![('<', '>'), ('[', ']')],
7080                view,
7081                cx,
7082            );
7083
7084            view.move_to_next_word_end(&MoveToNextWordEnd, cx);
7085            assert_selection_ranges(
7086                "use std::<>str::{foo, bar}\n\n  {[]baz.qux()}",
7087                vec![('<', '>'), ('[', ']')],
7088                view,
7089                cx,
7090            );
7091
7092            view.move_right(&MoveRight, cx);
7093            view.select_to_previous_word_start(&SelectToPreviousWordBoundary, cx);
7094            assert_selection_ranges(
7095                "use std::>s<tr::{foo, bar}\n\n  {]b[az.qux()}",
7096                vec![('<', '>'), ('[', ']')],
7097                view,
7098                cx,
7099            );
7100
7101            view.select_to_previous_word_start(&SelectToPreviousWordBoundary, cx);
7102            assert_selection_ranges(
7103                "use std>::s<tr::{foo, bar}\n\n  ]{b[az.qux()}",
7104                vec![('<', '>'), ('[', ']')],
7105                view,
7106                cx,
7107            );
7108
7109            view.select_to_next_word_end(&SelectToNextWordBoundary, cx);
7110            assert_selection_ranges(
7111                "use std::>s<tr::{foo, bar}\n\n  {]b[az.qux()}",
7112                vec![('<', '>'), ('[', ']')],
7113                view,
7114                cx,
7115            );
7116        });
7117    }
7118
7119    #[gpui::test]
7120    fn test_prev_next_word_bounds_with_soft_wrap(cx: &mut gpui::MutableAppContext) {
7121        populate_settings(cx);
7122        let buffer = MultiBuffer::build_simple("use one::{\n    two::three::four::five\n};", cx);
7123        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
7124
7125        view.update(cx, |view, cx| {
7126            view.set_wrap_width(Some(140.), cx);
7127            assert_eq!(
7128                view.display_text(cx),
7129                "use one::{\n    two::three::\n    four::five\n};"
7130            );
7131
7132            view.select_display_ranges(&[DisplayPoint::new(1, 7)..DisplayPoint::new(1, 7)], cx);
7133
7134            view.move_to_next_word_end(&MoveToNextWordEnd, cx);
7135            assert_eq!(
7136                view.selected_display_ranges(cx),
7137                &[DisplayPoint::new(1, 9)..DisplayPoint::new(1, 9)]
7138            );
7139
7140            view.move_to_next_word_end(&MoveToNextWordEnd, cx);
7141            assert_eq!(
7142                view.selected_display_ranges(cx),
7143                &[DisplayPoint::new(1, 14)..DisplayPoint::new(1, 14)]
7144            );
7145
7146            view.move_to_next_word_end(&MoveToNextWordEnd, cx);
7147            assert_eq!(
7148                view.selected_display_ranges(cx),
7149                &[DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4)]
7150            );
7151
7152            view.move_to_next_word_end(&MoveToNextWordEnd, cx);
7153            assert_eq!(
7154                view.selected_display_ranges(cx),
7155                &[DisplayPoint::new(2, 8)..DisplayPoint::new(2, 8)]
7156            );
7157
7158            view.move_to_previous_word_start(&MoveToPreviousWordStart, cx);
7159            assert_eq!(
7160                view.selected_display_ranges(cx),
7161                &[DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4)]
7162            );
7163
7164            view.move_to_previous_word_start(&MoveToPreviousWordStart, cx);
7165            assert_eq!(
7166                view.selected_display_ranges(cx),
7167                &[DisplayPoint::new(1, 14)..DisplayPoint::new(1, 14)]
7168            );
7169        });
7170    }
7171
7172    #[gpui::test]
7173    fn test_delete_to_word_boundary(cx: &mut gpui::MutableAppContext) {
7174        populate_settings(cx);
7175        let buffer = MultiBuffer::build_simple("one two three four", cx);
7176        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer.clone(), cx));
7177
7178        view.update(cx, |view, cx| {
7179            view.select_display_ranges(
7180                &[
7181                    // an empty selection - the preceding word fragment is deleted
7182                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7183                    // characters selected - they are deleted
7184                    DisplayPoint::new(0, 9)..DisplayPoint::new(0, 12),
7185                ],
7186                cx,
7187            );
7188            view.delete_to_previous_word_start(&DeleteToPreviousWordBoundary, cx);
7189        });
7190
7191        assert_eq!(buffer.read(cx).read(cx).text(), "e two te four");
7192
7193        view.update(cx, |view, cx| {
7194            view.select_display_ranges(
7195                &[
7196                    // an empty selection - the following word fragment is deleted
7197                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
7198                    // characters selected - they are deleted
7199                    DisplayPoint::new(0, 9)..DisplayPoint::new(0, 10),
7200                ],
7201                cx,
7202            );
7203            view.delete_to_next_word_end(&DeleteToNextWordBoundary, cx);
7204        });
7205
7206        assert_eq!(buffer.read(cx).read(cx).text(), "e t te our");
7207    }
7208
7209    #[gpui::test]
7210    fn test_newline(cx: &mut gpui::MutableAppContext) {
7211        populate_settings(cx);
7212        let buffer = MultiBuffer::build_simple("aaaa\n    bbbb\n", cx);
7213        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer.clone(), cx));
7214
7215        view.update(cx, |view, cx| {
7216            view.select_display_ranges(
7217                &[
7218                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7219                    DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
7220                    DisplayPoint::new(1, 6)..DisplayPoint::new(1, 6),
7221                ],
7222                cx,
7223            );
7224
7225            view.newline(&Newline, cx);
7226            assert_eq!(view.text(cx), "aa\naa\n  \n    bb\n    bb\n");
7227        });
7228    }
7229
7230    #[gpui::test]
7231    fn test_newline_with_old_selections(cx: &mut gpui::MutableAppContext) {
7232        populate_settings(cx);
7233        let buffer = MultiBuffer::build_simple(
7234            "
7235                a
7236                b(
7237                    X
7238                )
7239                c(
7240                    X
7241                )
7242            "
7243            .unindent()
7244            .as_str(),
7245            cx,
7246        );
7247
7248        let (_, editor) = cx.add_window(Default::default(), |cx| {
7249            let mut editor = build_editor(buffer.clone(), cx);
7250            editor.select_ranges(
7251                [
7252                    Point::new(2, 4)..Point::new(2, 5),
7253                    Point::new(5, 4)..Point::new(5, 5),
7254                ],
7255                None,
7256                cx,
7257            );
7258            editor
7259        });
7260
7261        // Edit the buffer directly, deleting ranges surrounding the editor's selections
7262        buffer.update(cx, |buffer, cx| {
7263            buffer.edit(
7264                [
7265                    Point::new(1, 2)..Point::new(3, 0),
7266                    Point::new(4, 2)..Point::new(6, 0),
7267                ],
7268                "",
7269                cx,
7270            );
7271            assert_eq!(
7272                buffer.read(cx).text(),
7273                "
7274                    a
7275                    b()
7276                    c()
7277                "
7278                .unindent()
7279            );
7280        });
7281
7282        editor.update(cx, |editor, cx| {
7283            assert_eq!(
7284                editor.selected_ranges(cx),
7285                &[
7286                    Point::new(1, 2)..Point::new(1, 2),
7287                    Point::new(2, 2)..Point::new(2, 2),
7288                ],
7289            );
7290
7291            editor.newline(&Newline, cx);
7292            assert_eq!(
7293                editor.text(cx),
7294                "
7295                    a
7296                    b(
7297                    )
7298                    c(
7299                    )
7300                "
7301                .unindent()
7302            );
7303
7304            // The selections are moved after the inserted newlines
7305            assert_eq!(
7306                editor.selected_ranges(cx),
7307                &[
7308                    Point::new(2, 0)..Point::new(2, 0),
7309                    Point::new(4, 0)..Point::new(4, 0),
7310                ],
7311            );
7312        });
7313    }
7314
7315    #[gpui::test]
7316    fn test_insert_with_old_selections(cx: &mut gpui::MutableAppContext) {
7317        populate_settings(cx);
7318        let buffer = MultiBuffer::build_simple("a( X ), b( Y ), c( Z )", cx);
7319        let (_, editor) = cx.add_window(Default::default(), |cx| {
7320            let mut editor = build_editor(buffer.clone(), cx);
7321            editor.select_ranges([3..4, 11..12, 19..20], None, cx);
7322            editor
7323        });
7324
7325        // Edit the buffer directly, deleting ranges surrounding the editor's selections
7326        buffer.update(cx, |buffer, cx| {
7327            buffer.edit([2..5, 10..13, 18..21], "", cx);
7328            assert_eq!(buffer.read(cx).text(), "a(), b(), c()".unindent());
7329        });
7330
7331        editor.update(cx, |editor, cx| {
7332            assert_eq!(editor.selected_ranges(cx), &[2..2, 7..7, 12..12],);
7333
7334            editor.insert("Z", cx);
7335            assert_eq!(editor.text(cx), "a(Z), b(Z), c(Z)");
7336
7337            // The selections are moved after the inserted characters
7338            assert_eq!(editor.selected_ranges(cx), &[3..3, 9..9, 15..15],);
7339        });
7340    }
7341
7342    #[gpui::test]
7343    fn test_indent_outdent(cx: &mut gpui::MutableAppContext) {
7344        populate_settings(cx);
7345        let buffer = MultiBuffer::build_simple("  one two\nthree\n four", cx);
7346        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer.clone(), cx));
7347
7348        view.update(cx, |view, cx| {
7349            // two selections on the same line
7350            view.select_display_ranges(
7351                &[
7352                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 5),
7353                    DisplayPoint::new(0, 6)..DisplayPoint::new(0, 9),
7354                ],
7355                cx,
7356            );
7357
7358            // indent from mid-tabstop to full tabstop
7359            view.tab(&Tab, cx);
7360            assert_eq!(view.text(cx), "    one two\nthree\n four");
7361            assert_eq!(
7362                view.selected_display_ranges(cx),
7363                &[
7364                    DisplayPoint::new(0, 4)..DisplayPoint::new(0, 7),
7365                    DisplayPoint::new(0, 8)..DisplayPoint::new(0, 11),
7366                ]
7367            );
7368
7369            // outdent from 1 tabstop to 0 tabstops
7370            view.outdent(&Outdent, cx);
7371            assert_eq!(view.text(cx), "one two\nthree\n four");
7372            assert_eq!(
7373                view.selected_display_ranges(cx),
7374                &[
7375                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 3),
7376                    DisplayPoint::new(0, 4)..DisplayPoint::new(0, 7),
7377                ]
7378            );
7379
7380            // select across line ending
7381            view.select_display_ranges(&[DisplayPoint::new(1, 1)..DisplayPoint::new(2, 0)], cx);
7382
7383            // indent and outdent affect only the preceding line
7384            view.tab(&Tab, cx);
7385            assert_eq!(view.text(cx), "one two\n    three\n four");
7386            assert_eq!(
7387                view.selected_display_ranges(cx),
7388                &[DisplayPoint::new(1, 5)..DisplayPoint::new(2, 0)]
7389            );
7390            view.outdent(&Outdent, cx);
7391            assert_eq!(view.text(cx), "one two\nthree\n four");
7392            assert_eq!(
7393                view.selected_display_ranges(cx),
7394                &[DisplayPoint::new(1, 1)..DisplayPoint::new(2, 0)]
7395            );
7396
7397            // Ensure that indenting/outdenting works when the cursor is at column 0.
7398            view.select_display_ranges(&[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)], cx);
7399            view.tab(&Tab, cx);
7400            assert_eq!(view.text(cx), "one two\n    three\n four");
7401            assert_eq!(
7402                view.selected_display_ranges(cx),
7403                &[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4)]
7404            );
7405
7406            view.select_display_ranges(&[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)], cx);
7407            view.outdent(&Outdent, cx);
7408            assert_eq!(view.text(cx), "one two\nthree\n four");
7409            assert_eq!(
7410                view.selected_display_ranges(cx),
7411                &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
7412            );
7413        });
7414    }
7415
7416    #[gpui::test]
7417    fn test_backspace(cx: &mut gpui::MutableAppContext) {
7418        populate_settings(cx);
7419        let (_, view) = cx.add_window(Default::default(), |cx| {
7420            build_editor(MultiBuffer::build_simple("", cx), cx)
7421        });
7422
7423        view.update(cx, |view, cx| {
7424            view.set_text("one two three\nfour five six\nseven eight nine\nten\n", cx);
7425            view.select_display_ranges(
7426                &[
7427                    // an empty selection - the preceding character is deleted
7428                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7429                    // one character selected - it is deleted
7430                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
7431                    // a line suffix selected - it is deleted
7432                    DisplayPoint::new(2, 6)..DisplayPoint::new(3, 0),
7433                ],
7434                cx,
7435            );
7436            view.backspace(&Backspace, cx);
7437            assert_eq!(view.text(cx), "oe two three\nfou five six\nseven ten\n");
7438
7439            view.set_text("    one\n        two\n        three\n   four", cx);
7440            view.select_display_ranges(
7441                &[
7442                    // cursors at the the end of leading indent - last indent is deleted
7443                    DisplayPoint::new(0, 4)..DisplayPoint::new(0, 4),
7444                    DisplayPoint::new(1, 8)..DisplayPoint::new(1, 8),
7445                    // cursors inside leading indent - overlapping indent deletions are coalesced
7446                    DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4),
7447                    DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
7448                    DisplayPoint::new(2, 6)..DisplayPoint::new(2, 6),
7449                    // cursor at the beginning of a line - preceding newline is deleted
7450                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
7451                    // selection inside leading indent - only the selected character is deleted
7452                    DisplayPoint::new(3, 2)..DisplayPoint::new(3, 3),
7453                ],
7454                cx,
7455            );
7456            view.backspace(&Backspace, cx);
7457            assert_eq!(view.text(cx), "one\n    two\n  three  four");
7458        });
7459    }
7460
7461    #[gpui::test]
7462    fn test_delete(cx: &mut gpui::MutableAppContext) {
7463        populate_settings(cx);
7464        let buffer =
7465            MultiBuffer::build_simple("one two three\nfour five six\nseven eight nine\nten\n", cx);
7466        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer.clone(), cx));
7467
7468        view.update(cx, |view, cx| {
7469            view.select_display_ranges(
7470                &[
7471                    // an empty selection - the following character is deleted
7472                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7473                    // one character selected - it is deleted
7474                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
7475                    // a line suffix selected - it is deleted
7476                    DisplayPoint::new(2, 6)..DisplayPoint::new(3, 0),
7477                ],
7478                cx,
7479            );
7480            view.delete(&Delete, cx);
7481        });
7482
7483        assert_eq!(
7484            buffer.read(cx).read(cx).text(),
7485            "on two three\nfou five six\nseven ten\n"
7486        );
7487    }
7488
7489    #[gpui::test]
7490    fn test_delete_line(cx: &mut gpui::MutableAppContext) {
7491        populate_settings(cx);
7492        let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
7493        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
7494        view.update(cx, |view, cx| {
7495            view.select_display_ranges(
7496                &[
7497                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
7498                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 1),
7499                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
7500                ],
7501                cx,
7502            );
7503            view.delete_line(&DeleteLine, cx);
7504            assert_eq!(view.display_text(cx), "ghi");
7505            assert_eq!(
7506                view.selected_display_ranges(cx),
7507                vec![
7508                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
7509                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)
7510                ]
7511            );
7512        });
7513
7514        populate_settings(cx);
7515        let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
7516        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
7517        view.update(cx, |view, cx| {
7518            view.select_display_ranges(&[DisplayPoint::new(2, 0)..DisplayPoint::new(0, 1)], cx);
7519            view.delete_line(&DeleteLine, cx);
7520            assert_eq!(view.display_text(cx), "ghi\n");
7521            assert_eq!(
7522                view.selected_display_ranges(cx),
7523                vec![DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)]
7524            );
7525        });
7526    }
7527
7528    #[gpui::test]
7529    fn test_duplicate_line(cx: &mut gpui::MutableAppContext) {
7530        populate_settings(cx);
7531        let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
7532        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
7533        view.update(cx, |view, cx| {
7534            view.select_display_ranges(
7535                &[
7536                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
7537                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7538                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
7539                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
7540                ],
7541                cx,
7542            );
7543            view.duplicate_line(&DuplicateLine, cx);
7544            assert_eq!(view.display_text(cx), "abc\nabc\ndef\ndef\nghi\n\n");
7545            assert_eq!(
7546                view.selected_display_ranges(cx),
7547                vec![
7548                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 1),
7549                    DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
7550                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
7551                    DisplayPoint::new(6, 0)..DisplayPoint::new(6, 0),
7552                ]
7553            );
7554        });
7555
7556        let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
7557        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
7558        view.update(cx, |view, cx| {
7559            view.select_display_ranges(
7560                &[
7561                    DisplayPoint::new(0, 1)..DisplayPoint::new(1, 1),
7562                    DisplayPoint::new(1, 2)..DisplayPoint::new(2, 1),
7563                ],
7564                cx,
7565            );
7566            view.duplicate_line(&DuplicateLine, cx);
7567            assert_eq!(view.display_text(cx), "abc\ndef\nghi\nabc\ndef\nghi\n");
7568            assert_eq!(
7569                view.selected_display_ranges(cx),
7570                vec![
7571                    DisplayPoint::new(3, 1)..DisplayPoint::new(4, 1),
7572                    DisplayPoint::new(4, 2)..DisplayPoint::new(5, 1),
7573                ]
7574            );
7575        });
7576    }
7577
7578    #[gpui::test]
7579    fn test_move_line_up_down(cx: &mut gpui::MutableAppContext) {
7580        populate_settings(cx);
7581        let buffer = MultiBuffer::build_simple(&sample_text(10, 5, 'a'), cx);
7582        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
7583        view.update(cx, |view, cx| {
7584            view.fold_ranges(
7585                vec![
7586                    Point::new(0, 2)..Point::new(1, 2),
7587                    Point::new(2, 3)..Point::new(4, 1),
7588                    Point::new(7, 0)..Point::new(8, 4),
7589                ],
7590                cx,
7591            );
7592            view.select_display_ranges(
7593                &[
7594                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
7595                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
7596                    DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
7597                    DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2),
7598                ],
7599                cx,
7600            );
7601            assert_eq!(
7602                view.display_text(cx),
7603                "aa…bbb\nccc…eeee\nfffff\nggggg\n…i\njjjjj"
7604            );
7605
7606            view.move_line_up(&MoveLineUp, cx);
7607            assert_eq!(
7608                view.display_text(cx),
7609                "aa…bbb\nccc…eeee\nggggg\n…i\njjjjj\nfffff"
7610            );
7611            assert_eq!(
7612                view.selected_display_ranges(cx),
7613                vec![
7614                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
7615                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
7616                    DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3),
7617                    DisplayPoint::new(4, 0)..DisplayPoint::new(4, 2)
7618                ]
7619            );
7620        });
7621
7622        view.update(cx, |view, cx| {
7623            view.move_line_down(&MoveLineDown, cx);
7624            assert_eq!(
7625                view.display_text(cx),
7626                "ccc…eeee\naa…bbb\nfffff\nggggg\n…i\njjjjj"
7627            );
7628            assert_eq!(
7629                view.selected_display_ranges(cx),
7630                vec![
7631                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
7632                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
7633                    DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
7634                    DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2)
7635                ]
7636            );
7637        });
7638
7639        view.update(cx, |view, cx| {
7640            view.move_line_down(&MoveLineDown, cx);
7641            assert_eq!(
7642                view.display_text(cx),
7643                "ccc…eeee\nfffff\naa…bbb\nggggg\n…i\njjjjj"
7644            );
7645            assert_eq!(
7646                view.selected_display_ranges(cx),
7647                vec![
7648                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
7649                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
7650                    DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
7651                    DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2)
7652                ]
7653            );
7654        });
7655
7656        view.update(cx, |view, cx| {
7657            view.move_line_up(&MoveLineUp, cx);
7658            assert_eq!(
7659                view.display_text(cx),
7660                "ccc…eeee\naa…bbb\nggggg\n…i\njjjjj\nfffff"
7661            );
7662            assert_eq!(
7663                view.selected_display_ranges(cx),
7664                vec![
7665                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
7666                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
7667                    DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3),
7668                    DisplayPoint::new(4, 0)..DisplayPoint::new(4, 2)
7669                ]
7670            );
7671        });
7672    }
7673
7674    #[gpui::test]
7675    fn test_move_line_up_down_with_blocks(cx: &mut gpui::MutableAppContext) {
7676        populate_settings(cx);
7677        let buffer = MultiBuffer::build_simple(&sample_text(10, 5, 'a'), cx);
7678        let snapshot = buffer.read(cx).snapshot(cx);
7679        let (_, editor) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
7680        editor.update(cx, |editor, cx| {
7681            editor.insert_blocks(
7682                [BlockProperties {
7683                    position: snapshot.anchor_after(Point::new(2, 0)),
7684                    disposition: BlockDisposition::Below,
7685                    height: 1,
7686                    render: Arc::new(|_| Empty::new().boxed()),
7687                }],
7688                cx,
7689            );
7690            editor.select_ranges([Point::new(2, 0)..Point::new(2, 0)], None, cx);
7691            editor.move_line_down(&MoveLineDown, cx);
7692        });
7693    }
7694
7695    #[gpui::test]
7696    fn test_clipboard(cx: &mut gpui::MutableAppContext) {
7697        populate_settings(cx);
7698        let buffer = MultiBuffer::build_simple("one✅ two three four five six ", cx);
7699        let view = cx
7700            .add_window(Default::default(), |cx| build_editor(buffer.clone(), cx))
7701            .1;
7702
7703        // Cut with three selections. Clipboard text is divided into three slices.
7704        view.update(cx, |view, cx| {
7705            view.select_ranges(vec![0..7, 11..17, 22..27], None, cx);
7706            view.cut(&Cut, cx);
7707            assert_eq!(view.display_text(cx), "two four six ");
7708        });
7709
7710        // Paste with three cursors. Each cursor pastes one slice of the clipboard text.
7711        view.update(cx, |view, cx| {
7712            view.select_ranges(vec![4..4, 9..9, 13..13], None, cx);
7713            view.paste(&Paste, cx);
7714            assert_eq!(view.display_text(cx), "two one✅ four three six five ");
7715            assert_eq!(
7716                view.selected_display_ranges(cx),
7717                &[
7718                    DisplayPoint::new(0, 11)..DisplayPoint::new(0, 11),
7719                    DisplayPoint::new(0, 22)..DisplayPoint::new(0, 22),
7720                    DisplayPoint::new(0, 31)..DisplayPoint::new(0, 31)
7721                ]
7722            );
7723        });
7724
7725        // Paste again but with only two cursors. Since the number of cursors doesn't
7726        // match the number of slices in the clipboard, the entire clipboard text
7727        // is pasted at each cursor.
7728        view.update(cx, |view, cx| {
7729            view.select_ranges(vec![0..0, 31..31], None, cx);
7730            view.handle_input(&Input("( ".into()), cx);
7731            view.paste(&Paste, cx);
7732            view.handle_input(&Input(") ".into()), cx);
7733            assert_eq!(
7734                view.display_text(cx),
7735                "( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
7736            );
7737        });
7738
7739        view.update(cx, |view, cx| {
7740            view.select_ranges(vec![0..0], None, cx);
7741            view.handle_input(&Input("123\n4567\n89\n".into()), cx);
7742            assert_eq!(
7743                view.display_text(cx),
7744                "123\n4567\n89\n( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
7745            );
7746        });
7747
7748        // Cut with three selections, one of which is full-line.
7749        view.update(cx, |view, cx| {
7750            view.select_display_ranges(
7751                &[
7752                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 2),
7753                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
7754                    DisplayPoint::new(2, 0)..DisplayPoint::new(2, 1),
7755                ],
7756                cx,
7757            );
7758            view.cut(&Cut, cx);
7759            assert_eq!(
7760                view.display_text(cx),
7761                "13\n9\n( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
7762            );
7763        });
7764
7765        // Paste with three selections, noticing how the copied selection that was full-line
7766        // gets inserted before the second cursor.
7767        view.update(cx, |view, cx| {
7768            view.select_display_ranges(
7769                &[
7770                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
7771                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
7772                    DisplayPoint::new(2, 2)..DisplayPoint::new(2, 3),
7773                ],
7774                cx,
7775            );
7776            view.paste(&Paste, cx);
7777            assert_eq!(
7778                view.display_text(cx),
7779                "123\n4567\n9\n( 8ne✅ three five ) two one✅ four three six five ( one✅ three five ) "
7780            );
7781            assert_eq!(
7782                view.selected_display_ranges(cx),
7783                &[
7784                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7785                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
7786                    DisplayPoint::new(3, 3)..DisplayPoint::new(3, 3),
7787                ]
7788            );
7789        });
7790
7791        // Copy with a single cursor only, which writes the whole line into the clipboard.
7792        view.update(cx, |view, cx| {
7793            view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)], cx);
7794            view.copy(&Copy, cx);
7795        });
7796
7797        // Paste with three selections, noticing how the copied full-line selection is inserted
7798        // before the empty selections but replaces the selection that is non-empty.
7799        view.update(cx, |view, cx| {
7800            view.select_display_ranges(
7801                &[
7802                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
7803                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 2),
7804                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
7805                ],
7806                cx,
7807            );
7808            view.paste(&Paste, cx);
7809            assert_eq!(
7810                view.display_text(cx),
7811                "123\n123\n123\n67\n123\n9\n( 8ne✅ three five ) two one✅ four three six five ( one✅ three five ) "
7812            );
7813            assert_eq!(
7814                view.selected_display_ranges(cx),
7815                &[
7816                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
7817                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
7818                    DisplayPoint::new(5, 1)..DisplayPoint::new(5, 1),
7819                ]
7820            );
7821        });
7822    }
7823
7824    #[gpui::test]
7825    fn test_select_all(cx: &mut gpui::MutableAppContext) {
7826        populate_settings(cx);
7827        let buffer = MultiBuffer::build_simple("abc\nde\nfgh", cx);
7828        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
7829        view.update(cx, |view, cx| {
7830            view.select_all(&SelectAll, cx);
7831            assert_eq!(
7832                view.selected_display_ranges(cx),
7833                &[DisplayPoint::new(0, 0)..DisplayPoint::new(2, 3)]
7834            );
7835        });
7836    }
7837
7838    #[gpui::test]
7839    fn test_select_line(cx: &mut gpui::MutableAppContext) {
7840        populate_settings(cx);
7841        let buffer = MultiBuffer::build_simple(&sample_text(6, 5, 'a'), cx);
7842        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
7843        view.update(cx, |view, cx| {
7844            view.select_display_ranges(
7845                &[
7846                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
7847                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7848                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
7849                    DisplayPoint::new(4, 2)..DisplayPoint::new(4, 2),
7850                ],
7851                cx,
7852            );
7853            view.select_line(&SelectLine, cx);
7854            assert_eq!(
7855                view.selected_display_ranges(cx),
7856                vec![
7857                    DisplayPoint::new(0, 0)..DisplayPoint::new(2, 0),
7858                    DisplayPoint::new(4, 0)..DisplayPoint::new(5, 0),
7859                ]
7860            );
7861        });
7862
7863        view.update(cx, |view, cx| {
7864            view.select_line(&SelectLine, cx);
7865            assert_eq!(
7866                view.selected_display_ranges(cx),
7867                vec![
7868                    DisplayPoint::new(0, 0)..DisplayPoint::new(3, 0),
7869                    DisplayPoint::new(4, 0)..DisplayPoint::new(5, 5),
7870                ]
7871            );
7872        });
7873
7874        view.update(cx, |view, cx| {
7875            view.select_line(&SelectLine, cx);
7876            assert_eq!(
7877                view.selected_display_ranges(cx),
7878                vec![DisplayPoint::new(0, 0)..DisplayPoint::new(5, 5)]
7879            );
7880        });
7881    }
7882
7883    #[gpui::test]
7884    fn test_split_selection_into_lines(cx: &mut gpui::MutableAppContext) {
7885        populate_settings(cx);
7886        let buffer = MultiBuffer::build_simple(&sample_text(9, 5, 'a'), cx);
7887        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
7888        view.update(cx, |view, cx| {
7889            view.fold_ranges(
7890                vec![
7891                    Point::new(0, 2)..Point::new(1, 2),
7892                    Point::new(2, 3)..Point::new(4, 1),
7893                    Point::new(7, 0)..Point::new(8, 4),
7894                ],
7895                cx,
7896            );
7897            view.select_display_ranges(
7898                &[
7899                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
7900                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7901                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
7902                    DisplayPoint::new(4, 4)..DisplayPoint::new(4, 4),
7903                ],
7904                cx,
7905            );
7906            assert_eq!(view.display_text(cx), "aa…bbb\nccc…eeee\nfffff\nggggg\n…i");
7907        });
7908
7909        view.update(cx, |view, cx| {
7910            view.split_selection_into_lines(&SplitSelectionIntoLines, cx);
7911            assert_eq!(
7912                view.display_text(cx),
7913                "aaaaa\nbbbbb\nccc…eeee\nfffff\nggggg\n…i"
7914            );
7915            assert_eq!(
7916                view.selected_display_ranges(cx),
7917                [
7918                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
7919                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7920                    DisplayPoint::new(2, 0)..DisplayPoint::new(2, 0),
7921                    DisplayPoint::new(5, 4)..DisplayPoint::new(5, 4)
7922                ]
7923            );
7924        });
7925
7926        view.update(cx, |view, cx| {
7927            view.select_display_ranges(&[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 1)], cx);
7928            view.split_selection_into_lines(&SplitSelectionIntoLines, cx);
7929            assert_eq!(
7930                view.display_text(cx),
7931                "aaaaa\nbbbbb\nccccc\nddddd\neeeee\nfffff\nggggg\nhhhhh\niiiii"
7932            );
7933            assert_eq!(
7934                view.selected_display_ranges(cx),
7935                [
7936                    DisplayPoint::new(0, 5)..DisplayPoint::new(0, 5),
7937                    DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
7938                    DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
7939                    DisplayPoint::new(3, 5)..DisplayPoint::new(3, 5),
7940                    DisplayPoint::new(4, 5)..DisplayPoint::new(4, 5),
7941                    DisplayPoint::new(5, 5)..DisplayPoint::new(5, 5),
7942                    DisplayPoint::new(6, 5)..DisplayPoint::new(6, 5),
7943                    DisplayPoint::new(7, 0)..DisplayPoint::new(7, 0)
7944                ]
7945            );
7946        });
7947    }
7948
7949    #[gpui::test]
7950    fn test_add_selection_above_below(cx: &mut gpui::MutableAppContext) {
7951        populate_settings(cx);
7952        let buffer = MultiBuffer::build_simple("abc\ndefghi\n\njk\nlmno\n", cx);
7953        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
7954
7955        view.update(cx, |view, cx| {
7956            view.select_display_ranges(&[DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)], cx);
7957        });
7958        view.update(cx, |view, cx| {
7959            view.add_selection_above(&AddSelectionAbove, cx);
7960            assert_eq!(
7961                view.selected_display_ranges(cx),
7962                vec![
7963                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
7964                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)
7965                ]
7966            );
7967        });
7968
7969        view.update(cx, |view, cx| {
7970            view.add_selection_above(&AddSelectionAbove, cx);
7971            assert_eq!(
7972                view.selected_display_ranges(cx),
7973                vec![
7974                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
7975                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)
7976                ]
7977            );
7978        });
7979
7980        view.update(cx, |view, cx| {
7981            view.add_selection_below(&AddSelectionBelow, cx);
7982            assert_eq!(
7983                view.selected_display_ranges(cx),
7984                vec![DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)]
7985            );
7986        });
7987
7988        view.update(cx, |view, cx| {
7989            view.add_selection_below(&AddSelectionBelow, cx);
7990            assert_eq!(
7991                view.selected_display_ranges(cx),
7992                vec![
7993                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
7994                    DisplayPoint::new(4, 3)..DisplayPoint::new(4, 3)
7995                ]
7996            );
7997        });
7998
7999        view.update(cx, |view, cx| {
8000            view.add_selection_below(&AddSelectionBelow, cx);
8001            assert_eq!(
8002                view.selected_display_ranges(cx),
8003                vec![
8004                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
8005                    DisplayPoint::new(4, 3)..DisplayPoint::new(4, 3)
8006                ]
8007            );
8008        });
8009
8010        view.update(cx, |view, cx| {
8011            view.select_display_ranges(&[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)], cx);
8012        });
8013        view.update(cx, |view, cx| {
8014            view.add_selection_below(&AddSelectionBelow, cx);
8015            assert_eq!(
8016                view.selected_display_ranges(cx),
8017                vec![
8018                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
8019                    DisplayPoint::new(4, 4)..DisplayPoint::new(4, 3)
8020                ]
8021            );
8022        });
8023
8024        view.update(cx, |view, cx| {
8025            view.add_selection_below(&AddSelectionBelow, cx);
8026            assert_eq!(
8027                view.selected_display_ranges(cx),
8028                vec![
8029                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
8030                    DisplayPoint::new(4, 4)..DisplayPoint::new(4, 3)
8031                ]
8032            );
8033        });
8034
8035        view.update(cx, |view, cx| {
8036            view.add_selection_above(&AddSelectionAbove, cx);
8037            assert_eq!(
8038                view.selected_display_ranges(cx),
8039                vec![DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)]
8040            );
8041        });
8042
8043        view.update(cx, |view, cx| {
8044            view.add_selection_above(&AddSelectionAbove, cx);
8045            assert_eq!(
8046                view.selected_display_ranges(cx),
8047                vec![DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)]
8048            );
8049        });
8050
8051        view.update(cx, |view, cx| {
8052            view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(1, 4)], cx);
8053            view.add_selection_below(&AddSelectionBelow, cx);
8054            assert_eq!(
8055                view.selected_display_ranges(cx),
8056                vec![
8057                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
8058                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
8059                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
8060                ]
8061            );
8062        });
8063
8064        view.update(cx, |view, cx| {
8065            view.add_selection_below(&AddSelectionBelow, cx);
8066            assert_eq!(
8067                view.selected_display_ranges(cx),
8068                vec![
8069                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
8070                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
8071                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
8072                    DisplayPoint::new(4, 1)..DisplayPoint::new(4, 4),
8073                ]
8074            );
8075        });
8076
8077        view.update(cx, |view, cx| {
8078            view.add_selection_above(&AddSelectionAbove, cx);
8079            assert_eq!(
8080                view.selected_display_ranges(cx),
8081                vec![
8082                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
8083                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
8084                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
8085                ]
8086            );
8087        });
8088
8089        view.update(cx, |view, cx| {
8090            view.select_display_ranges(&[DisplayPoint::new(4, 3)..DisplayPoint::new(1, 1)], cx);
8091        });
8092        view.update(cx, |view, cx| {
8093            view.add_selection_above(&AddSelectionAbove, cx);
8094            assert_eq!(
8095                view.selected_display_ranges(cx),
8096                vec![
8097                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 1),
8098                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 1),
8099                    DisplayPoint::new(3, 2)..DisplayPoint::new(3, 1),
8100                    DisplayPoint::new(4, 3)..DisplayPoint::new(4, 1),
8101                ]
8102            );
8103        });
8104
8105        view.update(cx, |view, cx| {
8106            view.add_selection_below(&AddSelectionBelow, cx);
8107            assert_eq!(
8108                view.selected_display_ranges(cx),
8109                vec![
8110                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 1),
8111                    DisplayPoint::new(3, 2)..DisplayPoint::new(3, 1),
8112                    DisplayPoint::new(4, 3)..DisplayPoint::new(4, 1),
8113                ]
8114            );
8115        });
8116    }
8117
8118    #[gpui::test]
8119    async fn test_select_larger_smaller_syntax_node(cx: &mut gpui::TestAppContext) {
8120        cx.update(populate_settings);
8121        let language = Arc::new(Language::new(
8122            LanguageConfig::default(),
8123            Some(tree_sitter_rust::language()),
8124        ));
8125
8126        let text = r#"
8127            use mod1::mod2::{mod3, mod4};
8128
8129            fn fn_1(param1: bool, param2: &str) {
8130                let var1 = "text";
8131            }
8132        "#
8133        .unindent();
8134
8135        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
8136        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
8137        let (_, view) = cx.add_window(|cx| build_editor(buffer, cx));
8138        view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
8139            .await;
8140
8141        view.update(cx, |view, cx| {
8142            view.select_display_ranges(
8143                &[
8144                    DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
8145                    DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
8146                    DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
8147                ],
8148                cx,
8149            );
8150            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
8151        });
8152        assert_eq!(
8153            view.update(cx, |view, cx| view.selected_display_ranges(cx)),
8154            &[
8155                DisplayPoint::new(0, 23)..DisplayPoint::new(0, 27),
8156                DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
8157                DisplayPoint::new(3, 15)..DisplayPoint::new(3, 21),
8158            ]
8159        );
8160
8161        view.update(cx, |view, cx| {
8162            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
8163        });
8164        assert_eq!(
8165            view.update(cx, |view, cx| view.selected_display_ranges(cx)),
8166            &[
8167                DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
8168                DisplayPoint::new(4, 1)..DisplayPoint::new(2, 0),
8169            ]
8170        );
8171
8172        view.update(cx, |view, cx| {
8173            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
8174        });
8175        assert_eq!(
8176            view.update(cx, |view, cx| view.selected_display_ranges(cx)),
8177            &[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 0)]
8178        );
8179
8180        // Trying to expand the selected syntax node one more time has no effect.
8181        view.update(cx, |view, cx| {
8182            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
8183        });
8184        assert_eq!(
8185            view.update(cx, |view, cx| view.selected_display_ranges(cx)),
8186            &[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 0)]
8187        );
8188
8189        view.update(cx, |view, cx| {
8190            view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
8191        });
8192        assert_eq!(
8193            view.update(cx, |view, cx| view.selected_display_ranges(cx)),
8194            &[
8195                DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
8196                DisplayPoint::new(4, 1)..DisplayPoint::new(2, 0),
8197            ]
8198        );
8199
8200        view.update(cx, |view, cx| {
8201            view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
8202        });
8203        assert_eq!(
8204            view.update(cx, |view, cx| view.selected_display_ranges(cx)),
8205            &[
8206                DisplayPoint::new(0, 23)..DisplayPoint::new(0, 27),
8207                DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
8208                DisplayPoint::new(3, 15)..DisplayPoint::new(3, 21),
8209            ]
8210        );
8211
8212        view.update(cx, |view, cx| {
8213            view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
8214        });
8215        assert_eq!(
8216            view.update(cx, |view, cx| view.selected_display_ranges(cx)),
8217            &[
8218                DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
8219                DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
8220                DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
8221            ]
8222        );
8223
8224        // Trying to shrink the selected syntax node one more time has no effect.
8225        view.update(cx, |view, cx| {
8226            view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
8227        });
8228        assert_eq!(
8229            view.update(cx, |view, cx| view.selected_display_ranges(cx)),
8230            &[
8231                DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
8232                DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
8233                DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
8234            ]
8235        );
8236
8237        // Ensure that we keep expanding the selection if the larger selection starts or ends within
8238        // a fold.
8239        view.update(cx, |view, cx| {
8240            view.fold_ranges(
8241                vec![
8242                    Point::new(0, 21)..Point::new(0, 24),
8243                    Point::new(3, 20)..Point::new(3, 22),
8244                ],
8245                cx,
8246            );
8247            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
8248        });
8249        assert_eq!(
8250            view.update(cx, |view, cx| view.selected_display_ranges(cx)),
8251            &[
8252                DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
8253                DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
8254                DisplayPoint::new(3, 4)..DisplayPoint::new(3, 23),
8255            ]
8256        );
8257    }
8258
8259    #[gpui::test]
8260    async fn test_autoindent_selections(cx: &mut gpui::TestAppContext) {
8261        cx.update(populate_settings);
8262        let language = Arc::new(
8263            Language::new(
8264                LanguageConfig {
8265                    brackets: vec![
8266                        BracketPair {
8267                            start: "{".to_string(),
8268                            end: "}".to_string(),
8269                            close: false,
8270                            newline: true,
8271                        },
8272                        BracketPair {
8273                            start: "(".to_string(),
8274                            end: ")".to_string(),
8275                            close: false,
8276                            newline: true,
8277                        },
8278                    ],
8279                    ..Default::default()
8280                },
8281                Some(tree_sitter_rust::language()),
8282            )
8283            .with_indents_query(
8284                r#"
8285                (_ "(" ")" @end) @indent
8286                (_ "{" "}" @end) @indent
8287                "#,
8288            )
8289            .unwrap(),
8290        );
8291
8292        let text = "fn a() {}";
8293
8294        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
8295        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
8296        let (_, editor) = cx.add_window(|cx| build_editor(buffer, cx));
8297        editor
8298            .condition(&cx, |editor, cx| !editor.buffer.read(cx).is_parsing(cx))
8299            .await;
8300
8301        editor.update(cx, |editor, cx| {
8302            editor.select_ranges([5..5, 8..8, 9..9], None, cx);
8303            editor.newline(&Newline, cx);
8304            assert_eq!(editor.text(cx), "fn a(\n    \n) {\n    \n}\n");
8305            assert_eq!(
8306                editor.selected_ranges(cx),
8307                &[
8308                    Point::new(1, 4)..Point::new(1, 4),
8309                    Point::new(3, 4)..Point::new(3, 4),
8310                    Point::new(5, 0)..Point::new(5, 0)
8311                ]
8312            );
8313        });
8314    }
8315
8316    #[gpui::test]
8317    async fn test_autoclose_pairs(cx: &mut gpui::TestAppContext) {
8318        cx.update(populate_settings);
8319        let language = Arc::new(Language::new(
8320            LanguageConfig {
8321                brackets: vec![
8322                    BracketPair {
8323                        start: "{".to_string(),
8324                        end: "}".to_string(),
8325                        close: true,
8326                        newline: true,
8327                    },
8328                    BracketPair {
8329                        start: "/*".to_string(),
8330                        end: " */".to_string(),
8331                        close: true,
8332                        newline: true,
8333                    },
8334                ],
8335                autoclose_before: "})]".to_string(),
8336                ..Default::default()
8337            },
8338            Some(tree_sitter_rust::language()),
8339        ));
8340
8341        let text = r#"
8342            a
8343
8344            /
8345
8346        "#
8347        .unindent();
8348
8349        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
8350        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
8351        let (_, view) = cx.add_window(|cx| build_editor(buffer, cx));
8352        view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
8353            .await;
8354
8355        view.update(cx, |view, cx| {
8356            view.select_display_ranges(
8357                &[
8358                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
8359                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
8360                ],
8361                cx,
8362            );
8363
8364            view.handle_input(&Input("{".to_string()), cx);
8365            view.handle_input(&Input("{".to_string()), cx);
8366            view.handle_input(&Input("{".to_string()), cx);
8367            assert_eq!(
8368                view.text(cx),
8369                "
8370                {{{}}}
8371                {{{}}}
8372                /
8373
8374                "
8375                .unindent()
8376            );
8377
8378            view.move_right(&MoveRight, cx);
8379            view.handle_input(&Input("}".to_string()), cx);
8380            view.handle_input(&Input("}".to_string()), cx);
8381            view.handle_input(&Input("}".to_string()), cx);
8382            assert_eq!(
8383                view.text(cx),
8384                "
8385                {{{}}}}
8386                {{{}}}}
8387                /
8388
8389                "
8390                .unindent()
8391            );
8392
8393            view.undo(&Undo, cx);
8394            view.handle_input(&Input("/".to_string()), cx);
8395            view.handle_input(&Input("*".to_string()), cx);
8396            assert_eq!(
8397                view.text(cx),
8398                "
8399                /* */
8400                /* */
8401                /
8402
8403                "
8404                .unindent()
8405            );
8406
8407            view.undo(&Undo, cx);
8408            view.select_display_ranges(
8409                &[
8410                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
8411                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
8412                ],
8413                cx,
8414            );
8415            view.handle_input(&Input("*".to_string()), cx);
8416            assert_eq!(
8417                view.text(cx),
8418                "
8419                a
8420
8421                /*
8422                *
8423                "
8424                .unindent()
8425            );
8426
8427            // Don't autoclose if the next character isn't whitespace and isn't
8428            // listed in the language's "autoclose_before" section.
8429            view.finalize_last_transaction(cx);
8430            view.select_display_ranges(&[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)], cx);
8431            view.handle_input(&Input("{".to_string()), cx);
8432            assert_eq!(
8433                view.text(cx),
8434                "
8435                {a
8436
8437                /*
8438                *
8439                "
8440                .unindent()
8441            );
8442
8443            view.undo(&Undo, cx);
8444            view.select_display_ranges(&[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1)], cx);
8445            view.handle_input(&Input("{".to_string()), cx);
8446            assert_eq!(
8447                view.text(cx),
8448                "
8449                {a}
8450
8451                /*
8452                *
8453                "
8454                .unindent()
8455            );
8456            assert_eq!(
8457                view.selected_display_ranges(cx),
8458                [DisplayPoint::new(0, 1)..DisplayPoint::new(0, 2)]
8459            );
8460        });
8461    }
8462
8463    #[gpui::test]
8464    async fn test_snippets(cx: &mut gpui::TestAppContext) {
8465        cx.update(populate_settings);
8466
8467        let text = "
8468            a. b
8469            a. b
8470            a. b
8471        "
8472        .unindent();
8473        let buffer = cx.update(|cx| MultiBuffer::build_simple(&text, cx));
8474        let (_, editor) = cx.add_window(|cx| build_editor(buffer, cx));
8475
8476        editor.update(cx, |editor, cx| {
8477            let buffer = &editor.snapshot(cx).buffer_snapshot;
8478            let snippet = Snippet::parse("f(${1:one}, ${2:two}, ${1:three})$0").unwrap();
8479            let insertion_ranges = [
8480                Point::new(0, 2).to_offset(buffer)..Point::new(0, 2).to_offset(buffer),
8481                Point::new(1, 2).to_offset(buffer)..Point::new(1, 2).to_offset(buffer),
8482                Point::new(2, 2).to_offset(buffer)..Point::new(2, 2).to_offset(buffer),
8483            ];
8484
8485            editor
8486                .insert_snippet(&insertion_ranges, snippet, cx)
8487                .unwrap();
8488            assert_eq!(
8489                editor.text(cx),
8490                "
8491                    a.f(one, two, three) b
8492                    a.f(one, two, three) b
8493                    a.f(one, two, three) b
8494                "
8495                .unindent()
8496            );
8497            assert_eq!(
8498                editor.selected_ranges::<Point>(cx),
8499                &[
8500                    Point::new(0, 4)..Point::new(0, 7),
8501                    Point::new(0, 14)..Point::new(0, 19),
8502                    Point::new(1, 4)..Point::new(1, 7),
8503                    Point::new(1, 14)..Point::new(1, 19),
8504                    Point::new(2, 4)..Point::new(2, 7),
8505                    Point::new(2, 14)..Point::new(2, 19),
8506                ]
8507            );
8508
8509            // Can't move earlier than the first tab stop
8510            editor.move_to_prev_snippet_tabstop(cx);
8511            assert_eq!(
8512                editor.selected_ranges::<Point>(cx),
8513                &[
8514                    Point::new(0, 4)..Point::new(0, 7),
8515                    Point::new(0, 14)..Point::new(0, 19),
8516                    Point::new(1, 4)..Point::new(1, 7),
8517                    Point::new(1, 14)..Point::new(1, 19),
8518                    Point::new(2, 4)..Point::new(2, 7),
8519                    Point::new(2, 14)..Point::new(2, 19),
8520                ]
8521            );
8522
8523            assert!(editor.move_to_next_snippet_tabstop(cx));
8524            assert_eq!(
8525                editor.selected_ranges::<Point>(cx),
8526                &[
8527                    Point::new(0, 9)..Point::new(0, 12),
8528                    Point::new(1, 9)..Point::new(1, 12),
8529                    Point::new(2, 9)..Point::new(2, 12)
8530                ]
8531            );
8532
8533            editor.move_to_prev_snippet_tabstop(cx);
8534            assert_eq!(
8535                editor.selected_ranges::<Point>(cx),
8536                &[
8537                    Point::new(0, 4)..Point::new(0, 7),
8538                    Point::new(0, 14)..Point::new(0, 19),
8539                    Point::new(1, 4)..Point::new(1, 7),
8540                    Point::new(1, 14)..Point::new(1, 19),
8541                    Point::new(2, 4)..Point::new(2, 7),
8542                    Point::new(2, 14)..Point::new(2, 19),
8543                ]
8544            );
8545
8546            assert!(editor.move_to_next_snippet_tabstop(cx));
8547            assert!(editor.move_to_next_snippet_tabstop(cx));
8548            assert_eq!(
8549                editor.selected_ranges::<Point>(cx),
8550                &[
8551                    Point::new(0, 20)..Point::new(0, 20),
8552                    Point::new(1, 20)..Point::new(1, 20),
8553                    Point::new(2, 20)..Point::new(2, 20)
8554                ]
8555            );
8556
8557            // As soon as the last tab stop is reached, snippet state is gone
8558            editor.move_to_prev_snippet_tabstop(cx);
8559            assert_eq!(
8560                editor.selected_ranges::<Point>(cx),
8561                &[
8562                    Point::new(0, 20)..Point::new(0, 20),
8563                    Point::new(1, 20)..Point::new(1, 20),
8564                    Point::new(2, 20)..Point::new(2, 20)
8565                ]
8566            );
8567        });
8568    }
8569
8570    #[gpui::test]
8571    async fn test_completion(cx: &mut gpui::TestAppContext) {
8572        cx.update(populate_settings);
8573
8574        let (mut language_server_config, mut fake_servers) = LanguageServerConfig::fake();
8575        language_server_config.set_fake_capabilities(lsp::ServerCapabilities {
8576            completion_provider: Some(lsp::CompletionOptions {
8577                trigger_characters: Some(vec![".".to_string(), ":".to_string()]),
8578                ..Default::default()
8579            }),
8580            ..Default::default()
8581        });
8582        let language = Arc::new(Language::new(
8583            LanguageConfig {
8584                name: "Rust".into(),
8585                path_suffixes: vec!["rs".to_string()],
8586                language_server: Some(language_server_config),
8587                ..Default::default()
8588            },
8589            Some(tree_sitter_rust::language()),
8590        ));
8591
8592        let text = "
8593            one
8594            two
8595            three
8596        "
8597        .unindent();
8598
8599        let fs = FakeFs::new(cx.background().clone());
8600        fs.insert_file("/file.rs", text).await;
8601
8602        let project = Project::test(fs, cx);
8603        project.update(cx, |project, _| project.languages().add(language));
8604
8605        let worktree_id = project
8606            .update(cx, |project, cx| {
8607                project.find_or_create_local_worktree("/file.rs", true, cx)
8608            })
8609            .await
8610            .unwrap()
8611            .0
8612            .read_with(cx, |tree, _| tree.id());
8613        let buffer = project
8614            .update(cx, |project, cx| project.open_buffer((worktree_id, ""), cx))
8615            .await
8616            .unwrap();
8617        let mut fake_server = fake_servers.next().await.unwrap();
8618
8619        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
8620        let (_, editor) = cx.add_window(|cx| build_editor(buffer, cx));
8621
8622        editor.update(cx, |editor, cx| {
8623            editor.project = Some(project);
8624            editor.select_ranges([Point::new(0, 3)..Point::new(0, 3)], None, cx);
8625            editor.handle_input(&Input(".".to_string()), cx);
8626        });
8627
8628        handle_completion_request(
8629            &mut fake_server,
8630            "/file.rs",
8631            Point::new(0, 4),
8632            vec![
8633                (Point::new(0, 4)..Point::new(0, 4), "first_completion"),
8634                (Point::new(0, 4)..Point::new(0, 4), "second_completion"),
8635            ],
8636        )
8637        .await;
8638        editor
8639            .condition(&cx, |editor, _| editor.context_menu_visible())
8640            .await;
8641
8642        let apply_additional_edits = editor.update(cx, |editor, cx| {
8643            editor.move_down(&MoveDown, cx);
8644            let apply_additional_edits = editor
8645                .confirm_completion(&ConfirmCompletion(None), cx)
8646                .unwrap();
8647            assert_eq!(
8648                editor.text(cx),
8649                "
8650                    one.second_completion
8651                    two
8652                    three
8653                "
8654                .unindent()
8655            );
8656            apply_additional_edits
8657        });
8658
8659        handle_resolve_completion_request(
8660            &mut fake_server,
8661            Some((Point::new(2, 5)..Point::new(2, 5), "\nadditional edit")),
8662        )
8663        .await;
8664        apply_additional_edits.await.unwrap();
8665        assert_eq!(
8666            editor.read_with(cx, |editor, cx| editor.text(cx)),
8667            "
8668                one.second_completion
8669                two
8670                three
8671                additional edit
8672            "
8673            .unindent()
8674        );
8675
8676        editor.update(cx, |editor, cx| {
8677            editor.select_ranges(
8678                [
8679                    Point::new(1, 3)..Point::new(1, 3),
8680                    Point::new(2, 5)..Point::new(2, 5),
8681                ],
8682                None,
8683                cx,
8684            );
8685
8686            editor.handle_input(&Input(" ".to_string()), cx);
8687            assert!(editor.context_menu.is_none());
8688            editor.handle_input(&Input("s".to_string()), cx);
8689            assert!(editor.context_menu.is_none());
8690        });
8691
8692        handle_completion_request(
8693            &mut fake_server,
8694            "/file.rs",
8695            Point::new(2, 7),
8696            vec![
8697                (Point::new(2, 6)..Point::new(2, 7), "fourth_completion"),
8698                (Point::new(2, 6)..Point::new(2, 7), "fifth_completion"),
8699                (Point::new(2, 6)..Point::new(2, 7), "sixth_completion"),
8700            ],
8701        )
8702        .await;
8703        editor
8704            .condition(&cx, |editor, _| editor.context_menu_visible())
8705            .await;
8706
8707        editor.update(cx, |editor, cx| {
8708            editor.handle_input(&Input("i".to_string()), cx);
8709        });
8710
8711        handle_completion_request(
8712            &mut fake_server,
8713            "/file.rs",
8714            Point::new(2, 8),
8715            vec![
8716                (Point::new(2, 6)..Point::new(2, 8), "fourth_completion"),
8717                (Point::new(2, 6)..Point::new(2, 8), "fifth_completion"),
8718                (Point::new(2, 6)..Point::new(2, 8), "sixth_completion"),
8719            ],
8720        )
8721        .await;
8722        editor
8723            .condition(&cx, |editor, _| editor.context_menu_visible())
8724            .await;
8725
8726        let apply_additional_edits = editor.update(cx, |editor, cx| {
8727            let apply_additional_edits = editor
8728                .confirm_completion(&ConfirmCompletion(None), cx)
8729                .unwrap();
8730            assert_eq!(
8731                editor.text(cx),
8732                "
8733                    one.second_completion
8734                    two sixth_completion
8735                    three sixth_completion
8736                    additional edit
8737                "
8738                .unindent()
8739            );
8740            apply_additional_edits
8741        });
8742        handle_resolve_completion_request(&mut fake_server, None).await;
8743        apply_additional_edits.await.unwrap();
8744
8745        async fn handle_completion_request(
8746            fake: &mut FakeLanguageServer,
8747            path: &'static str,
8748            position: Point,
8749            completions: Vec<(Range<Point>, &'static str)>,
8750        ) {
8751            fake.handle_request::<lsp::request::Completion, _>(move |params, _| {
8752                assert_eq!(
8753                    params.text_document_position.text_document.uri,
8754                    lsp::Url::from_file_path(path).unwrap()
8755                );
8756                assert_eq!(
8757                    params.text_document_position.position,
8758                    lsp::Position::new(position.row, position.column)
8759                );
8760                Some(lsp::CompletionResponse::Array(
8761                    completions
8762                        .iter()
8763                        .map(|(range, new_text)| lsp::CompletionItem {
8764                            label: new_text.to_string(),
8765                            text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
8766                                range: lsp::Range::new(
8767                                    lsp::Position::new(range.start.row, range.start.column),
8768                                    lsp::Position::new(range.start.row, range.start.column),
8769                                ),
8770                                new_text: new_text.to_string(),
8771                            })),
8772                            ..Default::default()
8773                        })
8774                        .collect(),
8775                ))
8776            })
8777            .next()
8778            .await;
8779        }
8780
8781        async fn handle_resolve_completion_request(
8782            fake: &mut FakeLanguageServer,
8783            edit: Option<(Range<Point>, &'static str)>,
8784        ) {
8785            fake.handle_request::<lsp::request::ResolveCompletionItem, _>(move |_, _| {
8786                lsp::CompletionItem {
8787                    additional_text_edits: edit.clone().map(|(range, new_text)| {
8788                        vec![lsp::TextEdit::new(
8789                            lsp::Range::new(
8790                                lsp::Position::new(range.start.row, range.start.column),
8791                                lsp::Position::new(range.end.row, range.end.column),
8792                            ),
8793                            new_text.to_string(),
8794                        )]
8795                    }),
8796                    ..Default::default()
8797                }
8798            })
8799            .next()
8800            .await;
8801        }
8802    }
8803
8804    #[gpui::test]
8805    async fn test_toggle_comment(cx: &mut gpui::TestAppContext) {
8806        cx.update(populate_settings);
8807        let language = Arc::new(Language::new(
8808            LanguageConfig {
8809                line_comment: Some("// ".to_string()),
8810                ..Default::default()
8811            },
8812            Some(tree_sitter_rust::language()),
8813        ));
8814
8815        let text = "
8816            fn a() {
8817                //b();
8818                // c();
8819                //  d();
8820            }
8821        "
8822        .unindent();
8823
8824        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
8825        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
8826        let (_, view) = cx.add_window(|cx| build_editor(buffer, cx));
8827
8828        view.update(cx, |editor, cx| {
8829            // If multiple selections intersect a line, the line is only
8830            // toggled once.
8831            editor.select_display_ranges(
8832                &[
8833                    DisplayPoint::new(1, 3)..DisplayPoint::new(2, 3),
8834                    DisplayPoint::new(3, 5)..DisplayPoint::new(3, 6),
8835                ],
8836                cx,
8837            );
8838            editor.toggle_comments(&ToggleComments, cx);
8839            assert_eq!(
8840                editor.text(cx),
8841                "
8842                    fn a() {
8843                        b();
8844                        c();
8845                         d();
8846                    }
8847                "
8848                .unindent()
8849            );
8850
8851            // The comment prefix is inserted at the same column for every line
8852            // in a selection.
8853            editor.select_display_ranges(&[DisplayPoint::new(1, 3)..DisplayPoint::new(3, 6)], cx);
8854            editor.toggle_comments(&ToggleComments, cx);
8855            assert_eq!(
8856                editor.text(cx),
8857                "
8858                    fn a() {
8859                        // b();
8860                        // c();
8861                        //  d();
8862                    }
8863                "
8864                .unindent()
8865            );
8866
8867            // If a selection ends at the beginning of a line, that line is not toggled.
8868            editor.select_display_ranges(&[DisplayPoint::new(2, 0)..DisplayPoint::new(3, 0)], cx);
8869            editor.toggle_comments(&ToggleComments, cx);
8870            assert_eq!(
8871                editor.text(cx),
8872                "
8873                        fn a() {
8874                            // b();
8875                            c();
8876                            //  d();
8877                        }
8878                    "
8879                .unindent()
8880            );
8881        });
8882    }
8883
8884    #[gpui::test]
8885    fn test_editing_disjoint_excerpts(cx: &mut gpui::MutableAppContext) {
8886        populate_settings(cx);
8887        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(3, 4, 'a'), cx));
8888        let multibuffer = cx.add_model(|cx| {
8889            let mut multibuffer = MultiBuffer::new(0);
8890            multibuffer.push_excerpts(
8891                buffer.clone(),
8892                [
8893                    Point::new(0, 0)..Point::new(0, 4),
8894                    Point::new(1, 0)..Point::new(1, 4),
8895                ],
8896                cx,
8897            );
8898            multibuffer
8899        });
8900
8901        assert_eq!(multibuffer.read(cx).read(cx).text(), "aaaa\nbbbb");
8902
8903        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(multibuffer, cx));
8904        view.update(cx, |view, cx| {
8905            assert_eq!(view.text(cx), "aaaa\nbbbb");
8906            view.select_ranges(
8907                [
8908                    Point::new(0, 0)..Point::new(0, 0),
8909                    Point::new(1, 0)..Point::new(1, 0),
8910                ],
8911                None,
8912                cx,
8913            );
8914
8915            view.handle_input(&Input("X".to_string()), cx);
8916            assert_eq!(view.text(cx), "Xaaaa\nXbbbb");
8917            assert_eq!(
8918                view.selected_ranges(cx),
8919                [
8920                    Point::new(0, 1)..Point::new(0, 1),
8921                    Point::new(1, 1)..Point::new(1, 1),
8922                ]
8923            )
8924        });
8925    }
8926
8927    #[gpui::test]
8928    fn test_editing_overlapping_excerpts(cx: &mut gpui::MutableAppContext) {
8929        populate_settings(cx);
8930        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(3, 4, 'a'), cx));
8931        let multibuffer = cx.add_model(|cx| {
8932            let mut multibuffer = MultiBuffer::new(0);
8933            multibuffer.push_excerpts(
8934                buffer,
8935                [
8936                    Point::new(0, 0)..Point::new(1, 4),
8937                    Point::new(1, 0)..Point::new(2, 4),
8938                ],
8939                cx,
8940            );
8941            multibuffer
8942        });
8943
8944        assert_eq!(
8945            multibuffer.read(cx).read(cx).text(),
8946            "aaaa\nbbbb\nbbbb\ncccc"
8947        );
8948
8949        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(multibuffer, cx));
8950        view.update(cx, |view, cx| {
8951            view.select_ranges(
8952                [
8953                    Point::new(1, 1)..Point::new(1, 1),
8954                    Point::new(2, 3)..Point::new(2, 3),
8955                ],
8956                None,
8957                cx,
8958            );
8959
8960            view.handle_input(&Input("X".to_string()), cx);
8961            assert_eq!(view.text(cx), "aaaa\nbXbbXb\nbXbbXb\ncccc");
8962            assert_eq!(
8963                view.selected_ranges(cx),
8964                [
8965                    Point::new(1, 2)..Point::new(1, 2),
8966                    Point::new(2, 5)..Point::new(2, 5),
8967                ]
8968            );
8969
8970            view.newline(&Newline, cx);
8971            assert_eq!(view.text(cx), "aaaa\nbX\nbbX\nb\nbX\nbbX\nb\ncccc");
8972            assert_eq!(
8973                view.selected_ranges(cx),
8974                [
8975                    Point::new(2, 0)..Point::new(2, 0),
8976                    Point::new(6, 0)..Point::new(6, 0),
8977                ]
8978            );
8979        });
8980    }
8981
8982    #[gpui::test]
8983    fn test_refresh_selections(cx: &mut gpui::MutableAppContext) {
8984        populate_settings(cx);
8985        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(3, 4, 'a'), cx));
8986        let mut excerpt1_id = None;
8987        let multibuffer = cx.add_model(|cx| {
8988            let mut multibuffer = MultiBuffer::new(0);
8989            excerpt1_id = multibuffer
8990                .push_excerpts(
8991                    buffer.clone(),
8992                    [
8993                        Point::new(0, 0)..Point::new(1, 4),
8994                        Point::new(1, 0)..Point::new(2, 4),
8995                    ],
8996                    cx,
8997                )
8998                .into_iter()
8999                .next();
9000            multibuffer
9001        });
9002        assert_eq!(
9003            multibuffer.read(cx).read(cx).text(),
9004            "aaaa\nbbbb\nbbbb\ncccc"
9005        );
9006        let (_, editor) = cx.add_window(Default::default(), |cx| {
9007            let mut editor = build_editor(multibuffer.clone(), cx);
9008            let snapshot = editor.snapshot(cx);
9009            editor.select_ranges([Point::new(1, 3)..Point::new(1, 3)], None, cx);
9010            editor.begin_selection(Point::new(2, 1).to_display_point(&snapshot), true, 1, cx);
9011            assert_eq!(
9012                editor.selected_ranges(cx),
9013                [
9014                    Point::new(1, 3)..Point::new(1, 3),
9015                    Point::new(2, 1)..Point::new(2, 1),
9016                ]
9017            );
9018            editor
9019        });
9020
9021        // Refreshing selections is a no-op when excerpts haven't changed.
9022        editor.update(cx, |editor, cx| {
9023            editor.refresh_selections(cx);
9024            assert_eq!(
9025                editor.selected_ranges(cx),
9026                [
9027                    Point::new(1, 3)..Point::new(1, 3),
9028                    Point::new(2, 1)..Point::new(2, 1),
9029                ]
9030            );
9031        });
9032
9033        multibuffer.update(cx, |multibuffer, cx| {
9034            multibuffer.remove_excerpts([&excerpt1_id.unwrap()], cx);
9035        });
9036        editor.update(cx, |editor, cx| {
9037            // Removing an excerpt causes the first selection to become degenerate.
9038            assert_eq!(
9039                editor.selected_ranges(cx),
9040                [
9041                    Point::new(0, 0)..Point::new(0, 0),
9042                    Point::new(0, 1)..Point::new(0, 1)
9043                ]
9044            );
9045
9046            // Refreshing selections will relocate the first selection to the original buffer
9047            // location.
9048            editor.refresh_selections(cx);
9049            assert_eq!(
9050                editor.selected_ranges(cx),
9051                [
9052                    Point::new(0, 1)..Point::new(0, 1),
9053                    Point::new(0, 3)..Point::new(0, 3)
9054                ]
9055            );
9056            assert!(editor.pending_selection.is_some());
9057        });
9058    }
9059
9060    #[gpui::test]
9061    fn test_refresh_selections_while_selecting_with_mouse(cx: &mut gpui::MutableAppContext) {
9062        populate_settings(cx);
9063        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(3, 4, 'a'), cx));
9064        let mut excerpt1_id = None;
9065        let multibuffer = cx.add_model(|cx| {
9066            let mut multibuffer = MultiBuffer::new(0);
9067            excerpt1_id = multibuffer
9068                .push_excerpts(
9069                    buffer.clone(),
9070                    [
9071                        Point::new(0, 0)..Point::new(1, 4),
9072                        Point::new(1, 0)..Point::new(2, 4),
9073                    ],
9074                    cx,
9075                )
9076                .into_iter()
9077                .next();
9078            multibuffer
9079        });
9080        assert_eq!(
9081            multibuffer.read(cx).read(cx).text(),
9082            "aaaa\nbbbb\nbbbb\ncccc"
9083        );
9084        let (_, editor) = cx.add_window(Default::default(), |cx| {
9085            let mut editor = build_editor(multibuffer.clone(), cx);
9086            let snapshot = editor.snapshot(cx);
9087            editor.begin_selection(Point::new(1, 3).to_display_point(&snapshot), false, 1, cx);
9088            assert_eq!(
9089                editor.selected_ranges(cx),
9090                [Point::new(1, 3)..Point::new(1, 3)]
9091            );
9092            editor
9093        });
9094
9095        multibuffer.update(cx, |multibuffer, cx| {
9096            multibuffer.remove_excerpts([&excerpt1_id.unwrap()], cx);
9097        });
9098        editor.update(cx, |editor, cx| {
9099            assert_eq!(
9100                editor.selected_ranges(cx),
9101                [Point::new(0, 0)..Point::new(0, 0)]
9102            );
9103
9104            // Ensure we don't panic when selections are refreshed and that the pending selection is finalized.
9105            editor.refresh_selections(cx);
9106            assert_eq!(
9107                editor.selected_ranges(cx),
9108                [Point::new(0, 3)..Point::new(0, 3)]
9109            );
9110            assert!(editor.pending_selection.is_some());
9111        });
9112    }
9113
9114    #[gpui::test]
9115    async fn test_extra_newline_insertion(cx: &mut gpui::TestAppContext) {
9116        cx.update(populate_settings);
9117        let language = Arc::new(Language::new(
9118            LanguageConfig {
9119                brackets: vec![
9120                    BracketPair {
9121                        start: "{".to_string(),
9122                        end: "}".to_string(),
9123                        close: true,
9124                        newline: true,
9125                    },
9126                    BracketPair {
9127                        start: "/* ".to_string(),
9128                        end: " */".to_string(),
9129                        close: true,
9130                        newline: true,
9131                    },
9132                ],
9133                ..Default::default()
9134            },
9135            Some(tree_sitter_rust::language()),
9136        ));
9137
9138        let text = concat!(
9139            "{   }\n",     // Suppress rustfmt
9140            "  x\n",       //
9141            "  /*   */\n", //
9142            "x\n",         //
9143            "{{} }\n",     //
9144        );
9145
9146        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
9147        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
9148        let (_, view) = cx.add_window(|cx| build_editor(buffer, cx));
9149        view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
9150            .await;
9151
9152        view.update(cx, |view, cx| {
9153            view.select_display_ranges(
9154                &[
9155                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 3),
9156                    DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
9157                    DisplayPoint::new(4, 4)..DisplayPoint::new(4, 4),
9158                ],
9159                cx,
9160            );
9161            view.newline(&Newline, cx);
9162
9163            assert_eq!(
9164                view.buffer().read(cx).read(cx).text(),
9165                concat!(
9166                    "{ \n",    // Suppress rustfmt
9167                    "\n",      //
9168                    "}\n",     //
9169                    "  x\n",   //
9170                    "  /* \n", //
9171                    "  \n",    //
9172                    "  */\n",  //
9173                    "x\n",     //
9174                    "{{} \n",  //
9175                    "}\n",     //
9176                )
9177            );
9178        });
9179    }
9180
9181    #[gpui::test]
9182    fn test_highlighted_ranges(cx: &mut gpui::MutableAppContext) {
9183        let buffer = MultiBuffer::build_simple(&sample_text(16, 8, 'a'), cx);
9184        populate_settings(cx);
9185        let (_, editor) = cx.add_window(Default::default(), |cx| build_editor(buffer.clone(), cx));
9186
9187        editor.update(cx, |editor, cx| {
9188            struct Type1;
9189            struct Type2;
9190
9191            let buffer = buffer.read(cx).snapshot(cx);
9192
9193            let anchor_range = |range: Range<Point>| {
9194                buffer.anchor_after(range.start)..buffer.anchor_after(range.end)
9195            };
9196
9197            editor.highlight_background::<Type1>(
9198                vec![
9199                    anchor_range(Point::new(2, 1)..Point::new(2, 3)),
9200                    anchor_range(Point::new(4, 2)..Point::new(4, 4)),
9201                    anchor_range(Point::new(6, 3)..Point::new(6, 5)),
9202                    anchor_range(Point::new(8, 4)..Point::new(8, 6)),
9203                ],
9204                Color::red(),
9205                cx,
9206            );
9207            editor.highlight_background::<Type2>(
9208                vec![
9209                    anchor_range(Point::new(3, 2)..Point::new(3, 5)),
9210                    anchor_range(Point::new(5, 3)..Point::new(5, 6)),
9211                    anchor_range(Point::new(7, 4)..Point::new(7, 7)),
9212                    anchor_range(Point::new(9, 5)..Point::new(9, 8)),
9213                ],
9214                Color::green(),
9215                cx,
9216            );
9217
9218            let snapshot = editor.snapshot(cx);
9219            let mut highlighted_ranges = editor.background_highlights_in_range(
9220                anchor_range(Point::new(3, 4)..Point::new(7, 4)),
9221                &snapshot,
9222            );
9223            // Enforce a consistent ordering based on color without relying on the ordering of the
9224            // highlight's `TypeId` which is non-deterministic.
9225            highlighted_ranges.sort_unstable_by_key(|(_, color)| *color);
9226            assert_eq!(
9227                highlighted_ranges,
9228                &[
9229                    (
9230                        DisplayPoint::new(3, 2)..DisplayPoint::new(3, 5),
9231                        Color::green(),
9232                    ),
9233                    (
9234                        DisplayPoint::new(5, 3)..DisplayPoint::new(5, 6),
9235                        Color::green(),
9236                    ),
9237                    (
9238                        DisplayPoint::new(4, 2)..DisplayPoint::new(4, 4),
9239                        Color::red(),
9240                    ),
9241                    (
9242                        DisplayPoint::new(6, 3)..DisplayPoint::new(6, 5),
9243                        Color::red(),
9244                    ),
9245                ]
9246            );
9247            assert_eq!(
9248                editor.background_highlights_in_range(
9249                    anchor_range(Point::new(5, 6)..Point::new(6, 4)),
9250                    &snapshot,
9251                ),
9252                &[(
9253                    DisplayPoint::new(6, 3)..DisplayPoint::new(6, 5),
9254                    Color::red(),
9255                )]
9256            );
9257        });
9258    }
9259
9260    #[gpui::test]
9261    fn test_following(cx: &mut gpui::MutableAppContext) {
9262        let buffer = MultiBuffer::build_simple(&sample_text(16, 8, 'a'), cx);
9263        populate_settings(cx);
9264
9265        let (_, leader) = cx.add_window(Default::default(), |cx| build_editor(buffer.clone(), cx));
9266        let (_, follower) = cx.add_window(
9267            WindowOptions {
9268                bounds: WindowBounds::Fixed(RectF::from_points(vec2f(0., 0.), vec2f(10., 80.))),
9269                ..Default::default()
9270            },
9271            |cx| build_editor(buffer.clone(), cx),
9272        );
9273
9274        let pending_update = Rc::new(RefCell::new(None));
9275        follower.update(cx, {
9276            let update = pending_update.clone();
9277            |_, cx| {
9278                cx.subscribe(&leader, move |_, leader, event, cx| {
9279                    leader
9280                        .read(cx)
9281                        .add_event_to_update_proto(event, &mut *update.borrow_mut(), cx);
9282                })
9283                .detach();
9284            }
9285        });
9286
9287        // Update the selections only
9288        leader.update(cx, |leader, cx| {
9289            leader.select_ranges([1..1], None, cx);
9290        });
9291        follower.update(cx, |follower, cx| {
9292            follower
9293                .apply_update_proto(pending_update.borrow_mut().take().unwrap(), cx)
9294                .unwrap();
9295        });
9296        assert_eq!(follower.read(cx).selected_ranges(cx), vec![1..1]);
9297
9298        // Update the scroll position only
9299        leader.update(cx, |leader, cx| {
9300            leader.set_scroll_position(vec2f(1.5, 3.5), cx);
9301        });
9302        follower.update(cx, |follower, cx| {
9303            follower
9304                .apply_update_proto(pending_update.borrow_mut().take().unwrap(), cx)
9305                .unwrap();
9306        });
9307        assert_eq!(
9308            follower.update(cx, |follower, cx| follower.scroll_position(cx)),
9309            vec2f(1.5, 3.5)
9310        );
9311
9312        // Update the selections and scroll position
9313        leader.update(cx, |leader, cx| {
9314            leader.select_ranges([0..0], None, cx);
9315            leader.request_autoscroll(Autoscroll::Newest, cx);
9316            leader.set_scroll_position(vec2f(1.5, 3.5), cx);
9317        });
9318        follower.update(cx, |follower, cx| {
9319            let initial_scroll_position = follower.scroll_position(cx);
9320            follower
9321                .apply_update_proto(pending_update.borrow_mut().take().unwrap(), cx)
9322                .unwrap();
9323            assert_eq!(follower.scroll_position(cx), initial_scroll_position);
9324            assert!(follower.autoscroll_request.is_some());
9325        });
9326        assert_eq!(follower.read(cx).selected_ranges(cx), vec![0..0]);
9327
9328        // Creating a pending selection that precedes another selection
9329        leader.update(cx, |leader, cx| {
9330            leader.select_ranges([1..1], None, cx);
9331            leader.begin_selection(DisplayPoint::new(0, 0), true, 1, cx);
9332        });
9333        follower.update(cx, |follower, cx| {
9334            follower
9335                .apply_update_proto(pending_update.borrow_mut().take().unwrap(), cx)
9336                .unwrap();
9337        });
9338        assert_eq!(follower.read(cx).selected_ranges(cx), vec![0..0, 1..1]);
9339
9340        // Extend the pending selection so that it surrounds another selection
9341        leader.update(cx, |leader, cx| {
9342            leader.extend_selection(DisplayPoint::new(0, 2), 1, cx);
9343        });
9344        follower.update(cx, |follower, cx| {
9345            follower
9346                .apply_update_proto(pending_update.borrow_mut().take().unwrap(), cx)
9347                .unwrap();
9348        });
9349        assert_eq!(follower.read(cx).selected_ranges(cx), vec![0..2]);
9350    }
9351
9352    #[test]
9353    fn test_combine_syntax_and_fuzzy_match_highlights() {
9354        let string = "abcdefghijklmnop";
9355        let syntax_ranges = [
9356            (
9357                0..3,
9358                HighlightStyle {
9359                    color: Some(Color::red()),
9360                    ..Default::default()
9361                },
9362            ),
9363            (
9364                4..8,
9365                HighlightStyle {
9366                    color: Some(Color::green()),
9367                    ..Default::default()
9368                },
9369            ),
9370        ];
9371        let match_indices = [4, 6, 7, 8];
9372        assert_eq!(
9373            combine_syntax_and_fuzzy_match_highlights(
9374                &string,
9375                Default::default(),
9376                syntax_ranges.into_iter(),
9377                &match_indices,
9378            ),
9379            &[
9380                (
9381                    0..3,
9382                    HighlightStyle {
9383                        color: Some(Color::red()),
9384                        ..Default::default()
9385                    },
9386                ),
9387                (
9388                    4..5,
9389                    HighlightStyle {
9390                        color: Some(Color::green()),
9391                        weight: Some(fonts::Weight::BOLD),
9392                        ..Default::default()
9393                    },
9394                ),
9395                (
9396                    5..6,
9397                    HighlightStyle {
9398                        color: Some(Color::green()),
9399                        ..Default::default()
9400                    },
9401                ),
9402                (
9403                    6..8,
9404                    HighlightStyle {
9405                        color: Some(Color::green()),
9406                        weight: Some(fonts::Weight::BOLD),
9407                        ..Default::default()
9408                    },
9409                ),
9410                (
9411                    8..9,
9412                    HighlightStyle {
9413                        weight: Some(fonts::Weight::BOLD),
9414                        ..Default::default()
9415                    },
9416                ),
9417            ]
9418        );
9419    }
9420
9421    fn empty_range(row: usize, column: usize) -> Range<DisplayPoint> {
9422        let point = DisplayPoint::new(row as u32, column as u32);
9423        point..point
9424    }
9425
9426    fn build_editor(buffer: ModelHandle<MultiBuffer>, cx: &mut ViewContext<Editor>) -> Editor {
9427        Editor::new(EditorMode::Full, buffer, None, None, cx)
9428    }
9429
9430    fn populate_settings(cx: &mut gpui::MutableAppContext) {
9431        let settings = Settings::test(cx);
9432        cx.set_global(settings);
9433    }
9434
9435    fn assert_selection_ranges(
9436        marked_text: &str,
9437        selection_marker_pairs: Vec<(char, char)>,
9438        view: &mut Editor,
9439        cx: &mut ViewContext<Editor>,
9440    ) {
9441        let snapshot = view.snapshot(cx).display_snapshot;
9442        let mut marker_chars = Vec::new();
9443        for (start, end) in selection_marker_pairs.iter() {
9444            marker_chars.push(*start);
9445            marker_chars.push(*end);
9446        }
9447        let (_, markers) = marked_text_by(marked_text, marker_chars);
9448        let asserted_ranges: Vec<Range<DisplayPoint>> = selection_marker_pairs
9449            .iter()
9450            .map(|(start, end)| {
9451                let start = markers.get(start).unwrap()[0].to_display_point(&snapshot);
9452                let end = markers.get(end).unwrap()[0].to_display_point(&snapshot);
9453                start..end
9454            })
9455            .collect();
9456        assert_eq!(
9457            view.selected_display_ranges(cx),
9458            &asserted_ranges[..],
9459            "Assert selections are {}",
9460            marked_text
9461        );
9462    }
9463}
9464
9465trait RangeExt<T> {
9466    fn sorted(&self) -> Range<T>;
9467    fn to_inclusive(&self) -> RangeInclusive<T>;
9468}
9469
9470impl<T: Ord + Clone> RangeExt<T> for Range<T> {
9471    fn sorted(&self) -> Self {
9472        cmp::min(&self.start, &self.end).clone()..cmp::max(&self.start, &self.end).clone()
9473    }
9474
9475    fn to_inclusive(&self) -> RangeInclusive<T> {
9476        self.start.clone()..=self.end.clone()
9477    }
9478}