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