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