editor.rs

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