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