editor.rs

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