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