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 clock::ReplicaId;
  12use collections::{BTreeMap, HashMap, HashSet};
  13pub use display_map::DisplayPoint;
  14use display_map::*;
  15pub use element::*;
  16use gpui::{
  17    action,
  18    color::Color,
  19    elements::*,
  20    fonts::TextStyle,
  21    geometry::vector::{vec2f, Vector2F},
  22    keymap::Binding,
  23    text_layout, AppContext, ClipboardItem, Element, ElementBox, Entity, ModelHandle,
  24    MutableAppContext, RenderContext, View, ViewContext, WeakModelHandle, WeakViewHandle,
  25};
  26use items::BufferItemHandle;
  27use itertools::Itertools as _;
  28use language::{
  29    AnchorRangeExt as _, BracketPair, Buffer, Diagnostic, DiagnosticSeverity, Language, Point,
  30    Selection, SelectionGoal, TransactionId,
  31};
  32use multi_buffer::MultiBufferChunks;
  33pub use multi_buffer::{
  34    Anchor, AnchorRangeExt, ExcerptId, ExcerptProperties, MultiBuffer, MultiBufferSnapshot,
  35    ToOffset, ToPoint,
  36};
  37use postage::watch;
  38use serde::{Deserialize, Serialize};
  39use smallvec::SmallVec;
  40use smol::Timer;
  41use std::{
  42    any::TypeId,
  43    cmp::{self, Ordering},
  44    iter::{self, FromIterator},
  45    mem,
  46    ops::{Deref, Range, RangeInclusive, Sub},
  47    sync::Arc,
  48    time::{Duration, Instant},
  49};
  50pub use sum_tree::Bias;
  51use text::rope::TextDimension;
  52use theme::{DiagnosticStyle, EditorStyle};
  53use util::post_inc;
  54use workspace::{ItemNavHistory, PathOpener, Workspace};
  55
  56const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  57const MAX_LINE_LEN: usize = 1024;
  58const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  59
  60action!(Cancel);
  61action!(Backspace);
  62action!(Delete);
  63action!(Input, String);
  64action!(Newline);
  65action!(Tab);
  66action!(Outdent);
  67action!(DeleteLine);
  68action!(DeleteToPreviousWordBoundary);
  69action!(DeleteToNextWordBoundary);
  70action!(DeleteToBeginningOfLine);
  71action!(DeleteToEndOfLine);
  72action!(CutToEndOfLine);
  73action!(DuplicateLine);
  74action!(MoveLineUp);
  75action!(MoveLineDown);
  76action!(Cut);
  77action!(Copy);
  78action!(Paste);
  79action!(Undo);
  80action!(Redo);
  81action!(MoveUp);
  82action!(MoveDown);
  83action!(MoveLeft);
  84action!(MoveRight);
  85action!(MoveToPreviousWordBoundary);
  86action!(MoveToNextWordBoundary);
  87action!(MoveToBeginningOfLine);
  88action!(MoveToEndOfLine);
  89action!(MoveToBeginning);
  90action!(MoveToEnd);
  91action!(SelectUp);
  92action!(SelectDown);
  93action!(SelectLeft);
  94action!(SelectRight);
  95action!(SelectToPreviousWordBoundary);
  96action!(SelectToNextWordBoundary);
  97action!(SelectToBeginningOfLine, bool);
  98action!(SelectToEndOfLine);
  99action!(SelectToBeginning);
 100action!(SelectToEnd);
 101action!(SelectAll);
 102action!(SelectLine);
 103action!(SplitSelectionIntoLines);
 104action!(AddSelectionAbove);
 105action!(AddSelectionBelow);
 106action!(SelectNext, bool);
 107action!(ToggleComments);
 108action!(SelectLargerSyntaxNode);
 109action!(SelectSmallerSyntaxNode);
 110action!(MoveToEnclosingBracket);
 111action!(ShowNextDiagnostic);
 112action!(GoToDefinition);
 113action!(PageUp);
 114action!(PageDown);
 115action!(Fold);
 116action!(Unfold);
 117action!(FoldSelectedRanges);
 118action!(Scroll, Vector2F);
 119action!(Select, SelectPhase);
 120action!(ShowAutocomplete);
 121
 122pub fn init(cx: &mut MutableAppContext, path_openers: &mut Vec<Box<dyn PathOpener>>) {
 123    path_openers.push(Box::new(items::BufferOpener));
 124    cx.add_bindings(vec![
 125        Binding::new("escape", Cancel, Some("Editor")),
 126        Binding::new("backspace", Backspace, Some("Editor")),
 127        Binding::new("ctrl-h", Backspace, Some("Editor")),
 128        Binding::new("delete", Delete, Some("Editor")),
 129        Binding::new("ctrl-d", Delete, Some("Editor")),
 130        Binding::new("enter", Newline, Some("Editor && mode == full")),
 131        Binding::new(
 132            "alt-enter",
 133            Input("\n".into()),
 134            Some("Editor && mode == auto_height"),
 135        ),
 136        Binding::new("tab", Tab, Some("Editor")),
 137        Binding::new("shift-tab", Outdent, Some("Editor")),
 138        Binding::new("ctrl-shift-K", DeleteLine, Some("Editor")),
 139        Binding::new(
 140            "alt-backspace",
 141            DeleteToPreviousWordBoundary,
 142            Some("Editor"),
 143        ),
 144        Binding::new("alt-h", DeleteToPreviousWordBoundary, Some("Editor")),
 145        Binding::new("alt-delete", DeleteToNextWordBoundary, Some("Editor")),
 146        Binding::new("alt-d", DeleteToNextWordBoundary, Some("Editor")),
 147        Binding::new("cmd-backspace", DeleteToBeginningOfLine, Some("Editor")),
 148        Binding::new("cmd-delete", DeleteToEndOfLine, Some("Editor")),
 149        Binding::new("ctrl-k", CutToEndOfLine, Some("Editor")),
 150        Binding::new("cmd-shift-D", DuplicateLine, Some("Editor")),
 151        Binding::new("ctrl-cmd-up", MoveLineUp, Some("Editor")),
 152        Binding::new("ctrl-cmd-down", MoveLineDown, Some("Editor")),
 153        Binding::new("cmd-x", Cut, Some("Editor")),
 154        Binding::new("cmd-c", Copy, Some("Editor")),
 155        Binding::new("cmd-v", Paste, Some("Editor")),
 156        Binding::new("cmd-z", Undo, Some("Editor")),
 157        Binding::new("cmd-shift-Z", Redo, Some("Editor")),
 158        Binding::new("up", MoveUp, Some("Editor")),
 159        Binding::new("down", MoveDown, Some("Editor")),
 160        Binding::new("left", MoveLeft, Some("Editor")),
 161        Binding::new("right", MoveRight, Some("Editor")),
 162        Binding::new("ctrl-p", MoveUp, Some("Editor")),
 163        Binding::new("ctrl-n", MoveDown, Some("Editor")),
 164        Binding::new("ctrl-b", MoveLeft, Some("Editor")),
 165        Binding::new("ctrl-f", MoveRight, Some("Editor")),
 166        Binding::new("alt-left", MoveToPreviousWordBoundary, Some("Editor")),
 167        Binding::new("alt-b", MoveToPreviousWordBoundary, Some("Editor")),
 168        Binding::new("alt-right", MoveToNextWordBoundary, Some("Editor")),
 169        Binding::new("alt-f", MoveToNextWordBoundary, Some("Editor")),
 170        Binding::new("cmd-left", MoveToBeginningOfLine, Some("Editor")),
 171        Binding::new("ctrl-a", MoveToBeginningOfLine, Some("Editor")),
 172        Binding::new("cmd-right", MoveToEndOfLine, Some("Editor")),
 173        Binding::new("ctrl-e", MoveToEndOfLine, Some("Editor")),
 174        Binding::new("cmd-up", MoveToBeginning, Some("Editor")),
 175        Binding::new("cmd-down", MoveToEnd, Some("Editor")),
 176        Binding::new("shift-up", SelectUp, Some("Editor")),
 177        Binding::new("ctrl-shift-P", SelectUp, Some("Editor")),
 178        Binding::new("shift-down", SelectDown, Some("Editor")),
 179        Binding::new("ctrl-shift-N", SelectDown, Some("Editor")),
 180        Binding::new("shift-left", SelectLeft, Some("Editor")),
 181        Binding::new("ctrl-shift-B", SelectLeft, Some("Editor")),
 182        Binding::new("shift-right", SelectRight, Some("Editor")),
 183        Binding::new("ctrl-shift-F", SelectRight, Some("Editor")),
 184        Binding::new(
 185            "alt-shift-left",
 186            SelectToPreviousWordBoundary,
 187            Some("Editor"),
 188        ),
 189        Binding::new("alt-shift-B", SelectToPreviousWordBoundary, Some("Editor")),
 190        Binding::new("alt-shift-right", SelectToNextWordBoundary, Some("Editor")),
 191        Binding::new("alt-shift-F", SelectToNextWordBoundary, Some("Editor")),
 192        Binding::new(
 193            "cmd-shift-left",
 194            SelectToBeginningOfLine(true),
 195            Some("Editor"),
 196        ),
 197        Binding::new(
 198            "ctrl-shift-A",
 199            SelectToBeginningOfLine(true),
 200            Some("Editor"),
 201        ),
 202        Binding::new("cmd-shift-right", SelectToEndOfLine, Some("Editor")),
 203        Binding::new("ctrl-shift-E", SelectToEndOfLine, Some("Editor")),
 204        Binding::new("cmd-shift-up", SelectToBeginning, Some("Editor")),
 205        Binding::new("cmd-shift-down", SelectToEnd, Some("Editor")),
 206        Binding::new("cmd-a", SelectAll, Some("Editor")),
 207        Binding::new("cmd-l", SelectLine, Some("Editor")),
 208        Binding::new("cmd-shift-L", SplitSelectionIntoLines, Some("Editor")),
 209        Binding::new("cmd-alt-up", AddSelectionAbove, Some("Editor")),
 210        Binding::new("cmd-ctrl-p", AddSelectionAbove, Some("Editor")),
 211        Binding::new("cmd-alt-down", AddSelectionBelow, Some("Editor")),
 212        Binding::new("cmd-ctrl-n", AddSelectionBelow, Some("Editor")),
 213        Binding::new("cmd-d", SelectNext(false), Some("Editor")),
 214        Binding::new("cmd-k cmd-d", SelectNext(true), Some("Editor")),
 215        Binding::new("cmd-/", ToggleComments, Some("Editor")),
 216        Binding::new("alt-up", SelectLargerSyntaxNode, Some("Editor")),
 217        Binding::new("ctrl-w", SelectLargerSyntaxNode, Some("Editor")),
 218        Binding::new("alt-down", SelectSmallerSyntaxNode, Some("Editor")),
 219        Binding::new("ctrl-shift-W", SelectSmallerSyntaxNode, Some("Editor")),
 220        Binding::new("f8", ShowNextDiagnostic, Some("Editor")),
 221        Binding::new("f12", GoToDefinition, Some("Editor")),
 222        Binding::new("ctrl-m", MoveToEnclosingBracket, Some("Editor")),
 223        Binding::new("pageup", PageUp, Some("Editor")),
 224        Binding::new("pagedown", PageDown, Some("Editor")),
 225        Binding::new("alt-cmd-[", Fold, Some("Editor")),
 226        Binding::new("alt-cmd-]", Unfold, Some("Editor")),
 227        Binding::new("alt-cmd-f", FoldSelectedRanges, Some("Editor")),
 228        Binding::new("ctrl-shift-A", ShowAutocomplete, Some("Editor")),
 229    ]);
 230
 231    cx.add_action(Editor::open_new);
 232    cx.add_action(|this: &mut Editor, action: &Scroll, cx| this.set_scroll_position(action.0, cx));
 233    cx.add_action(Editor::select);
 234    cx.add_action(Editor::cancel);
 235    cx.add_action(Editor::handle_input);
 236    cx.add_action(Editor::newline);
 237    cx.add_action(Editor::backspace);
 238    cx.add_action(Editor::delete);
 239    cx.add_action(Editor::tab);
 240    cx.add_action(Editor::outdent);
 241    cx.add_action(Editor::delete_line);
 242    cx.add_action(Editor::delete_to_previous_word_boundary);
 243    cx.add_action(Editor::delete_to_next_word_boundary);
 244    cx.add_action(Editor::delete_to_beginning_of_line);
 245    cx.add_action(Editor::delete_to_end_of_line);
 246    cx.add_action(Editor::cut_to_end_of_line);
 247    cx.add_action(Editor::duplicate_line);
 248    cx.add_action(Editor::move_line_up);
 249    cx.add_action(Editor::move_line_down);
 250    cx.add_action(Editor::cut);
 251    cx.add_action(Editor::copy);
 252    cx.add_action(Editor::paste);
 253    cx.add_action(Editor::undo);
 254    cx.add_action(Editor::redo);
 255    cx.add_action(Editor::move_up);
 256    cx.add_action(Editor::move_down);
 257    cx.add_action(Editor::move_left);
 258    cx.add_action(Editor::move_right);
 259    cx.add_action(Editor::move_to_previous_word_boundary);
 260    cx.add_action(Editor::move_to_next_word_boundary);
 261    cx.add_action(Editor::move_to_beginning_of_line);
 262    cx.add_action(Editor::move_to_end_of_line);
 263    cx.add_action(Editor::move_to_beginning);
 264    cx.add_action(Editor::move_to_end);
 265    cx.add_action(Editor::select_up);
 266    cx.add_action(Editor::select_down);
 267    cx.add_action(Editor::select_left);
 268    cx.add_action(Editor::select_right);
 269    cx.add_action(Editor::select_to_previous_word_boundary);
 270    cx.add_action(Editor::select_to_next_word_boundary);
 271    cx.add_action(Editor::select_to_beginning_of_line);
 272    cx.add_action(Editor::select_to_end_of_line);
 273    cx.add_action(Editor::select_to_beginning);
 274    cx.add_action(Editor::select_to_end);
 275    cx.add_action(Editor::select_all);
 276    cx.add_action(Editor::select_line);
 277    cx.add_action(Editor::split_selection_into_lines);
 278    cx.add_action(Editor::add_selection_above);
 279    cx.add_action(Editor::add_selection_below);
 280    cx.add_action(Editor::select_next);
 281    cx.add_action(Editor::toggle_comments);
 282    cx.add_action(Editor::select_larger_syntax_node);
 283    cx.add_action(Editor::select_smaller_syntax_node);
 284    cx.add_action(Editor::move_to_enclosing_bracket);
 285    cx.add_action(Editor::show_next_diagnostic);
 286    cx.add_action(Editor::go_to_definition);
 287    cx.add_action(Editor::page_up);
 288    cx.add_action(Editor::page_down);
 289    cx.add_action(Editor::fold);
 290    cx.add_action(Editor::unfold);
 291    cx.add_action(Editor::fold_selected_ranges);
 292    cx.add_action(Editor::show_autocomplete);
 293}
 294
 295trait SelectionExt {
 296    fn offset_range(&self, buffer: &MultiBufferSnapshot) -> Range<usize>;
 297    fn point_range(&self, buffer: &MultiBufferSnapshot) -> Range<Point>;
 298    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
 299    fn spanned_rows(&self, include_end_if_at_line_start: bool, map: &DisplaySnapshot)
 300        -> Range<u32>;
 301}
 302
 303#[derive(Clone, Debug)]
 304pub enum SelectPhase {
 305    Begin {
 306        position: DisplayPoint,
 307        add: bool,
 308        click_count: usize,
 309    },
 310    BeginColumnar {
 311        position: DisplayPoint,
 312        overshoot: u32,
 313    },
 314    Extend {
 315        position: DisplayPoint,
 316        click_count: usize,
 317    },
 318    Update {
 319        position: DisplayPoint,
 320        overshoot: u32,
 321        scroll_position: Vector2F,
 322    },
 323    End,
 324}
 325
 326#[derive(Clone, Debug)]
 327enum SelectMode {
 328    Character,
 329    Word(Range<Anchor>),
 330    Line(Range<Anchor>),
 331    All,
 332}
 333
 334#[derive(PartialEq, Eq)]
 335pub enum Autoscroll {
 336    Fit,
 337    Center,
 338    Newest,
 339}
 340
 341#[derive(Copy, Clone, PartialEq, Eq)]
 342pub enum EditorMode {
 343    SingleLine,
 344    AutoHeight { max_lines: usize },
 345    Full,
 346}
 347
 348#[derive(Clone)]
 349pub struct EditorSettings {
 350    pub tab_size: usize,
 351    pub soft_wrap: SoftWrap,
 352    pub style: EditorStyle,
 353}
 354
 355#[derive(Clone)]
 356pub enum SoftWrap {
 357    None,
 358    EditorWidth,
 359    Column(u32),
 360}
 361
 362pub type BuildSettings = Arc<dyn 'static + Send + Sync + Fn(&AppContext) -> EditorSettings>;
 363
 364pub struct Editor {
 365    handle: WeakViewHandle<Self>,
 366    buffer: ModelHandle<MultiBuffer>,
 367    display_map: ModelHandle<DisplayMap>,
 368    next_selection_id: usize,
 369    selections: Arc<[Selection<Anchor>]>,
 370    pending_selection: Option<PendingSelection>,
 371    columnar_selection_tail: Option<Anchor>,
 372    add_selections_state: Option<AddSelectionsState>,
 373    select_next_state: Option<SelectNextState>,
 374    selection_history:
 375        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
 376    autoclose_stack: Vec<BracketPairState>,
 377    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
 378    active_diagnostics: Option<ActiveDiagnosticGroup>,
 379    scroll_position: Vector2F,
 380    scroll_top_anchor: Option<Anchor>,
 381    autoscroll_request: Option<Autoscroll>,
 382    build_settings: BuildSettings,
 383    focused: bool,
 384    show_local_cursors: bool,
 385    blink_epoch: usize,
 386    blinking_paused: bool,
 387    mode: EditorMode,
 388    vertical_scroll_margin: f32,
 389    placeholder_text: Option<Arc<str>>,
 390    highlighted_rows: Option<Range<u32>>,
 391    highlighted_ranges: BTreeMap<TypeId, (Color, Vec<Range<Anchor>>)>,
 392    nav_history: Option<ItemNavHistory>,
 393}
 394
 395pub struct EditorSnapshot {
 396    pub mode: EditorMode,
 397    pub display_snapshot: DisplaySnapshot,
 398    pub placeholder_text: Option<Arc<str>>,
 399    is_focused: bool,
 400    scroll_position: Vector2F,
 401    scroll_top_anchor: Option<Anchor>,
 402}
 403
 404struct PendingSelection {
 405    selection: Selection<Anchor>,
 406    mode: SelectMode,
 407}
 408
 409struct AddSelectionsState {
 410    above: bool,
 411    stack: Vec<usize>,
 412}
 413
 414struct SelectNextState {
 415    query: AhoCorasick,
 416    wordwise: bool,
 417    done: bool,
 418}
 419
 420#[derive(Debug)]
 421struct BracketPairState {
 422    ranges: Vec<Range<Anchor>>,
 423    pair: BracketPair,
 424}
 425
 426#[derive(Debug)]
 427struct ActiveDiagnosticGroup {
 428    primary_range: Range<Anchor>,
 429    primary_message: String,
 430    blocks: HashMap<BlockId, Diagnostic>,
 431    is_valid: bool,
 432}
 433
 434#[derive(Serialize, Deserialize)]
 435struct ClipboardSelection {
 436    len: usize,
 437    is_entire_line: bool,
 438}
 439
 440pub struct NavigationData {
 441    anchor: Anchor,
 442    offset: usize,
 443}
 444
 445#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord)]
 446pub enum CharKind {
 447    Newline,
 448    Punctuation,
 449    Whitespace,
 450    Word,
 451}
 452
 453impl Editor {
 454    pub fn single_line(build_settings: BuildSettings, cx: &mut ViewContext<Self>) -> Self {
 455        let buffer = cx.add_model(|cx| Buffer::new(0, String::new(), cx));
 456        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
 457        let mut view = Self::for_buffer(buffer, build_settings, cx);
 458        view.mode = EditorMode::SingleLine;
 459        view
 460    }
 461
 462    pub fn auto_height(
 463        max_lines: usize,
 464        build_settings: BuildSettings,
 465        cx: &mut ViewContext<Self>,
 466    ) -> Self {
 467        let buffer = cx.add_model(|cx| Buffer::new(0, String::new(), cx));
 468        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
 469        let mut view = Self::for_buffer(buffer, build_settings, cx);
 470        view.mode = EditorMode::AutoHeight { max_lines };
 471        view
 472    }
 473
 474    pub fn for_buffer(
 475        buffer: ModelHandle<MultiBuffer>,
 476        build_settings: BuildSettings,
 477        cx: &mut ViewContext<Self>,
 478    ) -> Self {
 479        Self::new(buffer, build_settings, cx)
 480    }
 481
 482    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 483        let mut clone = Self::new(self.buffer.clone(), self.build_settings.clone(), cx);
 484        clone.scroll_position = self.scroll_position;
 485        clone.scroll_top_anchor = self.scroll_top_anchor.clone();
 486        clone.nav_history = self
 487            .nav_history
 488            .as_ref()
 489            .map(|nav_history| ItemNavHistory::new(nav_history.history(), &cx.handle()));
 490        clone
 491    }
 492
 493    pub fn new(
 494        buffer: ModelHandle<MultiBuffer>,
 495        build_settings: BuildSettings,
 496        cx: &mut ViewContext<Self>,
 497    ) -> Self {
 498        let settings = build_settings(cx);
 499        let display_map = cx.add_model(|cx| {
 500            DisplayMap::new(
 501                buffer.clone(),
 502                settings.tab_size,
 503                settings.style.text.font_id,
 504                settings.style.text.font_size,
 505                None,
 506                cx,
 507            )
 508        });
 509        cx.observe(&buffer, Self::on_buffer_changed).detach();
 510        cx.subscribe(&buffer, Self::on_buffer_event).detach();
 511        cx.observe(&display_map, Self::on_display_map_changed)
 512            .detach();
 513
 514        let mut this = Self {
 515            handle: cx.weak_handle(),
 516            buffer,
 517            display_map,
 518            selections: Arc::from([]),
 519            pending_selection: None,
 520            columnar_selection_tail: None,
 521            next_selection_id: 0,
 522            add_selections_state: None,
 523            select_next_state: None,
 524            selection_history: Default::default(),
 525            autoclose_stack: Default::default(),
 526            select_larger_syntax_node_stack: Vec::new(),
 527            active_diagnostics: None,
 528            build_settings,
 529            scroll_position: Vector2F::zero(),
 530            scroll_top_anchor: None,
 531            autoscroll_request: None,
 532            focused: false,
 533            show_local_cursors: false,
 534            blink_epoch: 0,
 535            blinking_paused: false,
 536            mode: EditorMode::Full,
 537            vertical_scroll_margin: 3.0,
 538            placeholder_text: None,
 539            highlighted_rows: None,
 540            highlighted_ranges: Default::default(),
 541            nav_history: None,
 542        };
 543        let selection = Selection {
 544            id: post_inc(&mut this.next_selection_id),
 545            start: 0,
 546            end: 0,
 547            reversed: false,
 548            goal: SelectionGoal::None,
 549        };
 550        this.update_selections(vec![selection], None, cx);
 551        this
 552    }
 553
 554    pub fn open_new(
 555        workspace: &mut Workspace,
 556        _: &workspace::OpenNew,
 557        cx: &mut ViewContext<Workspace>,
 558    ) {
 559        let buffer = cx
 560            .add_model(|cx| Buffer::new(0, "", cx).with_language(language::PLAIN_TEXT.clone(), cx));
 561        workspace.open_item(BufferItemHandle(buffer), cx);
 562    }
 563
 564    pub fn replica_id(&self, cx: &AppContext) -> ReplicaId {
 565        self.buffer.read(cx).replica_id()
 566    }
 567
 568    pub fn buffer(&self) -> &ModelHandle<MultiBuffer> {
 569        &self.buffer
 570    }
 571
 572    pub fn title(&self, cx: &AppContext) -> String {
 573        let filename = self
 574            .buffer()
 575            .read(cx)
 576            .file(cx)
 577            .map(|file| file.file_name(cx));
 578        if let Some(name) = filename {
 579            name.to_string_lossy().into()
 580        } else {
 581            "untitled".into()
 582        }
 583    }
 584
 585    pub fn snapshot(&mut self, cx: &mut MutableAppContext) -> EditorSnapshot {
 586        EditorSnapshot {
 587            mode: self.mode,
 588            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 589            scroll_position: self.scroll_position,
 590            scroll_top_anchor: self.scroll_top_anchor.clone(),
 591            placeholder_text: self.placeholder_text.clone(),
 592            is_focused: self
 593                .handle
 594                .upgrade(cx)
 595                .map_or(false, |handle| handle.is_focused(cx)),
 596        }
 597    }
 598
 599    pub fn language<'a>(&self, cx: &'a AppContext) -> Option<&'a Arc<Language>> {
 600        self.buffer.read(cx).language(cx)
 601    }
 602
 603    pub fn set_placeholder_text(
 604        &mut self,
 605        placeholder_text: impl Into<Arc<str>>,
 606        cx: &mut ViewContext<Self>,
 607    ) {
 608        self.placeholder_text = Some(placeholder_text.into());
 609        cx.notify();
 610    }
 611
 612    pub fn set_vertical_scroll_margin(&mut self, margin_rows: usize, cx: &mut ViewContext<Self>) {
 613        self.vertical_scroll_margin = margin_rows as f32;
 614        cx.notify();
 615    }
 616
 617    pub fn set_scroll_position(&mut self, scroll_position: Vector2F, cx: &mut ViewContext<Self>) {
 618        let map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 619
 620        if scroll_position.y() == 0. {
 621            self.scroll_top_anchor = None;
 622            self.scroll_position = scroll_position;
 623        } else {
 624            let scroll_top_buffer_offset =
 625                DisplayPoint::new(scroll_position.y() as u32, 0).to_offset(&map, Bias::Right);
 626            let anchor = map
 627                .buffer_snapshot
 628                .anchor_at(scroll_top_buffer_offset, Bias::Right);
 629            self.scroll_position = vec2f(
 630                scroll_position.x(),
 631                scroll_position.y() - anchor.to_display_point(&map).row() as f32,
 632            );
 633            self.scroll_top_anchor = Some(anchor);
 634        }
 635
 636        cx.notify();
 637    }
 638
 639    pub fn scroll_position(&self, cx: &mut ViewContext<Self>) -> Vector2F {
 640        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 641        compute_scroll_position(&display_map, self.scroll_position, &self.scroll_top_anchor)
 642    }
 643
 644    pub fn clamp_scroll_left(&mut self, max: f32) -> bool {
 645        if max < self.scroll_position.x() {
 646            self.scroll_position.set_x(max);
 647            true
 648        } else {
 649            false
 650        }
 651    }
 652
 653    pub fn autoscroll_vertically(
 654        &mut self,
 655        viewport_height: f32,
 656        line_height: f32,
 657        cx: &mut ViewContext<Self>,
 658    ) -> bool {
 659        let visible_lines = viewport_height / line_height;
 660        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 661        let mut scroll_position =
 662            compute_scroll_position(&display_map, self.scroll_position, &self.scroll_top_anchor);
 663        let max_scroll_top = if matches!(self.mode, EditorMode::AutoHeight { .. }) {
 664            (display_map.max_point().row() as f32 - visible_lines + 1.).max(0.)
 665        } else {
 666            display_map.max_point().row().saturating_sub(1) as f32
 667        };
 668        if scroll_position.y() > max_scroll_top {
 669            scroll_position.set_y(max_scroll_top);
 670            self.set_scroll_position(scroll_position, cx);
 671        }
 672
 673        let autoscroll = if let Some(autoscroll) = self.autoscroll_request.take() {
 674            autoscroll
 675        } else {
 676            return false;
 677        };
 678
 679        let first_cursor_top;
 680        let last_cursor_bottom;
 681        if let Some(highlighted_rows) = &self.highlighted_rows {
 682            first_cursor_top = highlighted_rows.start as f32;
 683            last_cursor_bottom = first_cursor_top + 1.;
 684        } else if autoscroll == Autoscroll::Newest {
 685            let newest_selection = self.newest_selection::<Point>(&display_map.buffer_snapshot);
 686            first_cursor_top = newest_selection.head().to_display_point(&display_map).row() as f32;
 687            last_cursor_bottom = first_cursor_top + 1.;
 688        } else {
 689            let selections = self.local_selections::<Point>(cx);
 690            first_cursor_top = selections
 691                .first()
 692                .unwrap()
 693                .head()
 694                .to_display_point(&display_map)
 695                .row() as f32;
 696            last_cursor_bottom = selections
 697                .last()
 698                .unwrap()
 699                .head()
 700                .to_display_point(&display_map)
 701                .row() as f32
 702                + 1.0;
 703        }
 704
 705        let margin = if matches!(self.mode, EditorMode::AutoHeight { .. }) {
 706            0.
 707        } else {
 708            ((visible_lines - (last_cursor_bottom - first_cursor_top)) / 2.0).floor()
 709        };
 710        if margin < 0.0 {
 711            return false;
 712        }
 713
 714        match autoscroll {
 715            Autoscroll::Fit | Autoscroll::Newest => {
 716                let margin = margin.min(self.vertical_scroll_margin);
 717                let target_top = (first_cursor_top - margin).max(0.0);
 718                let target_bottom = last_cursor_bottom + margin;
 719                let start_row = scroll_position.y();
 720                let end_row = start_row + visible_lines;
 721
 722                if target_top < start_row {
 723                    scroll_position.set_y(target_top);
 724                    self.set_scroll_position(scroll_position, cx);
 725                } else if target_bottom >= end_row {
 726                    scroll_position.set_y(target_bottom - visible_lines);
 727                    self.set_scroll_position(scroll_position, cx);
 728                }
 729            }
 730            Autoscroll::Center => {
 731                scroll_position.set_y((first_cursor_top - margin).max(0.0));
 732                self.set_scroll_position(scroll_position, cx);
 733            }
 734        }
 735
 736        true
 737    }
 738
 739    pub fn autoscroll_horizontally(
 740        &mut self,
 741        start_row: u32,
 742        viewport_width: f32,
 743        scroll_width: f32,
 744        max_glyph_width: f32,
 745        layouts: &[text_layout::Line],
 746        cx: &mut ViewContext<Self>,
 747    ) -> bool {
 748        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 749        let selections = self.local_selections::<Point>(cx);
 750
 751        let mut target_left;
 752        let mut target_right;
 753
 754        if self.highlighted_rows.is_some() {
 755            target_left = 0.0_f32;
 756            target_right = 0.0_f32;
 757        } else {
 758            target_left = std::f32::INFINITY;
 759            target_right = 0.0_f32;
 760            for selection in selections {
 761                let head = selection.head().to_display_point(&display_map);
 762                if head.row() >= start_row && head.row() < start_row + layouts.len() as u32 {
 763                    let start_column = head.column().saturating_sub(3);
 764                    let end_column = cmp::min(display_map.line_len(head.row()), head.column() + 3);
 765                    target_left = target_left.min(
 766                        layouts[(head.row() - start_row) as usize]
 767                            .x_for_index(start_column as usize),
 768                    );
 769                    target_right = target_right.max(
 770                        layouts[(head.row() - start_row) as usize].x_for_index(end_column as usize)
 771                            + max_glyph_width,
 772                    );
 773                }
 774            }
 775        }
 776
 777        target_right = target_right.min(scroll_width);
 778
 779        if target_right - target_left > viewport_width {
 780            return false;
 781        }
 782
 783        let scroll_left = self.scroll_position.x() * max_glyph_width;
 784        let scroll_right = scroll_left + viewport_width;
 785
 786        if target_left < scroll_left {
 787            self.scroll_position.set_x(target_left / max_glyph_width);
 788            true
 789        } else if target_right > scroll_right {
 790            self.scroll_position
 791                .set_x((target_right - viewport_width) / max_glyph_width);
 792            true
 793        } else {
 794            false
 795        }
 796    }
 797
 798    fn select(&mut self, Select(phase): &Select, cx: &mut ViewContext<Self>) {
 799        match phase {
 800            SelectPhase::Begin {
 801                position,
 802                add,
 803                click_count,
 804            } => self.begin_selection(*position, *add, *click_count, cx),
 805            SelectPhase::BeginColumnar {
 806                position,
 807                overshoot,
 808            } => self.begin_columnar_selection(*position, *overshoot, cx),
 809            SelectPhase::Extend {
 810                position,
 811                click_count,
 812            } => self.extend_selection(*position, *click_count, cx),
 813            SelectPhase::Update {
 814                position,
 815                overshoot,
 816                scroll_position,
 817            } => self.update_selection(*position, *overshoot, *scroll_position, cx),
 818            SelectPhase::End => self.end_selection(cx),
 819        }
 820    }
 821
 822    fn extend_selection(
 823        &mut self,
 824        position: DisplayPoint,
 825        click_count: usize,
 826        cx: &mut ViewContext<Self>,
 827    ) {
 828        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 829        let tail = self
 830            .newest_selection::<usize>(&display_map.buffer_snapshot)
 831            .tail();
 832        self.begin_selection(position, false, click_count, cx);
 833
 834        let position = position.to_offset(&display_map, Bias::Left);
 835        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 836        let pending = self.pending_selection.as_mut().unwrap();
 837
 838        if position >= tail {
 839            pending.selection.start = tail_anchor.clone();
 840        } else {
 841            pending.selection.end = tail_anchor.clone();
 842            pending.selection.reversed = true;
 843        }
 844
 845        match &mut pending.mode {
 846            SelectMode::Word(range) | SelectMode::Line(range) => {
 847                *range = tail_anchor.clone()..tail_anchor
 848            }
 849            _ => {}
 850        }
 851    }
 852
 853    fn begin_selection(
 854        &mut self,
 855        position: DisplayPoint,
 856        add: bool,
 857        click_count: usize,
 858        cx: &mut ViewContext<Self>,
 859    ) {
 860        if !self.focused {
 861            cx.focus_self();
 862            cx.emit(Event::Activate);
 863        }
 864
 865        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 866        let buffer = &display_map.buffer_snapshot;
 867        let newest_selection = self.newest_anchor_selection().unwrap().clone();
 868
 869        let start;
 870        let end;
 871        let mode;
 872        match click_count {
 873            1 => {
 874                start = buffer.anchor_before(position.to_point(&display_map));
 875                end = start.clone();
 876                mode = SelectMode::Character;
 877            }
 878            2 => {
 879                let range = movement::surrounding_word(&display_map, position);
 880                start = buffer.anchor_before(range.start.to_point(&display_map));
 881                end = buffer.anchor_before(range.end.to_point(&display_map));
 882                mode = SelectMode::Word(start.clone()..end.clone());
 883            }
 884            3 => {
 885                let position = display_map.clip_point(position, Bias::Left);
 886                let line_start = movement::line_beginning(&display_map, position, false);
 887                let mut next_line_start = line_start.clone();
 888                *next_line_start.row_mut() += 1;
 889                *next_line_start.column_mut() = 0;
 890                next_line_start = display_map.clip_point(next_line_start, Bias::Right);
 891
 892                start = buffer.anchor_before(line_start.to_point(&display_map));
 893                end = buffer.anchor_before(next_line_start.to_point(&display_map));
 894                mode = SelectMode::Line(start.clone()..end.clone());
 895            }
 896            _ => {
 897                start = buffer.anchor_before(0);
 898                end = buffer.anchor_before(buffer.len());
 899                mode = SelectMode::All;
 900            }
 901        }
 902
 903        self.push_to_nav_history(newest_selection.head(), Some(end.to_point(&buffer)), cx);
 904
 905        let selection = Selection {
 906            id: post_inc(&mut self.next_selection_id),
 907            start,
 908            end,
 909            reversed: false,
 910            goal: SelectionGoal::None,
 911        };
 912
 913        if !add {
 914            self.update_selections::<usize>(Vec::new(), None, cx);
 915        } else if click_count > 1 {
 916            // Remove the newest selection since it was only added as part of this multi-click.
 917            let mut selections = self.local_selections(cx);
 918            selections.retain(|selection| selection.id != newest_selection.id);
 919            self.update_selections::<usize>(selections, None, cx)
 920        }
 921
 922        self.pending_selection = Some(PendingSelection { selection, mode });
 923
 924        cx.notify();
 925    }
 926
 927    fn begin_columnar_selection(
 928        &mut self,
 929        position: DisplayPoint,
 930        overshoot: u32,
 931        cx: &mut ViewContext<Self>,
 932    ) {
 933        if !self.focused {
 934            cx.focus_self();
 935            cx.emit(Event::Activate);
 936        }
 937
 938        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 939        let tail = self
 940            .newest_selection::<Point>(&display_map.buffer_snapshot)
 941            .tail();
 942        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 943
 944        self.select_columns(
 945            tail.to_display_point(&display_map),
 946            position,
 947            overshoot,
 948            &display_map,
 949            cx,
 950        );
 951    }
 952
 953    fn update_selection(
 954        &mut self,
 955        position: DisplayPoint,
 956        overshoot: u32,
 957        scroll_position: Vector2F,
 958        cx: &mut ViewContext<Self>,
 959    ) {
 960        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 961
 962        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 963            let tail = tail.to_display_point(&display_map);
 964            self.select_columns(tail, position, overshoot, &display_map, cx);
 965        } else if let Some(PendingSelection { selection, mode }) = self.pending_selection.as_mut() {
 966            let buffer = self.buffer.read(cx).snapshot(cx);
 967            let head;
 968            let tail;
 969            match mode {
 970                SelectMode::Character => {
 971                    head = position.to_point(&display_map);
 972                    tail = selection.tail().to_point(&buffer);
 973                }
 974                SelectMode::Word(original_range) => {
 975                    let original_display_range = original_range.start.to_display_point(&display_map)
 976                        ..original_range.end.to_display_point(&display_map);
 977                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 978                        ..original_display_range.end.to_point(&display_map);
 979                    if movement::is_inside_word(&display_map, position)
 980                        || original_display_range.contains(&position)
 981                    {
 982                        let word_range = movement::surrounding_word(&display_map, position);
 983                        if word_range.start < original_display_range.start {
 984                            head = word_range.start.to_point(&display_map);
 985                        } else {
 986                            head = word_range.end.to_point(&display_map);
 987                        }
 988                    } else {
 989                        head = position.to_point(&display_map);
 990                    }
 991
 992                    if head <= original_buffer_range.start {
 993                        tail = original_buffer_range.end;
 994                    } else {
 995                        tail = original_buffer_range.start;
 996                    }
 997                }
 998                SelectMode::Line(original_range) => {
 999                    let original_display_range = original_range.start.to_display_point(&display_map)
1000                        ..original_range.end.to_display_point(&display_map);
1001                    let original_buffer_range = original_display_range.start.to_point(&display_map)
1002                        ..original_display_range.end.to_point(&display_map);
1003                    let line_start = movement::line_beginning(&display_map, position, false);
1004                    let mut next_line_start = line_start.clone();
1005                    *next_line_start.row_mut() += 1;
1006                    *next_line_start.column_mut() = 0;
1007                    next_line_start = display_map.clip_point(next_line_start, Bias::Right);
1008
1009                    if line_start < original_display_range.start {
1010                        head = line_start.to_point(&display_map);
1011                    } else {
1012                        head = next_line_start.to_point(&display_map);
1013                    }
1014
1015                    if head <= original_buffer_range.start {
1016                        tail = original_buffer_range.end;
1017                    } else {
1018                        tail = original_buffer_range.start;
1019                    }
1020                }
1021                SelectMode::All => {
1022                    return;
1023                }
1024            };
1025
1026            if head < tail {
1027                selection.start = buffer.anchor_before(head);
1028                selection.end = buffer.anchor_before(tail);
1029                selection.reversed = true;
1030            } else {
1031                selection.start = buffer.anchor_before(tail);
1032                selection.end = buffer.anchor_before(head);
1033                selection.reversed = false;
1034            }
1035        } else {
1036            log::error!("update_selection dispatched with no pending selection");
1037            return;
1038        }
1039
1040        self.set_scroll_position(scroll_position, cx);
1041        cx.notify();
1042    }
1043
1044    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
1045        self.columnar_selection_tail.take();
1046        if self.pending_selection.is_some() {
1047            let selections = self.local_selections::<usize>(cx);
1048            self.update_selections(selections, None, cx);
1049        }
1050    }
1051
1052    fn select_columns(
1053        &mut self,
1054        tail: DisplayPoint,
1055        head: DisplayPoint,
1056        overshoot: u32,
1057        display_map: &DisplaySnapshot,
1058        cx: &mut ViewContext<Self>,
1059    ) {
1060        let start_row = cmp::min(tail.row(), head.row());
1061        let end_row = cmp::max(tail.row(), head.row());
1062        let start_column = cmp::min(tail.column(), head.column() + overshoot);
1063        let end_column = cmp::max(tail.column(), head.column() + overshoot);
1064        let reversed = start_column < tail.column();
1065
1066        let selections = (start_row..=end_row)
1067            .filter_map(|row| {
1068                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
1069                    let start = display_map
1070                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
1071                        .to_point(&display_map);
1072                    let end = display_map
1073                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
1074                        .to_point(&display_map);
1075                    Some(Selection {
1076                        id: post_inc(&mut self.next_selection_id),
1077                        start,
1078                        end,
1079                        reversed,
1080                        goal: SelectionGoal::None,
1081                    })
1082                } else {
1083                    None
1084                }
1085            })
1086            .collect::<Vec<_>>();
1087
1088        self.update_selections(selections, None, cx);
1089        cx.notify();
1090    }
1091
1092    pub fn is_selecting(&self) -> bool {
1093        self.pending_selection.is_some() || self.columnar_selection_tail.is_some()
1094    }
1095
1096    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
1097        if self.mode != EditorMode::Full {
1098            cx.propagate_action();
1099            return;
1100        }
1101
1102        if self.active_diagnostics.is_some() {
1103            self.dismiss_diagnostics(cx);
1104        } else if let Some(PendingSelection { selection, .. }) = self.pending_selection.take() {
1105            let buffer = self.buffer.read(cx).snapshot(cx);
1106            let selection = Selection {
1107                id: selection.id,
1108                start: selection.start.to_point(&buffer),
1109                end: selection.end.to_point(&buffer),
1110                reversed: selection.reversed,
1111                goal: selection.goal,
1112            };
1113            if self.local_selections::<Point>(cx).is_empty() {
1114                self.update_selections(vec![selection], Some(Autoscroll::Fit), cx);
1115            }
1116        } else {
1117            let buffer = self.buffer.read(cx).snapshot(cx);
1118            let mut oldest_selection = self.oldest_selection::<usize>(&buffer);
1119            if self.selection_count() == 1 {
1120                if oldest_selection.is_empty() {
1121                    cx.propagate_action();
1122                    return;
1123                }
1124
1125                oldest_selection.start = oldest_selection.head().clone();
1126                oldest_selection.end = oldest_selection.head().clone();
1127            }
1128            self.update_selections(vec![oldest_selection], Some(Autoscroll::Fit), cx);
1129        }
1130    }
1131
1132    #[cfg(any(test, feature = "test-support"))]
1133    pub fn selected_ranges<D: TextDimension + Ord + Sub<D, Output = D>>(
1134        &self,
1135        cx: &mut MutableAppContext,
1136    ) -> Vec<Range<D>> {
1137        self.local_selections::<D>(cx)
1138            .iter()
1139            .map(|s| {
1140                if s.reversed {
1141                    s.end.clone()..s.start.clone()
1142                } else {
1143                    s.start.clone()..s.end.clone()
1144                }
1145            })
1146            .collect()
1147    }
1148
1149    #[cfg(any(test, feature = "test-support"))]
1150    pub fn selected_display_ranges(&self, cx: &mut MutableAppContext) -> Vec<Range<DisplayPoint>> {
1151        let display_map = self
1152            .display_map
1153            .update(cx, |display_map, cx| display_map.snapshot(cx));
1154        self.selections
1155            .iter()
1156            .chain(
1157                self.pending_selection
1158                    .as_ref()
1159                    .map(|pending| &pending.selection),
1160            )
1161            .map(|s| {
1162                if s.reversed {
1163                    s.end.to_display_point(&display_map)..s.start.to_display_point(&display_map)
1164                } else {
1165                    s.start.to_display_point(&display_map)..s.end.to_display_point(&display_map)
1166                }
1167            })
1168            .collect()
1169    }
1170
1171    pub fn select_ranges<I, T>(
1172        &mut self,
1173        ranges: I,
1174        autoscroll: Option<Autoscroll>,
1175        cx: &mut ViewContext<Self>,
1176    ) where
1177        I: IntoIterator<Item = Range<T>>,
1178        T: ToOffset,
1179    {
1180        let buffer = self.buffer.read(cx).snapshot(cx);
1181        let selections = ranges
1182            .into_iter()
1183            .map(|range| {
1184                let mut start = range.start.to_offset(&buffer);
1185                let mut end = range.end.to_offset(&buffer);
1186                let reversed = if start > end {
1187                    mem::swap(&mut start, &mut end);
1188                    true
1189                } else {
1190                    false
1191                };
1192                Selection {
1193                    id: post_inc(&mut self.next_selection_id),
1194                    start,
1195                    end,
1196                    reversed,
1197                    goal: SelectionGoal::None,
1198                }
1199            })
1200            .collect::<Vec<_>>();
1201        self.update_selections(selections, autoscroll, cx);
1202    }
1203
1204    #[cfg(any(test, feature = "test-support"))]
1205    pub fn select_display_ranges<'a, T>(&mut self, ranges: T, cx: &mut ViewContext<Self>)
1206    where
1207        T: IntoIterator<Item = &'a Range<DisplayPoint>>,
1208    {
1209        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1210        let selections = ranges
1211            .into_iter()
1212            .map(|range| {
1213                let mut start = range.start;
1214                let mut end = range.end;
1215                let reversed = if start > end {
1216                    mem::swap(&mut start, &mut end);
1217                    true
1218                } else {
1219                    false
1220                };
1221                Selection {
1222                    id: post_inc(&mut self.next_selection_id),
1223                    start: start.to_point(&display_map),
1224                    end: end.to_point(&display_map),
1225                    reversed,
1226                    goal: SelectionGoal::None,
1227                }
1228            })
1229            .collect();
1230        self.update_selections(selections, None, cx);
1231    }
1232
1233    pub fn handle_input(&mut self, action: &Input, cx: &mut ViewContext<Self>) {
1234        let text = action.0.as_ref();
1235        if !self.skip_autoclose_end(text, cx) {
1236            self.start_transaction(cx);
1237            self.insert(text, cx);
1238            self.autoclose_pairs(cx);
1239            self.end_transaction(cx);
1240        }
1241    }
1242
1243    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
1244        self.start_transaction(cx);
1245        let mut old_selections = SmallVec::<[_; 32]>::new();
1246        {
1247            let selections = self.local_selections::<Point>(cx);
1248            let buffer = self.buffer.read(cx).snapshot(cx);
1249            for selection in selections.iter() {
1250                let start_point = selection.start;
1251                let indent = buffer
1252                    .indent_column_for_line(start_point.row)
1253                    .min(start_point.column);
1254                let start = selection.start.to_offset(&buffer);
1255                let end = selection.end.to_offset(&buffer);
1256
1257                let mut insert_extra_newline = false;
1258                if let Some(language) = buffer.language() {
1259                    let leading_whitespace_len = buffer
1260                        .reversed_chars_at(start)
1261                        .take_while(|c| c.is_whitespace() && *c != '\n')
1262                        .map(|c| c.len_utf8())
1263                        .sum::<usize>();
1264
1265                    let trailing_whitespace_len = buffer
1266                        .chars_at(end)
1267                        .take_while(|c| c.is_whitespace() && *c != '\n')
1268                        .map(|c| c.len_utf8())
1269                        .sum::<usize>();
1270
1271                    insert_extra_newline = language.brackets().iter().any(|pair| {
1272                        let pair_start = pair.start.trim_end();
1273                        let pair_end = pair.end.trim_start();
1274
1275                        pair.newline
1276                            && buffer.contains_str_at(end + trailing_whitespace_len, pair_end)
1277                            && buffer.contains_str_at(
1278                                (start - leading_whitespace_len).saturating_sub(pair_start.len()),
1279                                pair_start,
1280                            )
1281                    });
1282                }
1283
1284                old_selections.push((selection.id, start..end, indent, insert_extra_newline));
1285            }
1286        }
1287
1288        self.buffer.update(cx, |buffer, cx| {
1289            let mut delta = 0_isize;
1290            let mut pending_edit: Option<PendingEdit> = None;
1291            for (_, range, indent, insert_extra_newline) in &old_selections {
1292                if pending_edit.as_ref().map_or(false, |pending| {
1293                    pending.indent != *indent
1294                        || pending.insert_extra_newline != *insert_extra_newline
1295                }) {
1296                    let pending = pending_edit.take().unwrap();
1297                    let mut new_text = String::with_capacity(1 + pending.indent as usize);
1298                    new_text.push('\n');
1299                    new_text.extend(iter::repeat(' ').take(pending.indent as usize));
1300                    if pending.insert_extra_newline {
1301                        new_text = new_text.repeat(2);
1302                    }
1303                    buffer.edit_with_autoindent(pending.ranges, new_text, cx);
1304                    delta += pending.delta;
1305                }
1306
1307                let start = (range.start as isize + delta) as usize;
1308                let end = (range.end as isize + delta) as usize;
1309                let mut text_len = *indent as usize + 1;
1310                if *insert_extra_newline {
1311                    text_len *= 2;
1312                }
1313
1314                let pending = pending_edit.get_or_insert_with(Default::default);
1315                pending.delta += text_len as isize - (end - start) as isize;
1316                pending.indent = *indent;
1317                pending.insert_extra_newline = *insert_extra_newline;
1318                pending.ranges.push(start..end);
1319            }
1320
1321            let pending = pending_edit.unwrap();
1322            let mut new_text = String::with_capacity(1 + pending.indent as usize);
1323            new_text.push('\n');
1324            new_text.extend(iter::repeat(' ').take(pending.indent as usize));
1325            if pending.insert_extra_newline {
1326                new_text = new_text.repeat(2);
1327            }
1328            buffer.edit_with_autoindent(pending.ranges, new_text, cx);
1329
1330            let buffer = buffer.read(cx);
1331            self.selections = self
1332                .selections
1333                .iter()
1334                .cloned()
1335                .zip(old_selections)
1336                .map(|(mut new_selection, (_, _, _, insert_extra_newline))| {
1337                    if insert_extra_newline {
1338                        let mut cursor = new_selection.start.to_point(&buffer);
1339                        cursor.row -= 1;
1340                        cursor.column = buffer.line_len(cursor.row);
1341                        let anchor = buffer.anchor_after(cursor);
1342                        new_selection.start = anchor.clone();
1343                        new_selection.end = anchor;
1344                    }
1345                    new_selection
1346                })
1347                .collect();
1348        });
1349
1350        self.request_autoscroll(Autoscroll::Fit, cx);
1351        self.end_transaction(cx);
1352
1353        #[derive(Default)]
1354        struct PendingEdit {
1355            indent: u32,
1356            insert_extra_newline: bool,
1357            delta: isize,
1358            ranges: SmallVec<[Range<usize>; 32]>,
1359        }
1360    }
1361
1362    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
1363        self.start_transaction(cx);
1364        let old_selections = self.local_selections::<usize>(cx);
1365        self.buffer.update(cx, |buffer, cx| {
1366            let edit_ranges = old_selections.iter().map(|s| s.start..s.end);
1367            buffer.edit_with_autoindent(edit_ranges, text, cx);
1368        });
1369
1370        let selections = self.local_selections::<usize>(cx);
1371        self.update_selections(selections, Some(Autoscroll::Fit), cx);
1372        self.end_transaction(cx);
1373    }
1374
1375    fn autoclose_pairs(&mut self, cx: &mut ViewContext<Self>) {
1376        let selections = self.local_selections::<usize>(cx);
1377        let mut bracket_pair_state = None;
1378        let mut new_selections = None;
1379        self.buffer.update(cx, |buffer, cx| {
1380            let mut snapshot = buffer.snapshot(cx);
1381            let left_biased_selections = selections
1382                .iter()
1383                .map(|selection| Selection {
1384                    id: selection.id,
1385                    start: snapshot.anchor_before(selection.start),
1386                    end: snapshot.anchor_before(selection.end),
1387                    reversed: selection.reversed,
1388                    goal: selection.goal,
1389                })
1390                .collect::<Vec<_>>();
1391
1392            let autoclose_pair = snapshot.language().and_then(|language| {
1393                let first_selection_start = selections.first().unwrap().start;
1394                let pair = language.brackets().iter().find(|pair| {
1395                    snapshot.contains_str_at(
1396                        first_selection_start.saturating_sub(pair.start.len()),
1397                        &pair.start,
1398                    )
1399                });
1400                pair.and_then(|pair| {
1401                    let should_autoclose = selections[1..].iter().all(|selection| {
1402                        snapshot.contains_str_at(
1403                            selection.start.saturating_sub(pair.start.len()),
1404                            &pair.start,
1405                        )
1406                    });
1407
1408                    if should_autoclose {
1409                        Some(pair.clone())
1410                    } else {
1411                        None
1412                    }
1413                })
1414            });
1415
1416            if let Some(pair) = autoclose_pair {
1417                let selection_ranges = selections
1418                    .iter()
1419                    .map(|selection| {
1420                        let start = selection.start.to_offset(&snapshot);
1421                        start..start
1422                    })
1423                    .collect::<SmallVec<[_; 32]>>();
1424
1425                buffer.edit(selection_ranges, &pair.end, cx);
1426                snapshot = buffer.snapshot(cx);
1427
1428                new_selections = Some(
1429                    self.resolve_selections::<usize, _>(left_biased_selections.iter(), &snapshot)
1430                        .collect::<Vec<_>>(),
1431                );
1432
1433                if pair.end.len() == 1 {
1434                    let mut delta = 0;
1435                    bracket_pair_state = Some(BracketPairState {
1436                        ranges: selections
1437                            .iter()
1438                            .map(move |selection| {
1439                                let offset = selection.start + delta;
1440                                delta += 1;
1441                                snapshot.anchor_before(offset)..snapshot.anchor_after(offset)
1442                            })
1443                            .collect(),
1444                        pair,
1445                    });
1446                }
1447            }
1448        });
1449
1450        if let Some(new_selections) = new_selections {
1451            self.update_selections(new_selections, None, cx);
1452        }
1453        if let Some(bracket_pair_state) = bracket_pair_state {
1454            self.autoclose_stack.push(bracket_pair_state);
1455        }
1456    }
1457
1458    fn skip_autoclose_end(&mut self, text: &str, cx: &mut ViewContext<Self>) -> bool {
1459        let old_selections = self.local_selections::<usize>(cx);
1460        let autoclose_pair = if let Some(autoclose_pair) = self.autoclose_stack.last() {
1461            autoclose_pair
1462        } else {
1463            return false;
1464        };
1465        if text != autoclose_pair.pair.end {
1466            return false;
1467        }
1468
1469        debug_assert_eq!(old_selections.len(), autoclose_pair.ranges.len());
1470
1471        let buffer = self.buffer.read(cx).snapshot(cx);
1472        if old_selections
1473            .iter()
1474            .zip(autoclose_pair.ranges.iter().map(|r| r.to_offset(&buffer)))
1475            .all(|(selection, autoclose_range)| {
1476                let autoclose_range_end = autoclose_range.end.to_offset(&buffer);
1477                selection.is_empty() && selection.start == autoclose_range_end
1478            })
1479        {
1480            let new_selections = old_selections
1481                .into_iter()
1482                .map(|selection| {
1483                    let cursor = selection.start + 1;
1484                    Selection {
1485                        id: selection.id,
1486                        start: cursor,
1487                        end: cursor,
1488                        reversed: false,
1489                        goal: SelectionGoal::None,
1490                    }
1491                })
1492                .collect();
1493            self.autoclose_stack.pop();
1494            self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
1495            true
1496        } else {
1497            false
1498        }
1499    }
1500
1501    fn show_autocomplete(&mut self, _: &ShowAutocomplete, cx: &mut ViewContext<Self>) {
1502        let position = self
1503            .newest_selection::<usize>(&self.buffer.read(cx).read(cx))
1504            .head();
1505        self.buffer
1506            .update(cx, |buffer, cx| buffer.completions(position, cx))
1507            .detach_and_log_err(cx);
1508    }
1509
1510    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
1511        self.start_transaction(cx);
1512        self.select_all(&SelectAll, cx);
1513        self.insert("", cx);
1514        self.end_transaction(cx);
1515    }
1516
1517    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
1518        self.start_transaction(cx);
1519        let mut selections = self.local_selections::<Point>(cx);
1520        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1521        for selection in &mut selections {
1522            if selection.is_empty() {
1523                let head = selection.head().to_display_point(&display_map);
1524                let cursor = movement::left(&display_map, head)
1525                    .unwrap()
1526                    .to_point(&display_map);
1527                selection.set_head(cursor);
1528                selection.goal = SelectionGoal::None;
1529            }
1530        }
1531        self.update_selections(selections, Some(Autoscroll::Fit), cx);
1532        self.insert("", cx);
1533        self.end_transaction(cx);
1534    }
1535
1536    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
1537        self.start_transaction(cx);
1538        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1539        let mut selections = self.local_selections::<Point>(cx);
1540        for selection in &mut selections {
1541            if selection.is_empty() {
1542                let head = selection.head().to_display_point(&display_map);
1543                let cursor = movement::right(&display_map, head)
1544                    .unwrap()
1545                    .to_point(&display_map);
1546                selection.set_head(cursor);
1547                selection.goal = SelectionGoal::None;
1548            }
1549        }
1550        self.update_selections(selections, Some(Autoscroll::Fit), cx);
1551        self.insert(&"", cx);
1552        self.end_transaction(cx);
1553    }
1554
1555    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
1556        self.start_transaction(cx);
1557        let tab_size = (self.build_settings)(cx).tab_size;
1558        let mut selections = self.local_selections::<Point>(cx);
1559        let mut last_indent = None;
1560        self.buffer.update(cx, |buffer, cx| {
1561            for selection in &mut selections {
1562                if selection.is_empty() {
1563                    let char_column = buffer
1564                        .read(cx)
1565                        .text_for_range(Point::new(selection.start.row, 0)..selection.start)
1566                        .flat_map(str::chars)
1567                        .count();
1568                    let chars_to_next_tab_stop = tab_size - (char_column % tab_size);
1569                    buffer.edit(
1570                        [selection.start..selection.start],
1571                        " ".repeat(chars_to_next_tab_stop),
1572                        cx,
1573                    );
1574                    selection.start.column += chars_to_next_tab_stop as u32;
1575                    selection.end = selection.start;
1576                } else {
1577                    let mut start_row = selection.start.row;
1578                    let mut end_row = selection.end.row + 1;
1579
1580                    // If a selection ends at the beginning of a line, don't indent
1581                    // that last line.
1582                    if selection.end.column == 0 {
1583                        end_row -= 1;
1584                    }
1585
1586                    // Avoid re-indenting a row that has already been indented by a
1587                    // previous selection, but still update this selection's column
1588                    // to reflect that indentation.
1589                    if let Some((last_indent_row, last_indent_len)) = last_indent {
1590                        if last_indent_row == selection.start.row {
1591                            selection.start.column += last_indent_len;
1592                            start_row += 1;
1593                        }
1594                        if last_indent_row == selection.end.row {
1595                            selection.end.column += last_indent_len;
1596                        }
1597                    }
1598
1599                    for row in start_row..end_row {
1600                        let indent_column = buffer.read(cx).indent_column_for_line(row) as usize;
1601                        let columns_to_next_tab_stop = tab_size - (indent_column % tab_size);
1602                        let row_start = Point::new(row, 0);
1603                        buffer.edit(
1604                            [row_start..row_start],
1605                            " ".repeat(columns_to_next_tab_stop),
1606                            cx,
1607                        );
1608
1609                        // Update this selection's endpoints to reflect the indentation.
1610                        if row == selection.start.row {
1611                            selection.start.column += columns_to_next_tab_stop as u32;
1612                        }
1613                        if row == selection.end.row {
1614                            selection.end.column += columns_to_next_tab_stop as u32;
1615                        }
1616
1617                        last_indent = Some((row, columns_to_next_tab_stop as u32));
1618                    }
1619                }
1620            }
1621        });
1622
1623        self.update_selections(selections, Some(Autoscroll::Fit), cx);
1624        self.end_transaction(cx);
1625    }
1626
1627    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
1628        self.start_transaction(cx);
1629        let tab_size = (self.build_settings)(cx).tab_size;
1630        let selections = self.local_selections::<Point>(cx);
1631        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1632        let mut deletion_ranges = Vec::new();
1633        let mut last_outdent = None;
1634        {
1635            let buffer = self.buffer.read(cx).read(cx);
1636            for selection in &selections {
1637                let mut rows = selection.spanned_rows(false, &display_map);
1638
1639                // Avoid re-outdenting a row that has already been outdented by a
1640                // previous selection.
1641                if let Some(last_row) = last_outdent {
1642                    if last_row == rows.start {
1643                        rows.start += 1;
1644                    }
1645                }
1646
1647                for row in rows {
1648                    let column = buffer.indent_column_for_line(row) as usize;
1649                    if column > 0 {
1650                        let mut deletion_len = (column % tab_size) as u32;
1651                        if deletion_len == 0 {
1652                            deletion_len = tab_size as u32;
1653                        }
1654                        deletion_ranges.push(Point::new(row, 0)..Point::new(row, deletion_len));
1655                        last_outdent = Some(row);
1656                    }
1657                }
1658            }
1659        }
1660        self.buffer.update(cx, |buffer, cx| {
1661            buffer.edit(deletion_ranges, "", cx);
1662        });
1663
1664        self.update_selections(
1665            self.local_selections::<usize>(cx),
1666            Some(Autoscroll::Fit),
1667            cx,
1668        );
1669        self.end_transaction(cx);
1670    }
1671
1672    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
1673        self.start_transaction(cx);
1674
1675        let selections = self.local_selections::<Point>(cx);
1676        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1677        let buffer = self.buffer.read(cx).snapshot(cx);
1678
1679        let mut new_cursors = Vec::new();
1680        let mut edit_ranges = Vec::new();
1681        let mut selections = selections.iter().peekable();
1682        while let Some(selection) = selections.next() {
1683            let mut rows = selection.spanned_rows(false, &display_map);
1684            let goal_display_column = selection.head().to_display_point(&display_map).column();
1685
1686            // Accumulate contiguous regions of rows that we want to delete.
1687            while let Some(next_selection) = selections.peek() {
1688                let next_rows = next_selection.spanned_rows(false, &display_map);
1689                if next_rows.start <= rows.end {
1690                    rows.end = next_rows.end;
1691                    selections.next().unwrap();
1692                } else {
1693                    break;
1694                }
1695            }
1696
1697            let mut edit_start = Point::new(rows.start, 0).to_offset(&buffer);
1698            let edit_end;
1699            let cursor_buffer_row;
1700            if buffer.max_point().row >= rows.end {
1701                // If there's a line after the range, delete the \n from the end of the row range
1702                // and position the cursor on the next line.
1703                edit_end = Point::new(rows.end, 0).to_offset(&buffer);
1704                cursor_buffer_row = rows.end;
1705            } else {
1706                // If there isn't a line after the range, delete the \n from the line before the
1707                // start of the row range and position the cursor there.
1708                edit_start = edit_start.saturating_sub(1);
1709                edit_end = buffer.len();
1710                cursor_buffer_row = rows.start.saturating_sub(1);
1711            }
1712
1713            let mut cursor = Point::new(cursor_buffer_row, 0).to_display_point(&display_map);
1714            *cursor.column_mut() =
1715                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
1716
1717            new_cursors.push((
1718                selection.id,
1719                buffer.anchor_after(cursor.to_point(&display_map)),
1720            ));
1721            edit_ranges.push(edit_start..edit_end);
1722        }
1723
1724        let buffer = self.buffer.update(cx, |buffer, cx| {
1725            buffer.edit(edit_ranges, "", cx);
1726            buffer.snapshot(cx)
1727        });
1728        let new_selections = new_cursors
1729            .into_iter()
1730            .map(|(id, cursor)| {
1731                let cursor = cursor.to_point(&buffer);
1732                Selection {
1733                    id,
1734                    start: cursor,
1735                    end: cursor,
1736                    reversed: false,
1737                    goal: SelectionGoal::None,
1738                }
1739            })
1740            .collect();
1741        self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
1742        self.end_transaction(cx);
1743    }
1744
1745    pub fn duplicate_line(&mut self, _: &DuplicateLine, cx: &mut ViewContext<Self>) {
1746        self.start_transaction(cx);
1747
1748        let selections = self.local_selections::<Point>(cx);
1749        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1750        let buffer = &display_map.buffer_snapshot;
1751
1752        let mut edits = Vec::new();
1753        let mut selections_iter = selections.iter().peekable();
1754        while let Some(selection) = selections_iter.next() {
1755            // Avoid duplicating the same lines twice.
1756            let mut rows = selection.spanned_rows(false, &display_map);
1757
1758            while let Some(next_selection) = selections_iter.peek() {
1759                let next_rows = next_selection.spanned_rows(false, &display_map);
1760                if next_rows.start <= rows.end - 1 {
1761                    rows.end = next_rows.end;
1762                    selections_iter.next().unwrap();
1763                } else {
1764                    break;
1765                }
1766            }
1767
1768            // Copy the text from the selected row region and splice it at the start of the region.
1769            let start = Point::new(rows.start, 0);
1770            let end = Point::new(rows.end - 1, buffer.line_len(rows.end - 1));
1771            let text = buffer
1772                .text_for_range(start..end)
1773                .chain(Some("\n"))
1774                .collect::<String>();
1775            edits.push((start, text, rows.len() as u32));
1776        }
1777
1778        self.buffer.update(cx, |buffer, cx| {
1779            for (point, text, _) in edits.into_iter().rev() {
1780                buffer.edit(Some(point..point), text, cx);
1781            }
1782        });
1783
1784        self.request_autoscroll(Autoscroll::Fit, cx);
1785        self.end_transaction(cx);
1786    }
1787
1788    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
1789        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1790        let buffer = self.buffer.read(cx).snapshot(cx);
1791
1792        let mut edits = Vec::new();
1793        let mut unfold_ranges = Vec::new();
1794        let mut refold_ranges = Vec::new();
1795
1796        let selections = self.local_selections::<Point>(cx);
1797        let mut selections = selections.iter().peekable();
1798        let mut contiguous_row_selections = Vec::new();
1799        let mut new_selections = Vec::new();
1800
1801        while let Some(selection) = selections.next() {
1802            // Find all the selections that span a contiguous row range
1803            contiguous_row_selections.push(selection.clone());
1804            let start_row = selection.start.row;
1805            let mut end_row = if selection.end.column > 0 || selection.is_empty() {
1806                display_map.next_line_boundary(selection.end).0.row + 1
1807            } else {
1808                selection.end.row
1809            };
1810
1811            while let Some(next_selection) = selections.peek() {
1812                if next_selection.start.row <= end_row {
1813                    end_row = if next_selection.end.column > 0 || next_selection.is_empty() {
1814                        display_map.next_line_boundary(next_selection.end).0.row + 1
1815                    } else {
1816                        next_selection.end.row
1817                    };
1818                    contiguous_row_selections.push(selections.next().unwrap().clone());
1819                } else {
1820                    break;
1821                }
1822            }
1823
1824            // Move the text spanned by the row range to be before the line preceding the row range
1825            if start_row > 0 {
1826                let range_to_move = Point::new(start_row - 1, buffer.line_len(start_row - 1))
1827                    ..Point::new(end_row - 1, buffer.line_len(end_row - 1));
1828                let insertion_point = display_map
1829                    .prev_line_boundary(Point::new(start_row - 1, 0))
1830                    .0;
1831
1832                // Don't move lines across excerpts
1833                if !buffer.range_contains_excerpt_boundary(insertion_point..range_to_move.end) {
1834                    let text = buffer
1835                        .text_for_range(range_to_move.clone())
1836                        .flat_map(|s| s.chars())
1837                        .skip(1)
1838                        .chain(['\n'])
1839                        .collect::<String>();
1840
1841                    edits.push((
1842                        buffer.anchor_after(range_to_move.start)
1843                            ..buffer.anchor_before(range_to_move.end),
1844                        String::new(),
1845                    ));
1846                    let insertion_anchor = buffer.anchor_after(insertion_point);
1847                    edits.push((insertion_anchor.clone()..insertion_anchor, text));
1848
1849                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
1850
1851                    // Move selections up
1852                    new_selections.extend(contiguous_row_selections.drain(..).map(
1853                        |mut selection| {
1854                            selection.start.row -= row_delta;
1855                            selection.end.row -= row_delta;
1856                            selection
1857                        },
1858                    ));
1859
1860                    // Move folds up
1861                    unfold_ranges.push(range_to_move.clone());
1862                    for fold in display_map.folds_in_range(
1863                        buffer.anchor_before(range_to_move.start)
1864                            ..buffer.anchor_after(range_to_move.end),
1865                    ) {
1866                        let mut start = fold.start.to_point(&buffer);
1867                        let mut end = fold.end.to_point(&buffer);
1868                        start.row -= row_delta;
1869                        end.row -= row_delta;
1870                        refold_ranges.push(start..end);
1871                    }
1872                }
1873            }
1874
1875            // If we didn't move line(s), preserve the existing selections
1876            new_selections.extend(contiguous_row_selections.drain(..));
1877        }
1878
1879        self.start_transaction(cx);
1880        self.unfold_ranges(unfold_ranges, cx);
1881        self.buffer.update(cx, |buffer, cx| {
1882            for (range, text) in edits {
1883                buffer.edit([range], text, cx);
1884            }
1885        });
1886        self.fold_ranges(refold_ranges, cx);
1887        self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
1888        self.end_transaction(cx);
1889    }
1890
1891    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
1892        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1893        let buffer = self.buffer.read(cx).snapshot(cx);
1894
1895        let mut edits = Vec::new();
1896        let mut unfold_ranges = Vec::new();
1897        let mut refold_ranges = Vec::new();
1898
1899        let selections = self.local_selections::<Point>(cx);
1900        let mut selections = selections.iter().peekable();
1901        let mut contiguous_row_selections = Vec::new();
1902        let mut new_selections = Vec::new();
1903
1904        while let Some(selection) = selections.next() {
1905            // Find all the selections that span a contiguous row range
1906            contiguous_row_selections.push(selection.clone());
1907            let start_row = selection.start.row;
1908            let mut end_row = if selection.end.column > 0 || selection.is_empty() {
1909                display_map.next_line_boundary(selection.end).0.row + 1
1910            } else {
1911                selection.end.row
1912            };
1913
1914            while let Some(next_selection) = selections.peek() {
1915                if next_selection.start.row <= end_row {
1916                    end_row = if next_selection.end.column > 0 || next_selection.is_empty() {
1917                        display_map.next_line_boundary(next_selection.end).0.row + 1
1918                    } else {
1919                        next_selection.end.row
1920                    };
1921                    contiguous_row_selections.push(selections.next().unwrap().clone());
1922                } else {
1923                    break;
1924                }
1925            }
1926
1927            // Move the text spanned by the row range to be after the last line of the row range
1928            if end_row <= buffer.max_point().row {
1929                let range_to_move = Point::new(start_row, 0)..Point::new(end_row, 0);
1930                let insertion_point = display_map.next_line_boundary(Point::new(end_row, 0)).0;
1931
1932                // Don't move lines across excerpt boundaries
1933                if !buffer.range_contains_excerpt_boundary(range_to_move.start..insertion_point) {
1934                    let mut text = String::from("\n");
1935                    text.extend(buffer.text_for_range(range_to_move.clone()));
1936                    text.pop(); // Drop trailing newline
1937                    edits.push((
1938                        buffer.anchor_after(range_to_move.start)
1939                            ..buffer.anchor_before(range_to_move.end),
1940                        String::new(),
1941                    ));
1942                    let insertion_anchor = buffer.anchor_after(insertion_point);
1943                    edits.push((insertion_anchor.clone()..insertion_anchor, text));
1944
1945                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
1946
1947                    // Move selections down
1948                    new_selections.extend(contiguous_row_selections.drain(..).map(
1949                        |mut selection| {
1950                            selection.start.row += row_delta;
1951                            selection.end.row += row_delta;
1952                            selection
1953                        },
1954                    ));
1955
1956                    // Move folds down
1957                    unfold_ranges.push(range_to_move.clone());
1958                    for fold in display_map.folds_in_range(
1959                        buffer.anchor_before(range_to_move.start)
1960                            ..buffer.anchor_after(range_to_move.end),
1961                    ) {
1962                        let mut start = fold.start.to_point(&buffer);
1963                        let mut end = fold.end.to_point(&buffer);
1964                        start.row += row_delta;
1965                        end.row += row_delta;
1966                        refold_ranges.push(start..end);
1967                    }
1968                }
1969            }
1970
1971            // If we didn't move line(s), preserve the existing selections
1972            new_selections.extend(contiguous_row_selections.drain(..));
1973        }
1974
1975        self.start_transaction(cx);
1976        self.unfold_ranges(unfold_ranges, cx);
1977        self.buffer.update(cx, |buffer, cx| {
1978            for (range, text) in edits {
1979                buffer.edit([range], text, cx);
1980            }
1981        });
1982        self.fold_ranges(refold_ranges, cx);
1983        self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
1984        self.end_transaction(cx);
1985    }
1986
1987    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
1988        self.start_transaction(cx);
1989        let mut text = String::new();
1990        let mut selections = self.local_selections::<Point>(cx);
1991        let mut clipboard_selections = Vec::with_capacity(selections.len());
1992        {
1993            let buffer = self.buffer.read(cx).read(cx);
1994            let max_point = buffer.max_point();
1995            for selection in &mut selections {
1996                let is_entire_line = selection.is_empty();
1997                if is_entire_line {
1998                    selection.start = Point::new(selection.start.row, 0);
1999                    selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
2000                }
2001                let mut len = 0;
2002                for chunk in buffer.text_for_range(selection.start..selection.end) {
2003                    text.push_str(chunk);
2004                    len += chunk.len();
2005                }
2006                clipboard_selections.push(ClipboardSelection {
2007                    len,
2008                    is_entire_line,
2009                });
2010            }
2011        }
2012        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2013        self.insert("", cx);
2014        self.end_transaction(cx);
2015
2016        cx.as_mut()
2017            .write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
2018    }
2019
2020    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
2021        let selections = self.local_selections::<Point>(cx);
2022        let mut text = String::new();
2023        let mut clipboard_selections = Vec::with_capacity(selections.len());
2024        {
2025            let buffer = self.buffer.read(cx).read(cx);
2026            let max_point = buffer.max_point();
2027            for selection in selections.iter() {
2028                let mut start = selection.start;
2029                let mut end = selection.end;
2030                let is_entire_line = selection.is_empty();
2031                if is_entire_line {
2032                    start = Point::new(start.row, 0);
2033                    end = cmp::min(max_point, Point::new(start.row + 1, 0));
2034                }
2035                let mut len = 0;
2036                for chunk in buffer.text_for_range(start..end) {
2037                    text.push_str(chunk);
2038                    len += chunk.len();
2039                }
2040                clipboard_selections.push(ClipboardSelection {
2041                    len,
2042                    is_entire_line,
2043                });
2044            }
2045        }
2046
2047        cx.as_mut()
2048            .write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
2049    }
2050
2051    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
2052        if let Some(item) = cx.as_mut().read_from_clipboard() {
2053            let clipboard_text = item.text();
2054            if let Some(mut clipboard_selections) = item.metadata::<Vec<ClipboardSelection>>() {
2055                let mut selections = self.local_selections::<usize>(cx);
2056                let all_selections_were_entire_line =
2057                    clipboard_selections.iter().all(|s| s.is_entire_line);
2058                if clipboard_selections.len() != selections.len() {
2059                    clipboard_selections.clear();
2060                }
2061
2062                let mut delta = 0_isize;
2063                let mut start_offset = 0;
2064                for (i, selection) in selections.iter_mut().enumerate() {
2065                    let to_insert;
2066                    let entire_line;
2067                    if let Some(clipboard_selection) = clipboard_selections.get(i) {
2068                        let end_offset = start_offset + clipboard_selection.len;
2069                        to_insert = &clipboard_text[start_offset..end_offset];
2070                        entire_line = clipboard_selection.is_entire_line;
2071                        start_offset = end_offset
2072                    } else {
2073                        to_insert = clipboard_text.as_str();
2074                        entire_line = all_selections_were_entire_line;
2075                    }
2076
2077                    selection.start = (selection.start as isize + delta) as usize;
2078                    selection.end = (selection.end as isize + delta) as usize;
2079
2080                    self.buffer.update(cx, |buffer, cx| {
2081                        // If the corresponding selection was empty when this slice of the
2082                        // clipboard text was written, then the entire line containing the
2083                        // selection was copied. If this selection is also currently empty,
2084                        // then paste the line before the current line of the buffer.
2085                        let range = if selection.is_empty() && entire_line {
2086                            let column = selection.start.to_point(&buffer.read(cx)).column as usize;
2087                            let line_start = selection.start - column;
2088                            line_start..line_start
2089                        } else {
2090                            selection.start..selection.end
2091                        };
2092
2093                        delta += to_insert.len() as isize - range.len() as isize;
2094                        buffer.edit([range], to_insert, cx);
2095                        selection.start += to_insert.len();
2096                        selection.end = selection.start;
2097                    });
2098                }
2099                self.update_selections(selections, Some(Autoscroll::Fit), cx);
2100            } else {
2101                self.insert(clipboard_text, cx);
2102            }
2103        }
2104    }
2105
2106    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
2107        if let Some(tx_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
2108            if let Some((selections, _)) = self.selection_history.get(&tx_id).cloned() {
2109                self.set_selections(selections, cx);
2110            }
2111            self.request_autoscroll(Autoscroll::Fit, cx);
2112        }
2113    }
2114
2115    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
2116        if let Some(tx_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
2117            if let Some((_, Some(selections))) = self.selection_history.get(&tx_id).cloned() {
2118                self.set_selections(selections, cx);
2119            }
2120            self.request_autoscroll(Autoscroll::Fit, cx);
2121        }
2122    }
2123
2124    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
2125        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2126        let mut selections = self.local_selections::<Point>(cx);
2127        for selection in &mut selections {
2128            let start = selection.start.to_display_point(&display_map);
2129            let end = selection.end.to_display_point(&display_map);
2130
2131            if start != end {
2132                selection.end = selection.start.clone();
2133            } else {
2134                let cursor = movement::left(&display_map, start)
2135                    .unwrap()
2136                    .to_point(&display_map);
2137                selection.start = cursor.clone();
2138                selection.end = cursor;
2139            }
2140            selection.reversed = false;
2141            selection.goal = SelectionGoal::None;
2142        }
2143        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2144    }
2145
2146    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
2147        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2148        let mut selections = self.local_selections::<Point>(cx);
2149        for selection in &mut selections {
2150            let head = selection.head().to_display_point(&display_map);
2151            let cursor = movement::left(&display_map, head)
2152                .unwrap()
2153                .to_point(&display_map);
2154            selection.set_head(cursor);
2155            selection.goal = SelectionGoal::None;
2156        }
2157        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2158    }
2159
2160    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
2161        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2162        let mut selections = self.local_selections::<Point>(cx);
2163        for selection in &mut selections {
2164            let start = selection.start.to_display_point(&display_map);
2165            let end = selection.end.to_display_point(&display_map);
2166
2167            if start != end {
2168                selection.start = selection.end.clone();
2169            } else {
2170                let cursor = movement::right(&display_map, end)
2171                    .unwrap()
2172                    .to_point(&display_map);
2173                selection.start = cursor;
2174                selection.end = cursor;
2175            }
2176            selection.reversed = false;
2177            selection.goal = SelectionGoal::None;
2178        }
2179        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2180    }
2181
2182    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
2183        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2184        let mut selections = self.local_selections::<Point>(cx);
2185        for selection in &mut selections {
2186            let head = selection.head().to_display_point(&display_map);
2187            let cursor = movement::right(&display_map, head)
2188                .unwrap()
2189                .to_point(&display_map);
2190            selection.set_head(cursor);
2191            selection.goal = SelectionGoal::None;
2192        }
2193        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2194    }
2195
2196    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
2197        if matches!(self.mode, EditorMode::SingleLine) {
2198            cx.propagate_action();
2199            return;
2200        }
2201
2202        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2203        let mut selections = self.local_selections::<Point>(cx);
2204        for selection in &mut selections {
2205            let start = selection.start.to_display_point(&display_map);
2206            let end = selection.end.to_display_point(&display_map);
2207            if start != end {
2208                selection.goal = SelectionGoal::None;
2209            }
2210
2211            let (start, goal) = movement::up(&display_map, start, selection.goal).unwrap();
2212            let cursor = start.to_point(&display_map);
2213            selection.start = cursor;
2214            selection.end = cursor;
2215            selection.goal = goal;
2216            selection.reversed = false;
2217        }
2218        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2219    }
2220
2221    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
2222        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2223        let mut selections = self.local_selections::<Point>(cx);
2224        for selection in &mut selections {
2225            let head = selection.head().to_display_point(&display_map);
2226            let (head, goal) = movement::up(&display_map, head, selection.goal).unwrap();
2227            let cursor = head.to_point(&display_map);
2228            selection.set_head(cursor);
2229            selection.goal = goal;
2230        }
2231        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2232    }
2233
2234    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
2235        if matches!(self.mode, EditorMode::SingleLine) {
2236            cx.propagate_action();
2237            return;
2238        }
2239
2240        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2241        let mut selections = self.local_selections::<Point>(cx);
2242        for selection in &mut selections {
2243            let start = selection.start.to_display_point(&display_map);
2244            let end = selection.end.to_display_point(&display_map);
2245            if start != end {
2246                selection.goal = SelectionGoal::None;
2247            }
2248
2249            let (start, goal) = movement::down(&display_map, end, selection.goal).unwrap();
2250            let cursor = start.to_point(&display_map);
2251            selection.start = cursor;
2252            selection.end = cursor;
2253            selection.goal = goal;
2254            selection.reversed = false;
2255        }
2256        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2257    }
2258
2259    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
2260        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2261        let mut selections = self.local_selections::<Point>(cx);
2262        for selection in &mut selections {
2263            let head = selection.head().to_display_point(&display_map);
2264            let (head, goal) = movement::down(&display_map, head, selection.goal).unwrap();
2265            let cursor = head.to_point(&display_map);
2266            selection.set_head(cursor);
2267            selection.goal = goal;
2268        }
2269        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2270    }
2271
2272    pub fn move_to_previous_word_boundary(
2273        &mut self,
2274        _: &MoveToPreviousWordBoundary,
2275        cx: &mut ViewContext<Self>,
2276    ) {
2277        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2278        let mut selections = self.local_selections::<Point>(cx);
2279        for selection in &mut selections {
2280            let head = selection.head().to_display_point(&display_map);
2281            let cursor = movement::prev_word_boundary(&display_map, head).to_point(&display_map);
2282            selection.start = cursor.clone();
2283            selection.end = cursor;
2284            selection.reversed = false;
2285            selection.goal = SelectionGoal::None;
2286        }
2287        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2288    }
2289
2290    pub fn select_to_previous_word_boundary(
2291        &mut self,
2292        _: &SelectToPreviousWordBoundary,
2293        cx: &mut ViewContext<Self>,
2294    ) {
2295        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2296        let mut selections = self.local_selections::<Point>(cx);
2297        for selection in &mut selections {
2298            let head = selection.head().to_display_point(&display_map);
2299            let cursor = movement::prev_word_boundary(&display_map, head).to_point(&display_map);
2300            selection.set_head(cursor);
2301            selection.goal = SelectionGoal::None;
2302        }
2303        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2304    }
2305
2306    pub fn delete_to_previous_word_boundary(
2307        &mut self,
2308        _: &DeleteToPreviousWordBoundary,
2309        cx: &mut ViewContext<Self>,
2310    ) {
2311        self.start_transaction(cx);
2312        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2313        let mut selections = self.local_selections::<Point>(cx);
2314        for selection in &mut selections {
2315            if selection.is_empty() {
2316                let head = selection.head().to_display_point(&display_map);
2317                let cursor =
2318                    movement::prev_word_boundary(&display_map, head).to_point(&display_map);
2319                selection.set_head(cursor);
2320                selection.goal = SelectionGoal::None;
2321            }
2322        }
2323        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2324        self.insert("", cx);
2325        self.end_transaction(cx);
2326    }
2327
2328    pub fn move_to_next_word_boundary(
2329        &mut self,
2330        _: &MoveToNextWordBoundary,
2331        cx: &mut ViewContext<Self>,
2332    ) {
2333        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2334        let mut selections = self.local_selections::<Point>(cx);
2335        for selection in &mut selections {
2336            let head = selection.head().to_display_point(&display_map);
2337            let cursor = movement::next_word_boundary(&display_map, head).to_point(&display_map);
2338            selection.start = cursor;
2339            selection.end = cursor;
2340            selection.reversed = false;
2341            selection.goal = SelectionGoal::None;
2342        }
2343        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2344    }
2345
2346    pub fn select_to_next_word_boundary(
2347        &mut self,
2348        _: &SelectToNextWordBoundary,
2349        cx: &mut ViewContext<Self>,
2350    ) {
2351        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2352        let mut selections = self.local_selections::<Point>(cx);
2353        for selection in &mut selections {
2354            let head = selection.head().to_display_point(&display_map);
2355            let cursor = movement::next_word_boundary(&display_map, head).to_point(&display_map);
2356            selection.set_head(cursor);
2357            selection.goal = SelectionGoal::None;
2358        }
2359        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2360    }
2361
2362    pub fn delete_to_next_word_boundary(
2363        &mut self,
2364        _: &DeleteToNextWordBoundary,
2365        cx: &mut ViewContext<Self>,
2366    ) {
2367        self.start_transaction(cx);
2368        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2369        let mut selections = self.local_selections::<Point>(cx);
2370        for selection in &mut selections {
2371            if selection.is_empty() {
2372                let head = selection.head().to_display_point(&display_map);
2373                let cursor =
2374                    movement::next_word_boundary(&display_map, head).to_point(&display_map);
2375                selection.set_head(cursor);
2376                selection.goal = SelectionGoal::None;
2377            }
2378        }
2379        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2380        self.insert("", cx);
2381        self.end_transaction(cx);
2382    }
2383
2384    pub fn move_to_beginning_of_line(
2385        &mut self,
2386        _: &MoveToBeginningOfLine,
2387        cx: &mut ViewContext<Self>,
2388    ) {
2389        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2390        let mut selections = self.local_selections::<Point>(cx);
2391        for selection in &mut selections {
2392            let head = selection.head().to_display_point(&display_map);
2393            let new_head = movement::line_beginning(&display_map, head, true);
2394            let cursor = new_head.to_point(&display_map);
2395            selection.start = cursor;
2396            selection.end = cursor;
2397            selection.reversed = false;
2398            selection.goal = SelectionGoal::None;
2399        }
2400        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2401    }
2402
2403    pub fn select_to_beginning_of_line(
2404        &mut self,
2405        SelectToBeginningOfLine(toggle_indent): &SelectToBeginningOfLine,
2406        cx: &mut ViewContext<Self>,
2407    ) {
2408        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2409        let mut selections = self.local_selections::<Point>(cx);
2410        for selection in &mut selections {
2411            let head = selection.head().to_display_point(&display_map);
2412            let new_head = movement::line_beginning(&display_map, head, *toggle_indent);
2413            selection.set_head(new_head.to_point(&display_map));
2414            selection.goal = SelectionGoal::None;
2415        }
2416        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2417    }
2418
2419    pub fn delete_to_beginning_of_line(
2420        &mut self,
2421        _: &DeleteToBeginningOfLine,
2422        cx: &mut ViewContext<Self>,
2423    ) {
2424        self.start_transaction(cx);
2425        self.select_to_beginning_of_line(&SelectToBeginningOfLine(false), cx);
2426        self.backspace(&Backspace, cx);
2427        self.end_transaction(cx);
2428    }
2429
2430    pub fn move_to_end_of_line(&mut self, _: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
2431        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2432        let mut selections = self.local_selections::<Point>(cx);
2433        {
2434            for selection in &mut selections {
2435                let head = selection.head().to_display_point(&display_map);
2436                let new_head = movement::line_end(&display_map, head);
2437                let anchor = new_head.to_point(&display_map);
2438                selection.start = anchor.clone();
2439                selection.end = anchor;
2440                selection.reversed = false;
2441                selection.goal = SelectionGoal::None;
2442            }
2443        }
2444        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2445    }
2446
2447    pub fn select_to_end_of_line(&mut self, _: &SelectToEndOfLine, cx: &mut ViewContext<Self>) {
2448        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2449        let mut selections = self.local_selections::<Point>(cx);
2450        for selection in &mut selections {
2451            let head = selection.head().to_display_point(&display_map);
2452            let new_head = movement::line_end(&display_map, head);
2453            selection.set_head(new_head.to_point(&display_map));
2454            selection.goal = SelectionGoal::None;
2455        }
2456        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2457    }
2458
2459    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
2460        self.start_transaction(cx);
2461        self.select_to_end_of_line(&SelectToEndOfLine, cx);
2462        self.delete(&Delete, cx);
2463        self.end_transaction(cx);
2464    }
2465
2466    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
2467        self.start_transaction(cx);
2468        self.select_to_end_of_line(&SelectToEndOfLine, cx);
2469        self.cut(&Cut, cx);
2470        self.end_transaction(cx);
2471    }
2472
2473    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
2474        if matches!(self.mode, EditorMode::SingleLine) {
2475            cx.propagate_action();
2476            return;
2477        }
2478
2479        let selection = Selection {
2480            id: post_inc(&mut self.next_selection_id),
2481            start: 0,
2482            end: 0,
2483            reversed: false,
2484            goal: SelectionGoal::None,
2485        };
2486        self.update_selections(vec![selection], Some(Autoscroll::Fit), cx);
2487    }
2488
2489    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
2490        let mut selection = self.local_selections::<Point>(cx).last().unwrap().clone();
2491        selection.set_head(Point::zero());
2492        self.update_selections(vec![selection], Some(Autoscroll::Fit), cx);
2493    }
2494
2495    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
2496        if matches!(self.mode, EditorMode::SingleLine) {
2497            cx.propagate_action();
2498            return;
2499        }
2500
2501        let cursor = self.buffer.read(cx).read(cx).len();
2502        let selection = Selection {
2503            id: post_inc(&mut self.next_selection_id),
2504            start: cursor,
2505            end: cursor,
2506            reversed: false,
2507            goal: SelectionGoal::None,
2508        };
2509        self.update_selections(vec![selection], Some(Autoscroll::Fit), cx);
2510    }
2511
2512    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
2513        self.nav_history = nav_history;
2514    }
2515
2516    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
2517        self.nav_history.as_ref()
2518    }
2519
2520    fn push_to_nav_history(
2521        &self,
2522        position: Anchor,
2523        new_position: Option<Point>,
2524        cx: &mut ViewContext<Self>,
2525    ) {
2526        if let Some(nav_history) = &self.nav_history {
2527            let buffer = self.buffer.read(cx).read(cx);
2528            let offset = position.to_offset(&buffer);
2529            let point = position.to_point(&buffer);
2530            drop(buffer);
2531
2532            if let Some(new_position) = new_position {
2533                let row_delta = (new_position.row as i64 - point.row as i64).abs();
2534                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
2535                    return;
2536                }
2537            }
2538
2539            nav_history.push(Some(NavigationData {
2540                anchor: position,
2541                offset,
2542            }));
2543        }
2544    }
2545
2546    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
2547        let mut selection = self.local_selections::<usize>(cx).first().unwrap().clone();
2548        selection.set_head(self.buffer.read(cx).read(cx).len());
2549        self.update_selections(vec![selection], Some(Autoscroll::Fit), cx);
2550    }
2551
2552    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
2553        let selection = Selection {
2554            id: post_inc(&mut self.next_selection_id),
2555            start: 0,
2556            end: self.buffer.read(cx).read(cx).len(),
2557            reversed: false,
2558            goal: SelectionGoal::None,
2559        };
2560        self.update_selections(vec![selection], None, cx);
2561    }
2562
2563    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
2564        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2565        let mut selections = self.local_selections::<Point>(cx);
2566        let max_point = display_map.buffer_snapshot.max_point();
2567        for selection in &mut selections {
2568            let rows = selection.spanned_rows(true, &display_map);
2569            selection.start = Point::new(rows.start, 0);
2570            selection.end = cmp::min(max_point, Point::new(rows.end, 0));
2571            selection.reversed = false;
2572        }
2573        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2574    }
2575
2576    pub fn split_selection_into_lines(
2577        &mut self,
2578        _: &SplitSelectionIntoLines,
2579        cx: &mut ViewContext<Self>,
2580    ) {
2581        let mut to_unfold = Vec::new();
2582        let mut new_selections = Vec::new();
2583        {
2584            let selections = self.local_selections::<Point>(cx);
2585            let buffer = self.buffer.read(cx).read(cx);
2586            for selection in selections {
2587                for row in selection.start.row..selection.end.row {
2588                    let cursor = Point::new(row, buffer.line_len(row));
2589                    new_selections.push(Selection {
2590                        id: post_inc(&mut self.next_selection_id),
2591                        start: cursor,
2592                        end: cursor,
2593                        reversed: false,
2594                        goal: SelectionGoal::None,
2595                    });
2596                }
2597                new_selections.push(Selection {
2598                    id: selection.id,
2599                    start: selection.end,
2600                    end: selection.end,
2601                    reversed: false,
2602                    goal: SelectionGoal::None,
2603                });
2604                to_unfold.push(selection.start..selection.end);
2605            }
2606        }
2607        self.unfold_ranges(to_unfold, cx);
2608        self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
2609    }
2610
2611    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
2612        self.add_selection(true, cx);
2613    }
2614
2615    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
2616        self.add_selection(false, cx);
2617    }
2618
2619    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
2620        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2621        let mut selections = self.local_selections::<Point>(cx);
2622        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
2623            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
2624            let range = oldest_selection.display_range(&display_map).sorted();
2625            let columns = cmp::min(range.start.column(), range.end.column())
2626                ..cmp::max(range.start.column(), range.end.column());
2627
2628            selections.clear();
2629            let mut stack = Vec::new();
2630            for row in range.start.row()..=range.end.row() {
2631                if let Some(selection) = self.build_columnar_selection(
2632                    &display_map,
2633                    row,
2634                    &columns,
2635                    oldest_selection.reversed,
2636                ) {
2637                    stack.push(selection.id);
2638                    selections.push(selection);
2639                }
2640            }
2641
2642            if above {
2643                stack.reverse();
2644            }
2645
2646            AddSelectionsState { above, stack }
2647        });
2648
2649        let last_added_selection = *state.stack.last().unwrap();
2650        let mut new_selections = Vec::new();
2651        if above == state.above {
2652            let end_row = if above {
2653                0
2654            } else {
2655                display_map.max_point().row()
2656            };
2657
2658            'outer: for selection in selections {
2659                if selection.id == last_added_selection {
2660                    let range = selection.display_range(&display_map).sorted();
2661                    debug_assert_eq!(range.start.row(), range.end.row());
2662                    let mut row = range.start.row();
2663                    let columns = if let SelectionGoal::ColumnRange { start, end } = selection.goal
2664                    {
2665                        start..end
2666                    } else {
2667                        cmp::min(range.start.column(), range.end.column())
2668                            ..cmp::max(range.start.column(), range.end.column())
2669                    };
2670
2671                    while row != end_row {
2672                        if above {
2673                            row -= 1;
2674                        } else {
2675                            row += 1;
2676                        }
2677
2678                        if let Some(new_selection) = self.build_columnar_selection(
2679                            &display_map,
2680                            row,
2681                            &columns,
2682                            selection.reversed,
2683                        ) {
2684                            state.stack.push(new_selection.id);
2685                            if above {
2686                                new_selections.push(new_selection);
2687                                new_selections.push(selection);
2688                            } else {
2689                                new_selections.push(selection);
2690                                new_selections.push(new_selection);
2691                            }
2692
2693                            continue 'outer;
2694                        }
2695                    }
2696                }
2697
2698                new_selections.push(selection);
2699            }
2700        } else {
2701            new_selections = selections;
2702            new_selections.retain(|s| s.id != last_added_selection);
2703            state.stack.pop();
2704        }
2705
2706        self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
2707        if state.stack.len() > 1 {
2708            self.add_selections_state = Some(state);
2709        }
2710    }
2711
2712    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) {
2713        let replace_newest = action.0;
2714        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2715        let buffer = &display_map.buffer_snapshot;
2716        let mut selections = self.local_selections::<usize>(cx);
2717        if let Some(mut select_next_state) = self.select_next_state.take() {
2718            let query = &select_next_state.query;
2719            if !select_next_state.done {
2720                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
2721                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
2722                let mut next_selected_range = None;
2723
2724                let bytes_after_last_selection =
2725                    buffer.bytes_in_range(last_selection.end..buffer.len());
2726                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
2727                let query_matches = query
2728                    .stream_find_iter(bytes_after_last_selection)
2729                    .map(|result| (last_selection.end, result))
2730                    .chain(
2731                        query
2732                            .stream_find_iter(bytes_before_first_selection)
2733                            .map(|result| (0, result)),
2734                    );
2735                for (start_offset, query_match) in query_matches {
2736                    let query_match = query_match.unwrap(); // can only fail due to I/O
2737                    let offset_range =
2738                        start_offset + query_match.start()..start_offset + query_match.end();
2739                    let display_range = offset_range.start.to_display_point(&display_map)
2740                        ..offset_range.end.to_display_point(&display_map);
2741
2742                    if !select_next_state.wordwise
2743                        || (!movement::is_inside_word(&display_map, display_range.start)
2744                            && !movement::is_inside_word(&display_map, display_range.end))
2745                    {
2746                        next_selected_range = Some(offset_range);
2747                        break;
2748                    }
2749                }
2750
2751                if let Some(next_selected_range) = next_selected_range {
2752                    if replace_newest {
2753                        if let Some(newest_id) =
2754                            selections.iter().max_by_key(|s| s.id).map(|s| s.id)
2755                        {
2756                            selections.retain(|s| s.id != newest_id);
2757                        }
2758                    }
2759                    selections.push(Selection {
2760                        id: post_inc(&mut self.next_selection_id),
2761                        start: next_selected_range.start,
2762                        end: next_selected_range.end,
2763                        reversed: false,
2764                        goal: SelectionGoal::None,
2765                    });
2766                    self.update_selections(selections, Some(Autoscroll::Newest), cx);
2767                } else {
2768                    select_next_state.done = true;
2769                }
2770            }
2771
2772            self.select_next_state = Some(select_next_state);
2773        } else if selections.len() == 1 {
2774            let selection = selections.last_mut().unwrap();
2775            if selection.start == selection.end {
2776                let word_range = movement::surrounding_word(
2777                    &display_map,
2778                    selection.start.to_display_point(&display_map),
2779                );
2780                selection.start = word_range.start.to_offset(&display_map, Bias::Left);
2781                selection.end = word_range.end.to_offset(&display_map, Bias::Left);
2782                selection.goal = SelectionGoal::None;
2783                selection.reversed = false;
2784
2785                let query = buffer
2786                    .text_for_range(selection.start..selection.end)
2787                    .collect::<String>();
2788                let select_state = SelectNextState {
2789                    query: AhoCorasick::new_auto_configured(&[query]),
2790                    wordwise: true,
2791                    done: false,
2792                };
2793                self.update_selections(selections, Some(Autoscroll::Newest), cx);
2794                self.select_next_state = Some(select_state);
2795            } else {
2796                let query = buffer
2797                    .text_for_range(selection.start..selection.end)
2798                    .collect::<String>();
2799                self.select_next_state = Some(SelectNextState {
2800                    query: AhoCorasick::new_auto_configured(&[query]),
2801                    wordwise: false,
2802                    done: false,
2803                });
2804                self.select_next(action, cx);
2805            }
2806        }
2807    }
2808
2809    pub fn toggle_comments(&mut self, _: &ToggleComments, cx: &mut ViewContext<Self>) {
2810        // Get the line comment prefix. Split its trailing whitespace into a separate string,
2811        // as that portion won't be used for detecting if a line is a comment.
2812        let full_comment_prefix =
2813            if let Some(prefix) = self.language(cx).and_then(|l| l.line_comment_prefix()) {
2814                prefix.to_string()
2815            } else {
2816                return;
2817            };
2818        let comment_prefix = full_comment_prefix.trim_end_matches(' ');
2819        let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
2820
2821        self.start_transaction(cx);
2822        let mut selections = self.local_selections::<Point>(cx);
2823        let mut all_selection_lines_are_comments = true;
2824        let mut edit_ranges = Vec::new();
2825        let mut last_toggled_row = None;
2826        self.buffer.update(cx, |buffer, cx| {
2827            for selection in &mut selections {
2828                edit_ranges.clear();
2829                let snapshot = buffer.snapshot(cx);
2830
2831                let end_row =
2832                    if selection.end.row > selection.start.row && selection.end.column == 0 {
2833                        selection.end.row
2834                    } else {
2835                        selection.end.row + 1
2836                    };
2837
2838                for row in selection.start.row..end_row {
2839                    // If multiple selections contain a given row, avoid processing that
2840                    // row more than once.
2841                    if last_toggled_row == Some(row) {
2842                        continue;
2843                    } else {
2844                        last_toggled_row = Some(row);
2845                    }
2846
2847                    if snapshot.is_line_blank(row) {
2848                        continue;
2849                    }
2850
2851                    let start = Point::new(row, snapshot.indent_column_for_line(row));
2852                    let mut line_bytes = snapshot
2853                        .bytes_in_range(start..snapshot.max_point())
2854                        .flatten()
2855                        .copied();
2856
2857                    // If this line currently begins with the line comment prefix, then record
2858                    // the range containing the prefix.
2859                    if all_selection_lines_are_comments
2860                        && line_bytes
2861                            .by_ref()
2862                            .take(comment_prefix.len())
2863                            .eq(comment_prefix.bytes())
2864                    {
2865                        // Include any whitespace that matches the comment prefix.
2866                        let matching_whitespace_len = line_bytes
2867                            .zip(comment_prefix_whitespace.bytes())
2868                            .take_while(|(a, b)| a == b)
2869                            .count() as u32;
2870                        let end = Point::new(
2871                            row,
2872                            start.column + comment_prefix.len() as u32 + matching_whitespace_len,
2873                        );
2874                        edit_ranges.push(start..end);
2875                    }
2876                    // If this line does not begin with the line comment prefix, then record
2877                    // the position where the prefix should be inserted.
2878                    else {
2879                        all_selection_lines_are_comments = false;
2880                        edit_ranges.push(start..start);
2881                    }
2882                }
2883
2884                if !edit_ranges.is_empty() {
2885                    if all_selection_lines_are_comments {
2886                        buffer.edit(edit_ranges.iter().cloned(), "", cx);
2887                    } else {
2888                        let min_column = edit_ranges.iter().map(|r| r.start.column).min().unwrap();
2889                        let edit_ranges = edit_ranges.iter().map(|range| {
2890                            let position = Point::new(range.start.row, min_column);
2891                            position..position
2892                        });
2893                        buffer.edit(edit_ranges, &full_comment_prefix, cx);
2894                    }
2895                }
2896            }
2897        });
2898
2899        self.update_selections(
2900            self.local_selections::<usize>(cx),
2901            Some(Autoscroll::Fit),
2902            cx,
2903        );
2904        self.end_transaction(cx);
2905    }
2906
2907    pub fn select_larger_syntax_node(
2908        &mut self,
2909        _: &SelectLargerSyntaxNode,
2910        cx: &mut ViewContext<Self>,
2911    ) {
2912        let old_selections = self.local_selections::<usize>(cx).into_boxed_slice();
2913        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2914        let buffer = self.buffer.read(cx).snapshot(cx);
2915
2916        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
2917        let mut selected_larger_node = false;
2918        let new_selections = old_selections
2919            .iter()
2920            .map(|selection| {
2921                let old_range = selection.start..selection.end;
2922                let mut new_range = old_range.clone();
2923                while let Some(containing_range) =
2924                    buffer.range_for_syntax_ancestor(new_range.clone())
2925                {
2926                    new_range = containing_range;
2927                    if !display_map.intersects_fold(new_range.start)
2928                        && !display_map.intersects_fold(new_range.end)
2929                    {
2930                        break;
2931                    }
2932                }
2933
2934                selected_larger_node |= new_range != old_range;
2935                Selection {
2936                    id: selection.id,
2937                    start: new_range.start,
2938                    end: new_range.end,
2939                    goal: SelectionGoal::None,
2940                    reversed: selection.reversed,
2941                }
2942            })
2943            .collect::<Vec<_>>();
2944
2945        if selected_larger_node {
2946            stack.push(old_selections);
2947            self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
2948        }
2949        self.select_larger_syntax_node_stack = stack;
2950    }
2951
2952    pub fn select_smaller_syntax_node(
2953        &mut self,
2954        _: &SelectSmallerSyntaxNode,
2955        cx: &mut ViewContext<Self>,
2956    ) {
2957        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
2958        if let Some(selections) = stack.pop() {
2959            self.update_selections(selections.to_vec(), Some(Autoscroll::Fit), cx);
2960        }
2961        self.select_larger_syntax_node_stack = stack;
2962    }
2963
2964    pub fn move_to_enclosing_bracket(
2965        &mut self,
2966        _: &MoveToEnclosingBracket,
2967        cx: &mut ViewContext<Self>,
2968    ) {
2969        let mut selections = self.local_selections::<usize>(cx);
2970        let buffer = self.buffer.read(cx).snapshot(cx);
2971        for selection in &mut selections {
2972            if let Some((open_range, close_range)) =
2973                buffer.enclosing_bracket_ranges(selection.start..selection.end)
2974            {
2975                let close_range = close_range.to_inclusive();
2976                let destination = if close_range.contains(&selection.start)
2977                    && close_range.contains(&selection.end)
2978                {
2979                    open_range.end
2980                } else {
2981                    *close_range.start()
2982                };
2983                selection.start = destination;
2984                selection.end = destination;
2985            }
2986        }
2987
2988        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2989    }
2990
2991    pub fn show_next_diagnostic(&mut self, _: &ShowNextDiagnostic, cx: &mut ViewContext<Self>) {
2992        let buffer = self.buffer.read(cx).snapshot(cx);
2993        let selection = self.newest_selection::<usize>(&buffer);
2994        let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
2995            active_diagnostics
2996                .primary_range
2997                .to_offset(&buffer)
2998                .to_inclusive()
2999        });
3000        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
3001            if active_primary_range.contains(&selection.head()) {
3002                *active_primary_range.end()
3003            } else {
3004                selection.head()
3005            }
3006        } else {
3007            selection.head()
3008        };
3009
3010        loop {
3011            let next_group = buffer
3012                .diagnostics_in_range::<_, usize>(search_start..buffer.len())
3013                .find_map(|entry| {
3014                    if entry.diagnostic.is_primary
3015                        && !entry.range.is_empty()
3016                        && Some(entry.range.end) != active_primary_range.as_ref().map(|r| *r.end())
3017                    {
3018                        Some((entry.range, entry.diagnostic.group_id))
3019                    } else {
3020                        None
3021                    }
3022                });
3023
3024            if let Some((primary_range, group_id)) = next_group {
3025                self.activate_diagnostics(group_id, cx);
3026                self.update_selections(
3027                    vec![Selection {
3028                        id: selection.id,
3029                        start: primary_range.start,
3030                        end: primary_range.start,
3031                        reversed: false,
3032                        goal: SelectionGoal::None,
3033                    }],
3034                    Some(Autoscroll::Center),
3035                    cx,
3036                );
3037                break;
3038            } else if search_start == 0 {
3039                break;
3040            } else {
3041                // Cycle around to the start of the buffer.
3042                search_start = 0;
3043            }
3044        }
3045    }
3046
3047    pub fn go_to_definition(
3048        workspace: &mut Workspace,
3049        _: &GoToDefinition,
3050        cx: &mut ViewContext<Workspace>,
3051    ) {
3052        let active_item = workspace.active_item(cx);
3053        let editor_handle = if let Some(editor) = active_item
3054            .as_ref()
3055            .and_then(|item| item.act_as::<Self>(cx))
3056        {
3057            editor
3058        } else {
3059            return;
3060        };
3061
3062        let editor = editor_handle.read(cx);
3063        let buffer = editor.buffer.read(cx);
3064        let head = editor.newest_selection::<usize>(&buffer.read(cx)).head();
3065        let (buffer, head) = editor.buffer.read(cx).text_anchor_for_position(head, cx);
3066        let definitions = workspace
3067            .project()
3068            .update(cx, |project, cx| project.definition(&buffer, head, cx));
3069        cx.spawn(|workspace, mut cx| async move {
3070            let definitions = definitions.await?;
3071            workspace.update(&mut cx, |workspace, cx| {
3072                for definition in definitions {
3073                    let range = definition
3074                        .target_range
3075                        .to_offset(definition.target_buffer.read(cx));
3076                    let target_editor_handle = workspace
3077                        .open_item(BufferItemHandle(definition.target_buffer), cx)
3078                        .downcast::<Self>()
3079                        .unwrap();
3080
3081                    target_editor_handle.update(cx, |target_editor, cx| {
3082                        // When selecting a definition in a different buffer, disable the nav history
3083                        // to avoid creating a history entry at the previous cursor location.
3084                        let disabled_history = if editor_handle == target_editor_handle {
3085                            None
3086                        } else {
3087                            target_editor.nav_history.take()
3088                        };
3089                        target_editor.select_ranges([range], Some(Autoscroll::Center), cx);
3090                        if disabled_history.is_some() {
3091                            target_editor.nav_history = disabled_history;
3092                        }
3093                    });
3094                }
3095            });
3096
3097            Ok::<(), anyhow::Error>(())
3098        })
3099        .detach_and_log_err(cx);
3100    }
3101
3102    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
3103        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
3104            let buffer = self.buffer.read(cx).snapshot(cx);
3105            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
3106            let is_valid = buffer
3107                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone())
3108                .any(|entry| {
3109                    entry.diagnostic.is_primary
3110                        && !entry.range.is_empty()
3111                        && entry.range.start == primary_range_start
3112                        && entry.diagnostic.message == active_diagnostics.primary_message
3113                });
3114
3115            if is_valid != active_diagnostics.is_valid {
3116                active_diagnostics.is_valid = is_valid;
3117                let mut new_styles = HashMap::default();
3118                for (block_id, diagnostic) in &active_diagnostics.blocks {
3119                    new_styles.insert(
3120                        *block_id,
3121                        diagnostic_block_renderer(
3122                            diagnostic.clone(),
3123                            is_valid,
3124                            self.build_settings.clone(),
3125                        ),
3126                    );
3127                }
3128                self.display_map
3129                    .update(cx, |display_map, _| display_map.replace_blocks(new_styles));
3130            }
3131        }
3132    }
3133
3134    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) {
3135        self.dismiss_diagnostics(cx);
3136        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
3137            let buffer = self.buffer.read(cx).snapshot(cx);
3138
3139            let mut primary_range = None;
3140            let mut primary_message = None;
3141            let mut group_end = Point::zero();
3142            let diagnostic_group = buffer
3143                .diagnostic_group::<Point>(group_id)
3144                .map(|entry| {
3145                    if entry.range.end > group_end {
3146                        group_end = entry.range.end;
3147                    }
3148                    if entry.diagnostic.is_primary {
3149                        primary_range = Some(entry.range.clone());
3150                        primary_message = Some(entry.diagnostic.message.clone());
3151                    }
3152                    entry
3153                })
3154                .collect::<Vec<_>>();
3155            let primary_range = primary_range.unwrap();
3156            let primary_message = primary_message.unwrap();
3157            let primary_range =
3158                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
3159
3160            let blocks = display_map
3161                .insert_blocks(
3162                    diagnostic_group.iter().map(|entry| {
3163                        let build_settings = self.build_settings.clone();
3164                        let diagnostic = entry.diagnostic.clone();
3165                        let message_height = diagnostic.message.lines().count() as u8;
3166
3167                        BlockProperties {
3168                            position: buffer.anchor_after(entry.range.start),
3169                            height: message_height,
3170                            render: diagnostic_block_renderer(diagnostic, true, build_settings),
3171                            disposition: BlockDisposition::Below,
3172                        }
3173                    }),
3174                    cx,
3175                )
3176                .into_iter()
3177                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
3178                .collect();
3179
3180            Some(ActiveDiagnosticGroup {
3181                primary_range,
3182                primary_message,
3183                blocks,
3184                is_valid: true,
3185            })
3186        });
3187    }
3188
3189    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
3190        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
3191            self.display_map.update(cx, |display_map, cx| {
3192                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
3193            });
3194            cx.notify();
3195        }
3196    }
3197
3198    fn build_columnar_selection(
3199        &mut self,
3200        display_map: &DisplaySnapshot,
3201        row: u32,
3202        columns: &Range<u32>,
3203        reversed: bool,
3204    ) -> Option<Selection<Point>> {
3205        let is_empty = columns.start == columns.end;
3206        let line_len = display_map.line_len(row);
3207        if columns.start < line_len || (is_empty && columns.start == line_len) {
3208            let start = DisplayPoint::new(row, columns.start);
3209            let end = DisplayPoint::new(row, cmp::min(columns.end, line_len));
3210            Some(Selection {
3211                id: post_inc(&mut self.next_selection_id),
3212                start: start.to_point(display_map),
3213                end: end.to_point(display_map),
3214                reversed,
3215                goal: SelectionGoal::ColumnRange {
3216                    start: columns.start,
3217                    end: columns.end,
3218                },
3219            })
3220        } else {
3221            None
3222        }
3223    }
3224
3225    pub fn local_selections_in_range(
3226        &self,
3227        range: Range<Anchor>,
3228        display_map: &DisplaySnapshot,
3229    ) -> Vec<Selection<Point>> {
3230        let buffer = &display_map.buffer_snapshot;
3231
3232        let start_ix = match self
3233            .selections
3234            .binary_search_by(|probe| probe.end.cmp(&range.start, &buffer).unwrap())
3235        {
3236            Ok(ix) | Err(ix) => ix,
3237        };
3238        let end_ix = match self
3239            .selections
3240            .binary_search_by(|probe| probe.start.cmp(&range.end, &buffer).unwrap())
3241        {
3242            Ok(ix) => ix + 1,
3243            Err(ix) => ix,
3244        };
3245
3246        fn point_selection(
3247            selection: &Selection<Anchor>,
3248            buffer: &MultiBufferSnapshot,
3249        ) -> Selection<Point> {
3250            let start = selection.start.to_point(&buffer);
3251            let end = selection.end.to_point(&buffer);
3252            Selection {
3253                id: selection.id,
3254                start,
3255                end,
3256                reversed: selection.reversed,
3257                goal: selection.goal,
3258            }
3259        }
3260
3261        self.selections[start_ix..end_ix]
3262            .iter()
3263            .chain(
3264                self.pending_selection
3265                    .as_ref()
3266                    .map(|pending| &pending.selection),
3267            )
3268            .map(|s| point_selection(s, &buffer))
3269            .collect()
3270    }
3271
3272    pub fn local_selections<'a, D>(&self, cx: &'a AppContext) -> Vec<Selection<D>>
3273    where
3274        D: 'a + TextDimension + Ord + Sub<D, Output = D>,
3275    {
3276        let buffer = self.buffer.read(cx).snapshot(cx);
3277        let mut selections = self
3278            .resolve_selections::<D, _>(self.selections.iter(), &buffer)
3279            .peekable();
3280
3281        let mut pending_selection = self.pending_selection::<D>(&buffer);
3282
3283        iter::from_fn(move || {
3284            if let Some(pending) = pending_selection.as_mut() {
3285                while let Some(next_selection) = selections.peek() {
3286                    if pending.start <= next_selection.end && pending.end >= next_selection.start {
3287                        let next_selection = selections.next().unwrap();
3288                        if next_selection.start < pending.start {
3289                            pending.start = next_selection.start;
3290                        }
3291                        if next_selection.end > pending.end {
3292                            pending.end = next_selection.end;
3293                        }
3294                    } else if next_selection.end < pending.start {
3295                        return selections.next();
3296                    } else {
3297                        break;
3298                    }
3299                }
3300
3301                pending_selection.take()
3302            } else {
3303                selections.next()
3304            }
3305        })
3306        .collect()
3307    }
3308
3309    fn resolve_selections<'a, D, I>(
3310        &self,
3311        selections: I,
3312        snapshot: &MultiBufferSnapshot,
3313    ) -> impl 'a + Iterator<Item = Selection<D>>
3314    where
3315        D: TextDimension + Ord + Sub<D, Output = D>,
3316        I: 'a + IntoIterator<Item = &'a Selection<Anchor>>,
3317    {
3318        let (to_summarize, selections) = selections.into_iter().tee();
3319        let mut summaries = snapshot
3320            .summaries_for_anchors::<D, _>(to_summarize.flat_map(|s| [&s.start, &s.end]))
3321            .into_iter();
3322        selections.map(move |s| Selection {
3323            id: s.id,
3324            start: summaries.next().unwrap(),
3325            end: summaries.next().unwrap(),
3326            reversed: s.reversed,
3327            goal: s.goal,
3328        })
3329    }
3330
3331    fn pending_selection<D: TextDimension + Ord + Sub<D, Output = D>>(
3332        &self,
3333        snapshot: &MultiBufferSnapshot,
3334    ) -> Option<Selection<D>> {
3335        self.pending_selection
3336            .as_ref()
3337            .map(|pending| self.resolve_selection(&pending.selection, &snapshot))
3338    }
3339
3340    fn resolve_selection<D: TextDimension + Ord + Sub<D, Output = D>>(
3341        &self,
3342        selection: &Selection<Anchor>,
3343        buffer: &MultiBufferSnapshot,
3344    ) -> Selection<D> {
3345        Selection {
3346            id: selection.id,
3347            start: selection.start.summary::<D>(&buffer),
3348            end: selection.end.summary::<D>(&buffer),
3349            reversed: selection.reversed,
3350            goal: selection.goal,
3351        }
3352    }
3353
3354    fn selection_count<'a>(&self) -> usize {
3355        let mut count = self.selections.len();
3356        if self.pending_selection.is_some() {
3357            count += 1;
3358        }
3359        count
3360    }
3361
3362    pub fn oldest_selection<D: TextDimension + Ord + Sub<D, Output = D>>(
3363        &self,
3364        snapshot: &MultiBufferSnapshot,
3365    ) -> Selection<D> {
3366        self.selections
3367            .iter()
3368            .min_by_key(|s| s.id)
3369            .map(|selection| self.resolve_selection(selection, snapshot))
3370            .or_else(|| self.pending_selection(snapshot))
3371            .unwrap()
3372    }
3373
3374    pub fn newest_selection<D: TextDimension + Ord + Sub<D, Output = D>>(
3375        &self,
3376        snapshot: &MultiBufferSnapshot,
3377    ) -> Selection<D> {
3378        self.resolve_selection(self.newest_anchor_selection().unwrap(), snapshot)
3379    }
3380
3381    pub fn newest_anchor_selection(&self) -> Option<&Selection<Anchor>> {
3382        self.pending_selection
3383            .as_ref()
3384            .map(|s| &s.selection)
3385            .or_else(|| self.selections.iter().max_by_key(|s| s.id))
3386    }
3387
3388    pub fn update_selections<T>(
3389        &mut self,
3390        mut selections: Vec<Selection<T>>,
3391        autoscroll: Option<Autoscroll>,
3392        cx: &mut ViewContext<Self>,
3393    ) where
3394        T: ToOffset + ToPoint + Ord + std::marker::Copy + std::fmt::Debug,
3395    {
3396        let buffer = self.buffer.read(cx).snapshot(cx);
3397        let old_cursor_position = self.newest_anchor_selection().map(|s| s.head());
3398        selections.sort_unstable_by_key(|s| s.start);
3399
3400        // Merge overlapping selections.
3401        let mut i = 1;
3402        while i < selections.len() {
3403            if selections[i - 1].end >= selections[i].start {
3404                let removed = selections.remove(i);
3405                if removed.start < selections[i - 1].start {
3406                    selections[i - 1].start = removed.start;
3407                }
3408                if removed.end > selections[i - 1].end {
3409                    selections[i - 1].end = removed.end;
3410                }
3411            } else {
3412                i += 1;
3413            }
3414        }
3415
3416        self.pending_selection = None;
3417        self.add_selections_state = None;
3418        self.select_next_state = None;
3419        self.select_larger_syntax_node_stack.clear();
3420        while let Some(autoclose_pair) = self.autoclose_stack.last() {
3421            let all_selections_inside_autoclose_ranges =
3422                if selections.len() == autoclose_pair.ranges.len() {
3423                    selections
3424                        .iter()
3425                        .zip(autoclose_pair.ranges.iter().map(|r| r.to_point(&buffer)))
3426                        .all(|(selection, autoclose_range)| {
3427                            let head = selection.head().to_point(&buffer);
3428                            autoclose_range.start <= head && autoclose_range.end >= head
3429                        })
3430                } else {
3431                    false
3432                };
3433
3434            if all_selections_inside_autoclose_ranges {
3435                break;
3436            } else {
3437                self.autoclose_stack.pop();
3438            }
3439        }
3440
3441        if let Some(old_cursor_position) = old_cursor_position {
3442            let new_cursor_position = selections
3443                .iter()
3444                .max_by_key(|s| s.id)
3445                .map(|s| s.head().to_point(&buffer));
3446            if new_cursor_position.is_some() {
3447                self.push_to_nav_history(old_cursor_position, new_cursor_position, cx);
3448            }
3449        }
3450
3451        if let Some(autoscroll) = autoscroll {
3452            self.request_autoscroll(autoscroll, cx);
3453        }
3454        self.pause_cursor_blinking(cx);
3455
3456        self.set_selections(
3457            Arc::from_iter(selections.into_iter().map(|selection| {
3458                let end_bias = if selection.end > selection.start {
3459                    Bias::Left
3460                } else {
3461                    Bias::Right
3462                };
3463                Selection {
3464                    id: selection.id,
3465                    start: buffer.anchor_after(selection.start),
3466                    end: buffer.anchor_at(selection.end, end_bias),
3467                    reversed: selection.reversed,
3468                    goal: selection.goal,
3469                }
3470            })),
3471            cx,
3472        );
3473    }
3474
3475    /// Compute new ranges for any selections that were located in excerpts that have
3476    /// since been removed.
3477    ///
3478    /// Returns a `HashMap` indicating which selections whose former head position
3479    /// was no longer present. The keys of the map are selection ids. The values are
3480    /// the id of the new excerpt where the head of the selection has been moved.
3481    pub fn refresh_selections(&mut self, cx: &mut ViewContext<Self>) -> HashMap<usize, ExcerptId> {
3482        let snapshot = self.buffer.read(cx).read(cx);
3483        let anchors_with_status = snapshot.refresh_anchors(
3484            self.selections
3485                .iter()
3486                .flat_map(|selection| [&selection.start, &selection.end]),
3487        );
3488        let offsets =
3489            snapshot.summaries_for_anchors::<usize, _>(anchors_with_status.iter().map(|a| &a.1));
3490        let offsets = offsets.chunks(2);
3491        let statuses = anchors_with_status
3492            .chunks(2)
3493            .map(|a| (a[0].0 / 2, a[0].2, a[1].2));
3494
3495        let mut selections_with_lost_position = HashMap::default();
3496        let new_selections = offsets
3497            .zip(statuses)
3498            .map(|(offsets, (selection_ix, kept_start, kept_end))| {
3499                let selection = &self.selections[selection_ix];
3500                let kept_head = if selection.reversed {
3501                    kept_start
3502                } else {
3503                    kept_end
3504                };
3505                if !kept_head {
3506                    selections_with_lost_position
3507                        .insert(selection.id, selection.head().excerpt_id.clone());
3508                }
3509
3510                Selection {
3511                    id: selection.id,
3512                    start: offsets[0],
3513                    end: offsets[1],
3514                    reversed: selection.reversed,
3515                    goal: selection.goal,
3516                }
3517            })
3518            .collect();
3519        drop(snapshot);
3520        self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
3521        selections_with_lost_position
3522    }
3523
3524    fn set_selections(&mut self, selections: Arc<[Selection<Anchor>]>, cx: &mut ViewContext<Self>) {
3525        self.selections = selections;
3526        if self.focused {
3527            self.buffer.update(cx, |buffer, cx| {
3528                buffer.set_active_selections(&self.selections, cx)
3529            });
3530        }
3531        cx.emit(Event::SelectionsChanged);
3532    }
3533
3534    pub fn request_autoscroll(&mut self, autoscroll: Autoscroll, cx: &mut ViewContext<Self>) {
3535        self.autoscroll_request = Some(autoscroll);
3536        cx.notify();
3537    }
3538
3539    fn start_transaction(&mut self, cx: &mut ViewContext<Self>) {
3540        self.start_transaction_at(Instant::now(), cx);
3541    }
3542
3543    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
3544        self.end_selection(cx);
3545        if let Some(tx_id) = self
3546            .buffer
3547            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
3548        {
3549            self.selection_history
3550                .insert(tx_id, (self.selections.clone(), None));
3551        }
3552    }
3553
3554    fn end_transaction(&mut self, cx: &mut ViewContext<Self>) {
3555        self.end_transaction_at(Instant::now(), cx);
3556    }
3557
3558    fn end_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
3559        if let Some(tx_id) = self
3560            .buffer
3561            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
3562        {
3563            if let Some((_, end_selections)) = self.selection_history.get_mut(&tx_id) {
3564                *end_selections = Some(self.selections.clone());
3565            } else {
3566                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
3567            }
3568        }
3569    }
3570
3571    pub fn page_up(&mut self, _: &PageUp, _: &mut ViewContext<Self>) {
3572        log::info!("Editor::page_up");
3573    }
3574
3575    pub fn page_down(&mut self, _: &PageDown, _: &mut ViewContext<Self>) {
3576        log::info!("Editor::page_down");
3577    }
3578
3579    pub fn fold(&mut self, _: &Fold, cx: &mut ViewContext<Self>) {
3580        let mut fold_ranges = Vec::new();
3581
3582        let selections = self.local_selections::<Point>(cx);
3583        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3584        for selection in selections {
3585            let range = selection.display_range(&display_map).sorted();
3586            let buffer_start_row = range.start.to_point(&display_map).row;
3587
3588            for row in (0..=range.end.row()).rev() {
3589                if self.is_line_foldable(&display_map, row) && !display_map.is_line_folded(row) {
3590                    let fold_range = self.foldable_range_for_line(&display_map, row);
3591                    if fold_range.end.row >= buffer_start_row {
3592                        fold_ranges.push(fold_range);
3593                        if row <= range.start.row() {
3594                            break;
3595                        }
3596                    }
3597                }
3598            }
3599        }
3600
3601        self.fold_ranges(fold_ranges, cx);
3602    }
3603
3604    pub fn unfold(&mut self, _: &Unfold, cx: &mut ViewContext<Self>) {
3605        let selections = self.local_selections::<Point>(cx);
3606        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3607        let buffer = &display_map.buffer_snapshot;
3608        let ranges = selections
3609            .iter()
3610            .map(|s| {
3611                let range = s.display_range(&display_map).sorted();
3612                let mut start = range.start.to_point(&display_map);
3613                let mut end = range.end.to_point(&display_map);
3614                start.column = 0;
3615                end.column = buffer.line_len(end.row);
3616                start..end
3617            })
3618            .collect::<Vec<_>>();
3619        self.unfold_ranges(ranges, cx);
3620    }
3621
3622    fn is_line_foldable(&self, display_map: &DisplaySnapshot, display_row: u32) -> bool {
3623        let max_point = display_map.max_point();
3624        if display_row >= max_point.row() {
3625            false
3626        } else {
3627            let (start_indent, is_blank) = display_map.line_indent(display_row);
3628            if is_blank {
3629                false
3630            } else {
3631                for display_row in display_row + 1..=max_point.row() {
3632                    let (indent, is_blank) = display_map.line_indent(display_row);
3633                    if !is_blank {
3634                        return indent > start_indent;
3635                    }
3636                }
3637                false
3638            }
3639        }
3640    }
3641
3642    fn foldable_range_for_line(
3643        &self,
3644        display_map: &DisplaySnapshot,
3645        start_row: u32,
3646    ) -> Range<Point> {
3647        let max_point = display_map.max_point();
3648
3649        let (start_indent, _) = display_map.line_indent(start_row);
3650        let start = DisplayPoint::new(start_row, display_map.line_len(start_row));
3651        let mut end = None;
3652        for row in start_row + 1..=max_point.row() {
3653            let (indent, is_blank) = display_map.line_indent(row);
3654            if !is_blank && indent <= start_indent {
3655                end = Some(DisplayPoint::new(row - 1, display_map.line_len(row - 1)));
3656                break;
3657            }
3658        }
3659
3660        let end = end.unwrap_or(max_point);
3661        return start.to_point(display_map)..end.to_point(display_map);
3662    }
3663
3664    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
3665        let selections = self.local_selections::<Point>(cx);
3666        let ranges = selections.into_iter().map(|s| s.start..s.end);
3667        self.fold_ranges(ranges, cx);
3668    }
3669
3670    fn fold_ranges<T: ToOffset>(
3671        &mut self,
3672        ranges: impl IntoIterator<Item = Range<T>>,
3673        cx: &mut ViewContext<Self>,
3674    ) {
3675        let mut ranges = ranges.into_iter().peekable();
3676        if ranges.peek().is_some() {
3677            self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
3678            self.request_autoscroll(Autoscroll::Fit, cx);
3679            cx.notify();
3680        }
3681    }
3682
3683    fn unfold_ranges<T: ToOffset>(&mut self, ranges: Vec<Range<T>>, cx: &mut ViewContext<Self>) {
3684        if !ranges.is_empty() {
3685            self.display_map
3686                .update(cx, |map, cx| map.unfold(ranges, cx));
3687            self.request_autoscroll(Autoscroll::Fit, cx);
3688            cx.notify();
3689        }
3690    }
3691
3692    pub fn insert_blocks(
3693        &mut self,
3694        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
3695        cx: &mut ViewContext<Self>,
3696    ) -> Vec<BlockId> {
3697        let blocks = self
3698            .display_map
3699            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
3700        self.request_autoscroll(Autoscroll::Fit, cx);
3701        blocks
3702    }
3703
3704    pub fn replace_blocks(
3705        &mut self,
3706        blocks: HashMap<BlockId, RenderBlock>,
3707        cx: &mut ViewContext<Self>,
3708    ) {
3709        self.display_map
3710            .update(cx, |display_map, _| display_map.replace_blocks(blocks));
3711        self.request_autoscroll(Autoscroll::Fit, cx);
3712    }
3713
3714    pub fn remove_blocks(&mut self, block_ids: HashSet<BlockId>, cx: &mut ViewContext<Self>) {
3715        self.display_map.update(cx, |display_map, cx| {
3716            display_map.remove_blocks(block_ids, cx)
3717        });
3718    }
3719
3720    pub fn longest_row(&self, cx: &mut MutableAppContext) -> u32 {
3721        self.display_map
3722            .update(cx, |map, cx| map.snapshot(cx))
3723            .longest_row()
3724    }
3725
3726    pub fn max_point(&self, cx: &mut MutableAppContext) -> DisplayPoint {
3727        self.display_map
3728            .update(cx, |map, cx| map.snapshot(cx))
3729            .max_point()
3730    }
3731
3732    pub fn text(&self, cx: &AppContext) -> String {
3733        self.buffer.read(cx).read(cx).text()
3734    }
3735
3736    pub fn display_text(&self, cx: &mut MutableAppContext) -> String {
3737        self.display_map
3738            .update(cx, |map, cx| map.snapshot(cx))
3739            .text()
3740    }
3741
3742    pub fn set_wrap_width(&self, width: Option<f32>, cx: &mut MutableAppContext) -> bool {
3743        self.display_map
3744            .update(cx, |map, cx| map.set_wrap_width(width, cx))
3745    }
3746
3747    pub fn set_highlighted_rows(&mut self, rows: Option<Range<u32>>) {
3748        self.highlighted_rows = rows;
3749    }
3750
3751    pub fn highlighted_rows(&self) -> Option<Range<u32>> {
3752        self.highlighted_rows.clone()
3753    }
3754
3755    pub fn highlight_ranges<T: 'static>(
3756        &mut self,
3757        ranges: Vec<Range<Anchor>>,
3758        color: Color,
3759        cx: &mut ViewContext<Self>,
3760    ) {
3761        self.highlighted_ranges
3762            .insert(TypeId::of::<T>(), (color, ranges));
3763        cx.notify();
3764    }
3765
3766    pub fn clear_highlighted_ranges<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
3767        self.highlighted_ranges.remove(&TypeId::of::<T>());
3768        cx.notify();
3769    }
3770
3771    #[cfg(feature = "test-support")]
3772    pub fn all_highlighted_ranges(
3773        &mut self,
3774        cx: &mut ViewContext<Self>,
3775    ) -> Vec<(Range<DisplayPoint>, Color)> {
3776        let snapshot = self.snapshot(cx);
3777        let buffer = &snapshot.buffer_snapshot;
3778        let start = buffer.anchor_before(0);
3779        let end = buffer.anchor_after(buffer.len());
3780        self.highlighted_ranges_in_range(start..end, &snapshot)
3781    }
3782
3783    pub fn highlighted_ranges_for_type<T: 'static>(&self) -> Option<(Color, &[Range<Anchor>])> {
3784        self.highlighted_ranges
3785            .get(&TypeId::of::<T>())
3786            .map(|(color, ranges)| (*color, ranges.as_slice()))
3787    }
3788
3789    pub fn highlighted_ranges_in_range(
3790        &self,
3791        search_range: Range<Anchor>,
3792        display_snapshot: &DisplaySnapshot,
3793    ) -> Vec<(Range<DisplayPoint>, Color)> {
3794        let mut results = Vec::new();
3795        let buffer = &display_snapshot.buffer_snapshot;
3796        for (color, ranges) in self.highlighted_ranges.values() {
3797            let start_ix = match ranges.binary_search_by(|probe| {
3798                let cmp = probe.end.cmp(&search_range.start, &buffer).unwrap();
3799                if cmp.is_gt() {
3800                    Ordering::Greater
3801                } else {
3802                    Ordering::Less
3803                }
3804            }) {
3805                Ok(i) | Err(i) => i,
3806            };
3807            for range in &ranges[start_ix..] {
3808                if range.start.cmp(&search_range.end, &buffer).unwrap().is_ge() {
3809                    break;
3810                }
3811                let start = range
3812                    .start
3813                    .to_point(buffer)
3814                    .to_display_point(display_snapshot);
3815                let end = range
3816                    .end
3817                    .to_point(buffer)
3818                    .to_display_point(display_snapshot);
3819                results.push((start..end, *color))
3820            }
3821        }
3822        results
3823    }
3824
3825    fn next_blink_epoch(&mut self) -> usize {
3826        self.blink_epoch += 1;
3827        self.blink_epoch
3828    }
3829
3830    fn pause_cursor_blinking(&mut self, cx: &mut ViewContext<Self>) {
3831        if !self.focused {
3832            return;
3833        }
3834
3835        self.show_local_cursors = true;
3836        cx.notify();
3837
3838        let epoch = self.next_blink_epoch();
3839        cx.spawn(|this, mut cx| {
3840            let this = this.downgrade();
3841            async move {
3842                Timer::after(CURSOR_BLINK_INTERVAL).await;
3843                if let Some(this) = cx.read(|cx| this.upgrade(cx)) {
3844                    this.update(&mut cx, |this, cx| this.resume_cursor_blinking(epoch, cx))
3845                }
3846            }
3847        })
3848        .detach();
3849    }
3850
3851    fn resume_cursor_blinking(&mut self, epoch: usize, cx: &mut ViewContext<Self>) {
3852        if epoch == self.blink_epoch {
3853            self.blinking_paused = false;
3854            self.blink_cursors(epoch, cx);
3855        }
3856    }
3857
3858    fn blink_cursors(&mut self, epoch: usize, cx: &mut ViewContext<Self>) {
3859        if epoch == self.blink_epoch && self.focused && !self.blinking_paused {
3860            self.show_local_cursors = !self.show_local_cursors;
3861            cx.notify();
3862
3863            let epoch = self.next_blink_epoch();
3864            cx.spawn(|this, mut cx| {
3865                let this = this.downgrade();
3866                async move {
3867                    Timer::after(CURSOR_BLINK_INTERVAL).await;
3868                    if let Some(this) = cx.read(|cx| this.upgrade(cx)) {
3869                        this.update(&mut cx, |this, cx| this.blink_cursors(epoch, cx));
3870                    }
3871                }
3872            })
3873            .detach();
3874        }
3875    }
3876
3877    pub fn show_local_cursors(&self) -> bool {
3878        self.show_local_cursors
3879    }
3880
3881    fn on_buffer_changed(&mut self, _: ModelHandle<MultiBuffer>, cx: &mut ViewContext<Self>) {
3882        self.refresh_active_diagnostics(cx);
3883        cx.notify();
3884    }
3885
3886    fn on_buffer_event(
3887        &mut self,
3888        _: ModelHandle<MultiBuffer>,
3889        event: &language::Event,
3890        cx: &mut ViewContext<Self>,
3891    ) {
3892        match event {
3893            language::Event::Edited => cx.emit(Event::Edited),
3894            language::Event::Dirtied => cx.emit(Event::Dirtied),
3895            language::Event::Saved => cx.emit(Event::Saved),
3896            language::Event::FileHandleChanged => cx.emit(Event::TitleChanged),
3897            language::Event::Reloaded => cx.emit(Event::TitleChanged),
3898            language::Event::Closed => cx.emit(Event::Closed),
3899            _ => {}
3900        }
3901    }
3902
3903    fn on_display_map_changed(&mut self, _: ModelHandle<DisplayMap>, cx: &mut ViewContext<Self>) {
3904        cx.notify();
3905    }
3906}
3907
3908impl EditorSnapshot {
3909    pub fn is_focused(&self) -> bool {
3910        self.is_focused
3911    }
3912
3913    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
3914        self.placeholder_text.as_ref()
3915    }
3916
3917    pub fn scroll_position(&self) -> Vector2F {
3918        compute_scroll_position(
3919            &self.display_snapshot,
3920            self.scroll_position,
3921            &self.scroll_top_anchor,
3922        )
3923    }
3924}
3925
3926impl Deref for EditorSnapshot {
3927    type Target = DisplaySnapshot;
3928
3929    fn deref(&self) -> &Self::Target {
3930        &self.display_snapshot
3931    }
3932}
3933
3934impl EditorSettings {
3935    #[cfg(any(test, feature = "test-support"))]
3936    pub fn test(cx: &AppContext) -> Self {
3937        use theme::{ContainedLabel, ContainedText, DiagnosticHeader, DiagnosticPathHeader};
3938
3939        Self {
3940            tab_size: 4,
3941            soft_wrap: SoftWrap::None,
3942            style: {
3943                let font_cache: &gpui::FontCache = cx.font_cache();
3944                let font_family_name = Arc::from("Monaco");
3945                let font_properties = Default::default();
3946                let font_family_id = font_cache.load_family(&[&font_family_name]).unwrap();
3947                let font_id = font_cache
3948                    .select_font(font_family_id, &font_properties)
3949                    .unwrap();
3950                let text = gpui::fonts::TextStyle {
3951                    font_family_name,
3952                    font_family_id,
3953                    font_id,
3954                    font_size: 14.,
3955                    color: gpui::color::Color::from_u32(0xff0000ff),
3956                    font_properties,
3957                    underline: None,
3958                };
3959                let default_diagnostic_style = DiagnosticStyle {
3960                    message: text.clone().into(),
3961                    header: Default::default(),
3962                    text_scale_factor: 1.,
3963                };
3964                EditorStyle {
3965                    text: text.clone(),
3966                    placeholder_text: None,
3967                    background: Default::default(),
3968                    gutter_background: Default::default(),
3969                    gutter_padding_factor: 2.,
3970                    active_line_background: Default::default(),
3971                    highlighted_line_background: Default::default(),
3972                    line_number: Default::default(),
3973                    line_number_active: Default::default(),
3974                    selection: Default::default(),
3975                    guest_selections: Default::default(),
3976                    syntax: Default::default(),
3977                    diagnostic_path_header: DiagnosticPathHeader {
3978                        container: Default::default(),
3979                        filename: ContainedText {
3980                            container: Default::default(),
3981                            text: text.clone(),
3982                        },
3983                        path: ContainedText {
3984                            container: Default::default(),
3985                            text: text.clone(),
3986                        },
3987                        text_scale_factor: 1.,
3988                    },
3989                    diagnostic_header: DiagnosticHeader {
3990                        container: Default::default(),
3991                        message: ContainedLabel {
3992                            container: Default::default(),
3993                            label: text.clone().into(),
3994                        },
3995                        code: ContainedText {
3996                            container: Default::default(),
3997                            text: text.clone(),
3998                        },
3999                        icon_width_factor: 1.,
4000                        text_scale_factor: 1.,
4001                    },
4002                    error_diagnostic: default_diagnostic_style.clone(),
4003                    invalid_error_diagnostic: default_diagnostic_style.clone(),
4004                    warning_diagnostic: default_diagnostic_style.clone(),
4005                    invalid_warning_diagnostic: default_diagnostic_style.clone(),
4006                    information_diagnostic: default_diagnostic_style.clone(),
4007                    invalid_information_diagnostic: default_diagnostic_style.clone(),
4008                    hint_diagnostic: default_diagnostic_style.clone(),
4009                    invalid_hint_diagnostic: default_diagnostic_style.clone(),
4010                }
4011            },
4012        }
4013    }
4014}
4015
4016fn compute_scroll_position(
4017    snapshot: &DisplaySnapshot,
4018    mut scroll_position: Vector2F,
4019    scroll_top_anchor: &Option<Anchor>,
4020) -> Vector2F {
4021    if let Some(anchor) = scroll_top_anchor {
4022        let scroll_top = anchor.to_display_point(snapshot).row() as f32;
4023        scroll_position.set_y(scroll_top + scroll_position.y());
4024    } else {
4025        scroll_position.set_y(0.);
4026    }
4027    scroll_position
4028}
4029
4030#[derive(Copy, Clone)]
4031pub enum Event {
4032    Activate,
4033    Edited,
4034    Blurred,
4035    Dirtied,
4036    Saved,
4037    TitleChanged,
4038    SelectionsChanged,
4039    Closed,
4040}
4041
4042impl Entity for Editor {
4043    type Event = Event;
4044}
4045
4046impl View for Editor {
4047    fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
4048        let settings = (self.build_settings)(cx);
4049        self.display_map.update(cx, |map, cx| {
4050            map.set_font(
4051                settings.style.text.font_id,
4052                settings.style.text.font_size,
4053                cx,
4054            )
4055        });
4056        EditorElement::new(self.handle.clone(), settings).boxed()
4057    }
4058
4059    fn ui_name() -> &'static str {
4060        "Editor"
4061    }
4062
4063    fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
4064        self.focused = true;
4065        self.blink_cursors(self.blink_epoch, cx);
4066        self.buffer.update(cx, |buffer, cx| {
4067            buffer.avoid_grouping_next_transaction(cx);
4068            buffer.set_active_selections(&self.selections, cx)
4069        });
4070    }
4071
4072    fn on_blur(&mut self, cx: &mut ViewContext<Self>) {
4073        self.focused = false;
4074        self.show_local_cursors = false;
4075        self.buffer
4076            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
4077        cx.emit(Event::Blurred);
4078        cx.notify();
4079    }
4080
4081    fn keymap_context(&self, _: &AppContext) -> gpui::keymap::Context {
4082        let mut cx = Self::default_keymap_context();
4083        let mode = match self.mode {
4084            EditorMode::SingleLine => "single_line",
4085            EditorMode::AutoHeight { .. } => "auto_height",
4086            EditorMode::Full => "full",
4087        };
4088        cx.map.insert("mode".into(), mode.into());
4089        cx
4090    }
4091}
4092
4093impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
4094    fn point_range(&self, buffer: &MultiBufferSnapshot) -> Range<Point> {
4095        let start = self.start.to_point(buffer);
4096        let end = self.end.to_point(buffer);
4097        if self.reversed {
4098            end..start
4099        } else {
4100            start..end
4101        }
4102    }
4103
4104    fn offset_range(&self, buffer: &MultiBufferSnapshot) -> Range<usize> {
4105        let start = self.start.to_offset(buffer);
4106        let end = self.end.to_offset(buffer);
4107        if self.reversed {
4108            end..start
4109        } else {
4110            start..end
4111        }
4112    }
4113
4114    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
4115        let start = self
4116            .start
4117            .to_point(&map.buffer_snapshot)
4118            .to_display_point(map);
4119        let end = self
4120            .end
4121            .to_point(&map.buffer_snapshot)
4122            .to_display_point(map);
4123        if self.reversed {
4124            end..start
4125        } else {
4126            start..end
4127        }
4128    }
4129
4130    fn spanned_rows(
4131        &self,
4132        include_end_if_at_line_start: bool,
4133        map: &DisplaySnapshot,
4134    ) -> Range<u32> {
4135        let start = self.start.to_point(&map.buffer_snapshot);
4136        let mut end = self.end.to_point(&map.buffer_snapshot);
4137        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
4138            end.row -= 1;
4139        }
4140
4141        let buffer_start = map.prev_line_boundary(start).0;
4142        let buffer_end = map.next_line_boundary(end).0;
4143        buffer_start.row..buffer_end.row + 1
4144    }
4145}
4146
4147pub fn diagnostic_block_renderer(
4148    diagnostic: Diagnostic,
4149    is_valid: bool,
4150    build_settings: BuildSettings,
4151) -> RenderBlock {
4152    let mut highlighted_lines = Vec::new();
4153    for line in diagnostic.message.lines() {
4154        highlighted_lines.push(highlight_diagnostic_message(line));
4155    }
4156
4157    Arc::new(move |cx: &BlockContext| {
4158        let settings = build_settings(cx);
4159        let style = diagnostic_style(diagnostic.severity, is_valid, &settings.style);
4160        let font_size = (style.text_scale_factor * settings.style.text.font_size).round();
4161        Flex::column()
4162            .with_children(highlighted_lines.iter().map(|(line, highlights)| {
4163                Label::new(
4164                    line.clone(),
4165                    style.message.clone().with_font_size(font_size),
4166                )
4167                .with_highlights(highlights.clone())
4168                .contained()
4169                .with_margin_left(cx.anchor_x)
4170                .boxed()
4171            }))
4172            .aligned()
4173            .left()
4174            .boxed()
4175    })
4176}
4177
4178pub fn highlight_diagnostic_message(message: &str) -> (String, Vec<usize>) {
4179    let mut message_without_backticks = String::new();
4180    let mut prev_offset = 0;
4181    let mut inside_block = false;
4182    let mut highlights = Vec::new();
4183    for (match_ix, (offset, _)) in message
4184        .match_indices('`')
4185        .chain([(message.len(), "")])
4186        .enumerate()
4187    {
4188        message_without_backticks.push_str(&message[prev_offset..offset]);
4189        if inside_block {
4190            highlights.extend(prev_offset - match_ix..offset - match_ix);
4191        }
4192
4193        inside_block = !inside_block;
4194        prev_offset = offset + 1;
4195    }
4196
4197    (message_without_backticks, highlights)
4198}
4199
4200pub fn diagnostic_style(
4201    severity: DiagnosticSeverity,
4202    valid: bool,
4203    style: &EditorStyle,
4204) -> DiagnosticStyle {
4205    match (severity, valid) {
4206        (DiagnosticSeverity::ERROR, true) => style.error_diagnostic.clone(),
4207        (DiagnosticSeverity::ERROR, false) => style.invalid_error_diagnostic.clone(),
4208        (DiagnosticSeverity::WARNING, true) => style.warning_diagnostic.clone(),
4209        (DiagnosticSeverity::WARNING, false) => style.invalid_warning_diagnostic.clone(),
4210        (DiagnosticSeverity::INFORMATION, true) => style.information_diagnostic.clone(),
4211        (DiagnosticSeverity::INFORMATION, false) => style.invalid_information_diagnostic.clone(),
4212        (DiagnosticSeverity::HINT, true) => style.hint_diagnostic.clone(),
4213        (DiagnosticSeverity::HINT, false) => style.invalid_hint_diagnostic.clone(),
4214        _ => DiagnosticStyle {
4215            message: style.text.clone().into(),
4216            header: Default::default(),
4217            text_scale_factor: 1.,
4218        },
4219    }
4220}
4221
4222pub fn settings_builder(
4223    buffer: WeakModelHandle<MultiBuffer>,
4224    settings: watch::Receiver<workspace::Settings>,
4225) -> BuildSettings {
4226    Arc::new(move |cx| {
4227        let settings = settings.borrow();
4228        let font_cache = cx.font_cache();
4229        let font_family_id = settings.buffer_font_family;
4230        let font_family_name = cx.font_cache().family_name(font_family_id).unwrap();
4231        let font_properties = Default::default();
4232        let font_id = font_cache
4233            .select_font(font_family_id, &font_properties)
4234            .unwrap();
4235        let font_size = settings.buffer_font_size;
4236
4237        let mut theme = settings.theme.editor.clone();
4238        theme.text = TextStyle {
4239            color: theme.text.color,
4240            font_family_name,
4241            font_family_id,
4242            font_id,
4243            font_size,
4244            font_properties,
4245            underline: None,
4246        };
4247        let language = buffer.upgrade(cx).and_then(|buf| buf.read(cx).language(cx));
4248        let soft_wrap = match settings.soft_wrap(language) {
4249            workspace::settings::SoftWrap::None => SoftWrap::None,
4250            workspace::settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
4251            workspace::settings::SoftWrap::PreferredLineLength => {
4252                SoftWrap::Column(settings.preferred_line_length(language).saturating_sub(1))
4253            }
4254        };
4255
4256        EditorSettings {
4257            tab_size: settings.tab_size,
4258            soft_wrap,
4259            style: theme,
4260        }
4261    })
4262}
4263
4264pub fn char_kind(c: char) -> CharKind {
4265    if c == '\n' {
4266        CharKind::Newline
4267    } else if c.is_whitespace() {
4268        CharKind::Whitespace
4269    } else if c.is_alphanumeric() || c == '_' {
4270        CharKind::Word
4271    } else {
4272        CharKind::Punctuation
4273    }
4274}
4275
4276#[cfg(test)]
4277mod tests {
4278    use super::*;
4279    use language::LanguageConfig;
4280    use std::{cell::RefCell, rc::Rc, time::Instant};
4281    use text::Point;
4282    use unindent::Unindent;
4283    use util::test::sample_text;
4284
4285    #[gpui::test]
4286    fn test_undo_redo_with_selection_restoration(cx: &mut MutableAppContext) {
4287        let mut now = Instant::now();
4288        let buffer = cx.add_model(|cx| language::Buffer::new(0, "123456", cx));
4289        let group_interval = buffer.read(cx).transaction_group_interval();
4290        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
4291        let settings = EditorSettings::test(cx);
4292        let (_, editor) = cx.add_window(Default::default(), |cx| {
4293            build_editor(buffer.clone(), settings, cx)
4294        });
4295
4296        editor.update(cx, |editor, cx| {
4297            editor.start_transaction_at(now, cx);
4298            editor.select_ranges([2..4], None, cx);
4299            editor.insert("cd", cx);
4300            editor.end_transaction_at(now, cx);
4301            assert_eq!(editor.text(cx), "12cd56");
4302            assert_eq!(editor.selected_ranges(cx), vec![4..4]);
4303
4304            editor.start_transaction_at(now, cx);
4305            editor.select_ranges([4..5], None, cx);
4306            editor.insert("e", cx);
4307            editor.end_transaction_at(now, cx);
4308            assert_eq!(editor.text(cx), "12cde6");
4309            assert_eq!(editor.selected_ranges(cx), vec![5..5]);
4310
4311            now += group_interval + Duration::from_millis(1);
4312            editor.select_ranges([2..2], None, cx);
4313
4314            // Simulate an edit in another editor
4315            buffer.update(cx, |buffer, cx| {
4316                buffer.start_transaction_at(now, cx);
4317                buffer.edit([0..1], "a", cx);
4318                buffer.edit([1..1], "b", cx);
4319                buffer.end_transaction_at(now, cx);
4320            });
4321
4322            assert_eq!(editor.text(cx), "ab2cde6");
4323            assert_eq!(editor.selected_ranges(cx), vec![3..3]);
4324
4325            // Last transaction happened past the group interval in a different editor.
4326            // Undo it individually and don't restore selections.
4327            editor.undo(&Undo, cx);
4328            assert_eq!(editor.text(cx), "12cde6");
4329            assert_eq!(editor.selected_ranges(cx), vec![2..2]);
4330
4331            // First two transactions happened within the group interval in this editor.
4332            // Undo them together and restore selections.
4333            editor.undo(&Undo, cx);
4334            editor.undo(&Undo, cx); // Undo stack is empty here, so this is a no-op.
4335            assert_eq!(editor.text(cx), "123456");
4336            assert_eq!(editor.selected_ranges(cx), vec![0..0]);
4337
4338            // Redo the first two transactions together.
4339            editor.redo(&Redo, cx);
4340            assert_eq!(editor.text(cx), "12cde6");
4341            assert_eq!(editor.selected_ranges(cx), vec![5..5]);
4342
4343            // Redo the last transaction on its own.
4344            editor.redo(&Redo, cx);
4345            assert_eq!(editor.text(cx), "ab2cde6");
4346            assert_eq!(editor.selected_ranges(cx), vec![6..6]);
4347
4348            // Test empty transactions.
4349            editor.start_transaction_at(now, cx);
4350            editor.end_transaction_at(now, cx);
4351            editor.undo(&Undo, cx);
4352            assert_eq!(editor.text(cx), "12cde6");
4353        });
4354    }
4355
4356    #[gpui::test]
4357    fn test_selection_with_mouse(cx: &mut gpui::MutableAppContext) {
4358        let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
4359        let settings = EditorSettings::test(cx);
4360        let (_, editor) =
4361            cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4362
4363        editor.update(cx, |view, cx| {
4364            view.begin_selection(DisplayPoint::new(2, 2), false, 1, cx);
4365        });
4366
4367        assert_eq!(
4368            editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
4369            [DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2)]
4370        );
4371
4372        editor.update(cx, |view, cx| {
4373            view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
4374        });
4375
4376        assert_eq!(
4377            editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
4378            [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
4379        );
4380
4381        editor.update(cx, |view, cx| {
4382            view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
4383        });
4384
4385        assert_eq!(
4386            editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
4387            [DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1)]
4388        );
4389
4390        editor.update(cx, |view, cx| {
4391            view.end_selection(cx);
4392            view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
4393        });
4394
4395        assert_eq!(
4396            editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
4397            [DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1)]
4398        );
4399
4400        editor.update(cx, |view, cx| {
4401            view.begin_selection(DisplayPoint::new(3, 3), true, 1, cx);
4402            view.update_selection(DisplayPoint::new(0, 0), 0, Vector2F::zero(), cx);
4403        });
4404
4405        assert_eq!(
4406            editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
4407            [
4408                DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1),
4409                DisplayPoint::new(3, 3)..DisplayPoint::new(0, 0)
4410            ]
4411        );
4412
4413        editor.update(cx, |view, cx| {
4414            view.end_selection(cx);
4415        });
4416
4417        assert_eq!(
4418            editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
4419            [DisplayPoint::new(3, 3)..DisplayPoint::new(0, 0)]
4420        );
4421    }
4422
4423    #[gpui::test]
4424    fn test_canceling_pending_selection(cx: &mut gpui::MutableAppContext) {
4425        let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
4426        let settings = EditorSettings::test(cx);
4427        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4428
4429        view.update(cx, |view, cx| {
4430            view.begin_selection(DisplayPoint::new(2, 2), false, 1, cx);
4431            assert_eq!(
4432                view.selected_display_ranges(cx),
4433                [DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2)]
4434            );
4435        });
4436
4437        view.update(cx, |view, cx| {
4438            view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
4439            assert_eq!(
4440                view.selected_display_ranges(cx),
4441                [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
4442            );
4443        });
4444
4445        view.update(cx, |view, cx| {
4446            view.cancel(&Cancel, cx);
4447            view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
4448            assert_eq!(
4449                view.selected_display_ranges(cx),
4450                [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
4451            );
4452        });
4453    }
4454
4455    #[gpui::test]
4456    fn test_navigation_history(cx: &mut gpui::MutableAppContext) {
4457        cx.add_window(Default::default(), |cx| {
4458            use workspace::ItemView;
4459            let nav_history = Rc::new(RefCell::new(workspace::NavHistory::default()));
4460            let settings = EditorSettings::test(&cx);
4461            let buffer = MultiBuffer::build_simple(&sample_text(30, 5, 'a'), cx);
4462            let mut editor = build_editor(buffer.clone(), settings, cx);
4463            editor.nav_history = Some(ItemNavHistory::new(nav_history.clone(), &cx.handle()));
4464
4465            // Move the cursor a small distance.
4466            // Nothing is added to the navigation history.
4467            editor.select_display_ranges(&[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)], cx);
4468            editor.select_display_ranges(&[DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0)], cx);
4469            assert!(nav_history.borrow_mut().pop_backward().is_none());
4470
4471            // Move the cursor a large distance.
4472            // The history can jump back to the previous position.
4473            editor.select_display_ranges(&[DisplayPoint::new(13, 0)..DisplayPoint::new(13, 3)], cx);
4474            let nav_entry = nav_history.borrow_mut().pop_backward().unwrap();
4475            editor.navigate(nav_entry.data.unwrap(), cx);
4476            assert_eq!(nav_entry.item_view.id(), cx.view_id());
4477            assert_eq!(
4478                editor.selected_display_ranges(cx),
4479                &[DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0)]
4480            );
4481
4482            // Move the cursor a small distance via the mouse.
4483            // Nothing is added to the navigation history.
4484            editor.begin_selection(DisplayPoint::new(5, 0), false, 1, cx);
4485            editor.end_selection(cx);
4486            assert_eq!(
4487                editor.selected_display_ranges(cx),
4488                &[DisplayPoint::new(5, 0)..DisplayPoint::new(5, 0)]
4489            );
4490            assert!(nav_history.borrow_mut().pop_backward().is_none());
4491
4492            // Move the cursor a large distance via the mouse.
4493            // The history can jump back to the previous position.
4494            editor.begin_selection(DisplayPoint::new(15, 0), false, 1, cx);
4495            editor.end_selection(cx);
4496            assert_eq!(
4497                editor.selected_display_ranges(cx),
4498                &[DisplayPoint::new(15, 0)..DisplayPoint::new(15, 0)]
4499            );
4500            let nav_entry = nav_history.borrow_mut().pop_backward().unwrap();
4501            editor.navigate(nav_entry.data.unwrap(), cx);
4502            assert_eq!(nav_entry.item_view.id(), cx.view_id());
4503            assert_eq!(
4504                editor.selected_display_ranges(cx),
4505                &[DisplayPoint::new(5, 0)..DisplayPoint::new(5, 0)]
4506            );
4507
4508            editor
4509        });
4510    }
4511
4512    #[gpui::test]
4513    fn test_cancel(cx: &mut gpui::MutableAppContext) {
4514        let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
4515        let settings = EditorSettings::test(cx);
4516        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4517
4518        view.update(cx, |view, cx| {
4519            view.begin_selection(DisplayPoint::new(3, 4), false, 1, cx);
4520            view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
4521            view.end_selection(cx);
4522
4523            view.begin_selection(DisplayPoint::new(0, 1), true, 1, cx);
4524            view.update_selection(DisplayPoint::new(0, 3), 0, Vector2F::zero(), cx);
4525            view.end_selection(cx);
4526            assert_eq!(
4527                view.selected_display_ranges(cx),
4528                [
4529                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
4530                    DisplayPoint::new(3, 4)..DisplayPoint::new(1, 1),
4531                ]
4532            );
4533        });
4534
4535        view.update(cx, |view, cx| {
4536            view.cancel(&Cancel, cx);
4537            assert_eq!(
4538                view.selected_display_ranges(cx),
4539                [DisplayPoint::new(3, 4)..DisplayPoint::new(1, 1)]
4540            );
4541        });
4542
4543        view.update(cx, |view, cx| {
4544            view.cancel(&Cancel, cx);
4545            assert_eq!(
4546                view.selected_display_ranges(cx),
4547                [DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1)]
4548            );
4549        });
4550    }
4551
4552    #[gpui::test]
4553    fn test_fold(cx: &mut gpui::MutableAppContext) {
4554        let buffer = MultiBuffer::build_simple(
4555            &"
4556                impl Foo {
4557                    // Hello!
4558
4559                    fn a() {
4560                        1
4561                    }
4562
4563                    fn b() {
4564                        2
4565                    }
4566
4567                    fn c() {
4568                        3
4569                    }
4570                }
4571            "
4572            .unindent(),
4573            cx,
4574        );
4575        let settings = EditorSettings::test(&cx);
4576        let (_, view) = cx.add_window(Default::default(), |cx| {
4577            build_editor(buffer.clone(), settings, cx)
4578        });
4579
4580        view.update(cx, |view, cx| {
4581            view.select_display_ranges(&[DisplayPoint::new(8, 0)..DisplayPoint::new(12, 0)], cx);
4582            view.fold(&Fold, cx);
4583            assert_eq!(
4584                view.display_text(cx),
4585                "
4586                    impl Foo {
4587                        // Hello!
4588
4589                        fn a() {
4590                            1
4591                        }
4592
4593                        fn b() {…
4594                        }
4595
4596                        fn c() {…
4597                        }
4598                    }
4599                "
4600                .unindent(),
4601            );
4602
4603            view.fold(&Fold, cx);
4604            assert_eq!(
4605                view.display_text(cx),
4606                "
4607                    impl Foo {…
4608                    }
4609                "
4610                .unindent(),
4611            );
4612
4613            view.unfold(&Unfold, cx);
4614            assert_eq!(
4615                view.display_text(cx),
4616                "
4617                    impl Foo {
4618                        // Hello!
4619
4620                        fn a() {
4621                            1
4622                        }
4623
4624                        fn b() {…
4625                        }
4626
4627                        fn c() {…
4628                        }
4629                    }
4630                "
4631                .unindent(),
4632            );
4633
4634            view.unfold(&Unfold, cx);
4635            assert_eq!(view.display_text(cx), buffer.read(cx).read(cx).text());
4636        });
4637    }
4638
4639    #[gpui::test]
4640    fn test_move_cursor(cx: &mut gpui::MutableAppContext) {
4641        let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
4642        let settings = EditorSettings::test(&cx);
4643        let (_, view) = cx.add_window(Default::default(), |cx| {
4644            build_editor(buffer.clone(), settings, cx)
4645        });
4646
4647        buffer.update(cx, |buffer, cx| {
4648            buffer.edit(
4649                vec![
4650                    Point::new(1, 0)..Point::new(1, 0),
4651                    Point::new(1, 1)..Point::new(1, 1),
4652                ],
4653                "\t",
4654                cx,
4655            );
4656        });
4657
4658        view.update(cx, |view, cx| {
4659            assert_eq!(
4660                view.selected_display_ranges(cx),
4661                &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
4662            );
4663
4664            view.move_down(&MoveDown, cx);
4665            assert_eq!(
4666                view.selected_display_ranges(cx),
4667                &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
4668            );
4669
4670            view.move_right(&MoveRight, cx);
4671            assert_eq!(
4672                view.selected_display_ranges(cx),
4673                &[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4)]
4674            );
4675
4676            view.move_left(&MoveLeft, cx);
4677            assert_eq!(
4678                view.selected_display_ranges(cx),
4679                &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
4680            );
4681
4682            view.move_up(&MoveUp, cx);
4683            assert_eq!(
4684                view.selected_display_ranges(cx),
4685                &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
4686            );
4687
4688            view.move_to_end(&MoveToEnd, cx);
4689            assert_eq!(
4690                view.selected_display_ranges(cx),
4691                &[DisplayPoint::new(5, 6)..DisplayPoint::new(5, 6)]
4692            );
4693
4694            view.move_to_beginning(&MoveToBeginning, cx);
4695            assert_eq!(
4696                view.selected_display_ranges(cx),
4697                &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
4698            );
4699
4700            view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 2)], cx);
4701            view.select_to_beginning(&SelectToBeginning, cx);
4702            assert_eq!(
4703                view.selected_display_ranges(cx),
4704                &[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 0)]
4705            );
4706
4707            view.select_to_end(&SelectToEnd, cx);
4708            assert_eq!(
4709                view.selected_display_ranges(cx),
4710                &[DisplayPoint::new(0, 1)..DisplayPoint::new(5, 6)]
4711            );
4712        });
4713    }
4714
4715    #[gpui::test]
4716    fn test_move_cursor_multibyte(cx: &mut gpui::MutableAppContext) {
4717        let buffer = MultiBuffer::build_simple("ⓐⓑⓒⓓⓔ\nabcde\nαβγδε\n", cx);
4718        let settings = EditorSettings::test(&cx);
4719        let (_, view) = cx.add_window(Default::default(), |cx| {
4720            build_editor(buffer.clone(), settings, cx)
4721        });
4722
4723        assert_eq!('ⓐ'.len_utf8(), 3);
4724        assert_eq!('α'.len_utf8(), 2);
4725
4726        view.update(cx, |view, cx| {
4727            view.fold_ranges(
4728                vec![
4729                    Point::new(0, 6)..Point::new(0, 12),
4730                    Point::new(1, 2)..Point::new(1, 4),
4731                    Point::new(2, 4)..Point::new(2, 8),
4732                ],
4733                cx,
4734            );
4735            assert_eq!(view.display_text(cx), "ⓐⓑ…ⓔ\nab…e\nαβ…ε\n");
4736
4737            view.move_right(&MoveRight, cx);
4738            assert_eq!(
4739                view.selected_display_ranges(cx),
4740                &[empty_range(0, "".len())]
4741            );
4742            view.move_right(&MoveRight, cx);
4743            assert_eq!(
4744                view.selected_display_ranges(cx),
4745                &[empty_range(0, "ⓐⓑ".len())]
4746            );
4747            view.move_right(&MoveRight, cx);
4748            assert_eq!(
4749                view.selected_display_ranges(cx),
4750                &[empty_range(0, "ⓐⓑ…".len())]
4751            );
4752
4753            view.move_down(&MoveDown, cx);
4754            assert_eq!(
4755                view.selected_display_ranges(cx),
4756                &[empty_range(1, "ab…".len())]
4757            );
4758            view.move_left(&MoveLeft, cx);
4759            assert_eq!(
4760                view.selected_display_ranges(cx),
4761                &[empty_range(1, "ab".len())]
4762            );
4763            view.move_left(&MoveLeft, cx);
4764            assert_eq!(
4765                view.selected_display_ranges(cx),
4766                &[empty_range(1, "a".len())]
4767            );
4768
4769            view.move_down(&MoveDown, cx);
4770            assert_eq!(
4771                view.selected_display_ranges(cx),
4772                &[empty_range(2, "α".len())]
4773            );
4774            view.move_right(&MoveRight, cx);
4775            assert_eq!(
4776                view.selected_display_ranges(cx),
4777                &[empty_range(2, "αβ".len())]
4778            );
4779            view.move_right(&MoveRight, cx);
4780            assert_eq!(
4781                view.selected_display_ranges(cx),
4782                &[empty_range(2, "αβ…".len())]
4783            );
4784            view.move_right(&MoveRight, cx);
4785            assert_eq!(
4786                view.selected_display_ranges(cx),
4787                &[empty_range(2, "αβ…ε".len())]
4788            );
4789
4790            view.move_up(&MoveUp, cx);
4791            assert_eq!(
4792                view.selected_display_ranges(cx),
4793                &[empty_range(1, "ab…e".len())]
4794            );
4795            view.move_up(&MoveUp, cx);
4796            assert_eq!(
4797                view.selected_display_ranges(cx),
4798                &[empty_range(0, "ⓐⓑ…ⓔ".len())]
4799            );
4800            view.move_left(&MoveLeft, cx);
4801            assert_eq!(
4802                view.selected_display_ranges(cx),
4803                &[empty_range(0, "ⓐⓑ…".len())]
4804            );
4805            view.move_left(&MoveLeft, cx);
4806            assert_eq!(
4807                view.selected_display_ranges(cx),
4808                &[empty_range(0, "ⓐⓑ".len())]
4809            );
4810            view.move_left(&MoveLeft, cx);
4811            assert_eq!(
4812                view.selected_display_ranges(cx),
4813                &[empty_range(0, "".len())]
4814            );
4815        });
4816    }
4817
4818    #[gpui::test]
4819    fn test_move_cursor_different_line_lengths(cx: &mut gpui::MutableAppContext) {
4820        let buffer = MultiBuffer::build_simple("ⓐⓑⓒⓓⓔ\nabcd\nαβγ\nabcd\nⓐⓑⓒⓓⓔ\n", cx);
4821        let settings = EditorSettings::test(&cx);
4822        let (_, view) = cx.add_window(Default::default(), |cx| {
4823            build_editor(buffer.clone(), settings, cx)
4824        });
4825        view.update(cx, |view, cx| {
4826            view.select_display_ranges(&[empty_range(0, "ⓐⓑⓒⓓⓔ".len())], cx);
4827            view.move_down(&MoveDown, cx);
4828            assert_eq!(
4829                view.selected_display_ranges(cx),
4830                &[empty_range(1, "abcd".len())]
4831            );
4832
4833            view.move_down(&MoveDown, cx);
4834            assert_eq!(
4835                view.selected_display_ranges(cx),
4836                &[empty_range(2, "αβγ".len())]
4837            );
4838
4839            view.move_down(&MoveDown, cx);
4840            assert_eq!(
4841                view.selected_display_ranges(cx),
4842                &[empty_range(3, "abcd".len())]
4843            );
4844
4845            view.move_down(&MoveDown, cx);
4846            assert_eq!(
4847                view.selected_display_ranges(cx),
4848                &[empty_range(4, "ⓐⓑⓒⓓⓔ".len())]
4849            );
4850
4851            view.move_up(&MoveUp, cx);
4852            assert_eq!(
4853                view.selected_display_ranges(cx),
4854                &[empty_range(3, "abcd".len())]
4855            );
4856
4857            view.move_up(&MoveUp, cx);
4858            assert_eq!(
4859                view.selected_display_ranges(cx),
4860                &[empty_range(2, "αβγ".len())]
4861            );
4862        });
4863    }
4864
4865    #[gpui::test]
4866    fn test_beginning_end_of_line(cx: &mut gpui::MutableAppContext) {
4867        let buffer = MultiBuffer::build_simple("abc\n  def", cx);
4868        let settings = EditorSettings::test(&cx);
4869        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4870        view.update(cx, |view, cx| {
4871            view.select_display_ranges(
4872                &[
4873                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
4874                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4),
4875                ],
4876                cx,
4877            );
4878        });
4879
4880        view.update(cx, |view, cx| {
4881            view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
4882            assert_eq!(
4883                view.selected_display_ranges(cx),
4884                &[
4885                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4886                    DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
4887                ]
4888            );
4889        });
4890
4891        view.update(cx, |view, cx| {
4892            view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
4893            assert_eq!(
4894                view.selected_display_ranges(cx),
4895                &[
4896                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4897                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4898                ]
4899            );
4900        });
4901
4902        view.update(cx, |view, cx| {
4903            view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
4904            assert_eq!(
4905                view.selected_display_ranges(cx),
4906                &[
4907                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4908                    DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
4909                ]
4910            );
4911        });
4912
4913        view.update(cx, |view, cx| {
4914            view.move_to_end_of_line(&MoveToEndOfLine, cx);
4915            assert_eq!(
4916                view.selected_display_ranges(cx),
4917                &[
4918                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
4919                    DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
4920                ]
4921            );
4922        });
4923
4924        // Moving to the end of line again is a no-op.
4925        view.update(cx, |view, cx| {
4926            view.move_to_end_of_line(&MoveToEndOfLine, cx);
4927            assert_eq!(
4928                view.selected_display_ranges(cx),
4929                &[
4930                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
4931                    DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
4932                ]
4933            );
4934        });
4935
4936        view.update(cx, |view, cx| {
4937            view.move_left(&MoveLeft, cx);
4938            view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
4939            assert_eq!(
4940                view.selected_display_ranges(cx),
4941                &[
4942                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
4943                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 2),
4944                ]
4945            );
4946        });
4947
4948        view.update(cx, |view, cx| {
4949            view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
4950            assert_eq!(
4951                view.selected_display_ranges(cx),
4952                &[
4953                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
4954                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 0),
4955                ]
4956            );
4957        });
4958
4959        view.update(cx, |view, cx| {
4960            view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
4961            assert_eq!(
4962                view.selected_display_ranges(cx),
4963                &[
4964                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
4965                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 2),
4966                ]
4967            );
4968        });
4969
4970        view.update(cx, |view, cx| {
4971            view.select_to_end_of_line(&SelectToEndOfLine, cx);
4972            assert_eq!(
4973                view.selected_display_ranges(cx),
4974                &[
4975                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 3),
4976                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 5),
4977                ]
4978            );
4979        });
4980
4981        view.update(cx, |view, cx| {
4982            view.delete_to_end_of_line(&DeleteToEndOfLine, cx);
4983            assert_eq!(view.display_text(cx), "ab\n  de");
4984            assert_eq!(
4985                view.selected_display_ranges(cx),
4986                &[
4987                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4988                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4),
4989                ]
4990            );
4991        });
4992
4993        view.update(cx, |view, cx| {
4994            view.delete_to_beginning_of_line(&DeleteToBeginningOfLine, cx);
4995            assert_eq!(view.display_text(cx), "\n");
4996            assert_eq!(
4997                view.selected_display_ranges(cx),
4998                &[
4999                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
5000                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
5001                ]
5002            );
5003        });
5004    }
5005
5006    #[gpui::test]
5007    fn test_prev_next_word_boundary(cx: &mut gpui::MutableAppContext) {
5008        let buffer = MultiBuffer::build_simple("use std::str::{foo, bar}\n\n  {baz.qux()}", cx);
5009        let settings = EditorSettings::test(&cx);
5010        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5011        view.update(cx, |view, cx| {
5012            view.select_display_ranges(
5013                &[
5014                    DisplayPoint::new(0, 11)..DisplayPoint::new(0, 11),
5015                    DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4),
5016                ],
5017                cx,
5018            );
5019        });
5020
5021        view.update(cx, |view, cx| {
5022            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
5023            assert_eq!(
5024                view.selected_display_ranges(cx),
5025                &[
5026                    DisplayPoint::new(0, 9)..DisplayPoint::new(0, 9),
5027                    DisplayPoint::new(2, 3)..DisplayPoint::new(2, 3),
5028                ]
5029            );
5030        });
5031
5032        view.update(cx, |view, cx| {
5033            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
5034            assert_eq!(
5035                view.selected_display_ranges(cx),
5036                &[
5037                    DisplayPoint::new(0, 7)..DisplayPoint::new(0, 7),
5038                    DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2),
5039                ]
5040            );
5041        });
5042
5043        view.update(cx, |view, cx| {
5044            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
5045            assert_eq!(
5046                view.selected_display_ranges(cx),
5047                &[
5048                    DisplayPoint::new(0, 4)..DisplayPoint::new(0, 4),
5049                    DisplayPoint::new(2, 0)..DisplayPoint::new(2, 0),
5050                ]
5051            );
5052        });
5053
5054        view.update(cx, |view, cx| {
5055            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
5056            assert_eq!(
5057                view.selected_display_ranges(cx),
5058                &[
5059                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
5060                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
5061                ]
5062            );
5063        });
5064
5065        view.update(cx, |view, cx| {
5066            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
5067            assert_eq!(
5068                view.selected_display_ranges(cx),
5069                &[
5070                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
5071                    DisplayPoint::new(0, 23)..DisplayPoint::new(0, 23),
5072                ]
5073            );
5074        });
5075
5076        view.update(cx, |view, cx| {
5077            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
5078            assert_eq!(
5079                view.selected_display_ranges(cx),
5080                &[
5081                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
5082                    DisplayPoint::new(0, 24)..DisplayPoint::new(0, 24),
5083                ]
5084            );
5085        });
5086
5087        view.update(cx, |view, cx| {
5088            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
5089            assert_eq!(
5090                view.selected_display_ranges(cx),
5091                &[
5092                    DisplayPoint::new(0, 7)..DisplayPoint::new(0, 7),
5093                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
5094                ]
5095            );
5096        });
5097
5098        view.update(cx, |view, cx| {
5099            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
5100            assert_eq!(
5101                view.selected_display_ranges(cx),
5102                &[
5103                    DisplayPoint::new(0, 9)..DisplayPoint::new(0, 9),
5104                    DisplayPoint::new(2, 3)..DisplayPoint::new(2, 3),
5105                ]
5106            );
5107        });
5108
5109        view.update(cx, |view, cx| {
5110            view.move_right(&MoveRight, cx);
5111            view.select_to_previous_word_boundary(&SelectToPreviousWordBoundary, cx);
5112            assert_eq!(
5113                view.selected_display_ranges(cx),
5114                &[
5115                    DisplayPoint::new(0, 10)..DisplayPoint::new(0, 9),
5116                    DisplayPoint::new(2, 4)..DisplayPoint::new(2, 3),
5117                ]
5118            );
5119        });
5120
5121        view.update(cx, |view, cx| {
5122            view.select_to_previous_word_boundary(&SelectToPreviousWordBoundary, cx);
5123            assert_eq!(
5124                view.selected_display_ranges(cx),
5125                &[
5126                    DisplayPoint::new(0, 10)..DisplayPoint::new(0, 7),
5127                    DisplayPoint::new(2, 4)..DisplayPoint::new(2, 2),
5128                ]
5129            );
5130        });
5131
5132        view.update(cx, |view, cx| {
5133            view.select_to_next_word_boundary(&SelectToNextWordBoundary, cx);
5134            assert_eq!(
5135                view.selected_display_ranges(cx),
5136                &[
5137                    DisplayPoint::new(0, 10)..DisplayPoint::new(0, 9),
5138                    DisplayPoint::new(2, 4)..DisplayPoint::new(2, 3),
5139                ]
5140            );
5141        });
5142    }
5143
5144    #[gpui::test]
5145    fn test_prev_next_word_bounds_with_soft_wrap(cx: &mut gpui::MutableAppContext) {
5146        let buffer = MultiBuffer::build_simple("use one::{\n    two::three::four::five\n};", cx);
5147        let settings = EditorSettings::test(&cx);
5148        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5149
5150        view.update(cx, |view, cx| {
5151            view.set_wrap_width(Some(140.), cx);
5152            assert_eq!(
5153                view.display_text(cx),
5154                "use one::{\n    two::three::\n    four::five\n};"
5155            );
5156
5157            view.select_display_ranges(&[DisplayPoint::new(1, 7)..DisplayPoint::new(1, 7)], cx);
5158
5159            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
5160            assert_eq!(
5161                view.selected_display_ranges(cx),
5162                &[DisplayPoint::new(1, 9)..DisplayPoint::new(1, 9)]
5163            );
5164
5165            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
5166            assert_eq!(
5167                view.selected_display_ranges(cx),
5168                &[DisplayPoint::new(1, 14)..DisplayPoint::new(1, 14)]
5169            );
5170
5171            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
5172            assert_eq!(
5173                view.selected_display_ranges(cx),
5174                &[DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4)]
5175            );
5176
5177            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
5178            assert_eq!(
5179                view.selected_display_ranges(cx),
5180                &[DisplayPoint::new(2, 8)..DisplayPoint::new(2, 8)]
5181            );
5182
5183            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
5184            assert_eq!(
5185                view.selected_display_ranges(cx),
5186                &[DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4)]
5187            );
5188
5189            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
5190            assert_eq!(
5191                view.selected_display_ranges(cx),
5192                &[DisplayPoint::new(1, 14)..DisplayPoint::new(1, 14)]
5193            );
5194        });
5195    }
5196
5197    #[gpui::test]
5198    fn test_delete_to_word_boundary(cx: &mut gpui::MutableAppContext) {
5199        let buffer = MultiBuffer::build_simple("one two three four", cx);
5200        let settings = EditorSettings::test(&cx);
5201        let (_, view) = cx.add_window(Default::default(), |cx| {
5202            build_editor(buffer.clone(), settings, cx)
5203        });
5204
5205        view.update(cx, |view, cx| {
5206            view.select_display_ranges(
5207                &[
5208                    // an empty selection - the preceding word fragment is deleted
5209                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
5210                    // characters selected - they are deleted
5211                    DisplayPoint::new(0, 9)..DisplayPoint::new(0, 12),
5212                ],
5213                cx,
5214            );
5215            view.delete_to_previous_word_boundary(&DeleteToPreviousWordBoundary, cx);
5216        });
5217
5218        assert_eq!(buffer.read(cx).read(cx).text(), "e two te four");
5219
5220        view.update(cx, |view, cx| {
5221            view.select_display_ranges(
5222                &[
5223                    // an empty selection - the following word fragment is deleted
5224                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
5225                    // characters selected - they are deleted
5226                    DisplayPoint::new(0, 9)..DisplayPoint::new(0, 10),
5227                ],
5228                cx,
5229            );
5230            view.delete_to_next_word_boundary(&DeleteToNextWordBoundary, cx);
5231        });
5232
5233        assert_eq!(buffer.read(cx).read(cx).text(), "e t te our");
5234    }
5235
5236    #[gpui::test]
5237    fn test_newline(cx: &mut gpui::MutableAppContext) {
5238        let buffer = MultiBuffer::build_simple("aaaa\n    bbbb\n", cx);
5239        let settings = EditorSettings::test(&cx);
5240        let (_, view) = cx.add_window(Default::default(), |cx| {
5241            build_editor(buffer.clone(), settings, cx)
5242        });
5243
5244        view.update(cx, |view, cx| {
5245            view.select_display_ranges(
5246                &[
5247                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
5248                    DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
5249                    DisplayPoint::new(1, 6)..DisplayPoint::new(1, 6),
5250                ],
5251                cx,
5252            );
5253
5254            view.newline(&Newline, cx);
5255            assert_eq!(view.text(cx), "aa\naa\n  \n    bb\n    bb\n");
5256        });
5257    }
5258
5259    #[gpui::test]
5260    fn test_indent_outdent(cx: &mut gpui::MutableAppContext) {
5261        let buffer = MultiBuffer::build_simple("  one two\nthree\n four", cx);
5262        let settings = EditorSettings::test(&cx);
5263        let (_, view) = cx.add_window(Default::default(), |cx| {
5264            build_editor(buffer.clone(), settings, cx)
5265        });
5266
5267        view.update(cx, |view, cx| {
5268            // two selections on the same line
5269            view.select_display_ranges(
5270                &[
5271                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 5),
5272                    DisplayPoint::new(0, 6)..DisplayPoint::new(0, 9),
5273                ],
5274                cx,
5275            );
5276
5277            // indent from mid-tabstop to full tabstop
5278            view.tab(&Tab, cx);
5279            assert_eq!(view.text(cx), "    one two\nthree\n four");
5280            assert_eq!(
5281                view.selected_display_ranges(cx),
5282                &[
5283                    DisplayPoint::new(0, 4)..DisplayPoint::new(0, 7),
5284                    DisplayPoint::new(0, 8)..DisplayPoint::new(0, 11),
5285                ]
5286            );
5287
5288            // outdent from 1 tabstop to 0 tabstops
5289            view.outdent(&Outdent, cx);
5290            assert_eq!(view.text(cx), "one two\nthree\n four");
5291            assert_eq!(
5292                view.selected_display_ranges(cx),
5293                &[
5294                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 3),
5295                    DisplayPoint::new(0, 4)..DisplayPoint::new(0, 7),
5296                ]
5297            );
5298
5299            // select across line ending
5300            view.select_display_ranges(&[DisplayPoint::new(1, 1)..DisplayPoint::new(2, 0)], cx);
5301
5302            // indent and outdent affect only the preceding line
5303            view.tab(&Tab, cx);
5304            assert_eq!(view.text(cx), "one two\n    three\n four");
5305            assert_eq!(
5306                view.selected_display_ranges(cx),
5307                &[DisplayPoint::new(1, 5)..DisplayPoint::new(2, 0)]
5308            );
5309            view.outdent(&Outdent, cx);
5310            assert_eq!(view.text(cx), "one two\nthree\n four");
5311            assert_eq!(
5312                view.selected_display_ranges(cx),
5313                &[DisplayPoint::new(1, 1)..DisplayPoint::new(2, 0)]
5314            );
5315
5316            // Ensure that indenting/outdenting works when the cursor is at column 0.
5317            view.select_display_ranges(&[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)], cx);
5318            view.tab(&Tab, cx);
5319            assert_eq!(view.text(cx), "one two\n    three\n four");
5320            assert_eq!(
5321                view.selected_display_ranges(cx),
5322                &[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4)]
5323            );
5324
5325            view.select_display_ranges(&[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)], cx);
5326            view.outdent(&Outdent, cx);
5327            assert_eq!(view.text(cx), "one two\nthree\n four");
5328            assert_eq!(
5329                view.selected_display_ranges(cx),
5330                &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
5331            );
5332        });
5333    }
5334
5335    #[gpui::test]
5336    fn test_backspace(cx: &mut gpui::MutableAppContext) {
5337        let buffer =
5338            MultiBuffer::build_simple("one two three\nfour five six\nseven eight nine\nten\n", cx);
5339        let settings = EditorSettings::test(&cx);
5340        let (_, view) = cx.add_window(Default::default(), |cx| {
5341            build_editor(buffer.clone(), settings, cx)
5342        });
5343
5344        view.update(cx, |view, cx| {
5345            view.select_display_ranges(
5346                &[
5347                    // an empty selection - the preceding character is deleted
5348                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
5349                    // one character selected - it is deleted
5350                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
5351                    // a line suffix selected - it is deleted
5352                    DisplayPoint::new(2, 6)..DisplayPoint::new(3, 0),
5353                ],
5354                cx,
5355            );
5356            view.backspace(&Backspace, cx);
5357        });
5358
5359        assert_eq!(
5360            buffer.read(cx).read(cx).text(),
5361            "oe two three\nfou five six\nseven ten\n"
5362        );
5363    }
5364
5365    #[gpui::test]
5366    fn test_delete(cx: &mut gpui::MutableAppContext) {
5367        let buffer =
5368            MultiBuffer::build_simple("one two three\nfour five six\nseven eight nine\nten\n", cx);
5369        let settings = EditorSettings::test(&cx);
5370        let (_, view) = cx.add_window(Default::default(), |cx| {
5371            build_editor(buffer.clone(), settings, cx)
5372        });
5373
5374        view.update(cx, |view, cx| {
5375            view.select_display_ranges(
5376                &[
5377                    // an empty selection - the following character is deleted
5378                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
5379                    // one character selected - it is deleted
5380                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
5381                    // a line suffix selected - it is deleted
5382                    DisplayPoint::new(2, 6)..DisplayPoint::new(3, 0),
5383                ],
5384                cx,
5385            );
5386            view.delete(&Delete, cx);
5387        });
5388
5389        assert_eq!(
5390            buffer.read(cx).read(cx).text(),
5391            "on two three\nfou five six\nseven ten\n"
5392        );
5393    }
5394
5395    #[gpui::test]
5396    fn test_delete_line(cx: &mut gpui::MutableAppContext) {
5397        let settings = EditorSettings::test(&cx);
5398        let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
5399        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5400        view.update(cx, |view, cx| {
5401            view.select_display_ranges(
5402                &[
5403                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
5404                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 1),
5405                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
5406                ],
5407                cx,
5408            );
5409            view.delete_line(&DeleteLine, cx);
5410            assert_eq!(view.display_text(cx), "ghi");
5411            assert_eq!(
5412                view.selected_display_ranges(cx),
5413                vec![
5414                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
5415                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)
5416                ]
5417            );
5418        });
5419
5420        let settings = EditorSettings::test(&cx);
5421        let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
5422        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5423        view.update(cx, |view, cx| {
5424            view.select_display_ranges(&[DisplayPoint::new(2, 0)..DisplayPoint::new(0, 1)], cx);
5425            view.delete_line(&DeleteLine, cx);
5426            assert_eq!(view.display_text(cx), "ghi\n");
5427            assert_eq!(
5428                view.selected_display_ranges(cx),
5429                vec![DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)]
5430            );
5431        });
5432    }
5433
5434    #[gpui::test]
5435    fn test_duplicate_line(cx: &mut gpui::MutableAppContext) {
5436        let settings = EditorSettings::test(&cx);
5437        let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
5438        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5439        view.update(cx, |view, cx| {
5440            view.select_display_ranges(
5441                &[
5442                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
5443                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
5444                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
5445                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
5446                ],
5447                cx,
5448            );
5449            view.duplicate_line(&DuplicateLine, cx);
5450            assert_eq!(view.display_text(cx), "abc\nabc\ndef\ndef\nghi\n\n");
5451            assert_eq!(
5452                view.selected_display_ranges(cx),
5453                vec![
5454                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 1),
5455                    DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
5456                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
5457                    DisplayPoint::new(6, 0)..DisplayPoint::new(6, 0),
5458                ]
5459            );
5460        });
5461
5462        let settings = EditorSettings::test(&cx);
5463        let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
5464        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5465        view.update(cx, |view, cx| {
5466            view.select_display_ranges(
5467                &[
5468                    DisplayPoint::new(0, 1)..DisplayPoint::new(1, 1),
5469                    DisplayPoint::new(1, 2)..DisplayPoint::new(2, 1),
5470                ],
5471                cx,
5472            );
5473            view.duplicate_line(&DuplicateLine, cx);
5474            assert_eq!(view.display_text(cx), "abc\ndef\nghi\nabc\ndef\nghi\n");
5475            assert_eq!(
5476                view.selected_display_ranges(cx),
5477                vec![
5478                    DisplayPoint::new(3, 1)..DisplayPoint::new(4, 1),
5479                    DisplayPoint::new(4, 2)..DisplayPoint::new(5, 1),
5480                ]
5481            );
5482        });
5483    }
5484
5485    #[gpui::test]
5486    fn test_move_line_up_down(cx: &mut gpui::MutableAppContext) {
5487        let settings = EditorSettings::test(&cx);
5488        let buffer = MultiBuffer::build_simple(&sample_text(10, 5, 'a'), cx);
5489        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5490        view.update(cx, |view, cx| {
5491            view.fold_ranges(
5492                vec![
5493                    Point::new(0, 2)..Point::new(1, 2),
5494                    Point::new(2, 3)..Point::new(4, 1),
5495                    Point::new(7, 0)..Point::new(8, 4),
5496                ],
5497                cx,
5498            );
5499            view.select_display_ranges(
5500                &[
5501                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
5502                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
5503                    DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
5504                    DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2),
5505                ],
5506                cx,
5507            );
5508            assert_eq!(
5509                view.display_text(cx),
5510                "aa…bbb\nccc…eeee\nfffff\nggggg\n…i\njjjjj"
5511            );
5512
5513            view.move_line_up(&MoveLineUp, cx);
5514            assert_eq!(
5515                view.display_text(cx),
5516                "aa…bbb\nccc…eeee\nggggg\n…i\njjjjj\nfffff"
5517            );
5518            assert_eq!(
5519                view.selected_display_ranges(cx),
5520                vec![
5521                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
5522                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
5523                    DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3),
5524                    DisplayPoint::new(4, 0)..DisplayPoint::new(4, 2)
5525                ]
5526            );
5527        });
5528
5529        view.update(cx, |view, cx| {
5530            view.move_line_down(&MoveLineDown, cx);
5531            assert_eq!(
5532                view.display_text(cx),
5533                "ccc…eeee\naa…bbb\nfffff\nggggg\n…i\njjjjj"
5534            );
5535            assert_eq!(
5536                view.selected_display_ranges(cx),
5537                vec![
5538                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
5539                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
5540                    DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
5541                    DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2)
5542                ]
5543            );
5544        });
5545
5546        view.update(cx, |view, cx| {
5547            view.move_line_down(&MoveLineDown, cx);
5548            assert_eq!(
5549                view.display_text(cx),
5550                "ccc…eeee\nfffff\naa…bbb\nggggg\n…i\njjjjj"
5551            );
5552            assert_eq!(
5553                view.selected_display_ranges(cx),
5554                vec![
5555                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
5556                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
5557                    DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
5558                    DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2)
5559                ]
5560            );
5561        });
5562
5563        view.update(cx, |view, cx| {
5564            view.move_line_up(&MoveLineUp, cx);
5565            assert_eq!(
5566                view.display_text(cx),
5567                "ccc…eeee\naa…bbb\nggggg\n…i\njjjjj\nfffff"
5568            );
5569            assert_eq!(
5570                view.selected_display_ranges(cx),
5571                vec![
5572                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
5573                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
5574                    DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3),
5575                    DisplayPoint::new(4, 0)..DisplayPoint::new(4, 2)
5576                ]
5577            );
5578        });
5579    }
5580
5581    #[gpui::test]
5582    fn test_move_line_up_down_with_blocks(cx: &mut gpui::MutableAppContext) {
5583        let settings = EditorSettings::test(&cx);
5584        let buffer = MultiBuffer::build_simple(&sample_text(10, 5, 'a'), cx);
5585        let snapshot = buffer.read(cx).snapshot(cx);
5586        let (_, editor) =
5587            cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5588        editor.update(cx, |editor, cx| {
5589            editor.insert_blocks(
5590                [BlockProperties {
5591                    position: snapshot.anchor_after(Point::new(2, 0)),
5592                    disposition: BlockDisposition::Below,
5593                    height: 1,
5594                    render: Arc::new(|_| Empty::new().boxed()),
5595                }],
5596                cx,
5597            );
5598            editor.select_ranges([Point::new(2, 0)..Point::new(2, 0)], None, cx);
5599            editor.move_line_down(&MoveLineDown, cx);
5600        });
5601    }
5602
5603    #[gpui::test]
5604    fn test_clipboard(cx: &mut gpui::MutableAppContext) {
5605        let buffer = MultiBuffer::build_simple("one✅ two three four five six ", cx);
5606        let settings = EditorSettings::test(&cx);
5607        let view = cx
5608            .add_window(Default::default(), |cx| {
5609                build_editor(buffer.clone(), settings, cx)
5610            })
5611            .1;
5612
5613        // Cut with three selections. Clipboard text is divided into three slices.
5614        view.update(cx, |view, cx| {
5615            view.select_ranges(vec![0..7, 11..17, 22..27], None, cx);
5616            view.cut(&Cut, cx);
5617            assert_eq!(view.display_text(cx), "two four six ");
5618        });
5619
5620        // Paste with three cursors. Each cursor pastes one slice of the clipboard text.
5621        view.update(cx, |view, cx| {
5622            view.select_ranges(vec![4..4, 9..9, 13..13], None, cx);
5623            view.paste(&Paste, cx);
5624            assert_eq!(view.display_text(cx), "two one✅ four three six five ");
5625            assert_eq!(
5626                view.selected_display_ranges(cx),
5627                &[
5628                    DisplayPoint::new(0, 11)..DisplayPoint::new(0, 11),
5629                    DisplayPoint::new(0, 22)..DisplayPoint::new(0, 22),
5630                    DisplayPoint::new(0, 31)..DisplayPoint::new(0, 31)
5631                ]
5632            );
5633        });
5634
5635        // Paste again but with only two cursors. Since the number of cursors doesn't
5636        // match the number of slices in the clipboard, the entire clipboard text
5637        // is pasted at each cursor.
5638        view.update(cx, |view, cx| {
5639            view.select_ranges(vec![0..0, 31..31], None, cx);
5640            view.handle_input(&Input("( ".into()), cx);
5641            view.paste(&Paste, cx);
5642            view.handle_input(&Input(") ".into()), cx);
5643            assert_eq!(
5644                view.display_text(cx),
5645                "( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
5646            );
5647        });
5648
5649        view.update(cx, |view, cx| {
5650            view.select_ranges(vec![0..0], None, cx);
5651            view.handle_input(&Input("123\n4567\n89\n".into()), cx);
5652            assert_eq!(
5653                view.display_text(cx),
5654                "123\n4567\n89\n( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
5655            );
5656        });
5657
5658        // Cut with three selections, one of which is full-line.
5659        view.update(cx, |view, cx| {
5660            view.select_display_ranges(
5661                &[
5662                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 2),
5663                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
5664                    DisplayPoint::new(2, 0)..DisplayPoint::new(2, 1),
5665                ],
5666                cx,
5667            );
5668            view.cut(&Cut, cx);
5669            assert_eq!(
5670                view.display_text(cx),
5671                "13\n9\n( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
5672            );
5673        });
5674
5675        // Paste with three selections, noticing how the copied selection that was full-line
5676        // gets inserted before the second cursor.
5677        view.update(cx, |view, cx| {
5678            view.select_display_ranges(
5679                &[
5680                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
5681                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
5682                    DisplayPoint::new(2, 2)..DisplayPoint::new(2, 3),
5683                ],
5684                cx,
5685            );
5686            view.paste(&Paste, cx);
5687            assert_eq!(
5688                view.display_text(cx),
5689                "123\n4567\n9\n( 8ne✅ three five ) two one✅ four three six five ( one✅ three five ) "
5690            );
5691            assert_eq!(
5692                view.selected_display_ranges(cx),
5693                &[
5694                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
5695                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
5696                    DisplayPoint::new(3, 3)..DisplayPoint::new(3, 3),
5697                ]
5698            );
5699        });
5700
5701        // Copy with a single cursor only, which writes the whole line into the clipboard.
5702        view.update(cx, |view, cx| {
5703            view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)], cx);
5704            view.copy(&Copy, cx);
5705        });
5706
5707        // Paste with three selections, noticing how the copied full-line selection is inserted
5708        // before the empty selections but replaces the selection that is non-empty.
5709        view.update(cx, |view, cx| {
5710            view.select_display_ranges(
5711                &[
5712                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
5713                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 2),
5714                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
5715                ],
5716                cx,
5717            );
5718            view.paste(&Paste, cx);
5719            assert_eq!(
5720                view.display_text(cx),
5721                "123\n123\n123\n67\n123\n9\n( 8ne✅ three five ) two one✅ four three six five ( one✅ three five ) "
5722            );
5723            assert_eq!(
5724                view.selected_display_ranges(cx),
5725                &[
5726                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
5727                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
5728                    DisplayPoint::new(5, 1)..DisplayPoint::new(5, 1),
5729                ]
5730            );
5731        });
5732    }
5733
5734    #[gpui::test]
5735    fn test_select_all(cx: &mut gpui::MutableAppContext) {
5736        let buffer = MultiBuffer::build_simple("abc\nde\nfgh", cx);
5737        let settings = EditorSettings::test(&cx);
5738        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5739        view.update(cx, |view, cx| {
5740            view.select_all(&SelectAll, cx);
5741            assert_eq!(
5742                view.selected_display_ranges(cx),
5743                &[DisplayPoint::new(0, 0)..DisplayPoint::new(2, 3)]
5744            );
5745        });
5746    }
5747
5748    #[gpui::test]
5749    fn test_select_line(cx: &mut gpui::MutableAppContext) {
5750        let settings = EditorSettings::test(&cx);
5751        let buffer = MultiBuffer::build_simple(&sample_text(6, 5, 'a'), cx);
5752        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5753        view.update(cx, |view, cx| {
5754            view.select_display_ranges(
5755                &[
5756                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
5757                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
5758                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
5759                    DisplayPoint::new(4, 2)..DisplayPoint::new(4, 2),
5760                ],
5761                cx,
5762            );
5763            view.select_line(&SelectLine, cx);
5764            assert_eq!(
5765                view.selected_display_ranges(cx),
5766                vec![
5767                    DisplayPoint::new(0, 0)..DisplayPoint::new(2, 0),
5768                    DisplayPoint::new(4, 0)..DisplayPoint::new(5, 0),
5769                ]
5770            );
5771        });
5772
5773        view.update(cx, |view, cx| {
5774            view.select_line(&SelectLine, cx);
5775            assert_eq!(
5776                view.selected_display_ranges(cx),
5777                vec![
5778                    DisplayPoint::new(0, 0)..DisplayPoint::new(3, 0),
5779                    DisplayPoint::new(4, 0)..DisplayPoint::new(5, 5),
5780                ]
5781            );
5782        });
5783
5784        view.update(cx, |view, cx| {
5785            view.select_line(&SelectLine, cx);
5786            assert_eq!(
5787                view.selected_display_ranges(cx),
5788                vec![DisplayPoint::new(0, 0)..DisplayPoint::new(5, 5)]
5789            );
5790        });
5791    }
5792
5793    #[gpui::test]
5794    fn test_split_selection_into_lines(cx: &mut gpui::MutableAppContext) {
5795        let settings = EditorSettings::test(&cx);
5796        let buffer = MultiBuffer::build_simple(&sample_text(9, 5, 'a'), cx);
5797        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5798        view.update(cx, |view, cx| {
5799            view.fold_ranges(
5800                vec![
5801                    Point::new(0, 2)..Point::new(1, 2),
5802                    Point::new(2, 3)..Point::new(4, 1),
5803                    Point::new(7, 0)..Point::new(8, 4),
5804                ],
5805                cx,
5806            );
5807            view.select_display_ranges(
5808                &[
5809                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
5810                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
5811                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
5812                    DisplayPoint::new(4, 4)..DisplayPoint::new(4, 4),
5813                ],
5814                cx,
5815            );
5816            assert_eq!(view.display_text(cx), "aa…bbb\nccc…eeee\nfffff\nggggg\n…i");
5817        });
5818
5819        view.update(cx, |view, cx| {
5820            view.split_selection_into_lines(&SplitSelectionIntoLines, cx);
5821            assert_eq!(
5822                view.display_text(cx),
5823                "aaaaa\nbbbbb\nccc…eeee\nfffff\nggggg\n…i"
5824            );
5825            assert_eq!(
5826                view.selected_display_ranges(cx),
5827                [
5828                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
5829                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
5830                    DisplayPoint::new(2, 0)..DisplayPoint::new(2, 0),
5831                    DisplayPoint::new(5, 4)..DisplayPoint::new(5, 4)
5832                ]
5833            );
5834        });
5835
5836        view.update(cx, |view, cx| {
5837            view.select_display_ranges(&[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 1)], cx);
5838            view.split_selection_into_lines(&SplitSelectionIntoLines, cx);
5839            assert_eq!(
5840                view.display_text(cx),
5841                "aaaaa\nbbbbb\nccccc\nddddd\neeeee\nfffff\nggggg\nhhhhh\niiiii"
5842            );
5843            assert_eq!(
5844                view.selected_display_ranges(cx),
5845                [
5846                    DisplayPoint::new(0, 5)..DisplayPoint::new(0, 5),
5847                    DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
5848                    DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
5849                    DisplayPoint::new(3, 5)..DisplayPoint::new(3, 5),
5850                    DisplayPoint::new(4, 5)..DisplayPoint::new(4, 5),
5851                    DisplayPoint::new(5, 5)..DisplayPoint::new(5, 5),
5852                    DisplayPoint::new(6, 5)..DisplayPoint::new(6, 5),
5853                    DisplayPoint::new(7, 0)..DisplayPoint::new(7, 0)
5854                ]
5855            );
5856        });
5857    }
5858
5859    #[gpui::test]
5860    fn test_add_selection_above_below(cx: &mut gpui::MutableAppContext) {
5861        let settings = EditorSettings::test(&cx);
5862        let buffer = MultiBuffer::build_simple("abc\ndefghi\n\njk\nlmno\n", cx);
5863        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5864
5865        view.update(cx, |view, cx| {
5866            view.select_display_ranges(&[DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)], cx);
5867        });
5868        view.update(cx, |view, cx| {
5869            view.add_selection_above(&AddSelectionAbove, cx);
5870            assert_eq!(
5871                view.selected_display_ranges(cx),
5872                vec![
5873                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
5874                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)
5875                ]
5876            );
5877        });
5878
5879        view.update(cx, |view, cx| {
5880            view.add_selection_above(&AddSelectionAbove, cx);
5881            assert_eq!(
5882                view.selected_display_ranges(cx),
5883                vec![
5884                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
5885                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)
5886                ]
5887            );
5888        });
5889
5890        view.update(cx, |view, cx| {
5891            view.add_selection_below(&AddSelectionBelow, cx);
5892            assert_eq!(
5893                view.selected_display_ranges(cx),
5894                vec![DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)]
5895            );
5896        });
5897
5898        view.update(cx, |view, cx| {
5899            view.add_selection_below(&AddSelectionBelow, cx);
5900            assert_eq!(
5901                view.selected_display_ranges(cx),
5902                vec![
5903                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
5904                    DisplayPoint::new(4, 3)..DisplayPoint::new(4, 3)
5905                ]
5906            );
5907        });
5908
5909        view.update(cx, |view, cx| {
5910            view.add_selection_below(&AddSelectionBelow, cx);
5911            assert_eq!(
5912                view.selected_display_ranges(cx),
5913                vec![
5914                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
5915                    DisplayPoint::new(4, 3)..DisplayPoint::new(4, 3)
5916                ]
5917            );
5918        });
5919
5920        view.update(cx, |view, cx| {
5921            view.select_display_ranges(&[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)], cx);
5922        });
5923        view.update(cx, |view, cx| {
5924            view.add_selection_below(&AddSelectionBelow, cx);
5925            assert_eq!(
5926                view.selected_display_ranges(cx),
5927                vec![
5928                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
5929                    DisplayPoint::new(4, 4)..DisplayPoint::new(4, 3)
5930                ]
5931            );
5932        });
5933
5934        view.update(cx, |view, cx| {
5935            view.add_selection_below(&AddSelectionBelow, cx);
5936            assert_eq!(
5937                view.selected_display_ranges(cx),
5938                vec![
5939                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
5940                    DisplayPoint::new(4, 4)..DisplayPoint::new(4, 3)
5941                ]
5942            );
5943        });
5944
5945        view.update(cx, |view, cx| {
5946            view.add_selection_above(&AddSelectionAbove, cx);
5947            assert_eq!(
5948                view.selected_display_ranges(cx),
5949                vec![DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)]
5950            );
5951        });
5952
5953        view.update(cx, |view, cx| {
5954            view.add_selection_above(&AddSelectionAbove, cx);
5955            assert_eq!(
5956                view.selected_display_ranges(cx),
5957                vec![DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)]
5958            );
5959        });
5960
5961        view.update(cx, |view, cx| {
5962            view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(1, 4)], cx);
5963            view.add_selection_below(&AddSelectionBelow, cx);
5964            assert_eq!(
5965                view.selected_display_ranges(cx),
5966                vec![
5967                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
5968                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
5969                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
5970                ]
5971            );
5972        });
5973
5974        view.update(cx, |view, cx| {
5975            view.add_selection_below(&AddSelectionBelow, cx);
5976            assert_eq!(
5977                view.selected_display_ranges(cx),
5978                vec![
5979                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
5980                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
5981                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
5982                    DisplayPoint::new(4, 1)..DisplayPoint::new(4, 4),
5983                ]
5984            );
5985        });
5986
5987        view.update(cx, |view, cx| {
5988            view.add_selection_above(&AddSelectionAbove, cx);
5989            assert_eq!(
5990                view.selected_display_ranges(cx),
5991                vec![
5992                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
5993                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
5994                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
5995                ]
5996            );
5997        });
5998
5999        view.update(cx, |view, cx| {
6000            view.select_display_ranges(&[DisplayPoint::new(4, 3)..DisplayPoint::new(1, 1)], cx);
6001        });
6002        view.update(cx, |view, cx| {
6003            view.add_selection_above(&AddSelectionAbove, cx);
6004            assert_eq!(
6005                view.selected_display_ranges(cx),
6006                vec![
6007                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 1),
6008                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 1),
6009                    DisplayPoint::new(3, 2)..DisplayPoint::new(3, 1),
6010                    DisplayPoint::new(4, 3)..DisplayPoint::new(4, 1),
6011                ]
6012            );
6013        });
6014
6015        view.update(cx, |view, cx| {
6016            view.add_selection_below(&AddSelectionBelow, cx);
6017            assert_eq!(
6018                view.selected_display_ranges(cx),
6019                vec![
6020                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 1),
6021                    DisplayPoint::new(3, 2)..DisplayPoint::new(3, 1),
6022                    DisplayPoint::new(4, 3)..DisplayPoint::new(4, 1),
6023                ]
6024            );
6025        });
6026    }
6027
6028    #[gpui::test]
6029    async fn test_select_larger_smaller_syntax_node(mut cx: gpui::TestAppContext) {
6030        let settings = cx.read(EditorSettings::test);
6031        let language = Arc::new(Language::new(
6032            LanguageConfig::default(),
6033            Some(tree_sitter_rust::language()),
6034        ));
6035
6036        let text = r#"
6037            use mod1::mod2::{mod3, mod4};
6038
6039            fn fn_1(param1: bool, param2: &str) {
6040                let var1 = "text";
6041            }
6042        "#
6043        .unindent();
6044
6045        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
6046        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
6047        let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
6048        view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
6049            .await;
6050
6051        view.update(&mut cx, |view, cx| {
6052            view.select_display_ranges(
6053                &[
6054                    DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
6055                    DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
6056                    DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
6057                ],
6058                cx,
6059            );
6060            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
6061        });
6062        assert_eq!(
6063            view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
6064            &[
6065                DisplayPoint::new(0, 23)..DisplayPoint::new(0, 27),
6066                DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
6067                DisplayPoint::new(3, 15)..DisplayPoint::new(3, 21),
6068            ]
6069        );
6070
6071        view.update(&mut cx, |view, cx| {
6072            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
6073        });
6074        assert_eq!(
6075            view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
6076            &[
6077                DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
6078                DisplayPoint::new(4, 1)..DisplayPoint::new(2, 0),
6079            ]
6080        );
6081
6082        view.update(&mut cx, |view, cx| {
6083            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
6084        });
6085        assert_eq!(
6086            view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
6087            &[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 0)]
6088        );
6089
6090        // Trying to expand the selected syntax node one more time has no effect.
6091        view.update(&mut cx, |view, cx| {
6092            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
6093        });
6094        assert_eq!(
6095            view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
6096            &[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 0)]
6097        );
6098
6099        view.update(&mut cx, |view, cx| {
6100            view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
6101        });
6102        assert_eq!(
6103            view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
6104            &[
6105                DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
6106                DisplayPoint::new(4, 1)..DisplayPoint::new(2, 0),
6107            ]
6108        );
6109
6110        view.update(&mut cx, |view, cx| {
6111            view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
6112        });
6113        assert_eq!(
6114            view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
6115            &[
6116                DisplayPoint::new(0, 23)..DisplayPoint::new(0, 27),
6117                DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
6118                DisplayPoint::new(3, 15)..DisplayPoint::new(3, 21),
6119            ]
6120        );
6121
6122        view.update(&mut cx, |view, cx| {
6123            view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
6124        });
6125        assert_eq!(
6126            view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
6127            &[
6128                DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
6129                DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
6130                DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
6131            ]
6132        );
6133
6134        // Trying to shrink the selected syntax node one more time has no effect.
6135        view.update(&mut cx, |view, cx| {
6136            view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
6137        });
6138        assert_eq!(
6139            view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
6140            &[
6141                DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
6142                DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
6143                DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
6144            ]
6145        );
6146
6147        // Ensure that we keep expanding the selection if the larger selection starts or ends within
6148        // a fold.
6149        view.update(&mut cx, |view, cx| {
6150            view.fold_ranges(
6151                vec![
6152                    Point::new(0, 21)..Point::new(0, 24),
6153                    Point::new(3, 20)..Point::new(3, 22),
6154                ],
6155                cx,
6156            );
6157            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
6158        });
6159        assert_eq!(
6160            view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
6161            &[
6162                DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
6163                DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
6164                DisplayPoint::new(3, 4)..DisplayPoint::new(3, 23),
6165            ]
6166        );
6167    }
6168
6169    #[gpui::test]
6170    async fn test_autoindent_selections(mut cx: gpui::TestAppContext) {
6171        let settings = cx.read(EditorSettings::test);
6172        let language = Arc::new(
6173            Language::new(
6174                LanguageConfig {
6175                    brackets: vec![
6176                        BracketPair {
6177                            start: "{".to_string(),
6178                            end: "}".to_string(),
6179                            close: false,
6180                            newline: true,
6181                        },
6182                        BracketPair {
6183                            start: "(".to_string(),
6184                            end: ")".to_string(),
6185                            close: false,
6186                            newline: true,
6187                        },
6188                    ],
6189                    ..Default::default()
6190                },
6191                Some(tree_sitter_rust::language()),
6192            )
6193            .with_indents_query(
6194                r#"
6195                (_ "(" ")" @end) @indent
6196                (_ "{" "}" @end) @indent
6197                "#,
6198            )
6199            .unwrap(),
6200        );
6201
6202        let text = "fn a() {}";
6203
6204        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
6205        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
6206        let (_, editor) = cx.add_window(|cx| build_editor(buffer, settings, cx));
6207        editor
6208            .condition(&cx, |editor, cx| !editor.buffer.read(cx).is_parsing(cx))
6209            .await;
6210
6211        editor.update(&mut cx, |editor, cx| {
6212            editor.select_ranges([5..5, 8..8, 9..9], None, cx);
6213            editor.newline(&Newline, cx);
6214            assert_eq!(editor.text(cx), "fn a(\n    \n) {\n    \n}\n");
6215            assert_eq!(
6216                editor.selected_ranges(cx),
6217                &[
6218                    Point::new(1, 4)..Point::new(1, 4),
6219                    Point::new(3, 4)..Point::new(3, 4),
6220                    Point::new(5, 0)..Point::new(5, 0)
6221                ]
6222            );
6223        });
6224    }
6225
6226    #[gpui::test]
6227    async fn test_autoclose_pairs(mut cx: gpui::TestAppContext) {
6228        let settings = cx.read(EditorSettings::test);
6229        let language = Arc::new(Language::new(
6230            LanguageConfig {
6231                brackets: vec![
6232                    BracketPair {
6233                        start: "{".to_string(),
6234                        end: "}".to_string(),
6235                        close: true,
6236                        newline: true,
6237                    },
6238                    BracketPair {
6239                        start: "/*".to_string(),
6240                        end: " */".to_string(),
6241                        close: true,
6242                        newline: true,
6243                    },
6244                ],
6245                ..Default::default()
6246            },
6247            Some(tree_sitter_rust::language()),
6248        ));
6249
6250        let text = r#"
6251            a
6252
6253            /
6254
6255        "#
6256        .unindent();
6257
6258        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
6259        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
6260        let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
6261        view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
6262            .await;
6263
6264        view.update(&mut cx, |view, cx| {
6265            view.select_display_ranges(
6266                &[
6267                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
6268                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
6269                ],
6270                cx,
6271            );
6272            view.handle_input(&Input("{".to_string()), cx);
6273            view.handle_input(&Input("{".to_string()), cx);
6274            view.handle_input(&Input("{".to_string()), cx);
6275            assert_eq!(
6276                view.text(cx),
6277                "
6278                {{{}}}
6279                {{{}}}
6280                /
6281
6282                "
6283                .unindent()
6284            );
6285
6286            view.move_right(&MoveRight, cx);
6287            view.handle_input(&Input("}".to_string()), cx);
6288            view.handle_input(&Input("}".to_string()), cx);
6289            view.handle_input(&Input("}".to_string()), cx);
6290            assert_eq!(
6291                view.text(cx),
6292                "
6293                {{{}}}}
6294                {{{}}}}
6295                /
6296
6297                "
6298                .unindent()
6299            );
6300
6301            view.undo(&Undo, cx);
6302            view.handle_input(&Input("/".to_string()), cx);
6303            view.handle_input(&Input("*".to_string()), cx);
6304            assert_eq!(
6305                view.text(cx),
6306                "
6307                /* */
6308                /* */
6309                /
6310
6311                "
6312                .unindent()
6313            );
6314
6315            view.undo(&Undo, cx);
6316            view.select_display_ranges(
6317                &[
6318                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
6319                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
6320                ],
6321                cx,
6322            );
6323            view.handle_input(&Input("*".to_string()), cx);
6324            assert_eq!(
6325                view.text(cx),
6326                "
6327                a
6328
6329                /*
6330                *
6331                "
6332                .unindent()
6333            );
6334        });
6335    }
6336
6337    #[gpui::test]
6338    async fn test_toggle_comment(mut cx: gpui::TestAppContext) {
6339        let settings = cx.read(EditorSettings::test);
6340        let language = Arc::new(Language::new(
6341            LanguageConfig {
6342                line_comment: Some("// ".to_string()),
6343                ..Default::default()
6344            },
6345            Some(tree_sitter_rust::language()),
6346        ));
6347
6348        let text = "
6349            fn a() {
6350                //b();
6351                // c();
6352                //  d();
6353            }
6354        "
6355        .unindent();
6356
6357        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
6358        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
6359        let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
6360
6361        view.update(&mut cx, |editor, cx| {
6362            // If multiple selections intersect a line, the line is only
6363            // toggled once.
6364            editor.select_display_ranges(
6365                &[
6366                    DisplayPoint::new(1, 3)..DisplayPoint::new(2, 3),
6367                    DisplayPoint::new(3, 5)..DisplayPoint::new(3, 6),
6368                ],
6369                cx,
6370            );
6371            editor.toggle_comments(&ToggleComments, cx);
6372            assert_eq!(
6373                editor.text(cx),
6374                "
6375                    fn a() {
6376                        b();
6377                        c();
6378                         d();
6379                    }
6380                "
6381                .unindent()
6382            );
6383
6384            // The comment prefix is inserted at the same column for every line
6385            // in a selection.
6386            editor.select_display_ranges(&[DisplayPoint::new(1, 3)..DisplayPoint::new(3, 6)], cx);
6387            editor.toggle_comments(&ToggleComments, cx);
6388            assert_eq!(
6389                editor.text(cx),
6390                "
6391                    fn a() {
6392                        // b();
6393                        // c();
6394                        //  d();
6395                    }
6396                "
6397                .unindent()
6398            );
6399
6400            // If a selection ends at the beginning of a line, that line is not toggled.
6401            editor.select_display_ranges(&[DisplayPoint::new(2, 0)..DisplayPoint::new(3, 0)], cx);
6402            editor.toggle_comments(&ToggleComments, cx);
6403            assert_eq!(
6404                editor.text(cx),
6405                "
6406                        fn a() {
6407                            // b();
6408                            c();
6409                            //  d();
6410                        }
6411                    "
6412                .unindent()
6413            );
6414        });
6415    }
6416
6417    #[gpui::test]
6418    fn test_editing_disjoint_excerpts(cx: &mut gpui::MutableAppContext) {
6419        let settings = EditorSettings::test(cx);
6420        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(3, 4, 'a'), cx));
6421        let multibuffer = cx.add_model(|cx| {
6422            let mut multibuffer = MultiBuffer::new(0);
6423            multibuffer.push_excerpt(
6424                ExcerptProperties {
6425                    buffer: &buffer,
6426                    range: Point::new(0, 0)..Point::new(0, 4),
6427                },
6428                cx,
6429            );
6430            multibuffer.push_excerpt(
6431                ExcerptProperties {
6432                    buffer: &buffer,
6433                    range: Point::new(1, 0)..Point::new(1, 4),
6434                },
6435                cx,
6436            );
6437            multibuffer
6438        });
6439
6440        assert_eq!(multibuffer.read(cx).read(cx).text(), "aaaa\nbbbb");
6441
6442        let (_, view) = cx.add_window(Default::default(), |cx| {
6443            build_editor(multibuffer, settings, cx)
6444        });
6445        view.update(cx, |view, cx| {
6446            view.select_display_ranges(
6447                &[
6448                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
6449                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
6450                ],
6451                cx,
6452            );
6453
6454            view.handle_input(&Input("X".to_string()), cx);
6455            assert_eq!(view.text(cx), "Xaaaa\nXbbbb");
6456            assert_eq!(
6457                view.selected_display_ranges(cx),
6458                &[
6459                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
6460                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
6461                ]
6462            )
6463        });
6464    }
6465
6466    #[gpui::test]
6467    fn test_editing_overlapping_excerpts(cx: &mut gpui::MutableAppContext) {
6468        let settings = EditorSettings::test(cx);
6469        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(3, 4, 'a'), cx));
6470        let multibuffer = cx.add_model(|cx| {
6471            let mut multibuffer = MultiBuffer::new(0);
6472            multibuffer.push_excerpt(
6473                ExcerptProperties {
6474                    buffer: &buffer,
6475                    range: Point::new(0, 0)..Point::new(1, 4),
6476                },
6477                cx,
6478            );
6479            multibuffer.push_excerpt(
6480                ExcerptProperties {
6481                    buffer: &buffer,
6482                    range: Point::new(1, 0)..Point::new(2, 4),
6483                },
6484                cx,
6485            );
6486            multibuffer
6487        });
6488
6489        assert_eq!(
6490            multibuffer.read(cx).read(cx).text(),
6491            "aaaa\nbbbb\nbbbb\ncccc"
6492        );
6493
6494        let (_, view) = cx.add_window(Default::default(), |cx| {
6495            build_editor(multibuffer, settings, cx)
6496        });
6497        view.update(cx, |view, cx| {
6498            view.select_display_ranges(
6499                &[
6500                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
6501                    DisplayPoint::new(2, 3)..DisplayPoint::new(2, 3),
6502                ],
6503                cx,
6504            );
6505
6506            view.handle_input(&Input("X".to_string()), cx);
6507            assert_eq!(view.text(cx), "aaaa\nbXbbXb\nbXbbXb\ncccc");
6508            assert_eq!(
6509                view.selected_display_ranges(cx),
6510                &[
6511                    DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
6512                    DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
6513                ]
6514            );
6515
6516            view.newline(&Newline, cx);
6517            assert_eq!(view.text(cx), "aaaa\nbX\nbbX\nb\nbX\nbbX\nb\ncccc");
6518            assert_eq!(
6519                view.selected_display_ranges(cx),
6520                &[
6521                    DisplayPoint::new(2, 0)..DisplayPoint::new(2, 0),
6522                    DisplayPoint::new(6, 0)..DisplayPoint::new(6, 0),
6523                ]
6524            );
6525        });
6526    }
6527
6528    #[gpui::test]
6529    fn test_refresh_selections(cx: &mut gpui::MutableAppContext) {
6530        let settings = EditorSettings::test(cx);
6531        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(3, 4, 'a'), cx));
6532        let mut excerpt1_id = None;
6533        let multibuffer = cx.add_model(|cx| {
6534            let mut multibuffer = MultiBuffer::new(0);
6535            excerpt1_id = Some(multibuffer.push_excerpt(
6536                ExcerptProperties {
6537                    buffer: &buffer,
6538                    range: Point::new(0, 0)..Point::new(1, 4),
6539                },
6540                cx,
6541            ));
6542            multibuffer.push_excerpt(
6543                ExcerptProperties {
6544                    buffer: &buffer,
6545                    range: Point::new(1, 0)..Point::new(2, 4),
6546                },
6547                cx,
6548            );
6549            multibuffer
6550        });
6551        assert_eq!(
6552            multibuffer.read(cx).read(cx).text(),
6553            "aaaa\nbbbb\nbbbb\ncccc"
6554        );
6555        let (_, editor) = cx.add_window(Default::default(), |cx| {
6556            let mut editor = build_editor(multibuffer.clone(), settings, cx);
6557            editor.select_display_ranges(
6558                &[
6559                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
6560                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
6561                ],
6562                cx,
6563            );
6564            editor
6565        });
6566
6567        // Refreshing selections is a no-op when excerpts haven't changed.
6568        editor.update(cx, |editor, cx| {
6569            editor.refresh_selections(cx);
6570            assert_eq!(
6571                editor.selected_display_ranges(cx),
6572                [
6573                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
6574                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
6575                ]
6576            );
6577        });
6578
6579        multibuffer.update(cx, |multibuffer, cx| {
6580            multibuffer.remove_excerpts([&excerpt1_id.unwrap()], cx);
6581        });
6582        editor.update(cx, |editor, cx| {
6583            // Removing an excerpt causes the first selection to become degenerate.
6584            assert_eq!(
6585                editor.selected_display_ranges(cx),
6586                [
6587                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
6588                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)
6589                ]
6590            );
6591
6592            // Refreshing selections will relocate the first selection to the original buffer
6593            // location.
6594            editor.refresh_selections(cx);
6595            assert_eq!(
6596                editor.selected_display_ranges(cx),
6597                [
6598                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
6599                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3)
6600                ]
6601            );
6602        });
6603    }
6604
6605    #[gpui::test]
6606    async fn test_extra_newline_insertion(mut cx: gpui::TestAppContext) {
6607        let settings = cx.read(EditorSettings::test);
6608        let language = Arc::new(Language::new(
6609            LanguageConfig {
6610                brackets: vec![
6611                    BracketPair {
6612                        start: "{".to_string(),
6613                        end: "}".to_string(),
6614                        close: true,
6615                        newline: true,
6616                    },
6617                    BracketPair {
6618                        start: "/* ".to_string(),
6619                        end: " */".to_string(),
6620                        close: true,
6621                        newline: true,
6622                    },
6623                ],
6624                ..Default::default()
6625            },
6626            Some(tree_sitter_rust::language()),
6627        ));
6628
6629        let text = concat!(
6630            "{   }\n",     // Suppress rustfmt
6631            "  x\n",       //
6632            "  /*   */\n", //
6633            "x\n",         //
6634            "{{} }\n",     //
6635        );
6636
6637        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
6638        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
6639        let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
6640        view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
6641            .await;
6642
6643        view.update(&mut cx, |view, cx| {
6644            view.select_display_ranges(
6645                &[
6646                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 3),
6647                    DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
6648                    DisplayPoint::new(4, 4)..DisplayPoint::new(4, 4),
6649                ],
6650                cx,
6651            );
6652            view.newline(&Newline, cx);
6653
6654            assert_eq!(
6655                view.buffer().read(cx).read(cx).text(),
6656                concat!(
6657                    "{ \n",    // Suppress rustfmt
6658                    "\n",      //
6659                    "}\n",     //
6660                    "  x\n",   //
6661                    "  /* \n", //
6662                    "  \n",    //
6663                    "  */\n",  //
6664                    "x\n",     //
6665                    "{{} \n",  //
6666                    "}\n",     //
6667                )
6668            );
6669        });
6670    }
6671
6672    #[gpui::test]
6673    fn test_highlighted_ranges(cx: &mut gpui::MutableAppContext) {
6674        let buffer = MultiBuffer::build_simple(&sample_text(16, 8, 'a'), cx);
6675        let settings = EditorSettings::test(&cx);
6676        let (_, editor) = cx.add_window(Default::default(), |cx| {
6677            build_editor(buffer.clone(), settings, cx)
6678        });
6679
6680        editor.update(cx, |editor, cx| {
6681            struct Type1;
6682            struct Type2;
6683
6684            let buffer = buffer.read(cx).snapshot(cx);
6685
6686            let anchor_range = |range: Range<Point>| {
6687                buffer.anchor_after(range.start)..buffer.anchor_after(range.end)
6688            };
6689
6690            editor.highlight_ranges::<Type1>(
6691                vec![
6692                    anchor_range(Point::new(2, 1)..Point::new(2, 3)),
6693                    anchor_range(Point::new(4, 2)..Point::new(4, 4)),
6694                    anchor_range(Point::new(6, 3)..Point::new(6, 5)),
6695                    anchor_range(Point::new(8, 4)..Point::new(8, 6)),
6696                ],
6697                Color::red(),
6698                cx,
6699            );
6700            editor.highlight_ranges::<Type2>(
6701                vec![
6702                    anchor_range(Point::new(3, 2)..Point::new(3, 5)),
6703                    anchor_range(Point::new(5, 3)..Point::new(5, 6)),
6704                    anchor_range(Point::new(7, 4)..Point::new(7, 7)),
6705                    anchor_range(Point::new(9, 5)..Point::new(9, 8)),
6706                ],
6707                Color::green(),
6708                cx,
6709            );
6710
6711            let snapshot = editor.snapshot(cx);
6712            assert_eq!(
6713                editor.highlighted_ranges_in_range(
6714                    anchor_range(Point::new(3, 4)..Point::new(7, 4)),
6715                    &snapshot,
6716                ),
6717                &[
6718                    (
6719                        DisplayPoint::new(4, 2)..DisplayPoint::new(4, 4),
6720                        Color::red(),
6721                    ),
6722                    (
6723                        DisplayPoint::new(6, 3)..DisplayPoint::new(6, 5),
6724                        Color::red(),
6725                    ),
6726                    (
6727                        DisplayPoint::new(3, 2)..DisplayPoint::new(3, 5),
6728                        Color::green(),
6729                    ),
6730                    (
6731                        DisplayPoint::new(5, 3)..DisplayPoint::new(5, 6),
6732                        Color::green(),
6733                    ),
6734                ]
6735            );
6736            assert_eq!(
6737                editor.highlighted_ranges_in_range(
6738                    anchor_range(Point::new(5, 6)..Point::new(6, 4)),
6739                    &snapshot,
6740                ),
6741                &[(
6742                    DisplayPoint::new(6, 3)..DisplayPoint::new(6, 5),
6743                    Color::red(),
6744                )]
6745            );
6746        });
6747    }
6748
6749    fn empty_range(row: usize, column: usize) -> Range<DisplayPoint> {
6750        let point = DisplayPoint::new(row as u32, column as u32);
6751        point..point
6752    }
6753
6754    fn build_editor(
6755        buffer: ModelHandle<MultiBuffer>,
6756        settings: EditorSettings,
6757        cx: &mut ViewContext<Editor>,
6758    ) -> Editor {
6759        Editor::for_buffer(buffer, Arc::new(move |_| settings.clone()), cx)
6760    }
6761}
6762
6763trait RangeExt<T> {
6764    fn sorted(&self) -> Range<T>;
6765    fn to_inclusive(&self) -> RangeInclusive<T>;
6766}
6767
6768impl<T: Ord + Clone> RangeExt<T> for Range<T> {
6769    fn sorted(&self) -> Self {
6770        cmp::min(&self.start, &self.end).clone()..cmp::max(&self.start, &self.end).clone()
6771    }
6772
6773    fn to_inclusive(&self) -> RangeInclusive<T> {
6774        self.start.clone()..=self.end.clone()
6775    }
6776}