editor.rs

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