lib.rs

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