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