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