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