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