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