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