editor.rs

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