editor.rs

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