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