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