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