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