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