editor.rs

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