editor.rs

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