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