editor.rs

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