lib.rs

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