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