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