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                    diagnostic_path_header: Default::default(),
3695                    error_diagnostic: Default::default(),
3696                    invalid_error_diagnostic: Default::default(),
3697                    warning_diagnostic: Default::default(),
3698                    invalid_warning_diagnostic: Default::default(),
3699                    information_diagnostic: Default::default(),
3700                    invalid_information_diagnostic: Default::default(),
3701                    hint_diagnostic: Default::default(),
3702                    invalid_hint_diagnostic: Default::default(),
3703                }
3704            },
3705        }
3706    }
3707}
3708
3709fn compute_scroll_position(
3710    snapshot: &DisplaySnapshot,
3711    mut scroll_position: Vector2F,
3712    scroll_top_anchor: &Option<Anchor>,
3713) -> Vector2F {
3714    if let Some(anchor) = scroll_top_anchor {
3715        let scroll_top = anchor.to_display_point(snapshot).row() as f32;
3716        scroll_position.set_y(scroll_top + scroll_position.y());
3717    } else {
3718        scroll_position.set_y(0.);
3719    }
3720    scroll_position
3721}
3722
3723#[derive(Copy, Clone)]
3724pub enum Event {
3725    Activate,
3726    Edited,
3727    Blurred,
3728    Dirtied,
3729    Saved,
3730    FileHandleChanged,
3731    Closed,
3732}
3733
3734impl Entity for Editor {
3735    type Event = Event;
3736}
3737
3738impl View for Editor {
3739    fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
3740        let settings = (self.build_settings)(cx);
3741        self.display_map.update(cx, |map, cx| {
3742            map.set_font(
3743                settings.style.text.font_id,
3744                settings.style.text.font_size,
3745                cx,
3746            )
3747        });
3748        EditorElement::new(self.handle.clone(), settings).boxed()
3749    }
3750
3751    fn ui_name() -> &'static str {
3752        "Editor"
3753    }
3754
3755    fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
3756        self.focused = true;
3757        self.blink_cursors(self.blink_epoch, cx);
3758        self.buffer.update(cx, |buffer, cx| {
3759            buffer.set_active_selections(&self.selections, cx)
3760        });
3761    }
3762
3763    fn on_blur(&mut self, cx: &mut ViewContext<Self>) {
3764        self.focused = false;
3765        self.show_local_cursors = false;
3766        self.buffer
3767            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
3768        cx.emit(Event::Blurred);
3769        cx.notify();
3770    }
3771
3772    fn keymap_context(&self, _: &AppContext) -> gpui::keymap::Context {
3773        let mut cx = Self::default_keymap_context();
3774        let mode = match self.mode {
3775            EditorMode::SingleLine => "single_line",
3776            EditorMode::AutoHeight { .. } => "auto_height",
3777            EditorMode::Full => "full",
3778        };
3779        cx.map.insert("mode".into(), mode.into());
3780        cx
3781    }
3782}
3783
3784impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
3785    fn point_range(&self, buffer: &MultiBufferSnapshot) -> Range<Point> {
3786        let start = self.start.to_point(buffer);
3787        let end = self.end.to_point(buffer);
3788        if self.reversed {
3789            end..start
3790        } else {
3791            start..end
3792        }
3793    }
3794
3795    fn offset_range(&self, buffer: &MultiBufferSnapshot) -> Range<usize> {
3796        let start = self.start.to_offset(buffer);
3797        let end = self.end.to_offset(buffer);
3798        if self.reversed {
3799            end..start
3800        } else {
3801            start..end
3802        }
3803    }
3804
3805    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
3806        let start = self
3807            .start
3808            .to_point(&map.buffer_snapshot)
3809            .to_display_point(map);
3810        let end = self
3811            .end
3812            .to_point(&map.buffer_snapshot)
3813            .to_display_point(map);
3814        if self.reversed {
3815            end..start
3816        } else {
3817            start..end
3818        }
3819    }
3820
3821    fn spanned_rows(
3822        &self,
3823        include_end_if_at_line_start: bool,
3824        map: &DisplaySnapshot,
3825    ) -> Range<u32> {
3826        let start = self.start.to_point(&map.buffer_snapshot);
3827        let mut end = self.end.to_point(&map.buffer_snapshot);
3828        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
3829            end.row -= 1;
3830        }
3831
3832        let buffer_start = map.prev_line_boundary(start).0;
3833        let buffer_end = map.next_line_boundary(end).0;
3834        buffer_start.row..buffer_end.row + 1
3835    }
3836}
3837
3838pub fn diagnostic_block_renderer(
3839    diagnostic: Diagnostic,
3840    is_valid: bool,
3841    build_settings: BuildSettings,
3842) -> RenderBlock {
3843    Arc::new(move |cx: &BlockContext| {
3844        let settings = build_settings(cx);
3845        let mut text_style = settings.style.text.clone();
3846        text_style.color = diagnostic_style(diagnostic.severity, is_valid, &settings.style).text;
3847        Text::new(diagnostic.message.clone(), text_style)
3848            .with_soft_wrap(false)
3849            .contained()
3850            .with_margin_left(cx.anchor_x)
3851            .boxed()
3852    })
3853}
3854
3855pub fn diagnostic_style(
3856    severity: DiagnosticSeverity,
3857    valid: bool,
3858    style: &EditorStyle,
3859) -> DiagnosticStyle {
3860    match (severity, valid) {
3861        (DiagnosticSeverity::ERROR, true) => style.error_diagnostic,
3862        (DiagnosticSeverity::ERROR, false) => style.invalid_error_diagnostic,
3863        (DiagnosticSeverity::WARNING, true) => style.warning_diagnostic,
3864        (DiagnosticSeverity::WARNING, false) => style.invalid_warning_diagnostic,
3865        (DiagnosticSeverity::INFORMATION, true) => style.information_diagnostic,
3866        (DiagnosticSeverity::INFORMATION, false) => style.invalid_information_diagnostic,
3867        (DiagnosticSeverity::HINT, true) => style.hint_diagnostic,
3868        (DiagnosticSeverity::HINT, false) => style.invalid_hint_diagnostic,
3869        _ => Default::default(),
3870    }
3871}
3872
3873pub fn settings_builder(
3874    buffer: WeakModelHandle<MultiBuffer>,
3875    settings: watch::Receiver<workspace::Settings>,
3876) -> BuildSettings {
3877    Arc::new(move |cx| {
3878        let settings = settings.borrow();
3879        let font_cache = cx.font_cache();
3880        let font_family_id = settings.buffer_font_family;
3881        let font_family_name = cx.font_cache().family_name(font_family_id).unwrap();
3882        let font_properties = Default::default();
3883        let font_id = font_cache
3884            .select_font(font_family_id, &font_properties)
3885            .unwrap();
3886        let font_size = settings.buffer_font_size;
3887
3888        let mut theme = settings.theme.editor.clone();
3889        theme.text = TextStyle {
3890            color: theme.text.color,
3891            font_family_name,
3892            font_family_id,
3893            font_id,
3894            font_size,
3895            font_properties,
3896            underline: None,
3897        };
3898        let language = buffer.upgrade(cx).and_then(|buf| buf.read(cx).language(cx));
3899        let soft_wrap = match settings.soft_wrap(language) {
3900            workspace::settings::SoftWrap::None => SoftWrap::None,
3901            workspace::settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
3902            workspace::settings::SoftWrap::PreferredLineLength => {
3903                SoftWrap::Column(settings.preferred_line_length(language).saturating_sub(1))
3904            }
3905        };
3906
3907        EditorSettings {
3908            tab_size: settings.tab_size,
3909            soft_wrap,
3910            style: theme,
3911        }
3912    })
3913}
3914
3915#[cfg(test)]
3916mod tests {
3917    use super::*;
3918    use language::LanguageConfig;
3919    use std::time::Instant;
3920    use text::Point;
3921    use unindent::Unindent;
3922    use util::test::sample_text;
3923
3924    #[gpui::test]
3925    fn test_undo_redo_with_selection_restoration(cx: &mut MutableAppContext) {
3926        let mut now = Instant::now();
3927        let buffer = cx.add_model(|cx| language::Buffer::new(0, "123456", cx));
3928        let group_interval = buffer.read(cx).transaction_group_interval();
3929        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
3930        let settings = EditorSettings::test(cx);
3931        let (_, editor) = cx.add_window(Default::default(), |cx| {
3932            build_editor(buffer.clone(), settings, cx)
3933        });
3934
3935        editor.update(cx, |editor, cx| {
3936            editor.start_transaction_at(now, cx);
3937            editor.select_ranges([2..4], None, cx);
3938            editor.insert("cd", cx);
3939            editor.end_transaction_at(now, cx);
3940            assert_eq!(editor.text(cx), "12cd56");
3941            assert_eq!(editor.selected_ranges(cx), vec![4..4]);
3942
3943            editor.start_transaction_at(now, cx);
3944            editor.select_ranges([4..5], None, cx);
3945            editor.insert("e", cx);
3946            editor.end_transaction_at(now, cx);
3947            assert_eq!(editor.text(cx), "12cde6");
3948            assert_eq!(editor.selected_ranges(cx), vec![5..5]);
3949
3950            now += group_interval + Duration::from_millis(1);
3951            editor.select_ranges([2..2], None, cx);
3952
3953            // Simulate an edit in another editor
3954            buffer.update(cx, |buffer, cx| {
3955                buffer.start_transaction_at(now, cx);
3956                buffer.edit([0..1], "a", cx);
3957                buffer.edit([1..1], "b", cx);
3958                buffer.end_transaction_at(now, cx);
3959            });
3960
3961            assert_eq!(editor.text(cx), "ab2cde6");
3962            assert_eq!(editor.selected_ranges(cx), vec![3..3]);
3963
3964            // Last transaction happened past the group interval in a different editor.
3965            // Undo it individually and don't restore selections.
3966            editor.undo(&Undo, cx);
3967            assert_eq!(editor.text(cx), "12cde6");
3968            assert_eq!(editor.selected_ranges(cx), vec![2..2]);
3969
3970            // First two transactions happened within the group interval in this editor.
3971            // Undo them together and restore selections.
3972            editor.undo(&Undo, cx);
3973            editor.undo(&Undo, cx); // Undo stack is empty here, so this is a no-op.
3974            assert_eq!(editor.text(cx), "123456");
3975            assert_eq!(editor.selected_ranges(cx), vec![0..0]);
3976
3977            // Redo the first two transactions together.
3978            editor.redo(&Redo, cx);
3979            assert_eq!(editor.text(cx), "12cde6");
3980            assert_eq!(editor.selected_ranges(cx), vec![5..5]);
3981
3982            // Redo the last transaction on its own.
3983            editor.redo(&Redo, cx);
3984            assert_eq!(editor.text(cx), "ab2cde6");
3985            assert_eq!(editor.selected_ranges(cx), vec![6..6]);
3986
3987            // Test empty transactions.
3988            editor.start_transaction_at(now, cx);
3989            editor.end_transaction_at(now, cx);
3990            editor.undo(&Undo, cx);
3991            assert_eq!(editor.text(cx), "12cde6");
3992        });
3993    }
3994
3995    #[gpui::test]
3996    fn test_selection_with_mouse(cx: &mut gpui::MutableAppContext) {
3997        let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
3998        let settings = EditorSettings::test(cx);
3999        let (_, editor) =
4000            cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4001
4002        editor.update(cx, |view, cx| {
4003            view.begin_selection(DisplayPoint::new(2, 2), false, 1, cx);
4004        });
4005
4006        assert_eq!(
4007            editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
4008            [DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2)]
4009        );
4010
4011        editor.update(cx, |view, cx| {
4012            view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
4013        });
4014
4015        assert_eq!(
4016            editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
4017            [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
4018        );
4019
4020        editor.update(cx, |view, cx| {
4021            view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
4022        });
4023
4024        assert_eq!(
4025            editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
4026            [DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1)]
4027        );
4028
4029        editor.update(cx, |view, cx| {
4030            view.end_selection(cx);
4031            view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
4032        });
4033
4034        assert_eq!(
4035            editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
4036            [DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1)]
4037        );
4038
4039        editor.update(cx, |view, cx| {
4040            view.begin_selection(DisplayPoint::new(3, 3), true, 1, cx);
4041            view.update_selection(DisplayPoint::new(0, 0), 0, Vector2F::zero(), cx);
4042        });
4043
4044        assert_eq!(
4045            editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
4046            [
4047                DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1),
4048                DisplayPoint::new(3, 3)..DisplayPoint::new(0, 0)
4049            ]
4050        );
4051
4052        editor.update(cx, |view, cx| {
4053            view.end_selection(cx);
4054        });
4055
4056        assert_eq!(
4057            editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
4058            [DisplayPoint::new(3, 3)..DisplayPoint::new(0, 0)]
4059        );
4060    }
4061
4062    #[gpui::test]
4063    fn test_canceling_pending_selection(cx: &mut gpui::MutableAppContext) {
4064        let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
4065        let settings = EditorSettings::test(cx);
4066        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4067
4068        view.update(cx, |view, cx| {
4069            view.begin_selection(DisplayPoint::new(2, 2), false, 1, cx);
4070            assert_eq!(
4071                view.selected_display_ranges(cx),
4072                [DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2)]
4073            );
4074        });
4075
4076        view.update(cx, |view, cx| {
4077            view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
4078            assert_eq!(
4079                view.selected_display_ranges(cx),
4080                [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
4081            );
4082        });
4083
4084        view.update(cx, |view, cx| {
4085            view.cancel(&Cancel, cx);
4086            view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
4087            assert_eq!(
4088                view.selected_display_ranges(cx),
4089                [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
4090            );
4091        });
4092    }
4093
4094    #[gpui::test]
4095    fn test_cancel(cx: &mut gpui::MutableAppContext) {
4096        let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
4097        let settings = EditorSettings::test(cx);
4098        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4099
4100        view.update(cx, |view, cx| {
4101            view.begin_selection(DisplayPoint::new(3, 4), false, 1, cx);
4102            view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
4103            view.end_selection(cx);
4104
4105            view.begin_selection(DisplayPoint::new(0, 1), true, 1, cx);
4106            view.update_selection(DisplayPoint::new(0, 3), 0, Vector2F::zero(), cx);
4107            view.end_selection(cx);
4108            assert_eq!(
4109                view.selected_display_ranges(cx),
4110                [
4111                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
4112                    DisplayPoint::new(3, 4)..DisplayPoint::new(1, 1),
4113                ]
4114            );
4115        });
4116
4117        view.update(cx, |view, cx| {
4118            view.cancel(&Cancel, cx);
4119            assert_eq!(
4120                view.selected_display_ranges(cx),
4121                [DisplayPoint::new(3, 4)..DisplayPoint::new(1, 1)]
4122            );
4123        });
4124
4125        view.update(cx, |view, cx| {
4126            view.cancel(&Cancel, cx);
4127            assert_eq!(
4128                view.selected_display_ranges(cx),
4129                [DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1)]
4130            );
4131        });
4132    }
4133
4134    #[gpui::test]
4135    fn test_fold(cx: &mut gpui::MutableAppContext) {
4136        let buffer = MultiBuffer::build_simple(
4137            &"
4138                impl Foo {
4139                    // Hello!
4140
4141                    fn a() {
4142                        1
4143                    }
4144
4145                    fn b() {
4146                        2
4147                    }
4148
4149                    fn c() {
4150                        3
4151                    }
4152                }
4153            "
4154            .unindent(),
4155            cx,
4156        );
4157        let settings = EditorSettings::test(&cx);
4158        let (_, view) = cx.add_window(Default::default(), |cx| {
4159            build_editor(buffer.clone(), settings, cx)
4160        });
4161
4162        view.update(cx, |view, cx| {
4163            view.select_display_ranges(&[DisplayPoint::new(8, 0)..DisplayPoint::new(12, 0)], cx);
4164            view.fold(&Fold, cx);
4165            assert_eq!(
4166                view.display_text(cx),
4167                "
4168                    impl Foo {
4169                        // Hello!
4170
4171                        fn a() {
4172                            1
4173                        }
4174
4175                        fn b() {…
4176                        }
4177
4178                        fn c() {…
4179                        }
4180                    }
4181                "
4182                .unindent(),
4183            );
4184
4185            view.fold(&Fold, cx);
4186            assert_eq!(
4187                view.display_text(cx),
4188                "
4189                    impl Foo {…
4190                    }
4191                "
4192                .unindent(),
4193            );
4194
4195            view.unfold(&Unfold, cx);
4196            assert_eq!(
4197                view.display_text(cx),
4198                "
4199                    impl Foo {
4200                        // Hello!
4201
4202                        fn a() {
4203                            1
4204                        }
4205
4206                        fn b() {…
4207                        }
4208
4209                        fn c() {…
4210                        }
4211                    }
4212                "
4213                .unindent(),
4214            );
4215
4216            view.unfold(&Unfold, cx);
4217            assert_eq!(view.display_text(cx), buffer.read(cx).read(cx).text());
4218        });
4219    }
4220
4221    #[gpui::test]
4222    fn test_move_cursor(cx: &mut gpui::MutableAppContext) {
4223        let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
4224        let settings = EditorSettings::test(&cx);
4225        let (_, view) = cx.add_window(Default::default(), |cx| {
4226            build_editor(buffer.clone(), settings, cx)
4227        });
4228
4229        buffer.update(cx, |buffer, cx| {
4230            buffer.edit(
4231                vec![
4232                    Point::new(1, 0)..Point::new(1, 0),
4233                    Point::new(1, 1)..Point::new(1, 1),
4234                ],
4235                "\t",
4236                cx,
4237            );
4238        });
4239
4240        view.update(cx, |view, cx| {
4241            assert_eq!(
4242                view.selected_display_ranges(cx),
4243                &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
4244            );
4245
4246            view.move_down(&MoveDown, cx);
4247            assert_eq!(
4248                view.selected_display_ranges(cx),
4249                &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
4250            );
4251
4252            view.move_right(&MoveRight, cx);
4253            assert_eq!(
4254                view.selected_display_ranges(cx),
4255                &[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4)]
4256            );
4257
4258            view.move_left(&MoveLeft, cx);
4259            assert_eq!(
4260                view.selected_display_ranges(cx),
4261                &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
4262            );
4263
4264            view.move_up(&MoveUp, cx);
4265            assert_eq!(
4266                view.selected_display_ranges(cx),
4267                &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
4268            );
4269
4270            view.move_to_end(&MoveToEnd, cx);
4271            assert_eq!(
4272                view.selected_display_ranges(cx),
4273                &[DisplayPoint::new(5, 6)..DisplayPoint::new(5, 6)]
4274            );
4275
4276            view.move_to_beginning(&MoveToBeginning, cx);
4277            assert_eq!(
4278                view.selected_display_ranges(cx),
4279                &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
4280            );
4281
4282            view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 2)], cx);
4283            view.select_to_beginning(&SelectToBeginning, cx);
4284            assert_eq!(
4285                view.selected_display_ranges(cx),
4286                &[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 0)]
4287            );
4288
4289            view.select_to_end(&SelectToEnd, cx);
4290            assert_eq!(
4291                view.selected_display_ranges(cx),
4292                &[DisplayPoint::new(0, 1)..DisplayPoint::new(5, 6)]
4293            );
4294        });
4295    }
4296
4297    #[gpui::test]
4298    fn test_move_cursor_multibyte(cx: &mut gpui::MutableAppContext) {
4299        let buffer = MultiBuffer::build_simple("ⓐⓑⓒⓓⓔ\nabcde\nαβγδε\n", cx);
4300        let settings = EditorSettings::test(&cx);
4301        let (_, view) = cx.add_window(Default::default(), |cx| {
4302            build_editor(buffer.clone(), settings, cx)
4303        });
4304
4305        assert_eq!('ⓐ'.len_utf8(), 3);
4306        assert_eq!('α'.len_utf8(), 2);
4307
4308        view.update(cx, |view, cx| {
4309            view.fold_ranges(
4310                vec![
4311                    Point::new(0, 6)..Point::new(0, 12),
4312                    Point::new(1, 2)..Point::new(1, 4),
4313                    Point::new(2, 4)..Point::new(2, 8),
4314                ],
4315                cx,
4316            );
4317            assert_eq!(view.display_text(cx), "ⓐⓑ…ⓔ\nab…e\nαβ…ε\n");
4318
4319            view.move_right(&MoveRight, cx);
4320            assert_eq!(
4321                view.selected_display_ranges(cx),
4322                &[empty_range(0, "".len())]
4323            );
4324            view.move_right(&MoveRight, cx);
4325            assert_eq!(
4326                view.selected_display_ranges(cx),
4327                &[empty_range(0, "ⓐⓑ".len())]
4328            );
4329            view.move_right(&MoveRight, cx);
4330            assert_eq!(
4331                view.selected_display_ranges(cx),
4332                &[empty_range(0, "ⓐⓑ…".len())]
4333            );
4334
4335            view.move_down(&MoveDown, cx);
4336            assert_eq!(
4337                view.selected_display_ranges(cx),
4338                &[empty_range(1, "ab…".len())]
4339            );
4340            view.move_left(&MoveLeft, cx);
4341            assert_eq!(
4342                view.selected_display_ranges(cx),
4343                &[empty_range(1, "ab".len())]
4344            );
4345            view.move_left(&MoveLeft, cx);
4346            assert_eq!(
4347                view.selected_display_ranges(cx),
4348                &[empty_range(1, "a".len())]
4349            );
4350
4351            view.move_down(&MoveDown, cx);
4352            assert_eq!(
4353                view.selected_display_ranges(cx),
4354                &[empty_range(2, "α".len())]
4355            );
4356            view.move_right(&MoveRight, cx);
4357            assert_eq!(
4358                view.selected_display_ranges(cx),
4359                &[empty_range(2, "αβ".len())]
4360            );
4361            view.move_right(&MoveRight, cx);
4362            assert_eq!(
4363                view.selected_display_ranges(cx),
4364                &[empty_range(2, "αβ…".len())]
4365            );
4366            view.move_right(&MoveRight, cx);
4367            assert_eq!(
4368                view.selected_display_ranges(cx),
4369                &[empty_range(2, "αβ…ε".len())]
4370            );
4371
4372            view.move_up(&MoveUp, cx);
4373            assert_eq!(
4374                view.selected_display_ranges(cx),
4375                &[empty_range(1, "ab…e".len())]
4376            );
4377            view.move_up(&MoveUp, cx);
4378            assert_eq!(
4379                view.selected_display_ranges(cx),
4380                &[empty_range(0, "ⓐⓑ…ⓔ".len())]
4381            );
4382            view.move_left(&MoveLeft, cx);
4383            assert_eq!(
4384                view.selected_display_ranges(cx),
4385                &[empty_range(0, "ⓐⓑ…".len())]
4386            );
4387            view.move_left(&MoveLeft, cx);
4388            assert_eq!(
4389                view.selected_display_ranges(cx),
4390                &[empty_range(0, "ⓐⓑ".len())]
4391            );
4392            view.move_left(&MoveLeft, cx);
4393            assert_eq!(
4394                view.selected_display_ranges(cx),
4395                &[empty_range(0, "".len())]
4396            );
4397        });
4398    }
4399
4400    #[gpui::test]
4401    fn test_move_cursor_different_line_lengths(cx: &mut gpui::MutableAppContext) {
4402        let buffer = MultiBuffer::build_simple("ⓐⓑⓒⓓⓔ\nabcd\nαβγ\nabcd\nⓐⓑⓒⓓⓔ\n", cx);
4403        let settings = EditorSettings::test(&cx);
4404        let (_, view) = cx.add_window(Default::default(), |cx| {
4405            build_editor(buffer.clone(), settings, cx)
4406        });
4407        view.update(cx, |view, cx| {
4408            view.select_display_ranges(&[empty_range(0, "ⓐⓑⓒⓓⓔ".len())], cx);
4409            view.move_down(&MoveDown, cx);
4410            assert_eq!(
4411                view.selected_display_ranges(cx),
4412                &[empty_range(1, "abcd".len())]
4413            );
4414
4415            view.move_down(&MoveDown, cx);
4416            assert_eq!(
4417                view.selected_display_ranges(cx),
4418                &[empty_range(2, "αβγ".len())]
4419            );
4420
4421            view.move_down(&MoveDown, cx);
4422            assert_eq!(
4423                view.selected_display_ranges(cx),
4424                &[empty_range(3, "abcd".len())]
4425            );
4426
4427            view.move_down(&MoveDown, cx);
4428            assert_eq!(
4429                view.selected_display_ranges(cx),
4430                &[empty_range(4, "ⓐⓑⓒⓓⓔ".len())]
4431            );
4432
4433            view.move_up(&MoveUp, cx);
4434            assert_eq!(
4435                view.selected_display_ranges(cx),
4436                &[empty_range(3, "abcd".len())]
4437            );
4438
4439            view.move_up(&MoveUp, cx);
4440            assert_eq!(
4441                view.selected_display_ranges(cx),
4442                &[empty_range(2, "αβγ".len())]
4443            );
4444        });
4445    }
4446
4447    #[gpui::test]
4448    fn test_beginning_end_of_line(cx: &mut gpui::MutableAppContext) {
4449        let buffer = MultiBuffer::build_simple("abc\n  def", cx);
4450        let settings = EditorSettings::test(&cx);
4451        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4452        view.update(cx, |view, cx| {
4453            view.select_display_ranges(
4454                &[
4455                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
4456                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4),
4457                ],
4458                cx,
4459            );
4460        });
4461
4462        view.update(cx, |view, cx| {
4463            view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
4464            assert_eq!(
4465                view.selected_display_ranges(cx),
4466                &[
4467                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4468                    DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
4469                ]
4470            );
4471        });
4472
4473        view.update(cx, |view, cx| {
4474            view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
4475            assert_eq!(
4476                view.selected_display_ranges(cx),
4477                &[
4478                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4479                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4480                ]
4481            );
4482        });
4483
4484        view.update(cx, |view, cx| {
4485            view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
4486            assert_eq!(
4487                view.selected_display_ranges(cx),
4488                &[
4489                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4490                    DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
4491                ]
4492            );
4493        });
4494
4495        view.update(cx, |view, cx| {
4496            view.move_to_end_of_line(&MoveToEndOfLine, cx);
4497            assert_eq!(
4498                view.selected_display_ranges(cx),
4499                &[
4500                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
4501                    DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
4502                ]
4503            );
4504        });
4505
4506        // Moving to the end of line again is a no-op.
4507        view.update(cx, |view, cx| {
4508            view.move_to_end_of_line(&MoveToEndOfLine, cx);
4509            assert_eq!(
4510                view.selected_display_ranges(cx),
4511                &[
4512                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
4513                    DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
4514                ]
4515            );
4516        });
4517
4518        view.update(cx, |view, cx| {
4519            view.move_left(&MoveLeft, cx);
4520            view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
4521            assert_eq!(
4522                view.selected_display_ranges(cx),
4523                &[
4524                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
4525                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 2),
4526                ]
4527            );
4528        });
4529
4530        view.update(cx, |view, cx| {
4531            view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
4532            assert_eq!(
4533                view.selected_display_ranges(cx),
4534                &[
4535                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
4536                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 0),
4537                ]
4538            );
4539        });
4540
4541        view.update(cx, |view, cx| {
4542            view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
4543            assert_eq!(
4544                view.selected_display_ranges(cx),
4545                &[
4546                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
4547                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 2),
4548                ]
4549            );
4550        });
4551
4552        view.update(cx, |view, cx| {
4553            view.select_to_end_of_line(&SelectToEndOfLine, cx);
4554            assert_eq!(
4555                view.selected_display_ranges(cx),
4556                &[
4557                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 3),
4558                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 5),
4559                ]
4560            );
4561        });
4562
4563        view.update(cx, |view, cx| {
4564            view.delete_to_end_of_line(&DeleteToEndOfLine, cx);
4565            assert_eq!(view.display_text(cx), "ab\n  de");
4566            assert_eq!(
4567                view.selected_display_ranges(cx),
4568                &[
4569                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4570                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4),
4571                ]
4572            );
4573        });
4574
4575        view.update(cx, |view, cx| {
4576            view.delete_to_beginning_of_line(&DeleteToBeginningOfLine, cx);
4577            assert_eq!(view.display_text(cx), "\n");
4578            assert_eq!(
4579                view.selected_display_ranges(cx),
4580                &[
4581                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4582                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4583                ]
4584            );
4585        });
4586    }
4587
4588    #[gpui::test]
4589    fn test_prev_next_word_boundary(cx: &mut gpui::MutableAppContext) {
4590        let buffer = MultiBuffer::build_simple("use std::str::{foo, bar}\n\n  {baz.qux()}", cx);
4591        let settings = EditorSettings::test(&cx);
4592        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4593        view.update(cx, |view, cx| {
4594            view.select_display_ranges(
4595                &[
4596                    DisplayPoint::new(0, 11)..DisplayPoint::new(0, 11),
4597                    DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4),
4598                ],
4599                cx,
4600            );
4601        });
4602
4603        view.update(cx, |view, cx| {
4604            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4605            assert_eq!(
4606                view.selected_display_ranges(cx),
4607                &[
4608                    DisplayPoint::new(0, 9)..DisplayPoint::new(0, 9),
4609                    DisplayPoint::new(2, 3)..DisplayPoint::new(2, 3),
4610                ]
4611            );
4612        });
4613
4614        view.update(cx, |view, cx| {
4615            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4616            assert_eq!(
4617                view.selected_display_ranges(cx),
4618                &[
4619                    DisplayPoint::new(0, 7)..DisplayPoint::new(0, 7),
4620                    DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2),
4621                ]
4622            );
4623        });
4624
4625        view.update(cx, |view, cx| {
4626            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4627            assert_eq!(
4628                view.selected_display_ranges(cx),
4629                &[
4630                    DisplayPoint::new(0, 4)..DisplayPoint::new(0, 4),
4631                    DisplayPoint::new(2, 0)..DisplayPoint::new(2, 0),
4632                ]
4633            );
4634        });
4635
4636        view.update(cx, |view, cx| {
4637            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4638            assert_eq!(
4639                view.selected_display_ranges(cx),
4640                &[
4641                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4642                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4643                ]
4644            );
4645        });
4646
4647        view.update(cx, |view, cx| {
4648            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4649            assert_eq!(
4650                view.selected_display_ranges(cx),
4651                &[
4652                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4653                    DisplayPoint::new(0, 23)..DisplayPoint::new(0, 23),
4654                ]
4655            );
4656        });
4657
4658        view.update(cx, |view, cx| {
4659            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4660            assert_eq!(
4661                view.selected_display_ranges(cx),
4662                &[
4663                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
4664                    DisplayPoint::new(0, 24)..DisplayPoint::new(0, 24),
4665                ]
4666            );
4667        });
4668
4669        view.update(cx, |view, cx| {
4670            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4671            assert_eq!(
4672                view.selected_display_ranges(cx),
4673                &[
4674                    DisplayPoint::new(0, 7)..DisplayPoint::new(0, 7),
4675                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4676                ]
4677            );
4678        });
4679
4680        view.update(cx, |view, cx| {
4681            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4682            assert_eq!(
4683                view.selected_display_ranges(cx),
4684                &[
4685                    DisplayPoint::new(0, 9)..DisplayPoint::new(0, 9),
4686                    DisplayPoint::new(2, 3)..DisplayPoint::new(2, 3),
4687                ]
4688            );
4689        });
4690
4691        view.update(cx, |view, cx| {
4692            view.move_right(&MoveRight, cx);
4693            view.select_to_previous_word_boundary(&SelectToPreviousWordBoundary, cx);
4694            assert_eq!(
4695                view.selected_display_ranges(cx),
4696                &[
4697                    DisplayPoint::new(0, 10)..DisplayPoint::new(0, 9),
4698                    DisplayPoint::new(2, 4)..DisplayPoint::new(2, 3),
4699                ]
4700            );
4701        });
4702
4703        view.update(cx, |view, cx| {
4704            view.select_to_previous_word_boundary(&SelectToPreviousWordBoundary, cx);
4705            assert_eq!(
4706                view.selected_display_ranges(cx),
4707                &[
4708                    DisplayPoint::new(0, 10)..DisplayPoint::new(0, 7),
4709                    DisplayPoint::new(2, 4)..DisplayPoint::new(2, 2),
4710                ]
4711            );
4712        });
4713
4714        view.update(cx, |view, cx| {
4715            view.select_to_next_word_boundary(&SelectToNextWordBoundary, cx);
4716            assert_eq!(
4717                view.selected_display_ranges(cx),
4718                &[
4719                    DisplayPoint::new(0, 10)..DisplayPoint::new(0, 9),
4720                    DisplayPoint::new(2, 4)..DisplayPoint::new(2, 3),
4721                ]
4722            );
4723        });
4724    }
4725
4726    #[gpui::test]
4727    fn test_prev_next_word_bounds_with_soft_wrap(cx: &mut gpui::MutableAppContext) {
4728        let buffer = MultiBuffer::build_simple("use one::{\n    two::three::four::five\n};", cx);
4729        let settings = EditorSettings::test(&cx);
4730        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4731
4732        view.update(cx, |view, cx| {
4733            view.set_wrap_width(Some(140.), cx);
4734            assert_eq!(
4735                view.display_text(cx),
4736                "use one::{\n    two::three::\n    four::five\n};"
4737            );
4738
4739            view.select_display_ranges(&[DisplayPoint::new(1, 7)..DisplayPoint::new(1, 7)], cx);
4740
4741            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4742            assert_eq!(
4743                view.selected_display_ranges(cx),
4744                &[DisplayPoint::new(1, 9)..DisplayPoint::new(1, 9)]
4745            );
4746
4747            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4748            assert_eq!(
4749                view.selected_display_ranges(cx),
4750                &[DisplayPoint::new(1, 14)..DisplayPoint::new(1, 14)]
4751            );
4752
4753            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4754            assert_eq!(
4755                view.selected_display_ranges(cx),
4756                &[DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4)]
4757            );
4758
4759            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4760            assert_eq!(
4761                view.selected_display_ranges(cx),
4762                &[DisplayPoint::new(2, 8)..DisplayPoint::new(2, 8)]
4763            );
4764
4765            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4766            assert_eq!(
4767                view.selected_display_ranges(cx),
4768                &[DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4)]
4769            );
4770
4771            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4772            assert_eq!(
4773                view.selected_display_ranges(cx),
4774                &[DisplayPoint::new(1, 14)..DisplayPoint::new(1, 14)]
4775            );
4776        });
4777    }
4778
4779    #[gpui::test]
4780    fn test_delete_to_word_boundary(cx: &mut gpui::MutableAppContext) {
4781        let buffer = MultiBuffer::build_simple("one two three four", cx);
4782        let settings = EditorSettings::test(&cx);
4783        let (_, view) = cx.add_window(Default::default(), |cx| {
4784            build_editor(buffer.clone(), settings, cx)
4785        });
4786
4787        view.update(cx, |view, cx| {
4788            view.select_display_ranges(
4789                &[
4790                    // an empty selection - the preceding word fragment is deleted
4791                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4792                    // characters selected - they are deleted
4793                    DisplayPoint::new(0, 9)..DisplayPoint::new(0, 12),
4794                ],
4795                cx,
4796            );
4797            view.delete_to_previous_word_boundary(&DeleteToPreviousWordBoundary, cx);
4798        });
4799
4800        assert_eq!(buffer.read(cx).read(cx).text(), "e two te four");
4801
4802        view.update(cx, |view, cx| {
4803            view.select_display_ranges(
4804                &[
4805                    // an empty selection - the following word fragment is deleted
4806                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
4807                    // characters selected - they are deleted
4808                    DisplayPoint::new(0, 9)..DisplayPoint::new(0, 10),
4809                ],
4810                cx,
4811            );
4812            view.delete_to_next_word_boundary(&DeleteToNextWordBoundary, cx);
4813        });
4814
4815        assert_eq!(buffer.read(cx).read(cx).text(), "e t te our");
4816    }
4817
4818    #[gpui::test]
4819    fn test_newline(cx: &mut gpui::MutableAppContext) {
4820        let buffer = MultiBuffer::build_simple("aaaa\n    bbbb\n", cx);
4821        let settings = EditorSettings::test(&cx);
4822        let (_, view) = cx.add_window(Default::default(), |cx| {
4823            build_editor(buffer.clone(), settings, cx)
4824        });
4825
4826        view.update(cx, |view, cx| {
4827            view.select_display_ranges(
4828                &[
4829                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4830                    DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
4831                    DisplayPoint::new(1, 6)..DisplayPoint::new(1, 6),
4832                ],
4833                cx,
4834            );
4835
4836            view.newline(&Newline, cx);
4837            assert_eq!(view.text(cx), "aa\naa\n  \n    bb\n    bb\n");
4838        });
4839    }
4840
4841    #[gpui::test]
4842    fn test_indent_outdent(cx: &mut gpui::MutableAppContext) {
4843        let buffer = MultiBuffer::build_simple("  one two\nthree\n four", cx);
4844        let settings = EditorSettings::test(&cx);
4845        let (_, view) = cx.add_window(Default::default(), |cx| {
4846            build_editor(buffer.clone(), settings, cx)
4847        });
4848
4849        view.update(cx, |view, cx| {
4850            // two selections on the same line
4851            view.select_display_ranges(
4852                &[
4853                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 5),
4854                    DisplayPoint::new(0, 6)..DisplayPoint::new(0, 9),
4855                ],
4856                cx,
4857            );
4858
4859            // indent from mid-tabstop to full tabstop
4860            view.tab(&Tab, cx);
4861            assert_eq!(view.text(cx), "    one two\nthree\n four");
4862            assert_eq!(
4863                view.selected_display_ranges(cx),
4864                &[
4865                    DisplayPoint::new(0, 4)..DisplayPoint::new(0, 7),
4866                    DisplayPoint::new(0, 8)..DisplayPoint::new(0, 11),
4867                ]
4868            );
4869
4870            // outdent from 1 tabstop to 0 tabstops
4871            view.outdent(&Outdent, cx);
4872            assert_eq!(view.text(cx), "one two\nthree\n four");
4873            assert_eq!(
4874                view.selected_display_ranges(cx),
4875                &[
4876                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 3),
4877                    DisplayPoint::new(0, 4)..DisplayPoint::new(0, 7),
4878                ]
4879            );
4880
4881            // select across line ending
4882            view.select_display_ranges(&[DisplayPoint::new(1, 1)..DisplayPoint::new(2, 0)], cx);
4883
4884            // indent and outdent affect only the preceding line
4885            view.tab(&Tab, cx);
4886            assert_eq!(view.text(cx), "one two\n    three\n four");
4887            assert_eq!(
4888                view.selected_display_ranges(cx),
4889                &[DisplayPoint::new(1, 5)..DisplayPoint::new(2, 0)]
4890            );
4891            view.outdent(&Outdent, cx);
4892            assert_eq!(view.text(cx), "one two\nthree\n four");
4893            assert_eq!(
4894                view.selected_display_ranges(cx),
4895                &[DisplayPoint::new(1, 1)..DisplayPoint::new(2, 0)]
4896            );
4897
4898            // Ensure that indenting/outdenting works when the cursor is at column 0.
4899            view.select_display_ranges(&[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)], cx);
4900            view.tab(&Tab, cx);
4901            assert_eq!(view.text(cx), "one two\n    three\n four");
4902            assert_eq!(
4903                view.selected_display_ranges(cx),
4904                &[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4)]
4905            );
4906
4907            view.select_display_ranges(&[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)], cx);
4908            view.outdent(&Outdent, cx);
4909            assert_eq!(view.text(cx), "one two\nthree\n four");
4910            assert_eq!(
4911                view.selected_display_ranges(cx),
4912                &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
4913            );
4914        });
4915    }
4916
4917    #[gpui::test]
4918    fn test_backspace(cx: &mut gpui::MutableAppContext) {
4919        let buffer =
4920            MultiBuffer::build_simple("one two three\nfour five six\nseven eight nine\nten\n", cx);
4921        let settings = EditorSettings::test(&cx);
4922        let (_, view) = cx.add_window(Default::default(), |cx| {
4923            build_editor(buffer.clone(), settings, cx)
4924        });
4925
4926        view.update(cx, |view, cx| {
4927            view.select_display_ranges(
4928                &[
4929                    // an empty selection - the preceding character is deleted
4930                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4931                    // one character selected - it is deleted
4932                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
4933                    // a line suffix selected - it is deleted
4934                    DisplayPoint::new(2, 6)..DisplayPoint::new(3, 0),
4935                ],
4936                cx,
4937            );
4938            view.backspace(&Backspace, cx);
4939        });
4940
4941        assert_eq!(
4942            buffer.read(cx).read(cx).text(),
4943            "oe two three\nfou five six\nseven ten\n"
4944        );
4945    }
4946
4947    #[gpui::test]
4948    fn test_delete(cx: &mut gpui::MutableAppContext) {
4949        let buffer =
4950            MultiBuffer::build_simple("one two three\nfour five six\nseven eight nine\nten\n", cx);
4951        let settings = EditorSettings::test(&cx);
4952        let (_, view) = cx.add_window(Default::default(), |cx| {
4953            build_editor(buffer.clone(), settings, cx)
4954        });
4955
4956        view.update(cx, |view, cx| {
4957            view.select_display_ranges(
4958                &[
4959                    // an empty selection - the following character is deleted
4960                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4961                    // one character selected - it is deleted
4962                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
4963                    // a line suffix selected - it is deleted
4964                    DisplayPoint::new(2, 6)..DisplayPoint::new(3, 0),
4965                ],
4966                cx,
4967            );
4968            view.delete(&Delete, cx);
4969        });
4970
4971        assert_eq!(
4972            buffer.read(cx).read(cx).text(),
4973            "on two three\nfou five six\nseven ten\n"
4974        );
4975    }
4976
4977    #[gpui::test]
4978    fn test_delete_line(cx: &mut gpui::MutableAppContext) {
4979        let settings = EditorSettings::test(&cx);
4980        let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
4981        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4982        view.update(cx, |view, cx| {
4983            view.select_display_ranges(
4984                &[
4985                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
4986                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 1),
4987                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
4988                ],
4989                cx,
4990            );
4991            view.delete_line(&DeleteLine, cx);
4992            assert_eq!(view.display_text(cx), "ghi");
4993            assert_eq!(
4994                view.selected_display_ranges(cx),
4995                vec![
4996                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4997                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)
4998                ]
4999            );
5000        });
5001
5002        let settings = EditorSettings::test(&cx);
5003        let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
5004        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5005        view.update(cx, |view, cx| {
5006            view.select_display_ranges(&[DisplayPoint::new(2, 0)..DisplayPoint::new(0, 1)], cx);
5007            view.delete_line(&DeleteLine, cx);
5008            assert_eq!(view.display_text(cx), "ghi\n");
5009            assert_eq!(
5010                view.selected_display_ranges(cx),
5011                vec![DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)]
5012            );
5013        });
5014    }
5015
5016    #[gpui::test]
5017    fn test_duplicate_line(cx: &mut gpui::MutableAppContext) {
5018        let settings = EditorSettings::test(&cx);
5019        let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
5020        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5021        view.update(cx, |view, cx| {
5022            view.select_display_ranges(
5023                &[
5024                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
5025                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
5026                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
5027                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
5028                ],
5029                cx,
5030            );
5031            view.duplicate_line(&DuplicateLine, cx);
5032            assert_eq!(view.display_text(cx), "abc\nabc\ndef\ndef\nghi\n\n");
5033            assert_eq!(
5034                view.selected_display_ranges(cx),
5035                vec![
5036                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 1),
5037                    DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
5038                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
5039                    DisplayPoint::new(6, 0)..DisplayPoint::new(6, 0),
5040                ]
5041            );
5042        });
5043
5044        let settings = EditorSettings::test(&cx);
5045        let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
5046        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5047        view.update(cx, |view, cx| {
5048            view.select_display_ranges(
5049                &[
5050                    DisplayPoint::new(0, 1)..DisplayPoint::new(1, 1),
5051                    DisplayPoint::new(1, 2)..DisplayPoint::new(2, 1),
5052                ],
5053                cx,
5054            );
5055            view.duplicate_line(&DuplicateLine, cx);
5056            assert_eq!(view.display_text(cx), "abc\ndef\nghi\nabc\ndef\nghi\n");
5057            assert_eq!(
5058                view.selected_display_ranges(cx),
5059                vec![
5060                    DisplayPoint::new(3, 1)..DisplayPoint::new(4, 1),
5061                    DisplayPoint::new(4, 2)..DisplayPoint::new(5, 1),
5062                ]
5063            );
5064        });
5065    }
5066
5067    #[gpui::test]
5068    fn test_move_line_up_down(cx: &mut gpui::MutableAppContext) {
5069        let settings = EditorSettings::test(&cx);
5070        let buffer = MultiBuffer::build_simple(&sample_text(10, 5, 'a'), cx);
5071        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5072        view.update(cx, |view, cx| {
5073            view.fold_ranges(
5074                vec![
5075                    Point::new(0, 2)..Point::new(1, 2),
5076                    Point::new(2, 3)..Point::new(4, 1),
5077                    Point::new(7, 0)..Point::new(8, 4),
5078                ],
5079                cx,
5080            );
5081            view.select_display_ranges(
5082                &[
5083                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
5084                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
5085                    DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
5086                    DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2),
5087                ],
5088                cx,
5089            );
5090            assert_eq!(
5091                view.display_text(cx),
5092                "aa…bbb\nccc…eeee\nfffff\nggggg\n…i\njjjjj"
5093            );
5094
5095            view.move_line_up(&MoveLineUp, cx);
5096            assert_eq!(
5097                view.display_text(cx),
5098                "aa…bbb\nccc…eeee\nggggg\n…i\njjjjj\nfffff"
5099            );
5100            assert_eq!(
5101                view.selected_display_ranges(cx),
5102                vec![
5103                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
5104                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
5105                    DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3),
5106                    DisplayPoint::new(4, 0)..DisplayPoint::new(4, 2)
5107                ]
5108            );
5109        });
5110
5111        view.update(cx, |view, cx| {
5112            view.move_line_down(&MoveLineDown, cx);
5113            assert_eq!(
5114                view.display_text(cx),
5115                "ccc…eeee\naa…bbb\nfffff\nggggg\n…i\njjjjj"
5116            );
5117            assert_eq!(
5118                view.selected_display_ranges(cx),
5119                vec![
5120                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
5121                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
5122                    DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
5123                    DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2)
5124                ]
5125            );
5126        });
5127
5128        view.update(cx, |view, cx| {
5129            view.move_line_down(&MoveLineDown, cx);
5130            assert_eq!(
5131                view.display_text(cx),
5132                "ccc…eeee\nfffff\naa…bbb\nggggg\n…i\njjjjj"
5133            );
5134            assert_eq!(
5135                view.selected_display_ranges(cx),
5136                vec![
5137                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
5138                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
5139                    DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
5140                    DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2)
5141                ]
5142            );
5143        });
5144
5145        view.update(cx, |view, cx| {
5146            view.move_line_up(&MoveLineUp, cx);
5147            assert_eq!(
5148                view.display_text(cx),
5149                "ccc…eeee\naa…bbb\nggggg\n…i\njjjjj\nfffff"
5150            );
5151            assert_eq!(
5152                view.selected_display_ranges(cx),
5153                vec![
5154                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
5155                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
5156                    DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3),
5157                    DisplayPoint::new(4, 0)..DisplayPoint::new(4, 2)
5158                ]
5159            );
5160        });
5161    }
5162
5163    #[gpui::test]
5164    fn test_move_line_up_down_with_blocks(cx: &mut gpui::MutableAppContext) {
5165        let settings = EditorSettings::test(&cx);
5166        let buffer = MultiBuffer::build_simple(&sample_text(10, 5, 'a'), cx);
5167        let snapshot = buffer.read(cx).snapshot(cx);
5168        let (_, editor) =
5169            cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5170        editor.update(cx, |editor, cx| {
5171            editor.insert_blocks(
5172                [BlockProperties {
5173                    position: snapshot.anchor_after(Point::new(2, 0)),
5174                    disposition: BlockDisposition::Below,
5175                    height: 1,
5176                    render: Arc::new(|_| Empty::new().boxed()),
5177                }],
5178                cx,
5179            );
5180            editor.select_ranges([Point::new(2, 0)..Point::new(2, 0)], None, cx);
5181            editor.move_line_down(&MoveLineDown, cx);
5182        });
5183    }
5184
5185    #[gpui::test]
5186    fn test_clipboard(cx: &mut gpui::MutableAppContext) {
5187        let buffer = MultiBuffer::build_simple("one✅ two three four five six ", cx);
5188        let settings = EditorSettings::test(&cx);
5189        let view = cx
5190            .add_window(Default::default(), |cx| {
5191                build_editor(buffer.clone(), settings, cx)
5192            })
5193            .1;
5194
5195        // Cut with three selections. Clipboard text is divided into three slices.
5196        view.update(cx, |view, cx| {
5197            view.select_ranges(vec![0..7, 11..17, 22..27], None, cx);
5198            view.cut(&Cut, cx);
5199            assert_eq!(view.display_text(cx), "two four six ");
5200        });
5201
5202        // Paste with three cursors. Each cursor pastes one slice of the clipboard text.
5203        view.update(cx, |view, cx| {
5204            view.select_ranges(vec![4..4, 9..9, 13..13], None, cx);
5205            view.paste(&Paste, cx);
5206            assert_eq!(view.display_text(cx), "two one✅ four three six five ");
5207            assert_eq!(
5208                view.selected_display_ranges(cx),
5209                &[
5210                    DisplayPoint::new(0, 11)..DisplayPoint::new(0, 11),
5211                    DisplayPoint::new(0, 22)..DisplayPoint::new(0, 22),
5212                    DisplayPoint::new(0, 31)..DisplayPoint::new(0, 31)
5213                ]
5214            );
5215        });
5216
5217        // Paste again but with only two cursors. Since the number of cursors doesn't
5218        // match the number of slices in the clipboard, the entire clipboard text
5219        // is pasted at each cursor.
5220        view.update(cx, |view, cx| {
5221            view.select_ranges(vec![0..0, 31..31], None, cx);
5222            view.handle_input(&Input("( ".into()), cx);
5223            view.paste(&Paste, cx);
5224            view.handle_input(&Input(") ".into()), cx);
5225            assert_eq!(
5226                view.display_text(cx),
5227                "( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
5228            );
5229        });
5230
5231        view.update(cx, |view, cx| {
5232            view.select_ranges(vec![0..0], None, cx);
5233            view.handle_input(&Input("123\n4567\n89\n".into()), cx);
5234            assert_eq!(
5235                view.display_text(cx),
5236                "123\n4567\n89\n( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
5237            );
5238        });
5239
5240        // Cut with three selections, one of which is full-line.
5241        view.update(cx, |view, cx| {
5242            view.select_display_ranges(
5243                &[
5244                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 2),
5245                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
5246                    DisplayPoint::new(2, 0)..DisplayPoint::new(2, 1),
5247                ],
5248                cx,
5249            );
5250            view.cut(&Cut, cx);
5251            assert_eq!(
5252                view.display_text(cx),
5253                "13\n9\n( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
5254            );
5255        });
5256
5257        // Paste with three selections, noticing how the copied selection that was full-line
5258        // gets inserted before the second cursor.
5259        view.update(cx, |view, cx| {
5260            view.select_display_ranges(
5261                &[
5262                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
5263                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
5264                    DisplayPoint::new(2, 2)..DisplayPoint::new(2, 3),
5265                ],
5266                cx,
5267            );
5268            view.paste(&Paste, cx);
5269            assert_eq!(
5270                view.display_text(cx),
5271                "123\n4567\n9\n( 8ne✅ three five ) two one✅ four three six five ( one✅ three five ) "
5272            );
5273            assert_eq!(
5274                view.selected_display_ranges(cx),
5275                &[
5276                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
5277                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
5278                    DisplayPoint::new(3, 3)..DisplayPoint::new(3, 3),
5279                ]
5280            );
5281        });
5282
5283        // Copy with a single cursor only, which writes the whole line into the clipboard.
5284        view.update(cx, |view, cx| {
5285            view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)], cx);
5286            view.copy(&Copy, cx);
5287        });
5288
5289        // Paste with three selections, noticing how the copied full-line selection is inserted
5290        // before the empty selections but replaces the selection that is non-empty.
5291        view.update(cx, |view, cx| {
5292            view.select_display_ranges(
5293                &[
5294                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
5295                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 2),
5296                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
5297                ],
5298                cx,
5299            );
5300            view.paste(&Paste, cx);
5301            assert_eq!(
5302                view.display_text(cx),
5303                "123\n123\n123\n67\n123\n9\n( 8ne✅ three five ) two one✅ four three six five ( one✅ three five ) "
5304            );
5305            assert_eq!(
5306                view.selected_display_ranges(cx),
5307                &[
5308                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
5309                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
5310                    DisplayPoint::new(5, 1)..DisplayPoint::new(5, 1),
5311                ]
5312            );
5313        });
5314    }
5315
5316    #[gpui::test]
5317    fn test_select_all(cx: &mut gpui::MutableAppContext) {
5318        let buffer = MultiBuffer::build_simple("abc\nde\nfgh", cx);
5319        let settings = EditorSettings::test(&cx);
5320        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5321        view.update(cx, |view, cx| {
5322            view.select_all(&SelectAll, cx);
5323            assert_eq!(
5324                view.selected_display_ranges(cx),
5325                &[DisplayPoint::new(0, 0)..DisplayPoint::new(2, 3)]
5326            );
5327        });
5328    }
5329
5330    #[gpui::test]
5331    fn test_select_line(cx: &mut gpui::MutableAppContext) {
5332        let settings = EditorSettings::test(&cx);
5333        let buffer = MultiBuffer::build_simple(&sample_text(6, 5, 'a'), cx);
5334        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5335        view.update(cx, |view, cx| {
5336            view.select_display_ranges(
5337                &[
5338                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
5339                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
5340                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
5341                    DisplayPoint::new(4, 2)..DisplayPoint::new(4, 2),
5342                ],
5343                cx,
5344            );
5345            view.select_line(&SelectLine, cx);
5346            assert_eq!(
5347                view.selected_display_ranges(cx),
5348                vec![
5349                    DisplayPoint::new(0, 0)..DisplayPoint::new(2, 0),
5350                    DisplayPoint::new(4, 0)..DisplayPoint::new(5, 0),
5351                ]
5352            );
5353        });
5354
5355        view.update(cx, |view, cx| {
5356            view.select_line(&SelectLine, cx);
5357            assert_eq!(
5358                view.selected_display_ranges(cx),
5359                vec![
5360                    DisplayPoint::new(0, 0)..DisplayPoint::new(3, 0),
5361                    DisplayPoint::new(4, 0)..DisplayPoint::new(5, 5),
5362                ]
5363            );
5364        });
5365
5366        view.update(cx, |view, cx| {
5367            view.select_line(&SelectLine, cx);
5368            assert_eq!(
5369                view.selected_display_ranges(cx),
5370                vec![DisplayPoint::new(0, 0)..DisplayPoint::new(5, 5)]
5371            );
5372        });
5373    }
5374
5375    #[gpui::test]
5376    fn test_split_selection_into_lines(cx: &mut gpui::MutableAppContext) {
5377        let settings = EditorSettings::test(&cx);
5378        let buffer = MultiBuffer::build_simple(&sample_text(9, 5, 'a'), cx);
5379        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5380        view.update(cx, |view, cx| {
5381            view.fold_ranges(
5382                vec![
5383                    Point::new(0, 2)..Point::new(1, 2),
5384                    Point::new(2, 3)..Point::new(4, 1),
5385                    Point::new(7, 0)..Point::new(8, 4),
5386                ],
5387                cx,
5388            );
5389            view.select_display_ranges(
5390                &[
5391                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
5392                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
5393                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
5394                    DisplayPoint::new(4, 4)..DisplayPoint::new(4, 4),
5395                ],
5396                cx,
5397            );
5398            assert_eq!(view.display_text(cx), "aa…bbb\nccc…eeee\nfffff\nggggg\n…i");
5399        });
5400
5401        view.update(cx, |view, cx| {
5402            view.split_selection_into_lines(&SplitSelectionIntoLines, cx);
5403            assert_eq!(
5404                view.display_text(cx),
5405                "aaaaa\nbbbbb\nccc…eeee\nfffff\nggggg\n…i"
5406            );
5407            assert_eq!(
5408                view.selected_display_ranges(cx),
5409                [
5410                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
5411                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
5412                    DisplayPoint::new(2, 0)..DisplayPoint::new(2, 0),
5413                    DisplayPoint::new(5, 4)..DisplayPoint::new(5, 4)
5414                ]
5415            );
5416        });
5417
5418        view.update(cx, |view, cx| {
5419            view.select_display_ranges(&[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 1)], cx);
5420            view.split_selection_into_lines(&SplitSelectionIntoLines, cx);
5421            assert_eq!(
5422                view.display_text(cx),
5423                "aaaaa\nbbbbb\nccccc\nddddd\neeeee\nfffff\nggggg\nhhhhh\niiiii"
5424            );
5425            assert_eq!(
5426                view.selected_display_ranges(cx),
5427                [
5428                    DisplayPoint::new(0, 5)..DisplayPoint::new(0, 5),
5429                    DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
5430                    DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
5431                    DisplayPoint::new(3, 5)..DisplayPoint::new(3, 5),
5432                    DisplayPoint::new(4, 5)..DisplayPoint::new(4, 5),
5433                    DisplayPoint::new(5, 5)..DisplayPoint::new(5, 5),
5434                    DisplayPoint::new(6, 5)..DisplayPoint::new(6, 5),
5435                    DisplayPoint::new(7, 0)..DisplayPoint::new(7, 0)
5436                ]
5437            );
5438        });
5439    }
5440
5441    #[gpui::test]
5442    fn test_add_selection_above_below(cx: &mut gpui::MutableAppContext) {
5443        let settings = EditorSettings::test(&cx);
5444        let buffer = MultiBuffer::build_simple("abc\ndefghi\n\njk\nlmno\n", cx);
5445        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5446
5447        view.update(cx, |view, cx| {
5448            view.select_display_ranges(&[DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)], cx);
5449        });
5450        view.update(cx, |view, cx| {
5451            view.add_selection_above(&AddSelectionAbove, cx);
5452            assert_eq!(
5453                view.selected_display_ranges(cx),
5454                vec![
5455                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
5456                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)
5457                ]
5458            );
5459        });
5460
5461        view.update(cx, |view, cx| {
5462            view.add_selection_above(&AddSelectionAbove, cx);
5463            assert_eq!(
5464                view.selected_display_ranges(cx),
5465                vec![
5466                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
5467                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)
5468                ]
5469            );
5470        });
5471
5472        view.update(cx, |view, cx| {
5473            view.add_selection_below(&AddSelectionBelow, cx);
5474            assert_eq!(
5475                view.selected_display_ranges(cx),
5476                vec![DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)]
5477            );
5478        });
5479
5480        view.update(cx, |view, cx| {
5481            view.add_selection_below(&AddSelectionBelow, cx);
5482            assert_eq!(
5483                view.selected_display_ranges(cx),
5484                vec![
5485                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
5486                    DisplayPoint::new(4, 3)..DisplayPoint::new(4, 3)
5487                ]
5488            );
5489        });
5490
5491        view.update(cx, |view, cx| {
5492            view.add_selection_below(&AddSelectionBelow, cx);
5493            assert_eq!(
5494                view.selected_display_ranges(cx),
5495                vec![
5496                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
5497                    DisplayPoint::new(4, 3)..DisplayPoint::new(4, 3)
5498                ]
5499            );
5500        });
5501
5502        view.update(cx, |view, cx| {
5503            view.select_display_ranges(&[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)], cx);
5504        });
5505        view.update(cx, |view, cx| {
5506            view.add_selection_below(&AddSelectionBelow, cx);
5507            assert_eq!(
5508                view.selected_display_ranges(cx),
5509                vec![
5510                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
5511                    DisplayPoint::new(4, 4)..DisplayPoint::new(4, 3)
5512                ]
5513            );
5514        });
5515
5516        view.update(cx, |view, cx| {
5517            view.add_selection_below(&AddSelectionBelow, cx);
5518            assert_eq!(
5519                view.selected_display_ranges(cx),
5520                vec![
5521                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
5522                    DisplayPoint::new(4, 4)..DisplayPoint::new(4, 3)
5523                ]
5524            );
5525        });
5526
5527        view.update(cx, |view, cx| {
5528            view.add_selection_above(&AddSelectionAbove, cx);
5529            assert_eq!(
5530                view.selected_display_ranges(cx),
5531                vec![DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)]
5532            );
5533        });
5534
5535        view.update(cx, |view, cx| {
5536            view.add_selection_above(&AddSelectionAbove, cx);
5537            assert_eq!(
5538                view.selected_display_ranges(cx),
5539                vec![DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)]
5540            );
5541        });
5542
5543        view.update(cx, |view, cx| {
5544            view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(1, 4)], cx);
5545            view.add_selection_below(&AddSelectionBelow, cx);
5546            assert_eq!(
5547                view.selected_display_ranges(cx),
5548                vec![
5549                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
5550                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
5551                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
5552                ]
5553            );
5554        });
5555
5556        view.update(cx, |view, cx| {
5557            view.add_selection_below(&AddSelectionBelow, cx);
5558            assert_eq!(
5559                view.selected_display_ranges(cx),
5560                vec![
5561                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
5562                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
5563                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
5564                    DisplayPoint::new(4, 1)..DisplayPoint::new(4, 4),
5565                ]
5566            );
5567        });
5568
5569        view.update(cx, |view, cx| {
5570            view.add_selection_above(&AddSelectionAbove, cx);
5571            assert_eq!(
5572                view.selected_display_ranges(cx),
5573                vec![
5574                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
5575                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
5576                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
5577                ]
5578            );
5579        });
5580
5581        view.update(cx, |view, cx| {
5582            view.select_display_ranges(&[DisplayPoint::new(4, 3)..DisplayPoint::new(1, 1)], cx);
5583        });
5584        view.update(cx, |view, cx| {
5585            view.add_selection_above(&AddSelectionAbove, cx);
5586            assert_eq!(
5587                view.selected_display_ranges(cx),
5588                vec![
5589                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 1),
5590                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 1),
5591                    DisplayPoint::new(3, 2)..DisplayPoint::new(3, 1),
5592                    DisplayPoint::new(4, 3)..DisplayPoint::new(4, 1),
5593                ]
5594            );
5595        });
5596
5597        view.update(cx, |view, cx| {
5598            view.add_selection_below(&AddSelectionBelow, cx);
5599            assert_eq!(
5600                view.selected_display_ranges(cx),
5601                vec![
5602                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 1),
5603                    DisplayPoint::new(3, 2)..DisplayPoint::new(3, 1),
5604                    DisplayPoint::new(4, 3)..DisplayPoint::new(4, 1),
5605                ]
5606            );
5607        });
5608    }
5609
5610    #[gpui::test]
5611    async fn test_select_larger_smaller_syntax_node(mut cx: gpui::TestAppContext) {
5612        let settings = cx.read(EditorSettings::test);
5613        let language = Some(Arc::new(Language::new(
5614            LanguageConfig::default(),
5615            Some(tree_sitter_rust::language()),
5616        )));
5617
5618        let text = r#"
5619            use mod1::mod2::{mod3, mod4};
5620
5621            fn fn_1(param1: bool, param2: &str) {
5622                let var1 = "text";
5623            }
5624        "#
5625        .unindent();
5626
5627        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, None, cx));
5628        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
5629        let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
5630        view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
5631            .await;
5632
5633        view.update(&mut cx, |view, cx| {
5634            view.select_display_ranges(
5635                &[
5636                    DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
5637                    DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
5638                    DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
5639                ],
5640                cx,
5641            );
5642            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
5643        });
5644        assert_eq!(
5645            view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
5646            &[
5647                DisplayPoint::new(0, 23)..DisplayPoint::new(0, 27),
5648                DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
5649                DisplayPoint::new(3, 15)..DisplayPoint::new(3, 21),
5650            ]
5651        );
5652
5653        view.update(&mut cx, |view, cx| {
5654            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
5655        });
5656        assert_eq!(
5657            view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
5658            &[
5659                DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
5660                DisplayPoint::new(4, 1)..DisplayPoint::new(2, 0),
5661            ]
5662        );
5663
5664        view.update(&mut cx, |view, cx| {
5665            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
5666        });
5667        assert_eq!(
5668            view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
5669            &[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 0)]
5670        );
5671
5672        // Trying to expand the selected syntax node one more time has no effect.
5673        view.update(&mut cx, |view, cx| {
5674            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
5675        });
5676        assert_eq!(
5677            view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
5678            &[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 0)]
5679        );
5680
5681        view.update(&mut cx, |view, cx| {
5682            view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
5683        });
5684        assert_eq!(
5685            view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
5686            &[
5687                DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
5688                DisplayPoint::new(4, 1)..DisplayPoint::new(2, 0),
5689            ]
5690        );
5691
5692        view.update(&mut cx, |view, cx| {
5693            view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
5694        });
5695        assert_eq!(
5696            view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
5697            &[
5698                DisplayPoint::new(0, 23)..DisplayPoint::new(0, 27),
5699                DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
5700                DisplayPoint::new(3, 15)..DisplayPoint::new(3, 21),
5701            ]
5702        );
5703
5704        view.update(&mut cx, |view, cx| {
5705            view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
5706        });
5707        assert_eq!(
5708            view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
5709            &[
5710                DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
5711                DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
5712                DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
5713            ]
5714        );
5715
5716        // Trying to shrink the selected syntax node one more time has no effect.
5717        view.update(&mut cx, |view, cx| {
5718            view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
5719        });
5720        assert_eq!(
5721            view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
5722            &[
5723                DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
5724                DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
5725                DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
5726            ]
5727        );
5728
5729        // Ensure that we keep expanding the selection if the larger selection starts or ends within
5730        // a fold.
5731        view.update(&mut cx, |view, cx| {
5732            view.fold_ranges(
5733                vec![
5734                    Point::new(0, 21)..Point::new(0, 24),
5735                    Point::new(3, 20)..Point::new(3, 22),
5736                ],
5737                cx,
5738            );
5739            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
5740        });
5741        assert_eq!(
5742            view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
5743            &[
5744                DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
5745                DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
5746                DisplayPoint::new(3, 4)..DisplayPoint::new(3, 23),
5747            ]
5748        );
5749    }
5750
5751    #[gpui::test]
5752    async fn test_autoindent_selections(mut cx: gpui::TestAppContext) {
5753        let settings = cx.read(EditorSettings::test);
5754        let language = Some(Arc::new(
5755            Language::new(
5756                LanguageConfig {
5757                    brackets: vec![
5758                        BracketPair {
5759                            start: "{".to_string(),
5760                            end: "}".to_string(),
5761                            close: false,
5762                            newline: true,
5763                        },
5764                        BracketPair {
5765                            start: "(".to_string(),
5766                            end: ")".to_string(),
5767                            close: false,
5768                            newline: true,
5769                        },
5770                    ],
5771                    ..Default::default()
5772                },
5773                Some(tree_sitter_rust::language()),
5774            )
5775            .with_indents_query(
5776                r#"
5777                (_ "(" ")" @end) @indent
5778                (_ "{" "}" @end) @indent
5779                "#,
5780            )
5781            .unwrap(),
5782        ));
5783
5784        let text = "fn a() {}";
5785
5786        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, None, cx));
5787        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
5788        let (_, editor) = cx.add_window(|cx| build_editor(buffer, settings, cx));
5789        editor
5790            .condition(&cx, |editor, cx| !editor.buffer.read(cx).is_parsing(cx))
5791            .await;
5792
5793        editor.update(&mut cx, |editor, cx| {
5794            editor.select_ranges([5..5, 8..8, 9..9], None, cx);
5795            editor.newline(&Newline, cx);
5796            assert_eq!(editor.text(cx), "fn a(\n    \n) {\n    \n}\n");
5797            assert_eq!(
5798                editor.selected_ranges(cx),
5799                &[
5800                    Point::new(1, 4)..Point::new(1, 4),
5801                    Point::new(3, 4)..Point::new(3, 4),
5802                    Point::new(5, 0)..Point::new(5, 0)
5803                ]
5804            );
5805        });
5806    }
5807
5808    #[gpui::test]
5809    async fn test_autoclose_pairs(mut cx: gpui::TestAppContext) {
5810        let settings = cx.read(EditorSettings::test);
5811        let language = Some(Arc::new(Language::new(
5812            LanguageConfig {
5813                brackets: vec![
5814                    BracketPair {
5815                        start: "{".to_string(),
5816                        end: "}".to_string(),
5817                        close: true,
5818                        newline: true,
5819                    },
5820                    BracketPair {
5821                        start: "/*".to_string(),
5822                        end: " */".to_string(),
5823                        close: true,
5824                        newline: true,
5825                    },
5826                ],
5827                ..Default::default()
5828            },
5829            Some(tree_sitter_rust::language()),
5830        )));
5831
5832        let text = r#"
5833            a
5834
5835            /
5836
5837        "#
5838        .unindent();
5839
5840        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, None, cx));
5841        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
5842        let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
5843        view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
5844            .await;
5845
5846        view.update(&mut cx, |view, cx| {
5847            view.select_display_ranges(
5848                &[
5849                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
5850                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
5851                ],
5852                cx,
5853            );
5854            view.handle_input(&Input("{".to_string()), cx);
5855            view.handle_input(&Input("{".to_string()), cx);
5856            view.handle_input(&Input("{".to_string()), cx);
5857            assert_eq!(
5858                view.text(cx),
5859                "
5860                {{{}}}
5861                {{{}}}
5862                /
5863
5864                "
5865                .unindent()
5866            );
5867
5868            view.move_right(&MoveRight, cx);
5869            view.handle_input(&Input("}".to_string()), cx);
5870            view.handle_input(&Input("}".to_string()), cx);
5871            view.handle_input(&Input("}".to_string()), cx);
5872            assert_eq!(
5873                view.text(cx),
5874                "
5875                {{{}}}}
5876                {{{}}}}
5877                /
5878
5879                "
5880                .unindent()
5881            );
5882
5883            view.undo(&Undo, cx);
5884            view.handle_input(&Input("/".to_string()), cx);
5885            view.handle_input(&Input("*".to_string()), cx);
5886            assert_eq!(
5887                view.text(cx),
5888                "
5889                /* */
5890                /* */
5891                /
5892
5893                "
5894                .unindent()
5895            );
5896
5897            view.undo(&Undo, cx);
5898            view.select_display_ranges(
5899                &[
5900                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
5901                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
5902                ],
5903                cx,
5904            );
5905            view.handle_input(&Input("*".to_string()), cx);
5906            assert_eq!(
5907                view.text(cx),
5908                "
5909                a
5910
5911                /*
5912                *
5913                "
5914                .unindent()
5915            );
5916        });
5917    }
5918
5919    #[gpui::test]
5920    async fn test_toggle_comment(mut cx: gpui::TestAppContext) {
5921        let settings = cx.read(EditorSettings::test);
5922        let language = Some(Arc::new(Language::new(
5923            LanguageConfig {
5924                line_comment: Some("// ".to_string()),
5925                ..Default::default()
5926            },
5927            Some(tree_sitter_rust::language()),
5928        )));
5929
5930        let text = "
5931            fn a() {
5932                //b();
5933                // c();
5934                //  d();
5935            }
5936        "
5937        .unindent();
5938
5939        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, None, cx));
5940        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
5941        let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
5942
5943        view.update(&mut cx, |editor, cx| {
5944            // If multiple selections intersect a line, the line is only
5945            // toggled once.
5946            editor.select_display_ranges(
5947                &[
5948                    DisplayPoint::new(1, 3)..DisplayPoint::new(2, 3),
5949                    DisplayPoint::new(3, 5)..DisplayPoint::new(3, 6),
5950                ],
5951                cx,
5952            );
5953            editor.toggle_comments(&ToggleComments, cx);
5954            assert_eq!(
5955                editor.text(cx),
5956                "
5957                    fn a() {
5958                        b();
5959                        c();
5960                         d();
5961                    }
5962                "
5963                .unindent()
5964            );
5965
5966            // The comment prefix is inserted at the same column for every line
5967            // in a selection.
5968            editor.select_display_ranges(&[DisplayPoint::new(1, 3)..DisplayPoint::new(3, 6)], cx);
5969            editor.toggle_comments(&ToggleComments, cx);
5970            assert_eq!(
5971                editor.text(cx),
5972                "
5973                    fn a() {
5974                        // b();
5975                        // c();
5976                        //  d();
5977                    }
5978                "
5979                .unindent()
5980            );
5981
5982            // If a selection ends at the beginning of a line, that line is not toggled.
5983            editor.select_display_ranges(&[DisplayPoint::new(2, 0)..DisplayPoint::new(3, 0)], cx);
5984            editor.toggle_comments(&ToggleComments, cx);
5985            assert_eq!(
5986                editor.text(cx),
5987                "
5988                        fn a() {
5989                            // b();
5990                            c();
5991                            //  d();
5992                        }
5993                    "
5994                .unindent()
5995            );
5996        });
5997    }
5998
5999    #[gpui::test]
6000    fn test_editing_disjoint_excerpts(cx: &mut gpui::MutableAppContext) {
6001        let settings = EditorSettings::test(cx);
6002        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(3, 4, 'a'), cx));
6003        let multibuffer = cx.add_model(|cx| {
6004            let mut multibuffer = MultiBuffer::new(0);
6005            multibuffer.push_excerpt(
6006                ExcerptProperties {
6007                    buffer: &buffer,
6008                    range: Point::new(0, 0)..Point::new(0, 4),
6009                },
6010                cx,
6011            );
6012            multibuffer.push_excerpt(
6013                ExcerptProperties {
6014                    buffer: &buffer,
6015                    range: Point::new(1, 0)..Point::new(1, 4),
6016                },
6017                cx,
6018            );
6019            multibuffer
6020        });
6021
6022        assert_eq!(multibuffer.read(cx).read(cx).text(), "aaaa\nbbbb");
6023
6024        let (_, view) = cx.add_window(Default::default(), |cx| {
6025            build_editor(multibuffer, settings, cx)
6026        });
6027        view.update(cx, |view, cx| {
6028            view.select_display_ranges(
6029                &[
6030                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
6031                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
6032                ],
6033                cx,
6034            );
6035
6036            view.handle_input(&Input("X".to_string()), cx);
6037            assert_eq!(view.text(cx), "Xaaaa\nXbbbb");
6038            assert_eq!(
6039                view.selected_display_ranges(cx),
6040                &[
6041                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
6042                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
6043                ]
6044            )
6045        });
6046    }
6047
6048    #[gpui::test]
6049    fn test_editing_overlapping_excerpts(cx: &mut gpui::MutableAppContext) {
6050        let settings = EditorSettings::test(cx);
6051        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(3, 4, 'a'), cx));
6052        let multibuffer = cx.add_model(|cx| {
6053            let mut multibuffer = MultiBuffer::new(0);
6054            multibuffer.push_excerpt(
6055                ExcerptProperties {
6056                    buffer: &buffer,
6057                    range: Point::new(0, 0)..Point::new(1, 4),
6058                },
6059                cx,
6060            );
6061            multibuffer.push_excerpt(
6062                ExcerptProperties {
6063                    buffer: &buffer,
6064                    range: Point::new(1, 0)..Point::new(2, 4),
6065                },
6066                cx,
6067            );
6068            multibuffer
6069        });
6070
6071        assert_eq!(
6072            multibuffer.read(cx).read(cx).text(),
6073            "aaaa\nbbbb\nbbbb\ncccc"
6074        );
6075
6076        let (_, view) = cx.add_window(Default::default(), |cx| {
6077            build_editor(multibuffer, settings, cx)
6078        });
6079        view.update(cx, |view, cx| {
6080            view.select_display_ranges(
6081                &[
6082                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
6083                    DisplayPoint::new(2, 3)..DisplayPoint::new(2, 3),
6084                ],
6085                cx,
6086            );
6087
6088            view.handle_input(&Input("X".to_string()), cx);
6089            assert_eq!(view.text(cx), "aaaa\nbXbbXb\nbXbbXb\ncccc");
6090            assert_eq!(
6091                view.selected_display_ranges(cx),
6092                &[
6093                    DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
6094                    DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
6095                ]
6096            );
6097
6098            view.newline(&Newline, cx);
6099            assert_eq!(view.text(cx), "aaaa\nbX\nbbX\nb\nbX\nbbX\nb\ncccc");
6100            assert_eq!(
6101                view.selected_display_ranges(cx),
6102                &[
6103                    DisplayPoint::new(2, 0)..DisplayPoint::new(2, 0),
6104                    DisplayPoint::new(6, 0)..DisplayPoint::new(6, 0),
6105                ]
6106            );
6107        });
6108    }
6109
6110    #[gpui::test]
6111    fn test_refresh_selections(cx: &mut gpui::MutableAppContext) {
6112        let settings = EditorSettings::test(cx);
6113        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(3, 4, 'a'), cx));
6114        let mut excerpt1_id = None;
6115        let multibuffer = cx.add_model(|cx| {
6116            let mut multibuffer = MultiBuffer::new(0);
6117            excerpt1_id = Some(multibuffer.push_excerpt(
6118                ExcerptProperties {
6119                    buffer: &buffer,
6120                    range: Point::new(0, 0)..Point::new(1, 4),
6121                },
6122                cx,
6123            ));
6124            multibuffer.push_excerpt(
6125                ExcerptProperties {
6126                    buffer: &buffer,
6127                    range: Point::new(1, 0)..Point::new(2, 4),
6128                },
6129                cx,
6130            );
6131            multibuffer
6132        });
6133        assert_eq!(
6134            multibuffer.read(cx).read(cx).text(),
6135            "aaaa\nbbbb\nbbbb\ncccc"
6136        );
6137        let (_, editor) = cx.add_window(Default::default(), |cx| {
6138            let mut editor = build_editor(multibuffer.clone(), settings, cx);
6139            editor.select_display_ranges(
6140                &[
6141                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
6142                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
6143                ],
6144                cx,
6145            );
6146            editor
6147        });
6148
6149        // Refreshing selections is a no-op when excerpts haven't changed.
6150        editor.update(cx, |editor, cx| {
6151            editor.refresh_selections(cx);
6152            assert_eq!(
6153                editor.selected_display_ranges(cx),
6154                [
6155                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
6156                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
6157                ]
6158            );
6159        });
6160
6161        multibuffer.update(cx, |multibuffer, cx| {
6162            multibuffer.remove_excerpts([&excerpt1_id.unwrap()], cx);
6163        });
6164        editor.update(cx, |editor, cx| {
6165            // Removing an excerpt causes the first selection to become degenerate.
6166            assert_eq!(
6167                editor.selected_display_ranges(cx),
6168                [
6169                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
6170                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)
6171                ]
6172            );
6173
6174            // Refreshing selections will relocate the first selection to the original buffer
6175            // location.
6176            editor.refresh_selections(cx);
6177            assert_eq!(
6178                editor.selected_display_ranges(cx),
6179                [
6180                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
6181                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3)
6182                ]
6183            );
6184        });
6185    }
6186
6187    #[gpui::test]
6188    async fn test_extra_newline_insertion(mut cx: gpui::TestAppContext) {
6189        let settings = cx.read(EditorSettings::test);
6190        let language = Some(Arc::new(Language::new(
6191            LanguageConfig {
6192                brackets: vec![
6193                    BracketPair {
6194                        start: "{".to_string(),
6195                        end: "}".to_string(),
6196                        close: true,
6197                        newline: true,
6198                    },
6199                    BracketPair {
6200                        start: "/* ".to_string(),
6201                        end: " */".to_string(),
6202                        close: true,
6203                        newline: true,
6204                    },
6205                ],
6206                ..Default::default()
6207            },
6208            Some(tree_sitter_rust::language()),
6209        )));
6210
6211        let text = concat!(
6212            "{   }\n",     // Suppress rustfmt
6213            "  x\n",       //
6214            "  /*   */\n", //
6215            "x\n",         //
6216            "{{} }\n",     //
6217        );
6218
6219        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, None, cx));
6220        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
6221        let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
6222        view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
6223            .await;
6224
6225        view.update(&mut cx, |view, cx| {
6226            view.select_display_ranges(
6227                &[
6228                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 3),
6229                    DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
6230                    DisplayPoint::new(4, 4)..DisplayPoint::new(4, 4),
6231                ],
6232                cx,
6233            );
6234            view.newline(&Newline, cx);
6235
6236            assert_eq!(
6237                view.buffer().read(cx).read(cx).text(),
6238                concat!(
6239                    "{ \n",    // Suppress rustfmt
6240                    "\n",      //
6241                    "}\n",     //
6242                    "  x\n",   //
6243                    "  /* \n", //
6244                    "  \n",    //
6245                    "  */\n",  //
6246                    "x\n",     //
6247                    "{{} \n",  //
6248                    "}\n",     //
6249                )
6250            );
6251        });
6252    }
6253
6254    fn empty_range(row: usize, column: usize) -> Range<DisplayPoint> {
6255        let point = DisplayPoint::new(row as u32, column as u32);
6256        point..point
6257    }
6258
6259    fn build_editor(
6260        buffer: ModelHandle<MultiBuffer>,
6261        settings: EditorSettings,
6262        cx: &mut ViewContext<Editor>,
6263    ) -> Editor {
6264        Editor::for_buffer(buffer, Arc::new(move |_| settings.clone()), cx)
6265    }
6266}
6267
6268trait RangeExt<T> {
6269    fn sorted(&self) -> Range<T>;
6270    fn to_inclusive(&self) -> RangeInclusive<T>;
6271}
6272
6273impl<T: Ord + Clone> RangeExt<T> for Range<T> {
6274    fn sorted(&self) -> Self {
6275        cmp::min(&self.start, &self.end).clone()..cmp::max(&self.start, &self.end).clone()
6276    }
6277
6278    fn to_inclusive(&self) -> RangeInclusive<T> {
6279        self.start.clone()..=self.end.clone()
6280    }
6281}